Initial implementation of OutputBuffer

This commit is contained in:
XANTRONIX 2024-11-26 18:43:08 -05:00
parent f53afa7812
commit e7669af962

View file

@ -4,6 +4,43 @@ class BufferOverflow(Exception):
def __init__(self): def __init__(self):
super().__init__("Buffer overflow") 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(): class LineBuffer():
__slots__ = 'buf', 'size', 'offset_i', 'offset_o', 'eof', 'done', __slots__ = 'buf', 'size', 'offset_i', 'offset_o', 'eof', 'done',