How to use the bitstring.CreationError function in bitstring

To help you get started, we’ve selected a few bitstring examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github scott-griffiths / bitstring / bitstring / bits.py View on Github external
def _setbytes_safe(self, data, length=None, offset=0):
        """Set the data from a string."""
        data = bytearray(data)
        if length is None:
            # Use to the end of the data
            length = (len(data) - (offset // 8)) * 8 - offset
            self._datastore = ByteStore(data, length, offset)
        else:
            if length + offset > len(data) * 8:
                msg = "Not enough data present. Need {0} bits, have {1}."
                raise bitstring.CreationError(msg, length + offset, len(data) * 8)
            if not length:
                self._datastore = ByteStore(bytearray(0))
            else:
                self._datastore = ByteStore(data, length, offset)
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
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 bitstring.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 bitstring.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 bitstring.CreationError("Unrecognised keyword '{0}' used to initialise.", k)
github scott-griffiths / bitstring / test / test_bits.py View on Github external
def testCreationFromSeErrors(self):
        self.assertRaises(bitstring.CreationError, Bits, se=-5, length=33)
        s = Bits(bin='001000')
        self.assertRaises(bitstring.InterpretError, s._getse)
github scott-griffiths / bitstring / test / test_bitarray.py View on Github external
def testCreationFromUint(self):
        s = BitArray(uint=15, length=6)
        self.assertEqual(s.bin, '001111')
        s = BitArray(uint=0, length=1)
        self.assertEqual(s.bin, '0')
        s.uint = 1
        self.assertEqual(s.uint, 1)
        s = BitArray(length=8)
        s.uint = 0
        self.assertEqual(s.uint, 0)
        s.uint = 255
        self.assertEqual(s.uint, 255)
        self.assertEqual(s.len, 8)
        self.assertRaises(bitstring.CreationError, s._setuint, 256)
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
offset gives the suggested bit offset of first significant
        bit, to optimise append etc.

        """
        if isinstance(bs, Bits):
            return bs
        try:
            return cache[(bs, offset)]
        except KeyError:
            if isinstance(bs, basestring):
                b = cls()
                try:
                    _, tokens = tokenparser(bs)
                except ValueError as e:
                    raise bitstring.CreationError(*e.args)
                if tokens:
                    b._append(Bits._init_with_token(*tokens[0]))
                    b._datastore = bitstore.offsetcopy(b._datastore, offset)
                    for token in tokens[1:]:
                        b._append(Bits._init_with_token(*token))
                assert b._assertsanity()
                assert b.len == 0 or b._offset == offset
                cache[(bs, offset)] = b
                return b
        except TypeError:
            # Unhashable type
            pass
        return cls(bs)
github scott-griffiths / bitstring / bitstring / bitstream.py View on Github external
continue
            if length is not None:
                length = int(length)
            if value is None:
                # Take the next value from the ones provided
                value = next(value_iter)
            s._append(BitStream._init_with_token(name, length, value))
    except StopIteration:
        raise bitstring.CreationError("Not enough parameters present to pack according to the "
                            "format. {0} values are needed.", len(tokens))
    try:
        next(value_iter)
    except StopIteration:
        # Good, we've used up all the *values.
        return s
    raise bitstring.CreationError("Too many parameters present to pack according to the format.")
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
elif name in ('uint', 'int', 'uintbe', 'intbe', 'uintle', 'intle', 'uintne', 'intne'):
                b = cls(**{name: int(value), 'length': token_length})
            elif name in ('float', 'floatbe', 'floatle', 'floatne'):
                b = cls(**{name: float(value), 'length': token_length})
            elif name == 'bool':
                if value in (1, 'True', '1'):
                    b = cls(bool=True)
                elif value in (0, 'False', '0'):
                    b = cls(bool=False)
                else:
                    raise bitstring.CreationError("bool token can only be 'True' or 'False'.")
            else:
                raise bitstring.CreationError("Can't parse token name {0}.", name)
        if token_length is not None and b.len != token_length:
            msg = "Token with length {0} packed with value of length {1} ({2}:{3}={4})."
            raise bitstring.CreationError(msg, token_length, b.len, name, token_length, value)
        return b
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
def _setint(self, int_, length=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 self.len != 0:
            length = self.len
        if length is None or length == 0:
            raise bitstring.CreationError("A non-zero length must be specified with an int initialiser.")
        if int_ >= (1 << (length - 1)) or int_ < -(1 << (length - 1)):
            raise bitstring.CreationError("{0} is too large a signed integer for a bitstring of length {1}. "
                                "The allowed range is [{2}, {3}].", int_, length, -(1 << (length - 1)),
                                (1 << (length - 1)) - 1)
        if int_ >= 0:
            self._setuint(int_, length)
            return
        # TODO: We should decide whether to just use the _setuint, or to do the bit flipping,
        # based upon which will be quicker. If the -ive number is less than half the maximum
        # possible then it's probably quicker to do the bit flipping...

        # Do the 2's complement thing. Add one, set to minus number, then flip bits.
        int_ += 1
        self._setuint(-int_, length)
        self._invert_all()
github scott-griffiths / bitstring / bitstring / bits.py View on Github external
def _setint(self, int_, length=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 self.len != 0:
            length = self.len
        if length is None or length == 0:
            raise bitstring.CreationError("A non-zero length must be specified with an int initialiser.")
        if int_ >= (1 << (length - 1)) or int_ < -(1 << (length - 1)):
            raise bitstring.CreationError("{0} is too large a signed integer for a bitstring of length {1}. "
                                "The allowed range is [{2}, {3}].", int_, length, -(1 << (length - 1)),
                                (1 << (length - 1)) - 1)
        if int_ >= 0:
            self._setuint(int_, length)
            return
        # TODO: We should decide whether to just use the _setuint, or to do the bit flipping,
        # based upon which will be quicker. If the -ive number is less than half the maximum
        # possible then it's probably quicker to do the bit flipping...

        # Do the 2's complement thing. Add one, set to minus number, then flip bits.
        int_ += 1
        self._setuint(-int_, length)
        self._invert_all()
github alexras / bread / bread / struct.py View on Github external
def __setattr__(self, attr, value):
        try:
            if attr[0] == '_':
                super(BreadStruct, self).__setattr__(attr, value)
            elif attr in self._fields:
                field = self._fields[attr]
                field.set(value)
            else:
                for conditional_field in self._conditional_fields:
                    try:
                        return setattr(conditional_field, attr, value)
                    except AttributeError:
                        pass

                raise AttributeError("No known field '%s'" % (attr))
        except CreationError as e:
            raise ValueError('Error while setting %s: %s' % (field._name, e))