]>
git.ipfire.org Git - people/shoehn/ipfire.org.git/blob - www/pages/torrent/client/bitfield.py
1 # Written by Bram Cohen, Uoti Urpala, and John Hoffman
2 # see LICENSE.txt for license information
9 bool = lambda x
: not not x
13 negsum
= lambda a
: len(a
)-sum(a
)
15 negsum
= lambda a
: reduce(lambda x
,y
: x
+(not y
), a
, 0)
17 def _int_to_booleans(x
):
20 r
.append(bool(x
& 0x80))
25 reverse_lookup_table
= {}
27 x
= _int_to_booleans(i
)
28 lookup_table
.append(x
)
29 reverse_lookup_table
[x
] = chr(i
)
33 def __init__(self
, length
= None, bitstring
= None, copyfrom
= None):
34 if copyfrom
is not None:
35 self
.length
= copyfrom
.length
36 self
.array
= copyfrom
.array
[:]
37 self
.numfalse
= copyfrom
.numfalse
40 raise ValueError, "length must be provided unless copying from another array"
42 if bitstring
is not None:
43 extra
= len(bitstring
) * 8 - length
44 if extra
< 0 or extra
>= 8:
51 if r
[-extra
:] != [0] * extra
:
55 self
.numfalse
= negsum(r
)
57 self
.array
= [False] * length
58 self
.numfalse
= length
60 def __setitem__(self
, index
, val
):
62 self
.numfalse
+= self
.array
[index
]-val
63 self
.array
[index
] = val
65 def __getitem__(self
, index
):
66 return self
.array
[index
]
73 t
= reverse_lookup_table
75 r
= [ t
[tuple(booleans
[x
:x
+8])] for x
in xrange(0, len(booleans
)-s
, 8) ]
77 r
+= t
[tuple(booleans
[-s
:] + ([0] * (8-s
)))]
81 return not self
.numfalse
96 x
= Bitfield(9, 'abc')
126 x
= Bitfield(7, chr(1))
131 x
= Bitfield(9, chr(0) + chr(0x40))
135 assert Bitfield(0, '').tostring() == ''
136 assert Bitfield(1, chr(0x80)).tostring() == chr(0x80)
137 assert Bitfield(7, chr(0x02)).tostring() == chr(0x02)
138 assert Bitfield(8, chr(0xFF)).tostring() == chr(0xFF)
139 assert Bitfield(9, chr(0) + chr(0x80)).tostring() == chr(0) + chr(0x80)
141 assert x
.numfalse
== 1
143 assert x
.numfalse
== 0
145 assert x
.numfalse
== 0
146 assert x
.tostring() == chr(0x80)
150 assert x
.numfalse
== 6
151 assert x
.tostring() == chr(0x02)
154 assert x
.tostring() == chr(1)
157 assert x
.numfalse
== 8
158 assert x
.tostring() == chr(0) + chr(0x80)
159 x
= Bitfield(8, chr(0xC4))
161 assert x
.numfalse
== 5
162 assert x
.tostring() == chr(0xC4)