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
|
class CustomBitsetType(object): INT_BITS = 64 - 1
def __init__(self): self.data = {}
def get_bit(self, index): key, bit_pos = divmod(index, CustomBitsetType.INT_BITS) if key not in self.data: return False return bool(self.data[key] & 1<<bit_pos)
def set_bit(self, index, bit_value): key, bit_pos = divmod(index, CustomBitsetType.INT_BITS) if key not in self.data: if bit_value: self.data[key] = 1 << bit_pos return
if bit_value: self.data[key] = self.data[key] | 1<<bit_pos return
value = self.data[key] & ~(1 << bit_pos) if value > 0: self.data[key] = value else: self.data.pop(key)
def on_setattr(self, key, old, new): old = old or 0 new = new or 0 for i in range(CustomBitsetType.INT_BITS): in_old = old & 1 << i > 0 in_new = new & 1 << i > 0 if in_old != in_new: self.on_set_bit(key * CustomBitsetType.INT_BITS + i, in_old, in_new)
def on_set_bit(self, index, old, new): self.set_bit(index, new)
bitset = CustomBitsetType() remote_bitset = CustomBitsetType()
print("[local]", bitset.get_bit(12)) print("[local]", bitset.set_bit(12, True)) print("[local]", bitset.get_bit(12)) print("=========================")
for k, v in bitset.data.items(): remote_bitset.on_setattr(k, 0, v) print("[remote]", remote_bitset.get_bit(11)) print("[remote]", remote_bitset.get_bit(12))
print(bitset.data, remote_bitset.data)
|