-
Notifications
You must be signed in to change notification settings - Fork 8
/
bitstring.py
4215 lines (3644 loc) · 161 KB
/
bitstring.py
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# cython: profile=True
"""
This package defines classes that simplify bit-wise creation, manipulation and
interpretation of data.
Classes:
Bits -- An immutable container for binary data.
BitArray -- A mutable container for binary data.
ConstBitStream -- An immutable container with streaming methods.
BitStream -- A mutable container with streaming methods.
Bits (base class)
/ \
+ mutating methods / \ + streaming methods
/ \
BitArray ConstBitStream
\ /
\ /
\ /
BitStream
Functions:
pack -- Create a BitStream from a format string.
Exceptions:
Error -- Module exception base class.
CreationError -- Error during creation.
InterpretError -- Inappropriate interpretation of binary data.
ByteAlignError -- Whole byte position or length needed.
ReadError -- Reading or peeking past the end of a bitstring.
http://python-bitstring.googlecode.com
"""
__licence__ = """
The MIT License
Copyright (c) 2006-2012 Scott Griffiths ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
__version__ = "3.0.2"
__author__ = "Scott Griffiths"
import numbers
import copy
import sys
import re
import binascii
import mmap
import os
import struct
import operator
import collections
byteorder = sys.byteorder
bytealigned = False
"""Determines whether a number of methods default to working only on byte boundaries."""
# Maximum number of digits to use in __str__ and __repr__.
MAX_CHARS = 250
# Maximum size of caches used for speed optimisations.
CACHE_SIZE = 1000
class Error(Exception):
"""Base class for errors in the bitstring module."""
def __init__(self, *params):
self.msg = params[0] if params else ''
self.params = params[1:]
def __str__(self):
if self.params:
return self.msg.format(*self.params)
return self.msg
class ReadError(Error, IndexError):
"""Reading or peeking past the end of a bitstring."""
def __init__(self, *params):
Error.__init__(self, *params)
class InterpretError(Error, ValueError):
"""Inappropriate interpretation of binary data."""
def __init__(self, *params):
Error.__init__(self, *params)
class ByteAlignError(Error):
"""Whole-byte position or length needed."""
def __init__(self, *params):
Error.__init__(self, *params)
class CreationError(Error, ValueError):
"""Inappropriate argument during bitstring creation."""
def __init__(self, *params):
Error.__init__(self, *params)
class ConstByteStore(object):
"""Stores raw bytes together with a bit offset and length.
Used internally - not part of public interface.
"""
__slots__ = ('offset', '_rawarray', 'bitlength')
def __init__(self, data, bitlength=None, offset=None):
"""data is either a bytearray or a MmapByteArray"""
self._rawarray = data
if offset is None:
offset = 0
if bitlength is None:
bitlength = 8 * len(data) - offset
self.offset = offset
self.bitlength = bitlength
def getbit(self, pos):
assert 0 <= pos < self.bitlength
byte, bit = divmod(self.offset + pos, 8)
return bool(self._rawarray[byte] & (128 >> bit))
def getbyte(self, pos):
"""Direct access to byte data."""
return self._rawarray[pos]
def getbyteslice(self, start, end):
"""Direct access to byte data."""
c = self._rawarray[start:end]
return c
@property
def bytelength(self):
if not self.bitlength:
return 0
sb = self.offset // 8
eb = (self.offset + self.bitlength - 1) // 8
return eb - sb + 1
def __copy__(self):
return ByteStore(self._rawarray[:], self.bitlength, self.offset)
def _appendstore(self, store):
"""Join another store on to the end of this one."""
if not store.bitlength:
return
# Set new array offset to the number of bits in the final byte of current array.
store = offsetcopy(store, (self.offset + self.bitlength) % 8)
if store.offset:
# first do the byte with the join.
joinval = (self._rawarray.pop() & (255 ^ (255 >> store.offset)) |
(store.getbyte(0) & (255 >> store.offset)))
self._rawarray.append(joinval)
self._rawarray.extend(store._rawarray[1:])
else:
self._rawarray.extend(store._rawarray)
self.bitlength += store.bitlength
@property
def byteoffset(self):
return self.offset // 8
@property
def rawbytes(self):
return self._rawarray
class ByteStore(ConstByteStore):
"""Adding mutating methods to ConstByteStore
Used internally - not part of public interface.
"""
__slots__ = ()
def setbit(self, pos):
assert 0 <= pos < self.bitlength
byte, bit = divmod(self.offset + pos, 8)
self._rawarray[byte] |= (128 >> bit)
def unsetbit(self, pos):
assert 0 <= pos < self.bitlength
byte, bit = divmod(self.offset + pos, 8)
self._rawarray[byte] &= ~(128 >> bit)
def invertbit(self, pos):
assert 0 <= pos < self.bitlength
byte, bit = divmod(self.offset + pos, 8)
self._rawarray[byte] ^= (128 >> bit)
def setbyte(self, pos, value):
self._rawarray[pos + self.byteoffset] = value
def setbyteslice(self, start, end, value):
self._rawarray[start + self.byteoffset:end + self.byteoffset] = value
def appendstore(self, store):
"""Join another store on to the end of this one."""
self._appendstore(store)
def prependstore(self, store):
"""Join another store on to the start of this one."""
if not store.bitlength:
return
# Set the offset of copy of store so that it's final byte
# ends in a position that matches the offset of self,
# then join self on to the end of it.
store = offsetcopy(store, (self.offset - store.bitlength) % 8)
assert (store.offset + store.bitlength) % 8 == self.offset
if self.offset:
# first do the byte with the join.
store.setbyte(-1, (store.getbyte(-1) & (255 ^ (255 >> self.offset)) |\
(self._rawarray[0] & (255 >> self.offset))))
store._rawarray.extend(self._rawarray[1: self.bytelength])
else:
store._rawarray.extend(self._rawarray[0: self.bytelength])
self._rawarray = store._rawarray
self.offset = store.offset
self.bitlength += store.bitlength
def offsetcopy(s, newoffset):
"""Return a copy of a ByteStore with the newoffset.
Not part of public interface.
"""
assert 0 <= newoffset < 8
if not s.bitlength:
return copy.copy(s)
else:
if newoffset == s.offset % 8:
return ByteStore(s.getbyteslice(0, s.bytelength), s.bitlength, newoffset)
newdata = []
d = s._rawarray
assert newoffset != s.offset % 8
if newoffset < s.offset % 8:
# We need to shift everything left
shiftleft = s.offset % 8 - newoffset
# First deal with everything except for the final byte
for x in range(s.byteoffset, s.byteoffset + s.bytelength - 1):
newdata.append(((d[x] << shiftleft) & 0xff) +\
(d[x + 1] >> (8 - shiftleft)))
bits_in_last_byte = (s.offset + s.bitlength) % 8
if not bits_in_last_byte:
bits_in_last_byte = 8
if bits_in_last_byte > shiftleft:
newdata.append((d[s.byteoffset + s.bytelength - 1] << shiftleft) & 0xff)
else: # newoffset > s._offset % 8
shiftright = newoffset - s.offset % 8
newdata.append(s.getbyte(0) >> shiftright)
for x in range(1, s.bytelength):
newdata.append(((d[x - 1] << (8 - shiftright)) & 0xff) +\
(d[x] >> shiftright))
bits_in_last_byte = (s.offset + s.bitlength) % 8
if not bits_in_last_byte:
bits_in_last_byte = 8
if bits_in_last_byte + shiftright > 8:
newdata.append((d[s.byteoffset + s.bytelength - 1] << (8 - shiftright)) & 0xff)
new_s = ByteStore(bytearray(newdata), s.bitlength, newoffset)
assert new_s.offset == newoffset
return new_s
def equal(a, b):
"""Return True if ByteStores a == b.
Not part of public interface.
"""
# We want to return False for inequality as soon as possible, which
# means we get lots of special cases.
# First the easy one - compare lengths:
a_bitlength = a.bitlength
b_bitlength = b.bitlength
if a_bitlength != b_bitlength:
return False
if not a_bitlength:
assert b_bitlength == 0
return True
# Make 'a' the one with the smaller offset
if (a.offset % 8) > (b.offset % 8):
a, b = b, a
# and create some aliases
a_bitoff = a.offset % 8
b_bitoff = b.offset % 8
a_byteoffset = a.byteoffset
b_byteoffset = b.byteoffset
a_bytelength = a.bytelength
b_bytelength = b.bytelength
da = a._rawarray
db = b._rawarray
# If they are pointing to the same data, they must be equal
if da is db and a.offset == b.offset:
return True
if a_bitoff == b_bitoff:
bits_spare_in_last_byte = 8 - (a_bitoff + a_bitlength) % 8
if bits_spare_in_last_byte == 8:
bits_spare_in_last_byte = 0
# Special case for a, b contained in a single byte
if a_bytelength == 1:
a_val = ((da[a_byteoffset] << a_bitoff) & 0xff) >> (8 - a_bitlength)
b_val = ((db[b_byteoffset] << b_bitoff) & 0xff) >> (8 - b_bitlength)
return a_val == b_val
# Otherwise check first byte
if da[a_byteoffset] & (0xff >> a_bitoff) != db[b_byteoffset] & (0xff >> b_bitoff):
return False
# then everything up to the last
b_a_offset = b_byteoffset - a_byteoffset
for x in range(1 + a_byteoffset, a_byteoffset + a_bytelength - 1):
if da[x] != db[b_a_offset + x]:
return False
# and finally the last byte
return (da[a_byteoffset + a_bytelength - 1] >> bits_spare_in_last_byte ==
db[b_byteoffset + b_bytelength - 1] >> bits_spare_in_last_byte)
assert a_bitoff != b_bitoff
# This is how much we need to shift a to the right to compare with b:
shift = b_bitoff - a_bitoff
# Special case for b only one byte long
if b_bytelength == 1:
assert a_bytelength == 1
a_val = ((da[a_byteoffset] << a_bitoff) & 0xff) >> (8 - a_bitlength)
b_val = ((db[b_byteoffset] << b_bitoff) & 0xff) >> (8 - b_bitlength)
return a_val == b_val
# Special case for a only one byte long
if a_bytelength == 1:
assert b_bytelength == 2
a_val = ((da[a_byteoffset] << a_bitoff) & 0xff) >> (8 - a_bitlength)
b_val = ((db[b_byteoffset] << 8) + db[b_byteoffset + 1]) << b_bitoff
b_val &= 0xffff
b_val >>= 16 - b_bitlength
return a_val == b_val
# Compare first byte of b with bits from first byte of a
if (da[a_byteoffset] & (0xff >> a_bitoff)) >> shift != db[b_byteoffset] & (0xff >> b_bitoff):
return False
# Now compare every full byte of b with bits from 2 bytes of a
for x in range(1, b_bytelength - 1):
# Construct byte from 2 bytes in a to compare to byte in b
b_val = db[b_byteoffset + x]
a_val = ((da[a_byteoffset + x - 1] << 8) + da[a_byteoffset + x]) >> shift
a_val &= 0xff
if a_val != b_val:
return False
# Now check bits in final byte of b
final_b_bits = (b.offset + b_bitlength) % 8
if not final_b_bits:
final_b_bits = 8
b_val = db[b_byteoffset + b_bytelength - 1] >> (8 - final_b_bits)
final_a_bits = (a.offset + a_bitlength) % 8
if not final_a_bits:
final_a_bits = 8
if b.bytelength > a_bytelength:
assert b_bytelength == a_bytelength + 1
a_val = da[a_byteoffset + a_bytelength - 1] >> (8 - final_a_bits)
a_val &= 0xff >> (8 - final_b_bits)
return a_val == b_val
assert a_bytelength == b_bytelength
a_val = da[a_byteoffset + a_bytelength - 2] << 8
a_val += da[a_byteoffset + a_bytelength - 1]
a_val >>= (8 - final_a_bits)
a_val &= 0xff >> (8 - final_b_bits)
return a_val == b_val
class MmapByteArray(object):
"""Looks like a bytearray, but from an mmap.
Not part of public interface.
"""
__slots__ = ('filemap', 'filelength', 'source', 'byteoffset', 'bytelength')
def __init__(self, source, bytelength=None, byteoffset=None):
self.source = source
source.seek(0, os.SEEK_END)
self.filelength = source.tell()
if byteoffset is None:
byteoffset = 0
if bytelength is None:
bytelength = self.filelength - byteoffset
self.byteoffset = byteoffset
self.bytelength = bytelength
self.filemap = mmap.mmap(source.fileno(), 0, access=mmap.ACCESS_READ)
def __getitem__(self, key):
try:
start = key.start
stop = key.stop
except AttributeError:
try:
assert 0 <= key < self.bytelength
return ord(self.filemap[key + self.byteoffset])
except TypeError:
# for Python 3
return self.filemap[key + self.byteoffset]
else:
if start is None:
start = 0
if stop is None:
stop = self.bytelength
assert key.step is None
assert 0 <= start < self.bytelength
assert 0 <= stop <= self.bytelength
s = slice(start + self.byteoffset, stop + self.byteoffset)
return bytearray(self.filemap.__getitem__(s))
def __len__(self):
return self.bytelength
# This creates a dictionary for every possible byte with the value being
# the key with its bits reversed.
BYTE_REVERSAL_DICT = dict()
# For Python 2.x/ 3.x coexistence
# Yes this is very very hacky.
try:
xrange
for i in range(256):
BYTE_REVERSAL_DICT[i] = chr(int("{0:08b}".format(i)[::-1], 2))
except NameError:
for i in range(256):
BYTE_REVERSAL_DICT[i] = bytes([int("{0:08b}".format(i)[::-1], 2)])
from io import IOBase as file
xrange = range
basestring = str
# Python 2.x octals start with '0', in Python 3 it's '0o'
LEADING_OCT_CHARS = len(oct(1)) - 1
def tidy_input_string(s):
"""Return string made lowercase and with all whitespace removed."""
s = ''.join(s.split()).lower()
return s
INIT_NAMES = ('uint', 'int', 'ue', 'se', 'sie', 'uie', 'hex', 'oct', 'bin', 'bits',
'uintbe', 'intbe', 'uintle', 'intle', 'uintne', 'intne',
'float', 'floatbe', 'floatle', 'floatne', 'bytes', 'bool')
TOKEN_RE = re.compile(r'(?P<name>' + '|'.join(INIT_NAMES) +
r')((:(?P<len>[^=]+)))?(=(?P<value>.*))?$', re.IGNORECASE)
DEFAULT_UINT = re.compile(r'(?P<len>[^=]+)?(=(?P<value>.*))?$', re.IGNORECASE)
MULTIPLICATIVE_RE = re.compile(r'(?P<factor>.*)\*(?P<token>.+)')
# Hex, oct or binary literals
LITERAL_RE = re.compile(r'(?P<name>0(x|o|b))(?P<value>.+)', re.IGNORECASE)
# An endianness indicator followed by one or more struct.pack codes
STRUCT_PACK_RE = re.compile(r'(?P<endian><|>|@)?(?P<fmt>(?:\d*[bBhHlLqQfd])+)$')
# A number followed by a single character struct.pack code
STRUCT_SPLIT_RE = re.compile(r'\d*[bBhHlLqQfd]')
# These replicate the struct.pack codes
# Big-endian
REPLACEMENTS_BE = {'b': 'intbe:8', 'B': 'uintbe:8',
'h': 'intbe:16', 'H': 'uintbe:16',
'l': 'intbe:32', 'L': 'uintbe:32',
'q': 'intbe:64', 'Q': 'uintbe:64',
'f': 'floatbe:32', 'd': 'floatbe:64'}
# Little-endian
REPLACEMENTS_LE = {'b': 'intle:8', 'B': 'uintle:8',
'h': 'intle:16', 'H': 'uintle:16',
'l': 'intle:32', 'L': 'uintle:32',
'q': 'intle:64', 'Q': 'uintle:64',
'f': 'floatle:32', 'd': 'floatle:64'}
# Size in bytes of all the pack codes.
PACK_CODE_SIZE = {'b': 1, 'B': 1, 'h': 2, 'H': 2, 'l': 4, 'L': 4,
'q': 8, 'Q': 8, 'f': 4, 'd': 8}
def structparser(token):
"""Parse struct-like format string token into sub-token list."""
m = STRUCT_PACK_RE.match(token)
if not m:
return [token]
else:
endian = m.group('endian')
if endian is None:
return [token]
# Split the format string into a list of 'q', '4h' etc.
formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt'))
# Now deal with mulitiplicative factors, 4h -> hhhh etc.
fmt = ''.join([f[-1] * int(f[:-1]) if len(f) != 1 else
f for f in formatlist])
if endian == '@':
# Native endianness
if byteorder == 'little':
endian = '<'
else:
assert byteorder == 'big'
endian = '>'
if endian == '<':
tokens = [REPLACEMENTS_LE[c] for c in fmt]
else:
assert endian == '>'
tokens = [REPLACEMENTS_BE[c] for c in fmt]
return tokens
def tokenparser(fmt, keys=None, token_cache={}):
"""Divide the format string into tokens and parse them.
Return stretchy token and list of [initialiser, length, value]
initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc.
length is None if not known, as is value.
If the token is in the keyword dictionary (keys) then it counts as a
special case and isn't messed with.
tokens must be of the form: [factor*][initialiser][:][length][=value]
"""
try:
return token_cache[(fmt, keys)]
except KeyError:
token_key = (fmt, keys)
# Very inefficient expanding of brackets.
fmt = expand_brackets(fmt)
# Split tokens by ',' and remove whitespace
# The meta_tokens can either be ordinary single tokens or multiple
# struct-format token strings.
meta_tokens = (''.join(f.split()) for f in fmt.split(','))
return_values = []
stretchy_token = False
for meta_token in meta_tokens:
# See if it has a multiplicative factor
m = MULTIPLICATIVE_RE.match(meta_token)
if not m:
factor = 1
else:
factor = int(m.group('factor'))
meta_token = m.group('token')
# See if it's a struct-like format
tokens = structparser(meta_token)
ret_vals = []
for token in tokens:
if keys and token in keys:
# Don't bother parsing it, it's a keyword argument
ret_vals.append([token, None, None])
continue
value = length = None
if token == '':
continue
# Match literal tokens of the form 0x... 0o... and 0b...
m = LITERAL_RE.match(token)
if m:
name = m.group('name')
value = m.group('value')
ret_vals.append([name, length, value])
continue
# Match everything else:
m1 = TOKEN_RE.match(token)
if not m1:
# and if you don't specify a 'name' then the default is 'uint':
m2 = DEFAULT_UINT.match(token)
if not m2:
raise ValueError("Don't understand token '{0}'.".format(token))
if m1:
name = m1.group('name')
length = m1.group('len')
if m1.group('value'):
value = m1.group('value')
else:
assert m2
name = 'uint'
length = m2.group('len')
if m2.group('value'):
value = m2.group('value')
if name == 'bool':
if length is not None:
raise ValueError("You can't specify a length with bool tokens - they are always one bit.")
length = 1
if length is None and name not in ('se', 'ue', 'sie', 'uie'):
stretchy_token = True
if length is not None:
# Try converting length to int, otherwise check it's a key.
try:
length = int(length)
if length < 0:
raise Error
# For the 'bytes' token convert length to bits.
if name == 'bytes':
length *= 8
except Error:
raise ValueError("Can't read a token with a negative length.")
except ValueError:
if not keys or length not in keys:
raise ValueError("Don't understand length '{0}' of token.".format(length))
ret_vals.append([name, length, value])
# This multiplies by the multiplicative factor, but this means that
# we can't allow keyword values as multipliers (e.g. n*uint:8).
# The only way to do this would be to return the factor in some fashion
# (we can't use the key's value here as it would mean that we couldn't
# sensibly continue to cache the function's results. (TODO).
return_values.extend(ret_vals * factor)
return_values = [tuple(x) for x in return_values]
if len(token_cache) < CACHE_SIZE:
token_cache[token_key] = stretchy_token, return_values
return stretchy_token, return_values
# Looks for first number*(
BRACKET_RE = re.compile(r'(?P<factor>\d+)\*\(')
def expand_brackets(s):
"""Remove whitespace and expand all brackets."""
s = ''.join(s.split())
while True:
start = s.find('(')
if start == -1:
break
count = 1 # Number of hanging open brackets
p = start + 1
while p < len(s):
if s[p] == '(':
count += 1
if s[p] == ')':
count -= 1
if not count:
break
p += 1
if count:
raise ValueError("Unbalanced parenthesis in '{0}'.".format(s))
if start == 0 or s[start - 1] != '*':
s = s[0:start] + s[start + 1:p] + s[p + 1:]
else:
m = BRACKET_RE.search(s)
if m:
factor = int(m.group('factor'))
matchstart = m.start('factor')
s = s[0:matchstart] + (factor - 1) * (s[start + 1:p] + ',') + s[start + 1:p] + s[p + 1:]
else:
raise ValueError("Failed to parse '{0}'.".format(s))
return s
# This byte to bitstring lookup really speeds things up.
BYTE_TO_BITS = ['{0:08b}'.format(i) for i in xrange(256)]
# And this converts a single octal digit to 3 bits.
OCT_TO_BITS = ['{0:03b}'.format(i) for i in xrange(8)]
# A dictionary of number of 1 bits contained in binary representation of any byte
BIT_COUNT = dict(zip(xrange(256), [bin(i).count('1') for i in xrange(256)]))
class Bits(object):
"""A container holding an immutable sequence of bits.
For a mutable container use the BitArray class instead.
Methods:
all() -- Check if all specified bits are set to 1 or 0.
any() -- Check if any of specified bits are set to 1 or 0.
count() -- Count the number of bits set to 1 or 0.
cut() -- Create generator of constant sized chunks.
endswith() -- Return whether the bitstring ends with a sub-string.
find() -- Find a sub-bitstring in the current bitstring.
findall() -- Find all occurrences of a sub-bitstring in the current bitstring.
join() -- Join bitstrings together using current bitstring.
rfind() -- Seek backwards to find a sub-bitstring.
split() -- Create generator of chunks split by a delimiter.
startswith() -- Return whether the bitstring starts with a sub-bitstring.
tobytes() -- Return bitstring as bytes, padding if needed.
tofile() -- Write bitstring to file, padding if needed.
unpack() -- Interpret bits using format string.
Special methods:
Also available are the operators [], ==, !=, +, *, ~, <<, >>, &, |, ^.
Properties:
bin -- The bitstring as a binary string.
bool -- For single bit bitstrings, interpret as True or False.
bytes -- The bitstring as a bytes object.
float -- Interpret as a floating point number.
floatbe -- Interpret as a big-endian floating point number.
floatle -- Interpret as a little-endian floating point number.
floatne -- Interpret as a native-endian floating point number.
hex -- The bitstring as a hexadecimal string.
int -- Interpret as a two's complement signed integer.
intbe -- Interpret as a big-endian signed integer.
intle -- Interpret as a little-endian signed integer.
intne -- Interpret as a native-endian signed integer.
len -- Length of the bitstring in bits.
oct -- The bitstring as an octal string.
se -- Interpret as a signed exponential-Golomb code.
ue -- Interpret as an unsigned exponential-Golomb code.
sie -- Interpret as a signed interleaved exponential-Golomb code.
uie -- Interpret as an unsigned interleaved exponential-Golomb code.
uint -- Interpret as a two's complement unsigned integer.
uintbe -- Interpret as a big-endian unsigned integer.
uintle -- Interpret as a little-endian unsigned integer.
uintne -- Interpret as a native-endian unsigned integer.
"""
__slots__ = ('_datastore')
def __init__(self, auto=None, length=None, offset=None, **kwargs):
"""Either specify an 'auto' initialiser:
auto -- a string of comma separated tokens, an integer, a file object,
a bytearray, a boolean iterable or another bitstring.
Or initialise via **kwargs with one (and only one) of:
bytes -- raw data as a string, for example read from a binary file.
bin -- binary string representation, e.g. '0b001010'.
hex -- hexadecimal string representation, e.g. '0x2ef'
oct -- octal string representation, e.g. '0o777'.
uint -- an unsigned integer.
int -- a signed integer.
float -- a floating point number.
uintbe -- an unsigned big-endian whole byte integer.
intbe -- a signed big-endian whole byte integer.
floatbe - a big-endian floating point number.
uintle -- an unsigned little-endian whole byte integer.
intle -- a signed little-endian whole byte integer.
floatle -- a little-endian floating point number.
uintne -- an unsigned native-endian whole byte integer.
intne -- a signed native-endian whole byte integer.
floatne -- a native-endian floating point number.
se -- a signed exponential-Golomb code.
ue -- an unsigned exponential-Golomb code.
sie -- a signed interleaved exponential-Golomb code.
uie -- an unsigned interleaved exponential-Golomb code.
bool -- a boolean (True or False).
filename -- a file which will be opened in binary read-only mode.
Other keyword arguments:
length -- length of the bitstring in bits, if needed and appropriate.
It must be supplied for all integer and float initialisers.
offset -- bit offset to the data. These offset bits are
ignored and this is mainly intended for use when
initialising using 'bytes' or 'filename'.
"""
pass
def __new__(cls, auto=None, length=None, offset=None, _cache={}, **kwargs):
# For instances auto-initialised with a string we intern the
# instance for re-use.
try:
if isinstance(auto, basestring):
try:
return _cache[auto]
except KeyError:
x = object.__new__(Bits)
try:
_, tokens = tokenparser(auto)
except ValueError as e:
raise CreationError(*e.args)
x._datastore = ConstByteStore(bytearray(0), 0, 0)
for token in tokens:
x._datastore._appendstore(Bits._init_with_token(*token)._datastore)
assert x._assertsanity()
if len(_cache) < CACHE_SIZE:
_cache[auto] = x
return x
if isinstance(auto, Bits):
return auto
except TypeError:
pass
x = super(Bits, cls).__new__(cls)
x._initialise(auto, length, offset, **kwargs)
return x
def _initialise(self, auto, length, offset, **kwargs):
if length is not None and length < 0:
raise CreationError("bitstring length cannot be negative.")
if offset is not None and offset < 0:
raise CreationError("offset must be >= 0.")
if auto is not None:
self._initialise_from_auto(auto, length, offset)
return
if not kwargs:
# No initialisers, so initialise with nothing or zero bits
if length is not None and length != 0:
data = bytearray((length + 7) // 8)
self._setbytes_unsafe(data, length, 0)
return
self._setbytes_unsafe(bytearray(0), 0, 0)
return
k, v = kwargs.popitem()
try:
init_without_length_or_offset[k](self, v)
if length is not None or offset is not None:
raise CreationError("Cannot use length or offset with this initialiser.")
except KeyError:
try:
init_with_length_only[k](self, v, length)
if offset is not None:
raise CreationError("Cannot use offset with this initialiser.")
except KeyError:
if offset is None:
offset = 0
try:
init_with_length_and_offset[k](self, v, length, offset)
except KeyError:
raise CreationError("Unrecognised keyword '{0}' used to initialise.", k)
def _initialise_from_auto(self, auto, length, offset):
if offset is None:
offset = 0
self._setauto(auto, length, offset)
return
def __copy__(self):
"""Return a new copy of the Bits for the copy module."""
# Note that if you want a new copy (different ID), use _copy instead.
# The copy can return self as it's immutable.
return self
def __lt__(self, other):
raise TypeError("unorderable type: {0}".format(type(self).__name__))
def __gt__(self, other):
raise TypeError("unorderable type: {0}".format(type(self).__name__))
def __le__(self, other):
raise TypeError("unorderable type: {0}".format(type(self).__name__))
def __ge__(self, other):
raise TypeError("unorderable type: {0}".format(type(self).__name__))
def __add__(self, bs):
"""Concatenate bitstrings and return new bitstring.
bs -- the bitstring to append.
"""
bs = Bits(bs)
if bs.len <= self.len:
s = self._copy()
s._append(bs)
else:
s = self.__class__(bs)
s._prepend(self)
return s
def __radd__(self, bs):
"""Append current bitstring to bs and return new bitstring.
bs -- the string for the 'auto' initialiser that will be appended to.
"""
bs = self._converttobitstring(bs)
return bs.__add__(self)
def __getitem__(self, key):
"""Return a new bitstring representing a slice of the current bitstring.
Indices are in units of the step parameter (default 1 bit).
Stepping is used to specify the number of bits in each item.
>>> print BitArray('0b00110')[1:4]
'0b011'
>>> print BitArray('0x00112233')[1:3:8]
'0x1122'
"""
length = self.len
try:
step = key.step if key.step is not None else 1
except AttributeError:
# single element
if key < 0:
key += length
if not 0 <= key < length:
raise IndexError("Slice index out of range.")
# Single bit, return True or False
return self._datastore.getbit(key)
else:
if step != 1:
# convert to binary string and use string slicing
bs = self.__class__()
bs._setbin_unsafe(self._getbin().__getitem__(key))
return bs
start, stop = 0, length
if key.start is not None:
start = key.start
if key.start < 0:
start += stop
if key.stop is not None:
stop = key.stop
if key.stop < 0:
stop += length
start = max(start, 0)
stop = min(stop, length)
if start < stop:
return self._slice(start, stop)
else:
return self.__class__()
def __len__(self):
"""Return the length of the bitstring in bits."""
return self._getlength()
def __str__(self):
"""Return approximate string representation of bitstring for printing.
Short strings will be given wholly in hexadecimal or binary. Longer
strings may be part hexadecimal and part binary. Very long strings will
be truncated with '...'.
"""
length = self.len
if not length:
return ''
if length > MAX_CHARS * 4:
# Too long for hex. Truncate...
return ''.join(('0x', self._readhex(MAX_CHARS * 4, 0), '...'))
# If it's quite short and we can't do hex then use bin
if length < 32 and length % 4 != 0:
return '0b' + self.bin
# If we can use hex then do so
if not length % 4:
return '0x' + self.hex
# Otherwise first we do as much as we can in hex
# then add on 1, 2 or 3 bits on at the end
bits_at_end = length % 4
return ''.join(('0x', self._readhex(length - bits_at_end, 0),
', ', '0b',
self._readbin(bits_at_end, length - bits_at_end)))
def __repr__(self):
"""Return representation that could be used to recreate the bitstring.
If the returned string is too long it will be truncated. See __str__().
"""
length = self.len
if isinstance(self._datastore._rawarray, MmapByteArray):
offsetstring = ''
if self._datastore.byteoffset or self._offset:
offsetstring = ", offset=%d" % (self._datastore._rawarray.byteoffset * 8 + self._offset)
lengthstring = ", length=%d" % length
return "{0}(filename='{1}'{2}{3})".format(self.__class__.__name__,
self._datastore._rawarray.source.name, lengthstring, offsetstring)
else:
s = self.__str__()
lengthstring = ''
if s.endswith('...'):
lengthstring = " # length={0}".format(length)
return "{0}('{1}'){2}".format(self.__class__.__name__, s, lengthstring)
def __eq__(self, bs):
"""Return True if two bitstrings have the same binary representation.
>>> BitArray('0b1110') == '0xe'
True
"""
try:
bs = Bits(bs)
except TypeError:
return False
return equal(self._datastore, bs._datastore)
def __ne__(self, bs):
"""Return False if two bitstrings have the same binary representation.
>>> BitArray('0b111') == '0x7'
False
"""
return not self.__eq__(bs)