blob: 24f57ffbc0a54fed71b3526e346a46376bc110af [file] [log] [blame]
Rachit Shrivastava8e435b42017-08-08 23:15:26 -04001from bitstring import BitArray
2import structlog
3
4log = structlog.get_logger()
5
6class IndexPool(object):
7 def __init__(self, max_entries, offset):
8 self.max_entries = max_entries
9 self.offset = offset
10 self.indices = BitArray(self.max_entries)
11
12 def get_next(self):
13 try:
14 _pos = self.indices.find('0b0')
15 self.indices.set(1, _pos)
16 return self.offset + _pos[0]
17 except IndexError:
18 log.info("exception-fail-to-allocate-id-all-bits-in-use")
19 return None
20
21 def release(self, index):
22 index -= self.offset
23 _pos = (index,)
24 try:
25 self.indices.set(0, _pos)
26 except IndexError:
27 log.info("bit-position-{}-out-of-range".format(index))
28
29 #index or multiple indices to set all of them to 1 - need to be a tuple
30 def pre_allocate(self, index):
31 if(isinstance(index, tuple)):
32 _lst = list(index)
33 for i in range(len(_lst)):
34 _lst[i] -= self.offset
35 index = tuple(_lst)
36 self.indices.set(1, index)