Skip to content

Commit

Permalink
Sanity checks.
Browse files Browse the repository at this point in the history
  • Loading branch information
eerimoq committed Aug 29, 2016
1 parent 3c13cac commit 3f87680
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
23 changes: 22 additions & 1 deletion bitstruct.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ def _unpack_float(size, bits):
elif size == 64:
value = struct.unpack('>d', packed)[0]
else:
raise ValueError('Bad float size {}. Must be 32 or 64 bits.'.format(size))
raise ValueError('expected float size of 32 of 64 bits (got {})'.format(
size))

return value

Expand Down Expand Up @@ -133,6 +134,17 @@ def pack(fmt, *args):
infos = _parse_format(fmt)
i = 0

# Sanity check of the number of arguments.
number_of_arguments = 0

for info in infos:
if info[0] != 'p':
number_of_arguments += 1

if number_of_arguments > len(args):
raise ValueError("pack expected {} item(s) for packing "
"(got {})".format(number_of_arguments, len(args)))

for _type, size, endianness in infos:
if _type == 'p':
bits += size * '0'
Expand Down Expand Up @@ -179,6 +191,15 @@ def unpack(fmt, data):

bits = ''.join(['{:08b}'.format(b) for b in bytearray(data)])
infos = _parse_format(fmt)

# Sanity check.
number_of_bits_to_unpack = sum([size for _, size, _ in infos])

if number_of_bits_to_unpack > len(bits):
raise ValueError("unpack requires at least {} bits to unpack "
"(got {})".format(number_of_bits_to_unpack,
len(bits)))

res = []
i = 0

Expand Down
26 changes: 23 additions & 3 deletions tests/test_bitstruct.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ def test_pack(self):
packed = pack('b1t24', False, "Hi!")
self.assertEqual(packed, b'$4\x90\x80')

# Too many values to pack.
try:
pack('b1t24', False)
self.fail()
except ValueError as e:
self.assertEqual(
str(e),
'pack expected 2 item(s) for packing (got 1)')

def test_unpack(self):
"""Unpack values.
Expand Down Expand Up @@ -91,12 +100,23 @@ def test_unpack(self):
unpacked = unpack('b1t24', packed)
self.assertEqual(unpacked, (False, u"Hi!"))

# bad float size
# Bad float size.
try:
unpack('f33', b'\x00\x00\x00\x00\x00')
self.fail()
except ValueError:
pass
except ValueError as e:
self.assertEqual(
str(e),
'expected float size of 32 of 64 bits (got 33)')

# Too many bits to unpack.
try:
unpack('u9', b'\x00')
self.fail()
except ValueError as e:
self.assertEqual(
str(e),
'unpack requires at least 9 bits to unpack (got 8)')

# gcc packed struct with bitfields
#
Expand Down

0 comments on commit 3f87680

Please sign in to comment.