Skip to content

Commit

Permalink
fix(binary): swapping out values with a different field now updates t…
Browse files Browse the repository at this point in the history
…he container size
  • Loading branch information
robinvandernoord committed Sep 18, 2023
1 parent 878f596 commit c76261a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/configuraptor/binary_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,17 @@ def _get_length(cls) -> int:

return struct.calcsize(fmt)

def __setattr__(self, key: str, value: typing.Any) -> None:
"""
When setting a new field for this config, update the _fields property to have the correct new type + size.
"""
if not key.startswith("_") and isinstance(value, BinaryConfig):
field = self._fields[key]
field.klass = value.__class__
field.length = value.__class__._get_length()

return super().__setattr__(key, value)


@dataclass
class _BinaryField:
Expand Down
22 changes: 22 additions & 0 deletions tests/test_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,25 @@ def test_binary_config_with_external_block():
assert data.second.major == 0

assert data._pack() == v1 + v2

class IsNumber(BinaryConfig):
value = BinaryField(int, format="h")

class IsBigNumber(BinaryConfig):
value = BinaryField(int, format="l")

class HasNumber(BinaryConfig):
contains = BinaryField(IsNumber)


def test_resize_config():
inst = HasNumber()
assert inst._get_length() == 2
inst.contains = 12
assert inst._get_length() == 2

big_num = IsBigNumber()
big_num.value = 420

inst.contains = big_num
assert inst._get_length() == 8

0 comments on commit c76261a

Please sign in to comment.