Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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):
__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 set_uint(self, value, nbits, bitpos):
import bitstring
if nbits // NBITS_PER_BYTE == 0:
bins = bitstring.Bits(uint=value, length=nbits)
else:
bins = bitstring.Bits(uintbe=value, length=24)
self.bit_stream[bitpos: bitpos + nbits] = bins
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)
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)
def _readuint(self, length, start):
"""Read bits and interpret as an unsigned int."""
if not length:
raise bitstring.InterpretError("Cannot interpret a zero length bitstring "
"as an integer.")
offset = self._offset
startbyte = (start + offset) // 8
endbyte = (start + offset + length - 1) // 8
b = binascii.hexlify(bytes(self._datastore.getbyteslice(startbyte, endbyte + 1)))
if not b:
return 0
i = int(b, 16)
final_bits = 8 - ((start + offset + length) % 8)
if final_bits != 8:
i >>= final_bits
i &= (1 << length) - 1
return i
def _readuintle(self, length, start):
"""Read bits and interpret as a little-endian unsigned int."""
if length % 8:
raise bitstring.InterpretError("Little-endian integers must be whole-byte. "
"Length = {0} bits.", length)
assert start + length <= self.len
absolute_pos = start + self._offset
startbyte, offset = divmod(absolute_pos, 8)
val = 0
if not offset:
endbyte = (absolute_pos + length - 1) // 8
chunksize = 4 # for 'L' format
while endbyte - chunksize + 1 >= startbyte:
val <<= 8 * chunksize
val += struct.unpack('
def _readoct(self, length, start):
"""Read bits and interpret as an octal string."""
if length % 3:
raise bitstring.InterpretError("Cannot convert to octal unambiguously - "
"not multiple of 3 bits.")
if not length:
return ''
# Get main octal bit by converting from int.
# Strip starting 0 or 0o depending on Python version.
end = oct(self._readuint(length, start))[LEADING_OCT_CHARS:]
if end.endswith('L'):
end = end[:-1]
middle = '0' * (length // 3 - len(end))
return middle + end
def _readhex(self, length, start):
"""Read bits and interpret as a hex string."""
if length % 4:
raise bitstring.InterpretError("Cannot convert to hex unambiguously - "
"not multiple of 4 bits.")
if not length:
return ''
# This monstrosity is the only thing I could get to work for both 2.6 and 3.1.
# TODO: Optimize: This really shouldn't call __getitem__.
# TODO: Is utf-8 really what we mean here?
s = str(binascii.hexlify(self[start:start + length].tobytes()).decode('utf-8'))
# If there's one nibble too many then cut it off
return s[:-1] if (length // 4) % 2 else s
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)
raise bitstring.CreationError("The offset keyword isn't applicable to this initialiser.")
if isinstance(s, basestring):
bs = self._converttobitstring(s)
assert bs._offset == 0
self._setbytes_unsafe(bs._datastore.rawbytes, bs.length, 0)
return
if isinstance(s, (bytes, bytearray)):
self._setbytes_unsafe(bytearray(s), len(s) * 8, 0)
return
if isinstance(s, numbers.Integral):
# Initialise with s zero bits.
if s < 0:
msg = "Can't create bitstring of negative length {0}."
raise bitstring.CreationError(msg, s)
data = bytearray((s + 7) // 8)
self._datastore = ByteStore(data, s, 0)
return
if isinstance(s, collections.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))
return
raise TypeError("Cannot initialise bitstring from {0}.".format(type(s)))