dissect.cstruct 5.0.dev24__py3-none-any.whl → 5.0.dev26__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dissect/cstruct/bitbuffer.py +8 -1
- dissect/cstruct/compiler.py +39 -17
- dissect/cstruct/cstruct.py +48 -9
- dissect/cstruct/declarative.py +4 -0
- dissect/cstruct/dump.py +1 -1
- dissect/cstruct/tools/stubgen.py +9 -2
- dissect/cstruct/types/base.py +125 -17
- dissect/cstruct/types/char.py +131 -24
- dissect/cstruct/types/enum.py +2 -1
- dissect/cstruct/types/int.py +7 -0
- dissect/cstruct/types/packed.py +18 -1
- dissect/cstruct/types/pointer.py +16 -12
- dissect/cstruct/types/structure.py +104 -26
- dissect/cstruct/types/void.py +9 -0
- dissect/cstruct/types/wchar.py +98 -13
- {dissect_cstruct-5.0.dev24.dist-info → dissect_cstruct-5.0.dev26.dist-info}/METADATA +41 -8
- dissect_cstruct-5.0.dev26.dist-info/RECORD +32 -0
- dissect_cstruct-5.0.dev24.dist-info/RECORD +0 -32
- {dissect_cstruct-5.0.dev24.dist-info → dissect_cstruct-5.0.dev26.dist-info}/WHEEL +0 -0
- {dissect_cstruct-5.0.dev24.dist-info → dissect_cstruct-5.0.dev26.dist-info}/entry_points.txt +0 -0
- {dissect_cstruct-5.0.dev24.dist-info → dissect_cstruct-5.0.dev26.dist-info}/licenses/COPYRIGHT +0 -0
- {dissect_cstruct-5.0.dev24.dist-info → dissect_cstruct-5.0.dev26.dist-info}/licenses/LICENSE +0 -0
- {dissect_cstruct-5.0.dev24.dist-info → dissect_cstruct-5.0.dev26.dist-info}/top_level.txt +0 -0
dissect/cstruct/bitbuffer.py
CHANGED
|
@@ -73,7 +73,14 @@ class BitBuffer:
|
|
|
73
73
|
|
|
74
74
|
def flush(self) -> None:
|
|
75
75
|
if self._type is not None:
|
|
76
|
-
|
|
76
|
+
buffer = self._buffer
|
|
77
|
+
if issubclass(self._type, bytes):
|
|
78
|
+
if self.endian == "<":
|
|
79
|
+
buffer = buffer.to_bytes(self._type.__size__, "little")
|
|
80
|
+
else:
|
|
81
|
+
buffer = buffer.to_bytes(self._type.__size__, "big")
|
|
82
|
+
|
|
83
|
+
self._type._write(self.stream, buffer, endian=self.endian)
|
|
77
84
|
self._type = None
|
|
78
85
|
self._remaining = 0
|
|
79
86
|
self._buffer = 0
|
dissect/cstruct/compiler.py
CHANGED
|
@@ -37,7 +37,13 @@ from dissect.cstruct.types import (
|
|
|
37
37
|
WcharArray,
|
|
38
38
|
)
|
|
39
39
|
from dissect.cstruct.types.enum import EnumMetaType
|
|
40
|
-
from dissect.cstruct.types.structure import
|
|
40
|
+
from dissect.cstruct.types.structure import (
|
|
41
|
+
StructureMetaType,
|
|
42
|
+
UnionMetaType,
|
|
43
|
+
UnionProxy,
|
|
44
|
+
_uses_generated_init,
|
|
45
|
+
_value_type,
|
|
46
|
+
)
|
|
41
47
|
from dissect.cstruct.util import ENDIANNESS_TO_BYTEORDER_MAP, _struct
|
|
42
48
|
|
|
43
49
|
if TYPE_CHECKING:
|
|
@@ -216,15 +222,15 @@ _PACKABLE_TYPES = (Array, Char, CharArray, Int, Packed, Pointer, Void, VoidArray
|
|
|
216
222
|
|
|
217
223
|
def _field_bytes(type_: type[BaseType], value: Any, endian: str) -> bytes:
|
|
218
224
|
"""Return the bytes of a char or wchar field that isn't of the right type yet or doesn't fit."""
|
|
219
|
-
|
|
220
|
-
if len(buf) > type_.__size__:
|
|
225
|
+
type_._write(out := io.BytesIO(), type_.__default__() if value is None else value, endian=endian)
|
|
226
|
+
if len(buf := out.getvalue()) > type_.__size__:
|
|
221
227
|
raise WriteError(f"Expected {type_.__size__} bytes for {type_.__name__}, got {len(buf)} instead.")
|
|
222
228
|
return buf
|
|
223
229
|
|
|
224
230
|
|
|
225
231
|
def _array_values(type_: type[Array], value: list[Any] | None) -> list[Any]:
|
|
226
|
-
"""Return the values of an array field that
|
|
227
|
-
return type_.__default__() if value is None else type_.
|
|
232
|
+
"""Return the values of an array field that isn't a list of the right size yet."""
|
|
233
|
+
return type_.__default__() if value is None else type_._entries(value)
|
|
228
234
|
|
|
229
235
|
|
|
230
236
|
def _or_default(value: Any, type_: type[BaseType]) -> Any:
|
|
@@ -235,6 +241,8 @@ def _or_default(value: Any, type_: type[BaseType]) -> Any:
|
|
|
235
241
|
# Globals that are available to all generated functions
|
|
236
242
|
_GLOBALS = {
|
|
237
243
|
"_type_call": type.__call__,
|
|
244
|
+
"_bytes_new": bytes.__new__,
|
|
245
|
+
"_str_new": str.__new__,
|
|
238
246
|
"_object_new": object.__new__,
|
|
239
247
|
"_setattr": setattr,
|
|
240
248
|
"_repeat": repeat,
|
|
@@ -412,6 +420,15 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
412
420
|
outro.append(f" obj.__dynamic_sizes__ = {sizes}")
|
|
413
421
|
outro.append(" return obj")
|
|
414
422
|
|
|
423
|
+
# Subclasses without their own __init__ or __new__ inherit __construct__, which also bypasses __init__
|
|
424
|
+
# It has a parameter for each field name, like the keyword arguments below
|
|
425
|
+
construct = self._add_symbol(self.cls.__construct__, "construct")
|
|
426
|
+
values = "".join(f", {var}" for var in dict(self._assigned).values())
|
|
427
|
+
outro.append(f"if cls.__construct__ is {construct}:")
|
|
428
|
+
outro.append(f" obj = {construct}(cls{values})")
|
|
429
|
+
outro.append(f" obj.__dynamic_sizes__ = {sizes}")
|
|
430
|
+
outro.append(" return obj")
|
|
431
|
+
|
|
415
432
|
# Using type.__call__ directly calls the __init__ method of the class
|
|
416
433
|
outro.append(f"obj = _type_call(cls, **{{{kwargs}}})")
|
|
417
434
|
outro.append(f"obj.__dynamic_sizes__ = {sizes}")
|
|
@@ -571,7 +588,16 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
571
588
|
lines.append("except _Error: raise")
|
|
572
589
|
lines.append(f"except (ArithmeticError, ValueError) as e: raise _ReadError({message!r} + str(e)) from e")
|
|
573
590
|
element = self._type_symbol(field.type.__type__)
|
|
574
|
-
|
|
591
|
+
entries = f"{element}._read_array(stream, _count, context={context}, endian=endian)"
|
|
592
|
+
|
|
593
|
+
# Create char and wchar arrays without the checks of their constructor
|
|
594
|
+
if issubclass(field.type, CharArray):
|
|
595
|
+
return f"_bytes_new({type_}, {entries})"
|
|
596
|
+
|
|
597
|
+
if issubclass(field.type, WcharArray):
|
|
598
|
+
return f"_str_new({type_}, {entries})"
|
|
599
|
+
|
|
600
|
+
return f"_type_call({type_}, {entries})"
|
|
575
601
|
|
|
576
602
|
def _generate_bits_source(self, field: Field) -> Iterator[str]:
|
|
577
603
|
"""Generate the code for reading a bit field."""
|
|
@@ -594,7 +620,7 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
594
620
|
lines.append(f"else: _bit_value = (_bit_buffer >> {remaining - field.bits}) & {mask}")
|
|
595
621
|
|
|
596
622
|
# Character bit fields are returned as the integer type they're read as
|
|
597
|
-
type_ = self._type_symbol(
|
|
623
|
+
type_ = self._type_symbol(_value_type(field))
|
|
598
624
|
|
|
599
625
|
if issubclass(field.type, (Enum, Flag)):
|
|
600
626
|
lines.append(_member_lookup(type_, "_bit_value"))
|
|
@@ -747,14 +773,14 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
747
773
|
|
|
748
774
|
lines.extend(target(field, f"_type_call({array}, {value})"))
|
|
749
775
|
|
|
750
|
-
elif issubclass(field_type, CharArray):
|
|
751
|
-
lines.extend(target(field, f"
|
|
776
|
+
elif issubclass(field_type, (Char, CharArray)):
|
|
777
|
+
lines.extend(target(field, f"_bytes_new({self._type_symbol(field.type)}, {getter})"))
|
|
752
778
|
|
|
753
779
|
elif issubclass(field_type, WcharArray) or issubclass(read_type, Wchar):
|
|
754
780
|
encoding = self._add_symbol(read_type.__encoding_map__, "encoding")
|
|
755
|
-
#
|
|
781
|
+
# Decoding like str() instead of .decode() also supports other bytes-like objects returned by the stream
|
|
756
782
|
type_ = self._type_symbol(field.type)
|
|
757
|
-
lines.extend(target(field, f"
|
|
783
|
+
lines.extend(target(field, f"_str_new({type_}, {getter}, {encoding}[endian], 'surrogatepass')"))
|
|
758
784
|
|
|
759
785
|
elif issubclass(field_type, Pointer):
|
|
760
786
|
context = self._context(lines)
|
|
@@ -1051,7 +1077,8 @@ class _WriteSourceGenerator(_SourceGenerator):
|
|
|
1051
1077
|
var = self._var("value")
|
|
1052
1078
|
num = field_type.__num_entries__
|
|
1053
1079
|
pack.lines.append(
|
|
1054
|
-
f"if ({var} := {value})
|
|
1080
|
+
f"if not isinstance({var} := {value}, list) or len({var}) != {num}: "
|
|
1081
|
+
f"{var} = _array_values({type_}, {var})"
|
|
1055
1082
|
)
|
|
1056
1083
|
|
|
1057
1084
|
# Entries can be enum members or plain integers, both can be packed as they are
|
|
@@ -1178,11 +1205,6 @@ def _can_inline_fields(fields: list[Field], size: int, is_union: bool, in_union:
|
|
|
1178
1205
|
return True
|
|
1179
1206
|
|
|
1180
1207
|
|
|
1181
|
-
def _uses_generated_init(type_: type[Structure]) -> bool:
|
|
1182
|
-
"""Return whether a structure type uses a generated ``__init__``, so we can bypass it by setting attributes."""
|
|
1183
|
-
return "__init__" in type_.__dict__ and type_.__new__ is object.__new__
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
1208
|
def _can_pack(type_: type[BaseType]) -> bool:
|
|
1187
1209
|
"""Determine if a value of a type can be written by packing it, instead of by using the ``_write`` method."""
|
|
1188
1210
|
if type_.__size__ is None:
|
dissect/cstruct/cstruct.py
CHANGED
|
@@ -21,6 +21,7 @@ from dissect.cstruct.types import (
|
|
|
21
21
|
BaseType,
|
|
22
22
|
Char,
|
|
23
23
|
Enum,
|
|
24
|
+
Field,
|
|
24
25
|
Flag,
|
|
25
26
|
Int,
|
|
26
27
|
Packed,
|
|
@@ -36,10 +37,7 @@ if TYPE_CHECKING:
|
|
|
36
37
|
from collections.abc import Generator, Iterable
|
|
37
38
|
from typing import TypeAlias
|
|
38
39
|
|
|
39
|
-
from dissect.cstruct.types import
|
|
40
|
-
Array,
|
|
41
|
-
Field,
|
|
42
|
-
)
|
|
40
|
+
from dissect.cstruct.types import Array
|
|
43
41
|
|
|
44
42
|
|
|
45
43
|
T = TypeVar("T", bound=BaseType)
|
|
@@ -245,21 +243,62 @@ class cstruct:
|
|
|
245
243
|
raise AttributeError(f"'{type(self).__name__}' object has no attribute {attr!r}")
|
|
246
244
|
|
|
247
245
|
def __copy__(self) -> cstruct:
|
|
248
|
-
cs = cstruct(endian=self.endian
|
|
246
|
+
cs = cstruct(endian=self.endian)
|
|
249
247
|
cs._anonymous_count = self._anonymous_count
|
|
250
248
|
cs.includes = self.includes.copy()
|
|
251
249
|
|
|
252
|
-
#
|
|
250
|
+
# Copy the types as new classes, including the unregistered types they refer to
|
|
251
|
+
copies = {}
|
|
253
252
|
for name, type_ in self.types.items():
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
cs.add_type(name, new_type, replace=True)
|
|
253
|
+
cs.add_type(name, cs._copy_type(type_, copies), replace=True)
|
|
254
|
+
cs.pointer = cs._copy_type(self.pointer, copies)
|
|
257
255
|
|
|
258
256
|
for name, value in self.consts.items():
|
|
259
257
|
cs.add_const(name, value)
|
|
260
258
|
|
|
261
259
|
return cs
|
|
262
260
|
|
|
261
|
+
def _copy_type(self, type_: type[BaseType], copies: dict[type[BaseType], type[BaseType]]) -> type[BaseType]:
|
|
262
|
+
if type_ in copies:
|
|
263
|
+
return copies[type_]
|
|
264
|
+
|
|
265
|
+
if issubclass(type_, (Enum, Flag)):
|
|
266
|
+
# Enum classes with members can't be created from their namespace
|
|
267
|
+
factory = self._make_flag if issubclass(type_, Flag) else self._make_enum
|
|
268
|
+
values = {name: member.value for name, member in type_.__members__.items()}
|
|
269
|
+
copies[type_] = factory(type_.__name__, self._copy_type(type_.__type__, copies), values)
|
|
270
|
+
return copies[type_]
|
|
271
|
+
|
|
272
|
+
# A type is registered before its subclasses, e.g. a declarative structure, so the copy of its base exists
|
|
273
|
+
bases = tuple(copies.get(base, base) for base in type_.__bases__)
|
|
274
|
+
|
|
275
|
+
# The namespace of a class doesn't hold its qualified name, e.g. of a declarative structure in a function
|
|
276
|
+
attrs = {**vars(type_), "__qualname__": type_.__qualname__}
|
|
277
|
+
|
|
278
|
+
# Register the copy before copying the types it refers to, so that a structure can point to itself
|
|
279
|
+
if issubclass(type_, Structure):
|
|
280
|
+
attrs["__members__"] = []
|
|
281
|
+
|
|
282
|
+
new_type = copies[type_] = self._make_type(
|
|
283
|
+
type_.__name__,
|
|
284
|
+
bases,
|
|
285
|
+
type_.__size__,
|
|
286
|
+
alignment=type_.__alignment__,
|
|
287
|
+
attrs=attrs,
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
if issubclass(type_, (BaseArray, Pointer)):
|
|
291
|
+
new_type.__type__ = self._copy_type(type_.__type__, copies)
|
|
292
|
+
|
|
293
|
+
if issubclass(type_, Structure):
|
|
294
|
+
new_type.__fields__ = [
|
|
295
|
+
Field(field.name, self._copy_type(field.type, copies), field.bits, field.offset)
|
|
296
|
+
for field in type_.__fields__
|
|
297
|
+
]
|
|
298
|
+
new_type.commit()
|
|
299
|
+
|
|
300
|
+
return new_type
|
|
301
|
+
|
|
263
302
|
# Hidden from type checkers, which otherwise accept assigning any attribute, e.g. a misspelled one
|
|
264
303
|
if not TYPE_CHECKING:
|
|
265
304
|
|
dissect/cstruct/declarative.py
CHANGED
|
@@ -395,6 +395,10 @@ class _Declarative:
|
|
|
395
395
|
def __init_subclass__(cls, *, cs: cstruct | None = None, align: bool | None = None, **kwargs):
|
|
396
396
|
super().__init_subclass__(**kwargs)
|
|
397
397
|
|
|
398
|
+
if "__fields__" in vars(cls):
|
|
399
|
+
# Created by cstruct with its fields, e.g. a copy made by cstruct.copy()
|
|
400
|
+
return
|
|
401
|
+
|
|
398
402
|
if cs is not None:
|
|
399
403
|
cls.__cs__ = cs
|
|
400
404
|
if align is not None:
|
dissect/cstruct/dump.py
CHANGED
|
@@ -465,7 +465,7 @@ def dumpstruct(
|
|
|
465
465
|
raise ValueError(f"Invalid output argument: {output!r} (should be 'print', 'string', 'dict' or 'json').")
|
|
466
466
|
|
|
467
467
|
if isinstance(obj, Structure):
|
|
468
|
-
data = obj
|
|
468
|
+
data = bytes(obj) if data is None else data
|
|
469
469
|
elif isinstance(obj, type) and issubclass(obj, Structure) and data is not None:
|
|
470
470
|
obj = obj(data)
|
|
471
471
|
else:
|
dissect/cstruct/tools/stubgen.py
CHANGED
|
@@ -158,7 +158,12 @@ def generate_structure_stub(
|
|
|
158
158
|
result = [f"class {name_prefix}{structure.__name__}({module_prefix}{structure.__base__.__name__}):"]
|
|
159
159
|
indent = " " * 4
|
|
160
160
|
|
|
161
|
-
|
|
161
|
+
# Fields can be named self, so prefix until there's no longer a clash
|
|
162
|
+
instance = "self"
|
|
163
|
+
while instance in structure.__members__:
|
|
164
|
+
instance = f"_{instance}"
|
|
165
|
+
|
|
166
|
+
args = [instance, "/"]
|
|
162
167
|
for field_name, field in structure.__members__.items():
|
|
163
168
|
inlined = False
|
|
164
169
|
|
|
@@ -182,7 +187,9 @@ def generate_structure_stub(
|
|
|
182
187
|
result.append(textwrap.indent(f"def __init__({', '.join(args)}): ...", prefix=indent))
|
|
183
188
|
result.append(textwrap.indent("@overload", prefix=indent))
|
|
184
189
|
result.append(
|
|
185
|
-
textwrap.indent(
|
|
190
|
+
textwrap.indent(
|
|
191
|
+
f"def __init__({instance}, fh: bytes | memoryview | bytearray | BinaryIO, /): ...", prefix=indent
|
|
192
|
+
)
|
|
186
193
|
)
|
|
187
194
|
result.append("")
|
|
188
195
|
return "\n".join(result)
|
dissect/cstruct/types/base.py
CHANGED
|
@@ -3,6 +3,7 @@ from __future__ import annotations
|
|
|
3
3
|
import contextlib
|
|
4
4
|
import functools
|
|
5
5
|
import struct
|
|
6
|
+
import sys
|
|
6
7
|
import warnings
|
|
7
8
|
from io import SEEK_CUR, BytesIO
|
|
8
9
|
from types import MethodType
|
|
@@ -44,17 +45,23 @@ class MetaType(type):
|
|
|
44
45
|
__ArrayType__: type[BaseArray] = "Array"
|
|
45
46
|
"""The array type for this type class."""
|
|
46
47
|
|
|
47
|
-
def __call__(cls, *args, **kwargs) -> Self: # type: ignore
|
|
48
|
-
"""
|
|
48
|
+
def __call__(cls, /, *args, **kwargs) -> Self: # type: ignore
|
|
49
|
+
"""Create a value of this type like its Python base type does, or parse it from data.
|
|
50
|
+
|
|
51
|
+
A bytes-like or file-like object is parsed, e.g. ``uint16(b"\\x01\\x00")`` is 1. Other values are given to the
|
|
52
|
+
Python base type, e.g. ``uint16("1")`` is 1 like ``int("1")``. Some types have exceptions, e.g. ``char(0x41)``
|
|
53
|
+
is ``b"A"``.
|
|
54
|
+
"""
|
|
49
55
|
if len(args) == 1 and not kwargs:
|
|
50
56
|
# Fast path for the most common case without keyword arguments
|
|
51
57
|
obj = args[0]
|
|
52
58
|
if type(obj) in _BUFFER_TYPES:
|
|
53
|
-
if len(obj) == cls.__size__ and isinstance(obj, bytes) and issubclass(cls, bytes):
|
|
54
|
-
# Shortcut for char/bytes type
|
|
55
|
-
return type.__call__(cls, obj)
|
|
56
59
|
return cls._read(BytesIO(obj), endian=cls.__cs__.endian)
|
|
57
60
|
|
|
61
|
+
if isinstance(obj, int):
|
|
62
|
+
# E.g. uint32(1)
|
|
63
|
+
return type.__call__(cls, obj)
|
|
64
|
+
|
|
58
65
|
if hasattr(obj, "read") and not isinstance(obj, cls):
|
|
59
66
|
return cls._read(obj, endian=cls.__cs__.endian)
|
|
60
67
|
|
|
@@ -69,10 +76,6 @@ class MetaType(type):
|
|
|
69
76
|
)
|
|
70
77
|
return cls._read(obj, endian=endian)
|
|
71
78
|
|
|
72
|
-
if isinstance(obj, bytes) and len(obj) == cls.__size__ and issubclass(cls, bytes):
|
|
73
|
-
# Shortcut for char/bytes type
|
|
74
|
-
return type.__call__(cls, *args, **kwargs)
|
|
75
|
-
|
|
76
79
|
if _is_buffer_type(obj):
|
|
77
80
|
return cls.reads(obj, endian=kwargs.get("endian"))
|
|
78
81
|
|
|
@@ -102,6 +105,23 @@ class MetaType(type):
|
|
|
102
105
|
"""Return the default value of this type."""
|
|
103
106
|
return cls()
|
|
104
107
|
|
|
108
|
+
def _normalize(cls, value: Any) -> Any:
|
|
109
|
+
"""Internal function for converting a value that is given to a field of this type when a structure is created.
|
|
110
|
+
|
|
111
|
+
Calls the type, so a field accepts the same values, e.g. ``uint16("1")`` and ``uint16(b"\\x01\\x00")``.
|
|
112
|
+
More bytes than the type needs raise a ``ValueError``, e.g. ``b"\\x01\\x00\\x02"`` for a ``uint16`` field.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
value: The value to convert, never ``None``.
|
|
116
|
+
"""
|
|
117
|
+
if isinstance(value, _BUFFER_TYPES):
|
|
118
|
+
stream = BytesIO(value)
|
|
119
|
+
result = cls._read(stream, endian=cls.__cs__.endian)
|
|
120
|
+
if (size := stream.tell()) != len(value):
|
|
121
|
+
raise ValueError(f"Expected {size} bytes for {cls.__name__}, got {len(value)} instead.")
|
|
122
|
+
return result
|
|
123
|
+
return cls(value)
|
|
124
|
+
|
|
105
125
|
def reads(cls, data: bytes | memoryview | bytearray, *, endian: AllowedEndianness | None = None) -> Self: # type: ignore
|
|
106
126
|
"""Parse the given data from a bytes-like object.
|
|
107
127
|
|
|
@@ -334,10 +354,22 @@ class _overload:
|
|
|
334
354
|
|
|
335
355
|
|
|
336
356
|
def _instance_dumps(self: BaseType, *, endian: AllowedEndianness | None = None) -> bytes:
|
|
357
|
+
warnings.warn(
|
|
358
|
+
"The 'dumps' method on instances is deprecated, use 'bytes(obj)' instead, or 'cls.dumps(obj)' to include the"
|
|
359
|
+
" null terminator of a null-terminated array.",
|
|
360
|
+
DeprecationWarning,
|
|
361
|
+
stacklevel=2,
|
|
362
|
+
)
|
|
337
363
|
return MetaType.dumps(self.__class__, self, endian=endian)
|
|
338
364
|
|
|
339
365
|
|
|
340
366
|
def _instance_write(self: BaseType, stream: BinaryIO, *, endian: AllowedEndianness | None = None) -> int:
|
|
367
|
+
warnings.warn(
|
|
368
|
+
"The 'write' method on instances is deprecated, use 'stream.write(bytes(obj))' instead, or"
|
|
369
|
+
" 'cls.write(stream, obj)' to include the null terminator of a null-terminated array.",
|
|
370
|
+
DeprecationWarning,
|
|
371
|
+
stacklevel=2,
|
|
372
|
+
)
|
|
341
373
|
return MetaType.write(self.__class__, stream, self, endian=endian)
|
|
342
374
|
|
|
343
375
|
|
|
@@ -354,6 +386,15 @@ class BaseType(metaclass=MetaType):
|
|
|
354
386
|
|
|
355
387
|
return self.__class__.__size__
|
|
356
388
|
|
|
389
|
+
def __bytes__(self) -> bytes:
|
|
390
|
+
return MetaType.dumps(self.__class__, self)
|
|
391
|
+
|
|
392
|
+
if sys.version_info >= (3, 12):
|
|
393
|
+
# The buffer protocol of Python classes, so that e.g. ``fh.write(obj)`` works, needs Python 3.12 or newer.
|
|
394
|
+
# It gives the same bytes as ``bytes(obj)``.
|
|
395
|
+
def __buffer__(self, flags: int) -> memoryview:
|
|
396
|
+
return memoryview(bytes(self))
|
|
397
|
+
|
|
357
398
|
|
|
358
399
|
T = TypeVar("T", bound=BaseType)
|
|
359
400
|
|
|
@@ -409,25 +450,31 @@ class BaseArray(BaseType):
|
|
|
409
450
|
|
|
410
451
|
@classmethod
|
|
411
452
|
def _write(cls, stream: BinaryIO, data: list[Any], *, endian: Endianness) -> int:
|
|
453
|
+
if not isinstance(data, list) or (isinstance(cls.__num_entries__, int) and len(data) != cls.__num_entries__):
|
|
454
|
+
# E.g. a tuple, or a list of another size
|
|
455
|
+
data = cls._entries(data)
|
|
456
|
+
|
|
412
457
|
if cls.__null_terminated__:
|
|
413
458
|
return cls.__type__._write_0(stream, data, endian=endian)
|
|
414
459
|
|
|
415
|
-
if not cls.__dynamic__:
|
|
416
|
-
data = cls._pad(data)
|
|
417
|
-
|
|
418
460
|
return cls.__type__._write_array(stream, data, endian=endian)
|
|
419
461
|
|
|
420
462
|
@classmethod
|
|
421
|
-
def
|
|
422
|
-
"""Internal function for
|
|
463
|
+
def _entries(cls, data: list[Any] | tuple[Any, ...]) -> list[Any] | tuple[Any, ...]:
|
|
464
|
+
"""Internal function for checking the entries of an array, and padding them to its fixed number of entries.
|
|
423
465
|
|
|
424
466
|
Args:
|
|
425
467
|
data: The entries of the array.
|
|
426
468
|
"""
|
|
427
|
-
if
|
|
469
|
+
if not isinstance(data, (list, tuple)):
|
|
470
|
+
# E.g. bytes, which aren't converted to entries
|
|
471
|
+
raise TypeError(f"Expected a list, got {type(data).__name__}")
|
|
472
|
+
|
|
473
|
+
# Also an array of entries with a dynamic size, e.g. LEB128 or a structure, has a fixed number of entries
|
|
474
|
+
if isinstance(cls.__num_entries__, int) and (remaining := cls.__num_entries__ - (actual_size := len(data))):
|
|
428
475
|
if remaining < 0:
|
|
429
476
|
raise WriteError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
|
|
430
|
-
data = data
|
|
477
|
+
data = [*data, *[cls.__type__.__default__()] * remaining]
|
|
431
478
|
|
|
432
479
|
return data
|
|
433
480
|
|
|
@@ -462,7 +509,68 @@ class BaseArray(BaseType):
|
|
|
462
509
|
return cls.__null_terminated__
|
|
463
510
|
|
|
464
511
|
|
|
465
|
-
class
|
|
512
|
+
class ArrayMetaType(MetaType):
|
|
513
|
+
"""Metaclass for array types."""
|
|
514
|
+
|
|
515
|
+
def __call__(cls, *args, **kwargs) -> Array:
|
|
516
|
+
if len(args) == 1 and not kwargs:
|
|
517
|
+
# Handle a few fast path cases
|
|
518
|
+
obj = args[0]
|
|
519
|
+
if hasattr(obj, "read") and not isinstance(obj, cls):
|
|
520
|
+
# E.g. uint8[4](fh)
|
|
521
|
+
return cls._read(obj, endian=cls.__cs__.endian)
|
|
522
|
+
|
|
523
|
+
if type(obj) in _BUFFER_TYPES:
|
|
524
|
+
# E.g. uint8[4](b"\x01\x02\x03\x04")
|
|
525
|
+
return cls._read(BytesIO(obj), endian=cls.__cs__.endian)
|
|
526
|
+
|
|
527
|
+
if not isinstance(obj, (list, tuple)):
|
|
528
|
+
# E.g. uint8[4](x for x in range(4))
|
|
529
|
+
if isinstance(obj, _BUFFER_TYPES):
|
|
530
|
+
# E.g. uint8[4](char[4](b"abcd"))
|
|
531
|
+
return cls._read(BytesIO(obj), endian=cls.__cs__.endian)
|
|
532
|
+
|
|
533
|
+
# list() would give the characters of a string, and a less clear error for an int
|
|
534
|
+
if isinstance(obj, (int, str)):
|
|
535
|
+
# E.g. uint8[4]("ab")
|
|
536
|
+
raise TypeError(f"Cannot create {cls.__name__} from {type(obj).__name__}")
|
|
537
|
+
|
|
538
|
+
# E.g. a generator, which has no length
|
|
539
|
+
obj = list(obj)
|
|
540
|
+
|
|
541
|
+
# E.g. initializing with a list-like
|
|
542
|
+
# Pad to the correct number of entries if the given value is too short
|
|
543
|
+
if isinstance(num_entries := cls.__num_entries__, int) and (actual_size := len(obj)) != num_entries:
|
|
544
|
+
# E.g. uint8[4]([1, 2])
|
|
545
|
+
if actual_size > num_entries:
|
|
546
|
+
# E.g. uint8[2]([1, 2, 3])
|
|
547
|
+
raise ValueError(f"Expected static array size {num_entries}, got {actual_size} instead.")
|
|
548
|
+
|
|
549
|
+
# Fill the default value, so that mutable entries like structures aren't shared
|
|
550
|
+
result = cls.__default__()
|
|
551
|
+
result[:actual_size] = obj
|
|
552
|
+
return result
|
|
553
|
+
|
|
554
|
+
return type.__call__(cls, obj)
|
|
555
|
+
|
|
556
|
+
if not args and not kwargs:
|
|
557
|
+
# Default value
|
|
558
|
+
# E.g. uint8[4]()
|
|
559
|
+
return cls.__default__()
|
|
560
|
+
|
|
561
|
+
# Everything else
|
|
562
|
+
# E.g. uint8[4](b"\x01\x02\x03\x04", endian=">")
|
|
563
|
+
return MetaType.__call__(cls, *args, **kwargs)
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
class Array(list[T], BaseArray, metaclass=ArrayMetaType):
|
|
567
|
+
def __bytes__(self) -> bytes:
|
|
568
|
+
# The byte representation of a null-terminated array doesn't include the null terminator.
|
|
569
|
+
if self.__null_terminated__:
|
|
570
|
+
return MetaType.dumps(self.__type__[len(self)], self)
|
|
571
|
+
|
|
572
|
+
return MetaType.dumps(self.__class__, self)
|
|
573
|
+
|
|
466
574
|
@classmethod
|
|
467
575
|
def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> list[T]:
|
|
468
576
|
return type.__call__(cls, super()._read(stream, context=context, endian=endian))
|