blob: 858cb3a1c7cbb982f8fdbeddff6d2c8be88f9cfa [file] [log] [blame]
Zack Williams41513bf2018-07-07 20:08:35 -07001# Copyright 2017-present Open Networking Foundation
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
Rachit Shrivastava8e435b42017-08-08 23:15:26 -040014from bitstring import BitArray
15import structlog
16
17log = structlog.get_logger()
18
19class IndexPool(object):
20 def __init__(self, max_entries, offset):
21 self.max_entries = max_entries
22 self.offset = offset
23 self.indices = BitArray(self.max_entries)
24
25 def get_next(self):
26 try:
27 _pos = self.indices.find('0b0')
28 self.indices.set(1, _pos)
29 return self.offset + _pos[0]
30 except IndexError:
31 log.info("exception-fail-to-allocate-id-all-bits-in-use")
32 return None
33
Chip Boling97bef1e2017-08-29 11:44:28 -050034 def allocate(self, index):
35 try:
36 _pos = index - self.offset
37 if not (0 <= _pos < self.max_entries):
38 log.info("{}-out-of-range".format(index))
39 return None
40 if self.indices[_pos]:
41 log.info("{}-is-already-allocated".format(index))
42 return None
43 self.indices.set(1, _pos)
44 return index
45
46 except IndexError:
47 return None
48
Rachit Shrivastava8e435b42017-08-08 23:15:26 -040049 def release(self, index):
50 index -= self.offset
51 _pos = (index,)
52 try:
53 self.indices.set(0, _pos)
54 except IndexError:
55 log.info("bit-position-{}-out-of-range".format(index))
56
57 #index or multiple indices to set all of them to 1 - need to be a tuple
58 def pre_allocate(self, index):
59 if(isinstance(index, tuple)):
60 _lst = list(index)
61 for i in range(len(_lst)):
62 _lst[i] -= self.offset
63 index = tuple(_lst)
64 self.indices.set(1, index)