342
|
1
|
|
2 import struct
|
|
3
|
398
|
4
|
342
|
5 def u16(h):
|
|
6 return struct.pack('<H', h)
|
|
7
|
|
8
|
|
9 def u32(x):
|
|
10 return struct.pack('<I', x)
|
|
11
|
|
12
|
398
|
13 def u8(x):
|
|
14 return struct.pack('<B', x)
|
|
15
|
|
16
|
342
|
17 def val2bit(v, bits):
|
|
18 b = []
|
|
19 for i in range(bits):
|
398
|
20 b.append(bool((1 << i) & v))
|
342
|
21 return b
|
|
22
|
|
23
|
|
24 def bit_range(b, e):
|
|
25 """ Property generator function """
|
|
26 getter = lambda s: s[b:e]
|
398
|
27
|
342
|
28 def setter(s, v):
|
|
29 s[b:e] = v
|
|
30 return property(getter, setter)
|
|
31
|
|
32
|
|
33 class Token:
|
|
34 def __init__(self, bitsize):
|
|
35 self.bitsize = bitsize
|
|
36 self.bit_value = 0
|
|
37
|
|
38 def set_bit(self, i, value):
|
|
39 value = bool(value)
|
|
40 assert i in range(0, self.bitsize)
|
|
41 mask = 1 << i
|
|
42 if value:
|
|
43 self.bit_value |= mask
|
|
44 else:
|
|
45 self.bit_value &= (~mask)
|
|
46
|
|
47 def __getitem__(self, key):
|
|
48 return False
|
|
49
|
|
50 def __setitem__(self, key, value):
|
|
51 if type(key) is int:
|
|
52 self.set_bit(key, value)
|
|
53 elif type(key) is slice:
|
|
54 assert key.step is None
|
|
55 bits = key.stop - key.start
|
394
|
56 assert value < (2**bits)
|
342
|
57 value_bits = val2bit(value, bits)
|
|
58 for i in range(key.start, key.stop):
|
|
59 self.set_bit(i, value_bits[i - key.start])
|
|
60 else:
|
|
61 raise KeyError()
|