Add 'sba.py'
parent
cc1d310a2f
commit
ed17353d05
@ -0,0 +1,51 @@
|
||||
import sys
|
||||
|
||||
class SBA:
|
||||
slots = ('_arr', '_size', '_memsize')
|
||||
|
||||
def __init__(self, size):
|
||||
if not isinstance(size, int):
|
||||
raise ValueError("Size should be integer!")
|
||||
self._arr = 1<<size
|
||||
self._size = size
|
||||
self._memsize = f"{round(sys.getsizeof(self._arr) / 1024, 2)} KByte"
|
||||
|
||||
@property
|
||||
def memsize(self):
|
||||
return self._memsize
|
||||
|
||||
def __getitem__(self, sliced):
|
||||
if not isinstance(sliced, int):
|
||||
raise ValueError("Only integers accepted as position!")
|
||||
if sliced >= self._size:
|
||||
raise ValueError("Range out of boundaries!")
|
||||
if (self._arr & 1<<sliced) > 0:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
def __setitem__(self, sliced, val):
|
||||
if not isinstance(sliced, int):
|
||||
raise ValueError("Only integers accepted as position!")
|
||||
if not isinstance(val, (int, bool)):
|
||||
raise ValueError("Values accepted as int or bool")
|
||||
if sliced >= self._size:
|
||||
raise ValueError("Range out of boundaries!")
|
||||
|
||||
if isinstance(val, bool):
|
||||
v = {True: 1, False: 0}[val]
|
||||
else:
|
||||
if 0 > val > 1:
|
||||
raise ValueError("Value is out of range!")
|
||||
v = val
|
||||
self._arr = self._arr | v<<sliced
|
||||
|
||||
def __len__(self):
|
||||
return self._size
|
||||
|
||||
if __name__ == "__main__":
|
||||
s = SBA(16)
|
||||
print(s[1])
|
||||
s[1] = 1
|
||||
print(s[1])
|
||||
print(len(s))
|
||||
print(s[16])
|
Loading…
Reference in New Issue