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.
@@ -1,34 +1,125 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from io import BytesIO
3
4
  from typing import TYPE_CHECKING, Any, BinaryIO
4
5
 
5
6
  from dissect.cstruct.exception import EOFError, WriteError
6
- from dissect.cstruct.types.base import EOF, BaseArray, BaseType, _is_seekable, _read_null_terminated
7
+ from dissect.cstruct.types.base import (
8
+ _BUFFER_TYPES,
9
+ EOF,
10
+ BaseArray,
11
+ BaseType,
12
+ MetaType,
13
+ _is_buffer_type,
14
+ _is_seekable,
15
+ _read_null_terminated,
16
+ )
7
17
 
8
18
  if TYPE_CHECKING:
19
+ from collections.abc import Iterable
20
+
9
21
  from typing_extensions import Self
10
22
 
11
23
  from dissect.cstruct.cstruct import Endianness
12
24
 
13
25
 
14
- class CharArray(bytes, BaseArray):
26
+ class CharMetaType(MetaType):
27
+ """Metaclass for character and character array types."""
28
+
29
+ def __call__(cls, *args, **kwargs) -> Char | CharArray:
30
+ if len(args) == 1 and not kwargs:
31
+ # Handle a few fast path cases
32
+ obj = args[0]
33
+ if isinstance(obj, bytes):
34
+ if len(obj) == (size := cls.__size__):
35
+ # E.g. char[4](b"abcd")
36
+ return bytes.__new__(cls, obj)
37
+
38
+ # Take the data up to the static size
39
+ if size is not None:
40
+ if len(obj) < size:
41
+ # E.g. char[4](b"ab")
42
+ raise EOFError(f"Read {len(obj)} bytes, but expected {size}")
43
+
44
+ # E.g. char[4](b"abcdef")
45
+ return bytes.__new__(cls, obj[:size])
46
+
47
+ if isinstance(obj, list) and len(obj) == cls.__size__:
48
+ # E.g. char[2]([1, 2])
49
+ return bytes.__new__(cls, obj)
50
+
51
+ if isinstance(obj, (int, list)):
52
+ # E.g. char(0x41) or char[4]([1, 2])
53
+ return cls.__new__(cls, obj)
54
+
55
+ if type(obj) in _BUFFER_TYPES:
56
+ # E.g. char[None](b"ab\x00") or char[4](bytearray(b"abcd"))
57
+ return cls._read(BytesIO(obj), endian=cls.__cs__.endian)
58
+
59
+ if hasattr(obj, "read") and not isinstance(obj, cls):
60
+ # E.g. char[4](fh)
61
+ return cls._read(obj, endian=cls.__cs__.endian)
62
+
63
+ if not _is_buffer_type(obj):
64
+ # E.g. char[4]((1, 2))
65
+ return cls.__new__(cls, obj)
66
+
67
+ elif not args and not kwargs:
68
+ # Default value
69
+ # E.g. char[4]()
70
+ return cls.__default__()
71
+
72
+ # Everything else
73
+ # E.g. char[4](b"abcd", endian=">")
74
+ return MetaType.__call__(cls, *args, **kwargs)
75
+
76
+ def _normalize(cls, value: Any) -> Char | CharArray:
77
+ if isinstance(value, _BUFFER_TYPES):
78
+ # The bytes of a char field are its value, e.g. b"ab" is b"ab\x00\x00" for a char[4] field
79
+ return cls.__new__(cls, value)
80
+ return cls(value)
81
+
82
+
83
+ class CharArray(bytes, BaseArray, metaclass=CharMetaType):
15
84
  """Character array type for reading and writing byte strings."""
16
85
 
86
+ def __new__(cls, value: bytes | bytearray | memoryview | Iterable[int]) -> Self:
87
+ if isinstance(value, int):
88
+ raise TypeError(f"Cannot create {cls.__name__} from {type(value).__name__}")
89
+
90
+ if isinstance(value, str):
91
+ raise TypeError(f"Cannot create {cls.__name__} from {type(value).__name__}, encode to bytes first")
92
+
93
+ result = bytes.__new__(cls, value)
94
+
95
+ if not cls.__dynamic__ and (remaining := cls.__num_entries__ - (actual_size := len(result))):
96
+ if remaining < 0:
97
+ raise ValueError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
98
+ result = bytes.__new__(cls, result + b"\x00" * remaining)
99
+
100
+ return result
101
+
102
+ def __bytes__(self) -> bytes:
103
+ # A char array is a bytes object, so give its content without the null terminator, like bytes does.
104
+ # Python 3.11 and newer use bytes.__bytes__ without this, but 3.10 would use BaseType.__bytes__.
105
+ return bytes(memoryview(self))
106
+
17
107
  @classmethod
18
108
  def __default__(cls) -> Self:
19
- return type.__call__(cls, b"\x00" * (0 if cls.__dynamic__ or cls.__null_terminated__ else cls.__num_entries__))
109
+ return bytes.__new__(cls, b"\x00" * (0 if cls.__dynamic__ or cls.__null_terminated__ else cls.__num_entries__))
20
110
 
21
111
  @classmethod
22
112
  def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
23
- return type.__call__(cls, super()._read(stream, context=context, endian=endian))
113
+ return bytes.__new__(cls, super()._read(stream, context=context, endian=endian))
24
114
 
25
115
  @classmethod
26
- def _write(cls, stream: BinaryIO, data: bytes | bytearray | str | list[int], *, endian: Endianness) -> int:
27
- # Copy mutable data types to bytes so we don't modify them in place
28
- if isinstance(data, (list, bytearray)):
116
+ def _write(cls, stream: BinaryIO, data: bytes | bytearray | memoryview, *, endian: Endianness) -> int:
117
+ # Convert other bytes-like data to bytes, so adding the null terminator and padding doesn't modify it in place
118
+ if isinstance(data, (bytearray, memoryview)):
29
119
  data = bytes(data)
30
- elif isinstance(data, str):
31
- data = data.encode("latin-1")
120
+ elif not isinstance(data, bytes):
121
+ hint = ", encode to bytes first" if isinstance(data, str) else ""
122
+ raise TypeError(f"Expected bytes, got {type(data).__name__}{hint}")
32
123
 
33
124
  if cls.__null_terminated__:
34
125
  data += b"\x00"
@@ -41,25 +132,43 @@ class CharArray(bytes, BaseArray):
41
132
  return stream.write(data)
42
133
 
43
134
 
44
- class Char(bytes, BaseType):
135
+ class Char(bytes, BaseType, metaclass=CharMetaType):
45
136
  """Character type for reading and writing bytes."""
46
137
 
47
138
  __ArrayType__ = CharArray
48
139
 
140
+ def __new__(cls, value: bytes | int | Iterable[int]) -> Self:
141
+ # Convert an int to a single character
142
+ if isinstance(value, int):
143
+ return bytes.__new__(cls, (value,))
144
+
145
+ if isinstance(value, str):
146
+ raise TypeError(f"Cannot create {cls.__name__} from {type(value).__name__}, encode to bytes first")
147
+
148
+ result = bytes.__new__(cls, value)
149
+
150
+ if (actual_size := len(result)) > 1:
151
+ raise ValueError(f"Expected a single character, got {actual_size} instead.")
152
+
153
+ return result or cls.__default__()
154
+
155
+ def __bytes__(self) -> bytes:
156
+ return bytes(memoryview(self))
157
+
49
158
  @classmethod
50
159
  def __default__(cls) -> Self:
51
- return type.__call__(cls, b"\x00")
160
+ return bytes.__new__(cls, b"\x00")
52
161
 
53
162
  @classmethod
54
163
  def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
55
- return cls._read_array(stream, 1, context=context, endian=endian)
164
+ return bytes.__new__(cls, cls._read_array(stream, 1, context=context, endian=endian))
56
165
 
57
166
  @classmethod
58
167
  def _read_array(
59
168
  cls, stream: BinaryIO, count: int, *, context: dict[str, Any] | None = None, endian: Endianness
60
- ) -> Self:
169
+ ) -> bytes:
61
170
  if count == 0:
62
- return type.__call__(cls, b"")
171
+ return b""
63
172
 
64
173
  try:
65
174
  data = stream.read(-1 if count == EOF else count)
@@ -69,12 +178,12 @@ class Char(bytes, BaseType):
69
178
  if count != EOF and len(data) != count:
70
179
  raise EOFError(f"Read {len(data)} bytes, but expected {count}")
71
180
 
72
- return type.__call__(cls, data)
181
+ return data
73
182
 
74
183
  @classmethod
75
- def _read_0(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
184
+ def _read_0(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> bytes:
76
185
  if _is_seekable(stream):
77
- return type.__call__(cls, _read_null_terminated(stream, 1))
186
+ return _read_null_terminated(stream, 1)
78
187
 
79
188
  buf = []
80
189
  while True:
@@ -87,15 +196,13 @@ class Char(bytes, BaseType):
87
196
 
88
197
  buf.append(byte)
89
198
 
90
- return type.__call__(cls, b"".join(buf))
199
+ return b"".join(buf)
91
200
 
92
201
  @classmethod
93
- def _write(cls, stream: BinaryIO, data: bytes | int | str, *, endian: Endianness) -> int:
94
- if isinstance(data, int):
95
- data = chr(data)
96
-
97
- if isinstance(data, str):
98
- data = data.encode("latin-1")
202
+ def _write(cls, stream: BinaryIO, data: bytes, *, endian: Endianness) -> int:
203
+ if not isinstance(data, _BUFFER_TYPES):
204
+ hint = ", encode to bytes first" if isinstance(data, str) else ""
205
+ raise TypeError(f"Expected bytes, got {type(data).__name__}{hint}")
99
206
 
100
207
  if (actual_size := len(data)) > 1:
101
208
  raise WriteError(f"Expected a single character, got {actual_size} instead.")
@@ -49,7 +49,8 @@ class EnumMetaType(EnumMeta, MetaType):
49
49
  if type(value) is not cls and (member := cls._value2member_map_.get(value)) is not None:
50
50
  return member
51
51
 
52
- return super().__call__(value)
52
+ # E.g. a member of another enum, which doesn't hash like its value
53
+ return super().__call__(value if type(value) is cls else int(value))
53
54
 
54
55
  # We are constructing a new Enum class
55
56
  # cs is the cstruct instance, but we can't isinstance check it due to circular imports
@@ -18,6 +18,13 @@ class Int(int, BaseType):
18
18
 
19
19
  __signed__: bool
20
20
 
21
+ @classmethod
22
+ def _normalize(cls, value: Any) -> Self:
23
+ if isinstance(value, int):
24
+ # Fast path for integers
25
+ return type.__call__(cls, value)
26
+ return MetaType._normalize(cls, value)
27
+
21
28
  @classmethod
22
29
  def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
23
30
  data = stream.read(cls.__size__)
@@ -25,23 +25,29 @@ class PackedMetaType(MetaType):
25
25
  # Handle a few fast path cases
26
26
  obj = args[0]
27
27
  if (tp := type(obj)) is bytes or tp is bytearray or (tp is memoryview and obj.c_contiguous):
28
+ # E.g. uint32(b"\x01\x00\x00\x00")
28
29
  data = obj.cast("B") if tp is memoryview else obj
29
30
  if len(data) < cls.__size__:
31
+ # E.g. uint32(b"\x01")
30
32
  raise EOFError(f"Read {len(data)} bytes, but expected {cls.__size__}")
31
33
 
32
34
  return cls.__new__(cls, _struct(cls.__cs__.endian, cls.__fmt__).unpack_from(data)[0])
33
35
 
34
36
  if hasattr(obj, "read") and not isinstance(obj, cls):
37
+ # E.g. uint32(fh)
35
38
  return cls._read(obj, endian=cls.__cs__.endian)
36
39
 
37
40
  if not _is_buffer_type(obj):
38
- # E.g. initializing with a value
41
+ # E.g. uint32(1)
39
42
  return type.__call__(cls, obj)
40
43
 
41
44
  elif not args and not kwargs:
42
45
  # Default value
46
+ # E.g. uint32()
43
47
  return type.__call__(cls)
44
48
 
49
+ # Everything else
50
+ # E.g. uint32(b"\x01\x00\x00\x00", endian=">")
45
51
  return MetaType.__call__(cls, *args, **kwargs)
46
52
 
47
53
 
@@ -51,6 +57,17 @@ class Packed(BaseType, Generic[T], metaclass=PackedMetaType):
51
57
  __fmt__: str
52
58
  __signed__: bool
53
59
 
60
+ @classmethod
61
+ def __default__(cls) -> Self:
62
+ return type.__call__(cls)
63
+
64
+ @classmethod
65
+ def _normalize(cls, value: Any) -> Self:
66
+ if isinstance(value, (int, float)):
67
+ # Fast path for numbers
68
+ return cls.__new__(cls, value)
69
+ return MetaType._normalize(cls, value)
70
+
54
71
  @classmethod
55
72
  def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
56
73
  data = stream.read(cls.__size__)
@@ -7,6 +7,7 @@ from dissect.cstruct.exception import EOFError, NullPointerDereference
7
7
  from dissect.cstruct.types.base import BaseType, normalize_endianness
8
8
  from dissect.cstruct.types.char import Char
9
9
  from dissect.cstruct.types.void import Void
10
+ from dissect.cstruct.types.wchar import Wchar
10
11
 
11
12
  if TYPE_CHECKING:
12
13
  from collections.abc import Callable
@@ -27,12 +28,21 @@ class Pointer(int, BaseType, Generic[T]):
27
28
  __endian: Endianness
28
29
 
29
30
  def __new__(
30
- cls, value: int, stream: BinaryIO | None, *, context: dict[str, Any] | None = None, endian: Endianness
31
+ cls,
32
+ value: int,
33
+ stream: BinaryIO | None = None,
34
+ *,
35
+ context: dict[str, Any] | None = None,
36
+ endian: Endianness | None = None,
31
37
  ) -> Self:
38
+ if stream is None and isinstance(value, Pointer):
39
+ # Keep the stream, so that e.g. a pointer of another type can still be dereferenced
40
+ stream, context, endian = value.__stream, value.__context, value.__endian
41
+
32
42
  obj = super().__new__(cls, value)
33
43
  obj.__stream = stream
34
44
  obj.__context = context
35
- obj.__endian = endian
45
+ obj.__endian = endian if endian is not None else cls.__cs__.endian
36
46
  obj.dereference = cache(obj.dereference)
37
47
  return obj
38
48
 
@@ -72,13 +82,7 @@ class Pointer(int, BaseType, Generic[T]):
72
82
 
73
83
  @classmethod
74
84
  def __default__(cls) -> Self:
75
- return cls.__new__(
76
- cls,
77
- cls.__cs__.pointer.__default__(),
78
- None,
79
- context=None,
80
- endian=cls.__cs__.endian,
81
- )
85
+ return cls.__new__(cls, cls.__cs__.pointer.__default__())
82
86
 
83
87
  @classmethod
84
88
  def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
@@ -115,9 +119,9 @@ class Pointer(int, BaseType, Generic[T]):
115
119
  except OverflowError:
116
120
  raise EOFError(f"Offset {int(self):#x} is beyond the end of the stream") from None
117
121
 
118
- if issubclass(self.__type__, Char):
119
- # This makes the assumption that a char pointer is a null-terminated string
120
- value = self.__type__._read_0(self.__stream, context=self.__context, endian=endian)
122
+ if issubclass(self.__type__, (Char, Wchar)):
123
+ # This makes the assumption that a char or wchar pointer is a null-terminated string
124
+ value = self.__type__[None]._read(self.__stream, context=self.__context, endian=endian)
121
125
  else:
122
126
  value = self.__type__._read(self.__stream, context=self.__context, endian=endian)
123
127
 
@@ -79,10 +79,13 @@ class StructureMetaType(MetaType):
79
79
  def __new__(metacls, name: str, bases: tuple[type, ...], classdict: dict[str, Any], **kwargs) -> Self: # type: ignore
80
80
  if (fields := classdict.pop("__members__", None)) is not None:
81
81
  metacls._update_fields(metacls, fields, align=classdict.get("__align__", False), classdict=classdict)
82
+ elif "__init__" in classdict or "__new__" in classdict:
83
+ # Read with type.__call__, so that the __init__ or __new__ of the subclass is called
84
+ classdict["__construct__"] = None
82
85
 
83
86
  return super().__new__(metacls, name, bases, classdict, **kwargs)
84
87
 
85
- def __call__(cls, *args, **kwargs) -> Self: # type: ignore
88
+ def __call__(cls, /, *args, **kwargs) -> Self: # type: ignore
86
89
  if len(args) == 1 and not kwargs:
87
90
  # Fast paths for the most common cases
88
91
  obj = args[0]
@@ -99,6 +102,12 @@ class StructureMetaType(MetaType):
99
102
 
100
103
  return super().__call__(*args, **kwargs)
101
104
 
105
+ def _normalize(cls, value: Any) -> Any:
106
+ if isinstance(value, (Structure, UnionProxy)):
107
+ # E.g. a structure of another type with the same fields
108
+ return value
109
+ return super()._normalize(value)
110
+
102
111
  def _update_fields(
103
112
  cls, fields: list[Field], align: bool = False, classdict: dict[str, Any] | None = None
104
113
  ) -> dict[str, Any]:
@@ -139,6 +148,7 @@ class StructureMetaType(MetaType):
139
148
  classdict["__eq__"] = Union.__eq__
140
149
  else:
141
150
  classdict["__init__"] = _generate_structure__init__(raw_lookup.values())
151
+ classdict["__construct__"] = _generate_structure__construct__(raw_lookup.keys())
142
152
  classdict["__eq__"] = _generate__eq__(field_names)
143
153
 
144
154
  classdict["__hash__"] = _generate__hash__(field_names)
@@ -294,9 +304,13 @@ class StructureMetaType(MetaType):
294
304
  # Align the stream
295
305
  stream.seek(-stream.tell() & (cls.__alignment__ - 1), io.SEEK_CUR)
296
306
 
297
- # Using type.__call__ directly calls the __init__ method of the class
298
- # This is faster than calling cls() and bypasses the metaclass __call__ method
299
- obj = type.__call__(cls, **result)
307
+ if (construct := cls.__construct__) is not None:
308
+ # This bypasses the __init__ method
309
+ obj = construct(cls, *result.values())
310
+ else:
311
+ # Using type.__call__ directly calls the __init__ method of the class
312
+ # This is faster than calling cls() and bypasses the metaclass __call__ method
313
+ obj = type.__call__(cls, **result)
300
314
  obj.__dynamic_sizes__ = sizes
301
315
  return obj
302
316
 
@@ -516,16 +530,19 @@ class Structure(BaseType, metaclass=StructureMetaType):
516
530
  """Base class for cstruct structure type classes.
517
531
 
518
532
  Note that setting attributes which do not correspond to a field in the structure results in undefined behavior.
519
- For performance reasons, the structure does not check if the field exists when writing to an attribute.
533
+ For performance reasons, the structure does not check if the field exists when writing to an attribute. It also
534
+ does not convert the value to the type of the field, unlike the values that are given on initialization.
520
535
  """
521
536
 
522
537
  __dynamic_sizes__: dict[str, int]
523
538
 
524
- def __len__(self) -> int:
525
- return len(self.dumps())
539
+ __construct__: Callable[..., Self] | None = None
540
+ """Creates an instance from the values of all fields, without calling ``__init__``."""
526
541
 
527
- def __bytes__(self) -> bytes:
528
- return self.dumps()
542
+ def __len__(self) -> int:
543
+ if self.__class__.__size__ is not None:
544
+ return self.__class__.__size__
545
+ return MetaType.write(self.__class__, io.BytesIO(), self)
529
546
 
530
547
  def __getitem__(self, item: str) -> Any:
531
548
  return getattr(self, item)
@@ -588,7 +605,7 @@ class StructureValuesProxy(MutableMapping):
588
605
  class UnionMetaType(StructureMetaType):
589
606
  """Base metaclass for cstruct union type classes."""
590
607
 
591
- def __call__(cls, *args, **kwargs) -> Self: # type: ignore
608
+ def __call__(cls, /, *args, **kwargs) -> Self: # type: ignore
592
609
  obj: Union = super().__call__(*args, **kwargs)
593
610
 
594
611
  if not hasattr(obj, "_buf"):
@@ -675,7 +692,7 @@ class UnionMetaType(StructureMetaType):
675
692
  size = stream.tell() - start
676
693
  stream.seek(start)
677
694
  buf = stream.read(size)
678
- elif "__init__" in cls.__dict__ and cls.__new__ is object.__new__:
695
+ elif _uses_generated_init(cls):
679
696
  # Fast path for static unions
680
697
  buf = stream.read(cls.__size__)
681
698
  result, sizes = cls._read_fields(io.BytesIO(buf), endian=endian)
@@ -802,10 +819,10 @@ class UnionProxy:
802
819
  object.__setattr__(self, "__target__", target)
803
820
 
804
821
  def __len__(self) -> int:
805
- return len(self.__target__.dumps())
822
+ return len(self.__target__)
806
823
 
807
824
  def __bytes__(self) -> bytes:
808
- return self.__target__.dumps()
825
+ return bytes(self.__target__)
809
826
 
810
827
  def __getitem__(self, item: str) -> Any:
811
828
  return getattr(self.__target__, item)
@@ -918,6 +935,15 @@ def attrsetter(path: str) -> Callable[[Any], Any]:
918
935
  return _func
919
936
 
920
937
 
938
+ def _uses_generated_init(type_: type[Structure]) -> bool:
939
+ """Return whether a structure type uses a generated ``__init__``, so we can bypass it by setting attributes.
940
+
941
+ The generated ``__init__`` is set together with ``__fields__``, so a subclass with only its own ``__init__``
942
+ doesn't count.
943
+ """
944
+ return "__fields__" in type_.__dict__ and type_.__new__ is object.__new__
945
+
946
+
921
947
  def _codegen(func: FunctionType) -> FunctionType:
922
948
  """Decorator that generates a template function with a specified number of fields.
923
949
 
@@ -955,14 +981,31 @@ def _make_structure__init__(fields: list[str]) -> str:
955
981
  fields: List of field names.
956
982
  """
957
983
  field_args = ", ".join(f"{field} = None" for field in fields)
984
+ # Fast path for values that already have the type of the field
958
985
  field_init = "\n".join(
959
- f" self.{name} = {name} if {name} is not None else _{i}_default()" for i, name in enumerate(fields)
986
+ f" self.{name} = _{i}_default() if {name} is None"
987
+ f" else {name} if type({name}) is _{i}_type else _{i}_normalize({name})"
988
+ for i, name in enumerate(fields)
960
989
  )
961
990
 
962
- code = f"def __init__(self{', ' + field_args or ''}):\n"
991
+ code = f"def __init__(self, /{', ' + field_args or ''}):\n"
963
992
  return code + (field_init or " pass")
964
993
 
965
994
 
995
+ @_codegen
996
+ def _make_structure__construct__(fields: list[str]) -> str:
997
+ """Generates a ``__construct__`` function for a structure with the specified fields.
998
+
999
+ Args:
1000
+ fields: List of field names.
1001
+ """
1002
+ field_args = "".join(f", {field}" for field in fields)
1003
+ field_init = "".join(f" self.{name} = {name}\n" for name in fields)
1004
+
1005
+ code = f"def __construct__(cls{field_args}):\n self = object.__new__(cls)\n"
1006
+ return code + field_init + " return self"
1007
+
1008
+
966
1009
  @_codegen
967
1010
  def _make_union__init__(fields: list[str]) -> str:
968
1011
  """Generates an ``__init__`` method for a class with the specified fields using setattr.
@@ -972,11 +1015,12 @@ def _make_union__init__(fields: list[str]) -> str:
972
1015
  """
973
1016
  field_args = ", ".join(f"{field} = None" for field in fields)
974
1017
  field_init = "\n".join(
975
- f" object.__setattr__(self, '{name}', {name} if {name} is not None else _{i}_default())"
1018
+ f" object.__setattr__(self, '{name}', _{i}_default() if {name} is None"
1019
+ f" else {name} if type({name}) is _{i}_type else _{i}_normalize({name}))"
976
1020
  for i, name in enumerate(fields)
977
1021
  )
978
1022
 
979
- code = f"def __init__(self{', ' + field_args or ''}):\n"
1023
+ code = f"def __init__(self, /{', ' + field_args or ''}):\n"
980
1024
  return code + (field_init or " pass")
981
1025
 
982
1026
 
@@ -1068,11 +1112,20 @@ def _generate_structure__init__(fields: list[Field]) -> FunctionType:
1068
1112
  co_names=_remap_co_values(template.__code__.co_names, mapping),
1069
1113
  co_varnames=_remap_co_values(template.__code__.co_varnames, mapping),
1070
1114
  ),
1071
- template.__globals__ | {f"__{field._name}_default__": _default_factory(field.type) for field in fields},
1115
+ template.__globals__ | _generate__init__globals(fields),
1072
1116
  argdefs=template.__defaults__,
1073
1117
  )
1074
1118
 
1075
1119
 
1120
+ def _generate_structure__construct__(fields: list[str]) -> FunctionType:
1121
+ """Generates a ``__construct__`` function for a structure with the specified fields.
1122
+
1123
+ Args:
1124
+ fields: List of field names.
1125
+ """
1126
+ return _patch_attributes(_make_structure__construct__(len(fields)), fields, 2)
1127
+
1128
+
1076
1129
  def _generate_union__init__(fields: list[Field]) -> FunctionType:
1077
1130
  """Generates an ``__init__`` method for a union with the specified fields.
1078
1131
 
@@ -1088,11 +1141,35 @@ def _generate_union__init__(fields: list[Field]) -> FunctionType:
1088
1141
  co_names=_remap_co_values(template.__code__.co_names, mapping),
1089
1142
  co_varnames=_remap_co_values(template.__code__.co_varnames, mapping),
1090
1143
  ),
1091
- template.__globals__ | {f"__{field._name}_default__": _default_factory(field.type) for field in fields},
1144
+ template.__globals__ | _generate__init__globals(fields),
1092
1145
  argdefs=template.__defaults__,
1093
1146
  )
1094
1147
 
1095
1148
 
1149
+ def _generate__init__globals(fields: list[Field]) -> dict[str, Any]:
1150
+ """Generates the default factories, types and conversion functions of fields for an ``__init__`` method.
1151
+
1152
+ The generated code uses the names ``_0_default``, ``_0_type`` and ``_0_normalize`` for the first field, etc.
1153
+
1154
+ Args:
1155
+ fields: List of fields.
1156
+ """
1157
+ result = {}
1158
+ for i, field in enumerate(fields):
1159
+ type_ = _value_type(field)
1160
+ result[f"_{i}_default"] = _default_factory(type_)
1161
+ result[f"_{i}_type"] = type_
1162
+ result[f"_{i}_normalize"] = type_._normalize
1163
+ return result
1164
+
1165
+
1166
+ def _value_type(field: Field) -> type[BaseType]:
1167
+ """Return the type of the values of a field, which is ``uint8`` for character bit fields."""
1168
+ if field.bits and issubclass(field.type, Char):
1169
+ return field.type.__cs__.uint8
1170
+ return field.type
1171
+
1172
+
1096
1173
  def _default_factory(type_: type[BaseType]) -> Callable[[], Any]:
1097
1174
  """Return a function that returns default values of a type, which are only shared if they're immutable."""
1098
1175
  value = type_.__default__()
@@ -1102,17 +1179,18 @@ def _default_factory(type_: type[BaseType]) -> Callable[[], Any]:
1102
1179
  def _generate_co_mapping(fields: list[Field]) -> dict[str, str]:
1103
1180
  """Generates a mapping of generated code object names to field names.
1104
1181
 
1105
- The generated code uses names like ``_0``, ``_1``, etc. for fields, and ``_0_default``, ``_1_default``, etc.
1106
- for default initializer values. Return a mapping of these names to the actual field names.
1182
+ The generated code uses names like ``_0``, ``_1``, etc. for fields. Return a mapping of these names to the actual
1183
+ field names, and of ``self`` to a name that no field has.
1107
1184
 
1108
1185
  Args:
1109
1186
  fields: List of field names.
1110
1187
  """
1111
- return {
1112
- key: value
1113
- for i, field in enumerate(fields)
1114
- for key, value in [(f"_{i}", field._name), (f"_{i}_default", f"__{field._name}_default__")]
1115
- }
1188
+ # Fields can be named self, so prefix until there's no longer a clash
1189
+ instance = "self"
1190
+ while any(field._name == instance for field in fields):
1191
+ instance = f"_{instance}"
1192
+
1193
+ return {"self": instance} | {f"_{i}": field._name for i, field in enumerate(fields)}
1116
1194
 
1117
1195
 
1118
1196
  def _remap_co_values(value: tuple[Any, ...], mapping: dict[str, str]) -> tuple[Any, ...]:
@@ -17,6 +17,10 @@ class VoidArray(list, BaseArray):
17
17
  def __default__(cls) -> Self:
18
18
  return cls()
19
19
 
20
+ @classmethod
21
+ def _normalize(cls, value: Any) -> Any:
22
+ return value
23
+
20
24
  @classmethod
21
25
  def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
22
26
  return cls()
@@ -37,6 +41,11 @@ class Void(BaseType):
37
41
  def __eq__(self, value: object) -> bool:
38
42
  return isinstance(value, Void)
39
43
 
44
+ @classmethod
45
+ def _normalize(cls, value: Any) -> Any:
46
+ # The value of a void field doesn't matter
47
+ return value
48
+
40
49
  @classmethod
41
50
  def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
42
51
  return cls.__new__(cls)