Last active
July 5, 2018 12:23
-
-
Save msoedov/b63c2e1be05b9823be4b286633d56605 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import deque | |
class RingBuff: | |
""" | |
# Spec for buffer | |
>>> buffer = RingBuff(5) | |
>>> buffer.write([1, 2, 3]) | |
3 | |
>>> buffer.write([4, 5, 6]) | |
2 | |
>>> buffer.read() | |
1 | |
>>> buffer.read() | |
2 | |
>>> buffer.read() | |
3 | |
>>> buffer.read() | |
4 | |
>>> buffer.read() | |
5 | |
>>> buffer.read() | |
Traceback (most recent call last): | |
... | |
IndexError: Empty ring | |
""" | |
def __init__(self, capacity=5): | |
self.fifo = deque(maxlen=capacity) | |
self.capacity = capacity | |
def write(self, objects: [object]) -> int: | |
size = self.capacity - len(self.fifo) | |
size = min(len(objects), size) | |
for o in objects[:size]: | |
self.fifo.append(o) | |
return size | |
def read(self) -> object or IndexError: | |
try: | |
return self.fifo.popleft() | |
except IndexError: | |
raise IndexError("Empty ring") | |
def __repr__(self) -> str: | |
return f"RingBuff<{self.fifo}>" | |
def main(): | |
import doctest | |
doctest.testmod() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment