Belle II Software development
ConstBitStream Class Reference
Inheritance diagram for ConstBitStream:
Bits BitStream

Public Member Functions

def __init__ (self, auto=None, length=None, offset=None, **kwargs)
 
def __new__ (cls, auto=None, length=None, offset=None, **kwargs)
 
def __copy__ (self)
 
def __add__ (self, bs)
 
def read (self, fmt)
 
def readlist (self, fmt, **kwargs)
 
def readto (self, bs, bytealigned=None)
 
def peek (self, fmt)
 
def peeklist (self, fmt, **kwargs)
 
def bytealign (self)
 

Protected Member Functions

def _setbytepos (self, bytepos)
 
def _getbytepos (self)
 
def _setbitpos (self, pos)
 
def _getbitpos (self)
 
def _clear (self)
 

Protected Attributes

 _pos
 

Properties

property pos
 
property bitpos
 
property bytepos
 

Static Private Attributes

tuple __slots__ = ('_pos')
 

Detailed Description

A container or stream holding an immutable sequence of bits.

For a mutable container use the BitStream class instead.

Methods inherited from Bits:

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.

Other methods:

bytealign() -- Align to next byte boundary.
peek() -- Peek at and interpret next bits as a single item.
peeklist() -- Peek at and interpret next bits as a list of items.
read() -- Read and interpret next bits as a single item.
readlist() -- Read and interpret next bits as a list of items.

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.
bytepos -- The current byte position in the bitstring.
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.
pos -- The current bit position in the bitstring.
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.

Definition at line 3699 of file bitstring.py.

Constructor & Destructor Documentation

◆ __init__()

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 intended for use when
          initialising using 'bytes' or 'filename'.

Reimplemented from Bits.

Reimplemented in BitStream.

Definition at line 3764 of file bitstring.py.

3764 def __init__(self, auto=None, length=None, offset=None, **kwargs):
3765 """Either specify an 'auto' initialiser:
3766 auto -- a string of comma separated tokens, an integer, a file object,
3767 a bytearray, a boolean iterable or another bitstring.
3768
3769 Or initialise via **kwargs with one (and only one) of:
3770 bytes -- raw data as a string, for example read from a binary file.
3771 bin -- binary string representation, e.g. '0b001010'.
3772 hex -- hexadecimal string representation, e.g. '0x2ef'
3773 oct -- octal string representation, e.g. '0o777'.
3774 uint -- an unsigned integer.
3775 int -- a signed integer.
3776 float -- a floating point number.
3777 uintbe -- an unsigned big-endian whole byte integer.
3778 intbe -- a signed big-endian whole byte integer.
3779 floatbe - a big-endian floating point number.
3780 uintle -- an unsigned little-endian whole byte integer.
3781 intle -- a signed little-endian whole byte integer.
3782 floatle -- a little-endian floating point number.
3783 uintne -- an unsigned native-endian whole byte integer.
3784 intne -- a signed native-endian whole byte integer.
3785 floatne -- a native-endian floating point number.
3786 se -- a signed exponential-Golomb code.
3787 ue -- an unsigned exponential-Golomb code.
3788 sie -- a signed interleaved exponential-Golomb code.
3789 uie -- an unsigned interleaved exponential-Golomb code.
3790 bool -- a boolean (True or False).
3791 filename -- a file which will be opened in binary read-only mode.
3792
3793 Other keyword arguments:
3794 length -- length of the bitstring in bits, if needed and appropriate.
3795 It must be supplied for all integer and float initialisers.
3796 offset -- bit offset to the data. These offset bits are
3797 ignored and this is intended for use when
3798 initialising using 'bytes' or 'filename'.
3799
3800 """
3801 self._pos = 0
3802

Member Function Documentation

◆ __add__()

def __add__ (   self,
  bs 
)
Concatenate bitstrings and return new bitstring.

bs -- the bitstring to append.

Reimplemented from Bits.

Definition at line 3844 of file bitstring.py.

3844 def __add__(self, bs):
3845 """Concatenate bitstrings and return new bitstring.
3846
3847 bs -- the bitstring to append.
3848
3849 """
3850 s = Bits.__add__(self, bs)
3851 s._pos = 0
3852 return s
3853

◆ __copy__()

def __copy__ (   self)
Return a new copy of the ConstBitStream for the copy module.

Reimplemented from Bits.

Reimplemented in BitStream.

Definition at line 3834 of file bitstring.py.

3834 def __copy__(self):
3835 """Return a new copy of the ConstBitStream for the copy module."""
3836 # Note that if you want a new copy (different ID), use _copy instead.
3837 # The copy can use the same datastore as it's immutable.
3838 s = ConstBitStream()
3839 s._datastore = self._datastore
3840 # Reset the bit position, don't copy it.
3841 s._pos = 0
3842 return s
3843

◆ __new__()

def __new__ (   cls,
  auto = None,
  length = None,
  offset = None,
**  kwargs 
)

Reimplemented from Bits.

Definition at line 3803 of file bitstring.py.

3803 def __new__(cls, auto=None, length=None, offset=None, **kwargs):
3804 x = super(ConstBitStream, cls).__new__(cls)
3805 x._initialise(auto, length, offset, **kwargs)
3806 return x
3807

◆ _clear()

def _clear (   self)
protected
Reset the bitstring to an empty state.

Reimplemented from Bits.

Definition at line 3830 of file bitstring.py.

3830 def _clear(self):
3831 Bits._clear(self)
3832 self._pos = 0
3833

◆ _getbitpos()

def _getbitpos (   self)
protected
Return the current position in the stream in bits.

Definition at line 3826 of file bitstring.py.

3826 def _getbitpos(self):
3827 """Return the current position in the stream in bits."""
3828 return self._pos
3829

◆ _getbytepos()

def _getbytepos (   self)
protected
Return the current position in the stream in bytes. Must be byte aligned.

Definition at line 3812 of file bitstring.py.

3812 def _getbytepos(self):
3813 """Return the current position in the stream in bytes. Must be byte aligned."""
3814 if self._pos % 8:
3815 raise ByteAlignError("Not byte aligned in _getbytepos().")
3816 return self._pos // 8
3817

◆ _setbitpos()

def _setbitpos (   self,
  pos 
)
protected
Move to absolute postion bit in bitstream.

Definition at line 3818 of file bitstring.py.

3818 def _setbitpos(self, pos):
3819 """Move to absolute postion bit in bitstream."""
3820 if pos < 0:
3821 raise ValueError("Bit position cannot be negative.")
3822 if pos > self.len:
3823 raise ValueError("Cannot seek past the end of the data.")
3824 self._pos = pos
3825

◆ _setbytepos()

def _setbytepos (   self,
  bytepos 
)
protected
Move to absolute byte-aligned position in stream.

Definition at line 3808 of file bitstring.py.

3808 def _setbytepos(self, bytepos):
3809 """Move to absolute byte-aligned position in stream."""
3810 self._setbitpos(bytepos * 8)
3811

◆ bytealign()

def bytealign (   self)
Align to next byte and return number of skipped bits.

Raises ValueError if the end of the bitstring is reached before
aligning to the next byte.

Definition at line 3997 of file bitstring.py.

3997 def bytealign(self):
3998 """Align to next byte and return number of skipped bits.
3999
4000 Raises ValueError if the end of the bitstring is reached before
4001 aligning to the next byte.
4002
4003 """
4004 skipped = (8 - (self._pos % 8)) % 8
4005 self.pos += self._offset + skipped
4006 assert self._assertsanity()
4007 return skipped
4008

◆ peek()

def peek (   self,
  fmt 
)
Interpret next bits according to format string and return result.

fmt -- Token string describing how to interpret the next bits.

The position in the bitstring is not changed. If not enough bits are
available then all bits to the end of the bitstring will be used.

Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.

See the docstring for 'read' for token examples.

Definition at line 3956 of file bitstring.py.

3956 def peek(self, fmt):
3957 """Interpret next bits according to format string and return result.
3958
3959 fmt -- Token string describing how to interpret the next bits.
3960
3961 The position in the bitstring is not changed. If not enough bits are
3962 available then all bits to the end of the bitstring will be used.
3963
3964 Raises ReadError if not enough bits are available.
3965 Raises ValueError if the format is not understood.
3966
3967 See the docstring for 'read' for token examples.
3968
3969 """
3970 pos_before = self._pos
3971 value = self.read(fmt)
3972 self._pos = pos_before
3973 return value
3974

◆ peeklist()

def peeklist (   self,
  fmt,
**  kwargs 
)
Interpret next bits according to format string(s) and return list.

fmt -- One or more strings with comma separated tokens describing
       how to interpret the next bits in the bitstring.
kwargs -- A dictionary or keyword-value pairs - the keywords used in the
          format string will be replaced with their given value.

The position in the bitstring is not changed. If not enough bits are
available then all bits to the end of the bitstring will be used.

Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.

See the docstring for 'read' for token examples.

Definition at line 3975 of file bitstring.py.

3975 def peeklist(self, fmt, **kwargs):
3976 """Interpret next bits according to format string(s) and return list.
3977
3978 fmt -- One or more strings with comma separated tokens describing
3979 how to interpret the next bits in the bitstring.
3980 kwargs -- A dictionary or keyword-value pairs - the keywords used in the
3981 format string will be replaced with their given value.
3982
3983 The position in the bitstring is not changed. If not enough bits are
3984 available then all bits to the end of the bitstring will be used.
3985
3986 Raises ReadError if not enough bits are available.
3987 Raises ValueError if the format is not understood.
3988
3989 See the docstring for 'read' for token examples.
3990
3991 """
3992 pos = self._pos
3993 return_values = self.readlist(fmt, **kwargs)
3994 self._pos = pos
3995 return return_values
3996

◆ read()

def read (   self,
  fmt 
)
Interpret next bits according to the format string and return result.

fmt -- Token string describing how to interpret the next bits.

Token examples: 'int:12'    : 12 bits as a signed integer
                'uint:8'    : 8 bits as an unsigned integer
                'float:64'  : 8 bytes as a big-endian float
                'intbe:16'  : 2 bytes as a big-endian signed integer
                'uintbe:16' : 2 bytes as a big-endian unsigned integer
                'intle:32'  : 4 bytes as a little-endian signed integer
                'uintle:32' : 4 bytes as a little-endian unsigned integer
                'floatle:64': 8 bytes as a little-endian float
                'intne:24'  : 3 bytes as a native-endian signed integer
                'uintne:24' : 3 bytes as a native-endian unsigned integer
                'floatne:32': 4 bytes as a native-endian float
                'hex:80'    : 80 bits as a hex string
                'oct:9'     : 9 bits as an octal string
                'bin:1'     : single bit binary string
                'ue'        : next bits as unsigned exp-Golomb code
                'se'        : next bits as signed exp-Golomb code
                'uie'       : next bits as unsigned interleaved exp-Golomb code
                'sie'       : next bits as signed interleaved exp-Golomb code
                'bits:5'    : 5 bits as a bitstring
                'bytes:10'  : 10 bytes as a bytes object
                'bool'      : 1 bit as a bool
                'pad:3'     : 3 bits of padding to ignore - returns None

fmt may also be an integer, which will be treated like the 'bits' token.

The position in the bitstring is advanced to after the read items.

Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.

Definition at line 3854 of file bitstring.py.

3854 def read(self, fmt):
3855 """Interpret next bits according to the format string and return result.
3856
3857 fmt -- Token string describing how to interpret the next bits.
3858
3859 Token examples: 'int:12' : 12 bits as a signed integer
3860 'uint:8' : 8 bits as an unsigned integer
3861 'float:64' : 8 bytes as a big-endian float
3862 'intbe:16' : 2 bytes as a big-endian signed integer
3863 'uintbe:16' : 2 bytes as a big-endian unsigned integer
3864 'intle:32' : 4 bytes as a little-endian signed integer
3865 'uintle:32' : 4 bytes as a little-endian unsigned integer
3866 'floatle:64': 8 bytes as a little-endian float
3867 'intne:24' : 3 bytes as a native-endian signed integer
3868 'uintne:24' : 3 bytes as a native-endian unsigned integer
3869 'floatne:32': 4 bytes as a native-endian float
3870 'hex:80' : 80 bits as a hex string
3871 'oct:9' : 9 bits as an octal string
3872 'bin:1' : single bit binary string
3873 'ue' : next bits as unsigned exp-Golomb code
3874 'se' : next bits as signed exp-Golomb code
3875 'uie' : next bits as unsigned interleaved exp-Golomb code
3876 'sie' : next bits as signed interleaved exp-Golomb code
3877 'bits:5' : 5 bits as a bitstring
3878 'bytes:10' : 10 bytes as a bytes object
3879 'bool' : 1 bit as a bool
3880 'pad:3' : 3 bits of padding to ignore - returns None
3881
3882 fmt may also be an integer, which will be treated like the 'bits' token.
3883
3884 The position in the bitstring is advanced to after the read items.
3885
3886 Raises ReadError if not enough bits are available.
3887 Raises ValueError if the format is not understood.
3888
3889 """
3890 if isinstance(fmt, numbers.Integral):
3891 if fmt < 0:
3892 raise ValueError("Cannot read negative amount.")
3893 if fmt > self.len - self._pos:
3894 raise ReadError("Cannot read {0} bits, only {1} available.",
3895 fmt, self.len - self._pos)
3896 bs = self._slice(self._pos, self._pos + fmt)
3897 self._pos += fmt
3898 return bs
3899 p = self._pos
3900 _, token = tokenparser(fmt)
3901 if len(token) != 1:
3902 self._pos = p
3903 raise ValueError("Format string should be a single token, not {0} "
3904 "tokens - use readlist() instead.".format(len(token)))
3905 name, length, _ = token[0]
3906 if length is None:
3907 length = self.len - self._pos
3908 value, self._pos = self._readtoken(name, self._pos, length)
3909 return value
3910

◆ readlist()

def readlist (   self,
  fmt,
**  kwargs 
)
Interpret next bits according to format string(s) and return list.

fmt -- A single string or list of strings with comma separated tokens
       describing how to interpret the next bits in the bitstring. Items
       can also be integers, for reading new bitstring of the given length.
kwargs -- A dictionary or keyword-value pairs - the keywords used in the
          format string will be replaced with their given value.

The position in the bitstring is advanced to after the read items.

Raises ReadError is not enough bits are available.
Raises ValueError if the format is not understood.

See the docstring for 'read' for token examples. 'pad' tokens are skipped
and not added to the returned list.

>>> h, b1, b2 = s.readlist('hex:20, bin:5, bin:3')
>>> i, bs1, bs2 = s.readlist(['uint:12', 10, 10])

Definition at line 3911 of file bitstring.py.

3911 def readlist(self, fmt, **kwargs):
3912 """Interpret next bits according to format string(s) and return list.
3913
3914 fmt -- A single string or list of strings with comma separated tokens
3915 describing how to interpret the next bits in the bitstring. Items
3916 can also be integers, for reading new bitstring of the given length.
3917 kwargs -- A dictionary or keyword-value pairs - the keywords used in the
3918 format string will be replaced with their given value.
3919
3920 The position in the bitstring is advanced to after the read items.
3921
3922 Raises ReadError is not enough bits are available.
3923 Raises ValueError if the format is not understood.
3924
3925 See the docstring for 'read' for token examples. 'pad' tokens are skipped
3926 and not added to the returned list.
3927
3928 >>> h, b1, b2 = s.readlist('hex:20, bin:5, bin:3')
3929 >>> i, bs1, bs2 = s.readlist(['uint:12', 10, 10])
3930
3931 """
3932 value, self._pos = self._readlist(fmt, self._pos, **kwargs)
3933 return value
3934

◆ readto()

def readto (   self,
  bs,
  bytealigned = None 
)
Read up to and including next occurrence of bs and return result.

bs -- The bitstring to find. An integer is not permitted.
bytealigned -- If True the bitstring will only be
               found on byte boundaries.

Raises ValueError if bs is empty.
Raises ReadError if bs is not found.

Definition at line 3935 of file bitstring.py.

3935 def readto(self, bs, bytealigned=None):
3936 """Read up to and including next occurrence of bs and return result.
3937
3938 bs -- The bitstring to find. An integer is not permitted.
3939 bytealigned -- If True the bitstring will only be
3940 found on byte boundaries.
3941
3942 Raises ValueError if bs is empty.
3943 Raises ReadError if bs is not found.
3944
3945 """
3946 if isinstance(bs, numbers.Integral):
3947 raise ValueError("Integers cannot be searched for")
3948 bs = Bits(bs)
3949 oldpos = self._pos
3950 p = self.find(bs, self._pos, bytealigned=bytealigned)
3951 if not p:
3952 raise ReadError("Substring not found")
3953 self._pos += bs.len
3954 return self._slice(oldpos, self._pos)
3955

Member Data Documentation

◆ __slots__

tuple __slots__ = ('_pos')
staticprivate

Definition at line 3762 of file bitstring.py.

◆ _pos

_pos
protected

Definition at line 3801 of file bitstring.py.

Property Documentation

◆ bitpos

property bitpos
static
Initial value:
= property(_getbitpos, _setbitpos,
doc=)

Definition at line 4012 of file bitstring.py.

◆ bytepos

property bytepos
static
Initial value:
= property(_getbytepos, _setbytepos,
doc=)

Definition at line 4015 of file bitstring.py.

◆ pos

property pos
static
Initial value:
= property(_getbitpos, _setbitpos,
doc=)

Definition at line 4009 of file bitstring.py.


The documentation for this class was generated from the following file: