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