-
Notifications
You must be signed in to change notification settings - Fork 67
/
bits.py
1786 lines (1484 loc) · 74.8 KB
/
bits.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
from __future__ import annotations
import numbers
import pathlib
import sys
import mmap
import struct
import array
import io
from collections import abc
import functools
from typing import Tuple, Union, List, Iterable, Any, Optional, BinaryIO, TextIO, overload, Iterator, Type, TypeVar
import bitarray
import bitarray.util
import bitstring
from bitstring.bitstore import BitStore
from bitstring import bitstore_helpers, utils
from bitstring.dtypes import Dtype, dtype_register
from bitstring.fp8 import p4binary_fmt, p3binary_fmt
from bitstring.mxfp import e3m2mxfp_fmt, e2m3mxfp_fmt, e2m1mxfp_fmt, e4m3mxfp_saturate_fmt, e5m2mxfp_saturate_fmt
from bitstring.bitstring_options import Colour
# Things that can be converted to Bits when a Bits type is needed
BitsType = Union['Bits', str, Iterable[Any], bool, BinaryIO, bytearray, bytes, memoryview, bitarray.bitarray]
TBits = TypeVar("TBits", bound='Bits')
# Maximum number of digits to use in __str__ and __repr__.
MAX_CHARS: int = 250
class Bits:
"""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.
copy() - Return a copy of the bitstring.
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.
fromstring() -- Create a bitstring from a formatted string.
join() -- Join bitstrings together using current bitstring.
pp() -- Pretty print the 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.
tobitarray() -- Return bitstring as a bitarray from the bitarray package.
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:
[GENERATED_PROPERTY_DESCRIPTIONS]
len -- Length of the bitstring in bits.
"""
__slots__ = ('_bitstore', '_filename')
def __init__(self, auto: Optional[Union[BitsType, int]] = None, /, length: Optional[int] = None,
offset: Optional[int] = None, **kwargs) -> None:
"""Either specify an 'auto' initialiser:
A string of comma separated tokens, an integer, a file object,
a bytearray, a boolean iterable, an array or another bitstring.
Or initialise via **kwargs with one (and only one) of:
bin -- binary string representation, e.g. '0b001010'.
hex -- hexadecimal string representation, e.g. '0x2ef'
oct -- octal string representation, e.g. '0o777'.
bytes -- raw data as a bytes object, for example read from a binary file.
int -- a signed integer.
uint -- an unsigned integer.
float / floatbe -- a big-endian floating point number.
bool -- a boolean (True or False).
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.
floatle -- a little-endian floating point number.
floatne -- a native-endian floating point number.
bfloat / bfloatbe - a big-endian bfloat format 16-bit floating point number.
bfloatle -- a little-endian bfloat format 16-bit floating point number.
bfloatne -- a native-endian bfloat format 16-bit floating point number.
intbe -- a signed big-endian whole byte integer.
intle -- a signed little-endian whole byte integer.
intne -- a signed native-endian whole byte integer.
uintbe -- an unsigned big-endian whole byte integer.
uintle -- an unsigned little-endian whole byte integer.
uintne -- an unsigned native-endian whole byte integer.
filename -- the path of 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'.
"""
self._bitstore.immutable = True
def __new__(cls: Type[TBits], auto: Optional[Union[BitsType, int]] = None, /, length: Optional[int] = None,
offset: Optional[int] = None, pos: Optional[int] = None, **kwargs) -> TBits:
x = super().__new__(cls)
if auto is None and not kwargs:
# No initialiser so fill with zero bits up to length
if length is not None:
x._bitstore = BitStore(length)
x._bitstore.setall(0)
else:
x._bitstore = BitStore()
return x
x._initialise(auto, length, offset, **kwargs)
return x
@classmethod
def _create_from_bitstype(cls: Type[TBits], auto: BitsType, /) -> TBits:
if isinstance(auto, cls):
return auto
b = super().__new__(cls)
b._setauto_no_length_or_offset(auto)
return b
def _initialise(self, auto: Any, /, length: Optional[int], offset: Optional[int], **kwargs) -> None:
if auto is not None:
if isinstance(auto, numbers.Integral):
# Initialise with s zero bits.
if auto < 0:
raise bitstring.CreationError(f"Can't create bitstring of negative length {auto}.")
self._bitstore = BitStore(int(auto))
self._bitstore.setall(0)
return
self._setauto(auto, length, offset)
return
k, v = kwargs.popitem()
if k == 'bytes':
# Special case for bytes as we want to allow offsets and lengths to work only on creation.
self._setbytes_with_truncation(v, length, offset)
return
if k == 'filename':
self._setfile(v, length, offset)
return
if k == 'bitarray':
self._setbitarray(v, length, offset)
return
if k == 'auto':
raise bitstring.CreationError(
f"The 'auto' parameter should not be given explicitly - just use the first positional argument. "
f"Instead of '{self.__class__.__name__}(auto=x)' use '{self.__class__.__name__}(x)'.")
if offset is not None:
raise bitstring.CreationError("offset cannot be used when initialising with '{k}'.")
try:
Dtype(k, length).set_fn(self, v)
except ValueError as e:
raise bitstring.CreationError(e)
def __getattr__(self, attribute: str) -> Any:
# Support for arbitrary attributes like u16 or f64.
try:
d = Dtype(attribute)
except ValueError:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attribute}'.")
if d.bitlength is not None and len(self) != d.bitlength:
raise ValueError(f"bitstring length {len(self)} doesn't match length {d.bitlength} of property '{attribute}'.")
return d.get_fn(self)
def __iter__(self) -> Iterable[bool]:
return iter(self._bitstore)
def __copy__(self: TBits) -> TBits:
"""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: Any) -> bool:
# bitstrings can't really be ordered.
return NotImplemented
def __gt__(self, other: Any) -> bool:
return NotImplemented
def __le__(self, other: Any) -> bool:
return NotImplemented
def __ge__(self, other: Any) -> bool:
return NotImplemented
def __add__(self: TBits, bs: BitsType) -> TBits:
"""Concatenate bitstrings and return new bitstring.
bs -- the bitstring to append.
"""
bs = self.__class__._create_from_bitstype(bs)
s = self._copy() if len(bs) <= len(self) else bs._copy()
if len(bs) <= len(self):
s._addright(bs)
else:
s._addleft(self)
return s
def __radd__(self: TBits, bs: BitsType) -> TBits:
"""Append current bitstring to bs and return new bitstring.
bs -- An object that can be 'auto' initialised as a bitstring that will be appended to.
"""
bs = self.__class__._create_from_bitstype(bs)
return bs.__add__(self)
@overload
def __getitem__(self: TBits, key: slice, /) -> TBits:
...
@overload
def __getitem__(self, key: int, /) -> bool:
...
def __getitem__(self: TBits, key: Union[slice, int], /) -> Union[TBits, bool]:
"""Return a new bitstring representing a slice of the current bitstring.
>>> print(Bits('0b00110')[1:4])
'0b011'
"""
if isinstance(key, numbers.Integral):
return bool(self._bitstore.getindex(key))
bs = super().__new__(self.__class__)
bs._bitstore = self._bitstore.getslice_withstep(key)
return bs
def __len__(self) -> int:
"""Return the length of the bitstring in bits."""
return self._getlength()
def __bytes__(self) -> bytes:
return self.tobytes()
def __str__(self) -> str:
"""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 = len(self)
if not length:
return ''
if length > MAX_CHARS * 4:
# Too long for hex. Truncate...
return ''.join(('0x', self[0:MAX_CHARS*4]._gethex(), '...'))
# 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[0:length - bits_at_end]._gethex(),
', ', '0b', self[length - bits_at_end:]._getbin()))
def _repr(self, classname: str, length: int, pos: int):
pos_string = f', pos={pos}' if pos else ''
if hasattr(self, '_filename') and self._filename:
return f"{classname}(filename={self._filename!r}, length={length}{pos_string})"
else:
s = self.__str__()
lengthstring = ''
if s.endswith('...'):
lengthstring = f' # length={length}'
return f"{classname}('{s}'{pos_string}){lengthstring}"
def __repr__(self) -> str:
"""Return representation that could be used to recreate the bitstring.
If the returned string is too long it will be truncated. See __str__().
"""
return self._repr(self.__class__.__name__, len(self), 0)
def __eq__(self, bs: Any, /) -> bool:
"""Return True if two bitstrings have the same binary representation.
>>> BitArray('0b1110') == '0xe'
True
"""
try:
return self._bitstore == Bits._create_from_bitstype(bs)._bitstore
except TypeError:
return False
def __ne__(self, bs: Any, /) -> bool:
"""Return False if two bitstrings have the same binary representation.
>>> BitArray('0b111') == '0x7'
False
"""
return not self.__eq__(bs)
def __invert__(self: TBits) -> TBits:
"""Return bitstring with every bit inverted.
Raises Error if the bitstring is empty.
"""
if len(self) == 0:
raise bitstring.Error("Cannot invert empty bitstring.")
s = self._copy()
s._invert_all()
return s
def __lshift__(self: TBits, n: int, /) -> TBits:
"""Return bitstring with bits shifted by n to the left.
n -- the number of bits to shift. Must be >= 0.
"""
if n < 0:
raise ValueError("Cannot shift by a negative amount.")
if len(self) == 0:
raise ValueError("Cannot shift an empty bitstring.")
n = min(n, len(self))
s = self._absolute_slice(n, len(self))
s._addright(Bits(n))
return s
def __rshift__(self: TBits, n: int, /) -> TBits:
"""Return bitstring with bits shifted by n to the right.
n -- the number of bits to shift. Must be >= 0.
"""
if n < 0:
raise ValueError("Cannot shift by a negative amount.")
if len(self) == 0:
raise ValueError("Cannot shift an empty bitstring.")
if not n:
return self._copy()
s = self.__class__(length=min(n, len(self)))
n = min(n, len(self))
s._addright(self._absolute_slice(0, len(self) - n))
return s
def __mul__(self: TBits, n: int, /) -> TBits:
"""Return bitstring consisting of n concatenations of self.
Called for expression of the form 'a = b*3'.
n -- The number of concatenations. Must be >= 0.
"""
if n < 0:
raise ValueError("Cannot multiply by a negative integer.")
if not n:
return self.__class__()
s = self._copy()
s._imul(n)
return s
def __rmul__(self: TBits, n: int, /) -> TBits:
"""Return bitstring consisting of n concatenations of self.
Called for expressions of the form 'a = 3*b'.
n -- The number of concatenations. Must be >= 0.
"""
return self.__mul__(n)
def __and__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'and' between two bitstrings. Returns new bitstring.
bs -- The bitstring to '&' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
if bs is self:
return self.copy()
bs = Bits._create_from_bitstype(bs)
s = object.__new__(self.__class__)
s._bitstore = self._bitstore & bs._bitstore
return s
def __rand__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'and' between two bitstrings. Returns new bitstring.
bs -- the bitstring to '&' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
return self.__and__(bs)
def __or__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'or' between two bitstrings. Returns new bitstring.
bs -- The bitstring to '|' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
if bs is self:
return self.copy()
bs = Bits._create_from_bitstype(bs)
s = object.__new__(self.__class__)
s._bitstore = self._bitstore | bs._bitstore
return s
def __ror__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'or' between two bitstrings. Returns new bitstring.
bs -- The bitstring to '|' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
return self.__or__(bs)
def __xor__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'xor' between two bitstrings. Returns new bitstring.
bs -- The bitstring to '^' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
bs = Bits._create_from_bitstype(bs)
s = object.__new__(self.__class__)
s._bitstore = self._bitstore ^ bs._bitstore
return s
def __rxor__(self: TBits, bs: BitsType, /) -> TBits:
"""Bit-wise 'xor' between two bitstrings. Returns new bitstring.
bs -- The bitstring to '^' with.
Raises ValueError if the two bitstrings have differing lengths.
"""
return self.__xor__(bs)
def __contains__(self, bs: BitsType, /) -> bool:
"""Return whether bs is contained in the current bitstring.
bs -- The bitstring to search for.
"""
found = Bits.find(self, bs, bytealigned=False)
return bool(found)
def __hash__(self) -> int:
"""Return an integer hash of the object."""
# Only requirement is that equal bitstring should return the same hash.
# For equal bitstrings the bytes at the start/end will be the same and they will have the same length
# (need to check the length as there could be zero padding when getting the bytes). We do not check any
# bit position inside the bitstring as that does not feature in the __eq__ operation.
if len(self) <= 2000:
# Use the whole bitstring.
return hash((self.tobytes(), len(self)))
else:
# We can't in general hash the whole bitstring (it could take hours!)
# So instead take some bits from the start and end.
return hash(((self[:800] + self[-800:]).tobytes(), len(self)))
def __bool__(self) -> bool:
"""Return False if bitstring is empty, otherwise return True."""
return len(self) != 0
def _clear(self) -> None:
"""Reset the bitstring to an empty state."""
self._bitstore = BitStore()
def _setauto_no_length_or_offset(self, s: BitsType, /) -> None:
"""Set bitstring from a bitstring, file, bool, array, iterable or string."""
if isinstance(s, str):
self._bitstore = bitstore_helpers.str_to_bitstore(s)
elif isinstance(s, Bits):
self._bitstore = s._bitstore.copy()
elif isinstance(s, (bytes, bytearray, memoryview)):
self._bitstore = BitStore.frombytes(bytearray(s))
elif isinstance(s, io.BytesIO):
self._bitstore = BitStore.frombytes(s.getvalue())
elif isinstance(s, io.BufferedReader):
self._setfile(s.name)
elif isinstance(s, bitarray.bitarray):
self._bitstore = BitStore(s)
elif isinstance(s, array.array):
self._bitstore = BitStore.frombytes(s.tobytes())
elif isinstance(s, abc.Iterable):
# Evaluate each item as True or False and set bits to 1 or 0.
self._setbin_unsafe(''.join(str(int(bool(x))) for x in s))
elif isinstance(s, numbers.Integral):
raise TypeError(f"It's no longer possible to auto initialise a bitstring from an integer."
f" Use '{self.__class__.__name__}({s})' instead of just '{s}' as this makes it "
f"clearer that a bitstring of {int(s)} zero bits will be created.")
else:
raise TypeError(f"Cannot initialise bitstring from type '{type(s)}'.")
def _setauto(self, s: BitsType, length: Optional[int], offset: Optional[int], /) -> None:
"""Set bitstring from a bitstring, file, bool, array, iterable or string."""
# As s can be so many different things it's important to do the checks
# in the correct order, as some types are also other allowed types.
if offset is None and length is None:
return self._setauto_no_length_or_offset(s)
if offset is None:
offset = 0
if isinstance(s, io.BytesIO):
if length is None:
length = s.seek(0, 2) * 8 - offset
byteoffset, offset = divmod(offset, 8)
bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset
if length + byteoffset * 8 + offset > s.seek(0, 2) * 8:
raise bitstring.CreationError("BytesIO object is not long enough for specified length and offset.")
self._bitstore = BitStore.frombytes(s.getvalue()[byteoffset: byteoffset + bytelength]).getslice(
offset, offset + length)
return
if isinstance(s, io.BufferedReader):
self._setfile(s.name, length, offset)
return
if isinstance(s, (str, Bits, bytes, bytearray, memoryview, io.BytesIO, io.BufferedReader,
bitarray.bitarray, array.array, abc.Iterable)):
raise bitstring.CreationError(f"Cannot initialise bitstring from type '{type(s)}' when using explicit lengths or offsets.")
raise TypeError(f"Cannot initialise bitstring from type '{type(s)}'.")
def _setfile(self, filename: str, length: Optional[int] = None, offset: Optional[int] = None) -> None:
"""Use file as source of bits."""
with open(pathlib.Path(filename), 'rb') as source:
if offset is None:
offset = 0
m = mmap.mmap(source.fileno(), 0, access=mmap.ACCESS_READ)
if offset == 0:
self._filename = source.name
self._bitstore = BitStore.frombuffer(m, length=length)
else:
# If offset is given then always read into memory.
temp = BitStore.frombuffer(m)
if length is None:
if offset > len(temp):
raise bitstring.CreationError(f"The offset of {offset} bits is greater than the file length ({len(temp)} bits).")
self._bitstore = temp.getslice(offset, None)
else:
self._bitstore = temp.getslice(offset, offset + length)
if len(self) != length:
raise bitstring.CreationError(f"Can't use a length of {length} bits and an offset of {offset} bits as file length is only {len(temp)} bits.")
def _setbitarray(self, ba: bitarray.bitarray, length: Optional[int], offset: Optional[int]) -> None:
if offset is None:
offset = 0
if offset > len(ba):
raise bitstring.CreationError(f"Offset of {offset} too large for bitarray of length {len(ba)}.")
if length is None:
self._bitstore = BitStore(ba[offset:])
else:
if offset + length > len(ba):
raise bitstring.CreationError(
f"Offset of {offset} and length of {length} too large for bitarray of length {len(ba)}.")
self._bitstore = BitStore(ba[offset: offset + length])
def _setbits(self, bs: BitsType, length: None = None) -> None:
bs = Bits._create_from_bitstype(bs)
self._bitstore = bs._bitstore
def _setp3binary(self, f: float) -> None:
self._bitstore = bitstore_helpers.p3binary2bitstore(f)
def _setp4binary(self, f: float) -> None:
self._bitstore = bitstore_helpers.p4binary2bitstore(f)
def _sete4m3mxfp(self, f: float) -> None:
self._bitstore = bitstore_helpers.e4m3mxfp2bitstore(f)
def _sete5m2mxfp(self, f: float) -> None:
self._bitstore = bitstore_helpers.e5m2mxfp2bitstore(f)
def _sete3m2mxfp(self, f: float) -> None:
self._bitstore = bitstore_helpers.e3m2mxfp2bitstore(f)
def _sete2m3mxfp(self, f: float) -> None:
self._bitstore = bitstore_helpers.e2m3mxfp2bitstore(f)
def _sete2m1mxfp(self, f: float) -> None:
self._bitstore = bitstore_helpers.e2m1mxfp2bitstore(f)
def _sete8m0mxfp(self, f: float) -> None:
self._bitstore = bitstore_helpers.e8m0mxfp2bitstore(f)
def _setmxint(self, f: float) -> None:
self._bitstore = bitstore_helpers.mxint2bitstore(f)
def _setbytes(self, data: Union[bytearray, bytes, List], length:None = None) -> None:
"""Set the data from a bytes or bytearray object."""
self._bitstore = BitStore.frombytes(bytes(data))
def _setbytes_with_truncation(self, data: Union[bytearray, bytes], length: Optional[int] = None, offset: Optional[int] = None) -> None:
"""Set the data from a bytes or bytearray object, with optional offset and length truncations."""
if offset is None and length is None:
return self._setbytes(data)
data = bytearray(data)
if offset is None:
offset = 0
if length is None:
# Use to the end of the data
length = len(data) * 8 - offset
else:
if length + offset > len(data) * 8:
raise bitstring.CreationError(f"Not enough data present. Need {length + offset} bits, have {len(data) * 8}.")
self._bitstore = BitStore.frombytes(data).getslice_msb0(offset, offset + length)
def _getbytes(self) -> bytes:
"""Return the data as an ordinary bytes object."""
if len(self) % 8:
raise bitstring.InterpretError("Cannot interpret as bytes unambiguously - not multiple of 8 bits.")
return self._bitstore.tobytes()
_unprintable = list(range(0x00, 0x20)) # ASCII control characters
_unprintable.extend(range(0x7f, 0xff)) # DEL char + non-ASCII
def _getbytes_printable(self) -> str:
"""Return an approximation of the data as a string of printable characters."""
bytes_ = self._getbytes()
# For everything that isn't printable ASCII, use value from 'Latin Extended-A' unicode block.
string = ''.join(chr(0x100 + x) if x in Bits._unprintable else chr(x) for x in bytes_)
return string
def _setuint(self, uint: int, length: Optional[int] = None) -> None:
"""Reset the bitstring to have given unsigned int interpretation."""
# If no length given, and we've previously been given a length, use it.
if length is None and hasattr(self, 'len') and len(self) != 0:
length = len(self)
if length is None or length == 0:
raise bitstring.CreationError("A non-zero length must be specified with a uint initialiser.")
self._bitstore = bitstore_helpers.int2bitstore(uint, length, False)
def _getuint(self) -> int:
"""Return data as an unsigned int."""
if len(self) == 0:
raise bitstring.InterpretError("Cannot interpret a zero length bitstring as an integer.")
return self._bitstore.slice_to_uint()
def _setint(self, int_: int, length: Optional[int] = None) -> None:
"""Reset the bitstring to have given signed int interpretation."""
# If no length given, and we've previously been given a length, use it.
if length is None and hasattr(self, 'len') and len(self) != 0:
length = len(self)
if length is None or length == 0:
raise bitstring.CreationError("A non-zero length must be specified with an int initialiser.")
self._bitstore = bitstore_helpers.int2bitstore(int_, length, True)
def _getint(self) -> int:
"""Return data as a two's complement signed int."""
if len(self) == 0:
raise bitstring.InterpretError("Cannot interpret bitstring without a length as an integer.")
return self._bitstore.slice_to_int()
def _setuintbe(self, uintbe: int, length: Optional[int] = None) -> None:
"""Set the bitstring to a big-endian unsigned int interpretation."""
if length is None and hasattr(self, 'len') and len(self) != 0:
length = len(self)
if length is None or length == 0:
raise bitstring.CreationError("A non-zero length must be specified with a uintbe initialiser.")
self._bitstore = bitstore_helpers.int2bitstore(uintbe, length, False)
def _getuintbe(self) -> int:
"""Return data as a big-endian two's complement unsigned int."""
if len(self) % 8:
raise bitstring.InterpretError(f"Big-endian integers must be whole-byte. Length = {len(self)} bits.")
return self._getuint()
def _setintbe(self, intbe: int, length: Optional[int] = None) -> None:
"""Set bitstring to a big-endian signed int interpretation."""
if length is None and hasattr(self, 'len') and len(self) != 0:
length = len(self)
if length is None or length == 0:
raise bitstring.CreationError("A non-zero length must be specified with a intbe initialiser.")
self._bitstore = bitstore_helpers.int2bitstore(intbe, length, True)
def _getintbe(self) -> int:
"""Return data as a big-endian two's complement signed int."""
if len(self) % 8:
raise bitstring.InterpretError(f"Big-endian integers must be whole-byte. Length = {len(self)} bits.")
return self._getint()
def _setuintle(self, uintle: int, length: Optional[int] = None) -> None:
if length is None and hasattr(self, 'len') and len(self) != 0:
length = len(self)
if length is None or length == 0:
raise bitstring.CreationError("A non-zero length must be specified with a uintle initialiser.")
self._bitstore = bitstore_helpers.intle2bitstore(uintle, length, False)
def _getuintle(self) -> int:
"""Interpret as a little-endian unsigned int."""
if len(self) % 8:
raise bitstring.InterpretError(f"Little-endian integers must be whole-byte. Length = {len(self)} bits.")
bs = BitStore.frombytes(self._bitstore.tobytes()[::-1])
return bs.slice_to_uint()
def _setintle(self, intle: int, length: Optional[int] = None) -> None:
if length is None and hasattr(self, 'len') and len(self) != 0:
length = len(self)
if length is None or length == 0:
raise bitstring.CreationError("A non-zero length must be specified with an intle initialiser.")
self._bitstore = bitstore_helpers.intle2bitstore(intle, length, True)
def _getintle(self) -> int:
"""Interpret as a little-endian signed int."""
if len(self) % 8:
raise bitstring.InterpretError(f"Little-endian integers must be whole-byte. Length = {len(self)} bits.")
bs = BitStore.frombytes(self._bitstore.tobytes()[::-1])
return bs.slice_to_int()
def _getp4binary(self) -> float:
u = self._getuint()
return p4binary_fmt.lut_binary8_to_float[u]
def _getp3binary(self) -> float:
u = self._getuint()
return p3binary_fmt.lut_binary8_to_float[u]
def _gete4m3mxfp(self) -> float:
u = self._getuint()
return e4m3mxfp_saturate_fmt.lut_int_to_float[u]
def _gete5m2mxfp(self) -> float:
u = self._getuint()
return e5m2mxfp_saturate_fmt.lut_int_to_float[u]
def _gete3m2mxfp(self) -> float:
u = self._getuint()
return e3m2mxfp_fmt.lut_int_to_float[u]
def _gete2m3mxfp(self) -> float:
u = self._getuint()
return e2m3mxfp_fmt.lut_int_to_float[u]
def _gete2m1mxfp(self) -> float:
u = self._getuint()
return e2m1mxfp_fmt.lut_int_to_float[u]
def _gete8m0mxfp(self) -> float:
u = self._getuint() - 127
if u == 128:
return float('nan')
return 2.0 ** u
def _getmxint(self) -> float:
u = self._getint()
return float(u) * 2 ** -6
def _setfloat(self, f: float, length: Optional[int], big_endian: bool) -> None:
if length is None and hasattr(self, 'len') and len(self) != 0:
length = len(self)
if length is None or length not in [16, 32, 64]:
raise bitstring.CreationError("A length of 16, 32, or 64 must be specified with a float initialiser.")
self._bitstore = bitstore_helpers.float2bitstore(f, length, big_endian)
def _setfloatbe(self, f: float, length: Optional[int] = None) -> None:
self._setfloat(f, length, True)
def _getfloatbe(self) -> float:
"""Interpret the whole bitstring as a big-endian float."""
fmt = {16: '>e', 32: '>f', 64: '>d'}[len(self)]
return struct.unpack(fmt, self._bitstore.tobytes())[0]
def _setfloatle(self, f: float, length: Optional[int] = None) -> None:
self._setfloat(f, length, False)
def _getfloatle(self) -> float:
"""Interpret the whole bitstring as a little-endian float."""
fmt = {16: '<e', 32: '<f', 64: '<d'}[len(self)]
return struct.unpack(fmt, self._bitstore.tobytes())[0]
def _getbfloatbe(self) -> float:
zero_padded = self + Bits(16)
return zero_padded._getfloatbe()
def _setbfloatbe(self, f: Union[float, str], length: Optional[int] = None) -> None:
if length is not None and length != 16:
raise bitstring.CreationError(f"bfloats must be length 16, received a length of {length} bits.")
self._bitstore = bitstore_helpers.bfloat2bitstore(f, True)
def _getbfloatle(self) -> float:
zero_padded = Bits(16) + self
return zero_padded._getfloatle()
def _setbfloatle(self, f: Union[float, str], length: Optional[int] = None) -> None:
if length is not None and length != 16:
raise bitstring.CreationError(f"bfloats must be length 16, received a length of {length} bits.")
self._bitstore = bitstore_helpers.bfloat2bitstore(f, False)
def _setue(self, i: int) -> None:
"""Initialise bitstring with unsigned exponential-Golomb code for integer i.
Raises CreationError if i < 0.
"""
if bitstring.options.lsb0:
raise bitstring.CreationError("Exp-Golomb codes cannot be used in lsb0 mode.")
self._bitstore = bitstore_helpers.ue2bitstore(i)
def _readue(self, pos: int) -> Tuple[int, int]:
"""Return interpretation of next bits as unsigned exponential-Golomb code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
"""
if bitstring.options.lsb0:
raise bitstring.ReadError("Exp-Golomb codes cannot be read in lsb0 mode.")
oldpos = pos
try:
while not self[pos]:
pos += 1
except IndexError:
raise bitstring.ReadError("Read off end of bitstring trying to read code.")
leadingzeros = pos - oldpos
codenum = (1 << leadingzeros) - 1
if leadingzeros > 0:
if pos + leadingzeros + 1 > len(self):
raise bitstring.ReadError("Read off end of bitstring trying to read code.")
codenum += self[pos + 1:pos + 1 + leadingzeros]._getuint()
pos += leadingzeros + 1
else:
assert codenum == 0
pos += 1
return codenum, pos
def _getue(self) -> Tuple[int, int]:
try:
return self._readue(0)
except bitstring.ReadError:
raise bitstring.InterpretError
def _getse(self) -> Tuple[int, int]:
try:
return self._readse(0)
except bitstring.ReadError:
raise bitstring.InterpretError
def _getuie(self) -> Tuple[int, int]:
try:
return self._readuie(0)
except bitstring.ReadError:
raise bitstring.InterpretError
def _getsie(self) -> Tuple[int, int]:
try:
return self._readsie(0)
except bitstring.ReadError:
raise bitstring.InterpretError
def _setse(self, i: int) -> None:
"""Initialise bitstring with signed exponential-Golomb code for integer i."""
if bitstring.options.lsb0:
raise bitstring.CreationError("Exp-Golomb codes cannot be used in lsb0 mode.")
self._bitstore = bitstore_helpers.se2bitstore(i)
def _readse(self, pos: int) -> Tuple[int, int]:
"""Return interpretation of next bits as a signed exponential-Golomb code.
Advances position to after the read code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
"""
codenum, pos = self._readue(pos)
m = (codenum + 1) // 2
return (m, pos) if codenum % 2 else (-m, pos)
def _setuie(self, i: int) -> None:
"""Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i.
Raises CreationError if i < 0.
"""
if bitstring.options.lsb0:
raise bitstring.CreationError("Exp-Golomb codes cannot be used in lsb0 mode.")
self._bitstore = bitstore_helpers.uie2bitstore(i)
def _readuie(self, pos: int) -> Tuple[int, int]:
"""Return interpretation of next bits as unsigned interleaved exponential-Golomb code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
"""
if bitstring.options.lsb0:
raise bitstring.ReadError("Exp-Golomb codes cannot be read in lsb0 mode.")
try:
codenum: int = 1
while not self[pos]:
pos += 1
codenum <<= 1
codenum += self[pos]
pos += 1
pos += 1
except IndexError:
raise bitstring.ReadError("Read off end of bitstring trying to read code.")
return codenum - 1, pos
def _setsie(self, i: int, ) -> None:
"""Initialise bitstring with signed interleaved exponential-Golomb code for integer i."""
if bitstring.options.lsb0:
raise bitstring.CreationError("Exp-Golomb codes cannot be used in lsb0 mode.")
self._bitstore = bitstore_helpers.sie2bitstore(i)
def _readsie(self, pos: int) -> Tuple[int, int]:
"""Return interpretation of next bits as a signed interleaved exponential-Golomb code.
Advances position to after the read code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
"""
codenum, pos = self._readuie(pos)
if not codenum:
return 0, pos
try:
return (-codenum, pos + 1) if self[pos] else (codenum, pos + 1)
except IndexError:
raise bitstring.ReadError("Read off end of bitstring trying to read code.")
def _setbool(self, value: Union[bool, str]) -> None:
# We deliberately don't want to have implicit conversions to bool here.
# If we did then it would be difficult to deal with the 'False' string.
if value in (1, 'True', '1'):
self._bitstore = BitStore('1')
elif value in (0, 'False', '0'):
self._bitstore = BitStore('0')
else:
raise bitstring.CreationError(f"Cannot initialise boolean with {value}.")
def _getbool(self) -> bool:
return self[0]
def _getpad(self) -> None:
return None
def _setpad(self, value: None, length: int) -> None:
self._bitstore = BitStore(length)
def _setbin_safe(self, binstring: str, length: None = None) -> None:
"""Reset the bitstring to the value given in binstring."""
self._bitstore = bitstore_helpers.bin2bitstore(binstring)
def _setbin_unsafe(self, binstring: str, length: None = None) -> None:
"""Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'."""
self._bitstore = bitstore_helpers.bin2bitstore_unsafe(binstring)
def _getbin(self) -> str:
"""Return interpretation as a binary string."""
return self._bitstore.slice_to_bin()
def _setoct(self, octstring: str, length: None = None) -> None:
"""Reset the bitstring to have the value given in octstring."""
self._bitstore = bitstore_helpers.oct2bitstore(octstring)
def _getoct(self) -> str:
"""Return interpretation as an octal string."""
return self._bitstore.slice_to_oct()
def _sethex(self, hexstring: str, length: None = None) -> None:
"""Reset the bitstring to have the value given in hexstring."""
self._bitstore = bitstore_helpers.hex2bitstore(hexstring)
def _gethex(self) -> str:
"""Return the hexadecimal representation as a string.
Raises an InterpretError if the bitstring's length is not a multiple of 4.
"""
return self._bitstore.slice_to_hex()
def _getlength(self) -> int:
"""Return the length of the bitstring in bits."""
return len(self._bitstore)
def _copy(self: TBits) -> TBits:
"""Create and return a new copy of the Bits (always in memory)."""
# Note that __copy__ may choose to return self if it's immutable. This method always makes a copy.