Initial implementation of OutputBuffer
This commit is contained in:
parent
f53afa7812
commit
e7669af962
1 changed files with 37 additions and 0 deletions
|
@ -4,6 +4,43 @@ class BufferOverflow(Exception):
|
|||
def __init__(self):
|
||||
super().__init__("Buffer overflow")
|
||||
|
||||
class OutputBuffer():
|
||||
__slots__ = 'buf', 'size', 'sock', 'offset',
|
||||
|
||||
BUFFER_SIZE = 20480
|
||||
|
||||
def __init__(self, sock: socket.socket, size: int=BUFFER_SIZE):
|
||||
self.buf: bytearray = bytearray(size)
|
||||
self.size: int = size
|
||||
self.sock: socket.socket = sock
|
||||
self.offset: int = 0
|
||||
|
||||
def print(self, text: str, end: str="\r\n"):
|
||||
data = bytes(text + end, 'utf-8')
|
||||
count = len(data)
|
||||
|
||||
if count > self.size:
|
||||
return self.sock.send(data)
|
||||
|
||||
if count + self.offset > self.size:
|
||||
to_fill = self.size - self.offset
|
||||
left = count - to_fill
|
||||
|
||||
self.buf[self.offset:self.size] = data[0:to_fill]
|
||||
|
||||
self.sock.send(self.buf)
|
||||
|
||||
self.offset = 0
|
||||
|
||||
self.buf[0:left] = data[to_fill:to_fill+left]
|
||||
else:
|
||||
self.buf[self.offset:self.offset+count] = data
|
||||
self.offset += count
|
||||
|
||||
def flush(self):
|
||||
self.sock.send(self.buf[0:self.offset])
|
||||
self.offset = 0
|
||||
|
||||
class LineBuffer():
|
||||
__slots__ = 'buf', 'size', 'offset_i', 'offset_o', 'eof', 'done',
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue