blob: d85d1ef35d7c80d8bda70066c40ad4f66c5e5589 [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
Chip Boling97bef1e2017-08-29 11:44:28 -050021 def allocate(self, index):
22 try:
23 _pos = index - self.offset
24 if not (0 <= _pos < self.max_entries):
25 log.info("{}-out-of-range".format(index))
26 return None
27 if self.indices[_pos]:
28 log.info("{}-is-already-allocated".format(index))
29 return None
30 self.indices.set(1, _pos)
31 return index
32
33 except IndexError:
34 return None
35
Rachit Shrivastava8e435b42017-08-08 23:15:26 -040036 def release(self, index):
37 index -= self.offset
38 _pos = (index,)
39 try:
40 self.indices.set(0, _pos)
41 except IndexError:
42 log.info("bit-position-{}-out-of-range".format(index))
43
44 #index or multiple indices to set all of them to 1 - need to be a tuple
45 def pre_allocate(self, index):
46 if(isinstance(index, tuple)):
47 _lst = list(index)
48 for i in range(len(_lst)):
49 _lst[i] -= self.offset
50 index = tuple(_lst)
51 self.indices.set(1, index)