-
Notifications
You must be signed in to change notification settings - Fork 0
/
History.py
78 lines (68 loc) · 2.4 KB
/
History.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""
Simple fifo to handle "backward" in a flow
- User must implement a class/hash/list/something and append them to this class
- Class stores a fixed size fifo of them
- User can go forward/backward
- A callback can be called for removed item
"""
class History:
buffer = [ ]
# current position in buffer
bufferPos = 0
# absolute position of first buffer item
iter0 = 0
def __init__(self,
_next, # callback to get a new item
_maxSize = 25, # fifo max size
_removeCallback = None, # callback for removed item
_first = None, # initialize fifo with this item
_initialIndex = 0 # force first item having this index
):
# TODO max must be > 1
self.bufferMax = _maxSize
self.nextCallback = _next
self.removeCallback = _removeCallback
self.iter0 = _initialIndex
if _first is not None:
self.buffer.append(_first)
def pop(self):
if len(self.buffer) == 0:
return None
result = self.buffer.pop(0)
if self.removeCallback is not None:
self.removeCallback(self.iter0, result)
self.iter0 += 1
return result
def forward(self):
if self.bufferPos >= 0 and self.bufferPos < len(self.buffer) - 1:
self.bufferPos += 1
return self.buffer[self.bufferPos], False
else:
nextOne = self.nextCallback()
if nextOne is None:
return None, True
self.buffer.append(nextOne)
if len(self.buffer) > self.bufferMax:
self.pop()
else:
self. bufferPos += 1
return self.buffer[self.bufferPos], True
def backward(self):
if self.bufferPos > 0:
self.bufferPos -= 1
return self.buffer[self.bufferPos]
return None
# return current item
def get(self, index = None):
if len(self.buffer) > 0:
if index is None:
pos = self.bufferPos
elif index >= 0:
pos = index if index <= self.bufferPos else self.bufferPos
else:
pos = self.bufferPos + index if self.bufferPos + index >= 0 else 0
return self.buffer[pos]
return None
# return index of current item
def index(self):
return self.iter0 + self.bufferPos