diff --git a/src/extrainterpreters/utils.py b/src/extrainterpreters/utils.py index 166d0e7..56fb00d 100644 --- a/src/extrainterpreters/utils.py +++ b/src/extrainterpreters/utils.py @@ -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]) @@ -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: diff --git a/tests/test_struct.py b/tests/test_struct.py index 6271e01..e491113 100644 --- a/tests/test_struct.py +++ b/tests/test_struct.py @@ -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):