feat(collections): init circular buffer

This commit is contained in:
Rodney, Tiara 2025-05-04 01:34:35 +02:00
parent 136b5567ce
commit 549fea06b1
No known key found for this signature in database
GPG key ID: 5CD8EC1D46106723

View file

@ -0,0 +1,37 @@
class CircularBuffer:
"""circular buffer implementation for managing streamed data
"""
#: internal buffer storage maintaining a fixed size
buf: bytearray
#: maximum capacity of the buffer
size: int
#: index of the oldest element in the buffer
start: int
#: index where the next element will be inserted
end: int
#: indicates whether the buffer has overwritten older data
filled: bool
def __init__(self, size: int):
"""initializes the circular buffer with a fixed capacity
:param size: maximum number of bytes the buffer can hold
"""
self.buf = bytearray(size)
self.size = size
self.start = 0
self.end = 0
self.filled = False
def append(self, data: bytes):
"""adds data to the circular buffer, overwriting old data if necessary
:param data: byte sequence to append to the buffer
"""
for byte in data:
self.buf[self.end] = byte
self.end = (self.end + 1) % self.size
if self.end == self.start: # Overwriting case
self.start = (self.start + 1) % self.size
self.filled = True