Skip to content

Commit 10a30ff

Browse files
authored
fix(corekit): keep a BitField's unnamed bits as captured (#1487) (#1495)
BitField.post_process read only the named subfields and pre_process packed from all zeros, so a bit outside every subfield was cleared on rebuild. post_process now records those bits under an `__unnamed__` key, present only when one is set, and pre_process seeds the buffer from it, masked so it can never override a named subfield. A value built without the key packs them as zeros, as before. Deletes the #1487 Gap row from the field round-trip table. Closes #1487
1 parent 00aa1fc commit 10a30ff

3 files changed

Lines changed: 117 additions & 9 deletions

File tree

‎pcapkit/corekit/fields/strings.py‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,17 @@ class BitField(_TextField[Dict[str, Any]]):
265265
callback: Callback function to be called upon
266266
:meth:`self.__call__ <pcapkit.corekit.fields.field.FieldBase.__call__>`.
267267
268+
Bits that no subfield names are kept as captured: where any of them is
269+
set, the unpacked value carries them under an ``__unnamed__`` key, as an
270+
integer over the whole field with every named bit cleared, and packing
271+
writes them back (:issue:`1487`). The key is absent when they are all
272+
zero, so a value built without it packs them as zeros.
273+
268274
"""
269275

276+
#: Key of the unpacked value that carries the unnamed bits.
277+
UNNAMED = '__unnamed__'
278+
270279
def __init__(self, length: 'int',
271280
default: 'dict[str, Any] | NoValueType' = NO_VALUE,
272281
namespace: 'Optional[dict[str, NamespaceEntry]]' = None,
@@ -288,6 +297,11 @@ def __init__(self, length: 'int',
288297
f'{start}-{start + size - 1} of a {width}-bit field'
289298
)
290299

300+
#: Mask of the bits no subfield names, most significant bit first.
301+
self._unnamed = (1 << width) - 1
302+
for start, size in self._namespace.values():
303+
self._unnamed &= ~(((1 << size) - 1) << (width - start - size))
304+
291305
def pre_process(self, value: 'dict[str, Any]', packet: 'dict[str, Any]') -> 'bytes': # pylint: disable=unused-argument
292306
"""Process field value before construction (packing).
293307
@@ -300,15 +314,24 @@ def pre_process(self, value: 'dict[str, Any]', packet: 'dict[str, Any]') -> 'byt
300314
301315
Raises:
302316
FieldValueError: If a subfield value does not fit the bits it was
303-
declared to occupy.
317+
declared to occupy, or the ``__unnamed__`` value is not an
318+
integer.
304319
305320
"""
306321
# NOTE: The buffer holds one ASCII digit per bit, so it must be seeded with
307322
# ``b'0'`` rather than with NUL bytes -- a zero bit written by the loop below
308323
# is the *character* ``b'0'``, which is itself non-zero, so a truthiness test
309324
# over the buffer cannot tell a cleared bit from a set one and would report
310325
# every named bit as set.
311-
buffer = bytearray(b'0' * (self.length * 8))
326+
#
327+
# The unnamed bits seed it, so that they come back as captured; masking
328+
# them keeps a stray named bit in the record from overriding a subfield.
329+
unnamed = value.get(self.UNNAMED, 0)
330+
if isinstance(unnamed, bool) or not isinstance(unnamed, int):
331+
raise FieldValueError(
332+
f'{type(self).__name__}: {self.UNNAMED} must be an int, not {unnamed!r}'
333+
)
334+
buffer = bytearray(f'{unnamed & self._unnamed:0{self.length * 8}b}'.encode())
312335
for name, (start, size) in self._namespace.items():
313336
bits = f'{value[name]:0{size}b}'
314337
if len(bits) > size:
@@ -335,6 +358,9 @@ def post_process(self, value: 'bytes', packet: 'dict[str, Any]') -> 'dict[str, A
335358
for name, (start, len) in self._namespace.items():
336359
end = start + len
337360
buffer[name] = int(binary[start:end], 2)
361+
unnamed = int.from_bytes(value, 'big') & self._unnamed
362+
if unnamed:
363+
buffer[self.UNNAMED] = unnamed
338364
return buffer
339365

340366

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# -*- coding: utf-8 -*-
2+
"""A BitField packs back the bits its namespace does not name.
3+
4+
GitHub issue #1487: :class:`~pcapkit.corekit.fields.strings.BitField` read only
5+
its named subfields and packed from all zeros, so octets with a bit outside
6+
every subfield set came back with it cleared. The unpacked value now carries
7+
those bits under ``__unnamed__`` when any is set, and a value without the key
8+
packs them as zeros, as before.
9+
10+
:mod:`pcapkit` is imported inside each test, after
11+
:func:`~tests._support.reimport_once_per_class`, not at module load.
12+
13+
"""
14+
15+
import unittest
16+
17+
from tests._support import reimport_once_per_class
18+
19+
#: ``a`` is bit 0 and ``c`` bits 8-11; bits 1-7 and 12-15 are unnamed.
20+
NAMESPACE = {'a': (0, 1), 'c': (8, 4)}
21+
22+
23+
class BitFieldUnnamedBitsTests(unittest.TestCase):
24+
"""GitHub issue #1487."""
25+
26+
def setUp(self) -> None:
27+
reimport_once_per_class(self)
28+
29+
from pcapkit.corekit.fields.strings import BitField
30+
31+
self.field = BitField(length=2, namespace=NAMESPACE)({})
32+
33+
def _round_trip(self, raw: bytes) -> bytes:
34+
return self.field.pack(self.field.unpack(raw, {}), {})
35+
36+
def test_unnamed_bits_survive_unpack_then_pack(self) -> None:
37+
for raw in (b'\xff\xff', b'\x01\x00', b'\x7f\x0f', b'\x00\x01', b'\x80\xf0', b'\x00\x00'):
38+
with self.subTest(raw=raw.hex()):
39+
self.assertEqual(self._round_trip(raw), raw)
40+
41+
def test_unpacked_value_names_the_unnamed_bits(self) -> None:
42+
self.assertEqual(self.field.unpack(b'\xff\xff', {}),
43+
{'a': 1, 'c': 15, '__unnamed__': 0x7f0f})
44+
45+
def test_key_is_absent_when_the_unnamed_bits_are_zero(self) -> None:
46+
self.assertEqual(self.field.unpack(b'\x80\xf0', {}), {'a': 1, 'c': 15})
47+
48+
def test_a_value_without_the_key_packs_unnamed_bits_as_zero(self) -> None:
49+
self.assertEqual(self.field.pack({'a': 1, 'c': 15}, {}), b'\x80\xf0')
50+
self.assertEqual(self.field.pack({'a': 0, 'c': 0}, {}), b'\x00\x00')
51+
52+
def test_named_subfields_win_over_the_record(self) -> None:
53+
"""A named bit set in ``__unnamed__`` does not override its subfield."""
54+
self.assertEqual(self.field.pack({'a': 0, 'c': 0, '__unnamed__': 0xffff}, {}), b'\x7f\x0f')
55+
56+
def test_edited_subfield_keeps_the_captured_unnamed_bits(self) -> None:
57+
value = self.field.unpack(b'\xff\xff', {})
58+
value['c'] = 0
59+
self.assertEqual(self.field.pack(value, {}), b'\xff\x0f')
60+
61+
def test_a_non_int_record_is_rejected(self) -> None:
62+
from pcapkit.utilities.exceptions import FieldValueError
63+
64+
for bad in ('1', 1.0, True, None):
65+
with self.subTest(bad=bad), self.assertRaises(FieldValueError):
66+
self.field.pack({'a': 0, 'c': 0, '__unnamed__': bad}, {})
67+
68+
def test_schema_to_dict_from_dict_keeps_the_unnamed_bits(self) -> None:
69+
from pcapkit.corekit.fields.strings import BitField
70+
from pcapkit.protocols.schema.schema import Schema, schema_final
71+
72+
@schema_final
73+
class Flags(Schema):
74+
flags: dict = BitField(length=2, namespace=NAMESPACE)
75+
76+
raw = b'\x7f\x0f'
77+
parsed = Flags.unpack(raw, len(raw), None)
78+
self.assertEqual(parsed.pack(), raw)
79+
self.assertEqual(Flags.from_dict(parsed.to_dict()).pack(), raw)
80+
81+
def test_full_namespace_never_gains_the_key(self) -> None:
82+
from pcapkit.corekit.fields.strings import BitField
83+
84+
field = BitField(length=1, namespace={'hi': (0, 4), 'lo': (4, 4)})({})
85+
self.assertEqual(field.unpack(b'\xff', {}), {'hi': 15, 'lo': 15})
86+
87+
88+
if __name__ == '__main__':
89+
unittest.main()

‎tests/corekit/test_field_roundtrip_unit.py‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -550,13 +550,6 @@ class FieldRoundTripTests(KnownFailureTable, unittest.TestCase):
550550
STATUSES = ('OK', 'PACK', 'UNPACK', 'VALUE', 'REPACK', 'WIRE', 'DICT', 'REJECTED', 'TIMEOUT')
551551

552552
KNOWN_FAILURES = (
553-
Gap(1487, 'BitField.post_process reads only the bits its namespace names, and '
554-
'pre_process seeds the rest as zeros, so octets with a bit outside every '
555-
'subfield set pack back with it cleared '
556-
'(pcapkit/corekit/fields/strings.py:311, :334). Not reachable from a shipped '
557-
'schema: all 102 BitFields cover every bit '
558-
'(test_every_schema_bitfield_covers_every_bit)',
559-
'WIRE', '', ('BitField/partial/wire/ffff', 'BitField/partial/wire/0100')),
560553
Gap(1488, 'NumberField with bit_length narrower than its octets masks the unpacked value '
561554
'to bit_length bits, so set high bits are dropped and pack writes them as '
562555
'zeros (pcapkit/corekit/fields/numbers.py:318, :322). Shipped use: vlan.TCI '

0 commit comments

Comments
 (0)