-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathfifo.py
More file actions
55 lines (41 loc) · 1.44 KB
/
fifo.py
File metadata and controls
55 lines (41 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""FIFO Set implementation.
This module provides a FIFOSet class, which behaves like a set
with a maximum size and first-in-first-out eviction policy.
"""
from collections import OrderedDict
class FIFOSet:
"""A set with FIFO eviction and a maximum size.
When the set exceeds the configured maximum size,
the oldest element is removed automatically.
"""
def __init__(self, max_size=100):
"""Initialize the FIFOSet.
Args:
max_size (int): Maximum number of items to retain.
"""
self.max_size = max_size
self.data = OrderedDict()
def add(self, item):
"""Add an item to the set.
If the item is already present, it is ignored.
If the set is full, the oldest item is evicted.
Args:
item: The item to add.
"""
if item in self.data:
return
if len(self.data) >= self.max_size:
self.data.popitem(last=False)
self.data[item] = None
def __contains__(self, item):
"""Check if an item is in the set (O(1))."""
return item in self.data
def __len__(self):
"""Return the number of items in the set."""
return len(self.data)
def __iter__(self):
"""Iterate over the items in FIFO order."""
return iter(self.data)
def __repr__(self):
"""Return a string representation of the set."""
return f"FIFOSet({list(self.data.keys())})"