Skip to content

Commit

Permalink
Structs: remove '_from_values', create '_push_to' method
Browse files Browse the repository at this point in the history
  • Loading branch information
jsbueno committed Sep 29, 2024
1 parent 70eea18 commit ed91f5c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
16 changes: 8 additions & 8 deletions src/extrainterpreters/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,14 +144,6 @@ def _fields(cls):
if isinstance(v, RawField):
yield k

@classmethod
def _from_values(cls, *args):
data = bytearray(b"\x00" * cls._size)
self = cls(data, 0)
for arg, field_name in zip(args, self._fields):
setattr(self, field_name, arg)
return self

@property
def _bytes(self):
return bytes(self._data[self._offset : self._offset + self._size])
Expand All @@ -173,6 +165,14 @@ def _get_offset_for_field(cls, field_name):
field = getattr(cls, field_name)
return field._calc_offset(cls)

def _push_to(self, data, offset=0):
"""Paste struct data into a new buffer given by data, offset
Returns a new instance pointing to the data in the new copy.
"""
data[offset: offset + self._size] = self._bytes
return self._from_data(data, offset)

def __repr__(self):
field_data = []
for field_name in self._fields:
Expand Down
12 changes: 12 additions & 0 deletions tests/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,18 @@ class Struct(StructBase):
assert s.data_offset == 1000
assert s.length == 2_000_000

def test_struct_push_to():
class Struct(StructBase):
data_offset = Field(2)
length = Field(4)

s = Struct(data_offset=1000, length=2_000_000)

data = bytearray(Struct._size)
n = s._push_to(data, 0)
assert n.data_offset == 1000
assert n.length == 2_000_000


def test_struct_bytes():
class Struct(StructBase):
Expand Down

0 comments on commit ed91f5c

Please sign in to comment.