dissect.cstruct 5.0.dev25__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.
@@ -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)
@@ -1,27 +1,102 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import sys
4
+ from io import BytesIO
4
5
  from typing import TYPE_CHECKING, Any, BinaryIO, ClassVar
5
6
 
6
7
  from dissect.cstruct.exception import EOFError, WriteError
7
- from dissect.cstruct.types.base import EOF, BaseArray, BaseType, _is_seekable, _read_null_terminated
8
+ from dissect.cstruct.types.base import (
9
+ _BUFFER_TYPES,
10
+ EOF,
11
+ BaseArray,
12
+ BaseType,
13
+ MetaType,
14
+ _is_seekable,
15
+ _read_null_terminated,
16
+ )
8
17
 
9
18
  if TYPE_CHECKING:
19
+ from typing_extensions import Self
20
+
10
21
  from dissect.cstruct.cstruct import Endianness
11
22
 
12
23
 
13
- class WcharArray(str, BaseArray):
24
+ class WcharMetaType(MetaType):
25
+ """Metaclass for wide-character and wide-character array types."""
26
+
27
+ def __call__(cls, *args, **kwargs) -> Wchar | WcharArray:
28
+ if len(args) == 1 and not kwargs:
29
+ # Handle a few fast path cases
30
+ obj = args[0]
31
+ if isinstance(obj, str):
32
+ # Fast path for a string of exactly the number of entries, in which a surrogate pair takes up two
33
+ if len(obj) * 2 == cls.__size__ and (obj.isascii() or _wchar_count(obj) == len(obj)):
34
+ # E.g. wchar[2]("ab")
35
+ return str.__new__(cls, obj)
36
+
37
+ # E.g. wchar[4]("ab")
38
+ # WcharArray.__new__ adds any necessary padding
39
+ return cls.__new__(cls, obj)
40
+
41
+ if isinstance(obj, _BUFFER_TYPES):
42
+ # E.g. wchar[2](b"a\x00b\x00")
43
+ return cls._read(BytesIO(obj), endian=cls.__cs__.endian)
44
+
45
+ if hasattr(obj, "read") and not isinstance(obj, cls):
46
+ # E.g. wchar[2](fh)
47
+ return cls._read(obj, endian=cls.__cs__.endian)
48
+
49
+ # E.g. wchar(65)
50
+ return cls.__new__(cls, obj)
51
+
52
+ if not args and not kwargs:
53
+ # Default value
54
+ # E.g. wchar[4]()
55
+ return cls.__default__()
56
+
57
+ # Everything else
58
+ # E.g. wchar[2](b"a\x00b\x00", endian=">")
59
+ return MetaType.__call__(cls, *args, **kwargs)
60
+
61
+
62
+ def _wchar_count(value: str) -> int:
63
+ """Return the number of ``wchar`` entries that a string takes up, in which a surrogate pair takes up two."""
64
+ # An ASCII string has no surrogate pairs, so it doesn't have to be encoded to count them
65
+ # CPython encodes "utf-16" without looking up the codec, but adds a byte order mark of 2 bytes
66
+ return len(value) if value.isascii() else len(value.encode("utf-16", "surrogatepass")) // 2 - 1
67
+
68
+
69
+ class WcharArray(str, BaseArray, metaclass=WcharMetaType):
14
70
  """Wide-character array type for reading and writing UTF-16 strings."""
15
71
 
16
72
  __slots__ = ()
17
73
 
74
+ def __new__(cls, value: str) -> Self:
75
+ if not isinstance(value, str):
76
+ raise TypeError(f"Cannot create {cls.__name__} from {type(value).__name__}")
77
+
78
+ # A surrogate pair is a single character that takes up two entries of the array
79
+ if not cls.__dynamic__ and (remaining := cls.__num_entries__ - (actual_size := _wchar_count(value))):
80
+ if remaining < 0:
81
+ raise ValueError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
82
+ value += "\x00" * remaining
83
+
84
+ return str.__new__(cls, value)
85
+
86
+ def __bytes__(self) -> bytes:
87
+ # The byte representation of a null-terminated array doesn't include the null terminator.
88
+ if self.__null_terminated__:
89
+ return self.encode(Wchar.__encoding_map__[self.__cs__.endian], "surrogatepass")
90
+
91
+ return MetaType.dumps(self.__class__, self)
92
+
18
93
  @classmethod
19
94
  def __default__(cls) -> WcharArray:
20
- return type.__call__(cls, "\x00" * (0 if cls.__dynamic__ or cls.__null_terminated__ else cls.__num_entries__))
95
+ return str.__new__(cls, "\x00" * (0 if cls.__dynamic__ or cls.__null_terminated__ else cls.__num_entries__))
21
96
 
22
97
  @classmethod
23
98
  def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> WcharArray:
24
- return type.__call__(cls, super()._read(stream, context=context, endian=endian))
99
+ return str.__new__(cls, super()._read(stream, context=context, endian=endian))
25
100
 
26
101
  @classmethod
27
102
  def _write(cls, stream: BinaryIO, data: str, *, endian: Endianness) -> int:
@@ -39,7 +114,7 @@ class WcharArray(str, BaseArray):
39
114
  return stream.write(buf)
40
115
 
41
116
 
42
- class Wchar(str, BaseType):
117
+ class Wchar(str, BaseType, metaclass=WcharMetaType):
43
118
  """Wide-character type for reading and writing UTF-16 characters."""
44
119
 
45
120
  __ArrayType__ = WcharArray
@@ -54,20 +129,30 @@ class Wchar(str, BaseType):
54
129
  "!": "utf-16-be",
55
130
  }
56
131
 
132
+ def __new__(cls, value: str) -> Self:
133
+ if not isinstance(value, str):
134
+ raise TypeError(f"Cannot create {cls.__name__} from {type(value).__name__}")
135
+
136
+ # A surrogate pair is a single character that doesn't fit in a single wchar
137
+ if (actual_size := _wchar_count(value)) > 1:
138
+ raise ValueError(f"Expected a single character, got {actual_size} instead.")
139
+
140
+ return str.__new__(cls, value) if value else cls.__default__()
141
+
57
142
  @classmethod
58
143
  def __default__(cls) -> Wchar:
59
- return type.__call__(cls, "\x00")
144
+ return str.__new__(cls, "\x00")
60
145
 
61
146
  @classmethod
62
147
  def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Wchar:
63
- return cls._read_array(stream, 1, context=context, endian=endian)
148
+ return str.__new__(cls, cls._read_array(stream, 1, context=context, endian=endian))
64
149
 
65
150
  @classmethod
66
151
  def _read_array(
67
152
  cls, stream: BinaryIO, count: int, *, context: dict[str, Any] | None = None, endian: Endianness
68
- ) -> Wchar:
153
+ ) -> str:
69
154
  if count == 0:
70
- return type.__call__(cls, "")
155
+ return ""
71
156
 
72
157
  if count == EOF:
73
158
  data = stream.read()
@@ -84,13 +169,13 @@ class Wchar(str, BaseType):
84
169
  if len(data) != length:
85
170
  raise EOFError(f"Read {len(data)} bytes, but expected {length}")
86
171
 
87
- return type.__call__(cls, str(data, cls.__encoding_map__[endian], "surrogatepass"))
172
+ return str(data, cls.__encoding_map__[endian], "surrogatepass")
88
173
 
89
174
  @classmethod
90
- def _read_0(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Wchar:
175
+ def _read_0(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> str:
91
176
  if _is_seekable(stream):
92
177
  data = _read_null_terminated(stream, 2)
93
- return type.__call__(cls, data.decode(cls.__encoding_map__[endian], "surrogatepass"))
178
+ return data.decode(cls.__encoding_map__[endian], "surrogatepass")
94
179
 
95
180
  buf = []
96
181
  while True:
@@ -103,7 +188,7 @@ class Wchar(str, BaseType):
103
188
 
104
189
  buf.append(point)
105
190
 
106
- return type.__call__(cls, b"".join(buf).decode(cls.__encoding_map__[endian], "surrogatepass"))
191
+ return b"".join(buf).decode(cls.__encoding_map__[endian], "surrogatepass")
107
192
 
108
193
  @classmethod
109
194
  def _write(cls, stream: BinaryIO, data: str, *, endian: Endianness) -> int:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev25
3
+ Version: 5.0.dev26
4
4
  Summary: A Dissect module implementing a parser for C-like structures: structure parsing in Python made easy
5
5
  Author-email: Dissect Team <dissect@fox-it.com>
6
6
  License-Expression: Apache-2.0
@@ -118,14 +118,13 @@ assert c_parser.Example.A == 0
118
118
  assert c_parser.Example.C == 6
119
119
  assert c_parser.Example(5) == c_parser.Example.B
120
120
 
121
- assert result.dumps() == data
121
+ assert bytes(result) == data
122
122
 
123
123
  # You can also instantiate structures from Python by using kwargs
124
- # Note that array sizes are not enforced
125
124
  instance = c_parser.some_struct(
126
- field_1=5, field_2="lorem", field_3="ipsum", field_4=[c_parser.Example.B, c_parser.Example.A]
125
+ field_1=5, field_2=b"lorem", field_3=b"ipsum", field_4=[c_parser.Example.B, c_parser.Example.A]
127
126
  )
128
- assert instance.dumps() == b"\x05loremipsum\x05\x00\x00\x00"
127
+ assert bytes(instance) == b"\x05loremipsum\x05\x00\x00\x00"
129
128
 
130
129
  ```
131
130
 
@@ -160,7 +159,7 @@ header = Header(data)
160
159
  assert header.data == b"KUSJESVANSRT"
161
160
  assert header.flags == 5
162
161
  assert header.trailer == b"<3"
163
- assert header.dumps() == data
162
+ assert bytes(header) == data
164
163
 
165
164
  cs = cstruct(endian=">")
166
165
 
@@ -205,6 +204,40 @@ assert cs.uint24[2](b"\x01\x00\x00\x02\x00\x00") == [1, 2] # You can also parse
205
204
  assert cs.char[None](b"hello world!\x00") == b"hello world!" # A list index of None means null terminated
206
205
  ```
207
206
 
207
+ ### Creating values
208
+ A type creates a value like its Python base type does, e.g. `int` for `uint32` and `list` for arrays. Bytes-like and file-like objects are parsed instead.
209
+
210
+ ```python
211
+ from dissect.cstruct import cstruct
212
+
213
+ cs = cstruct()
214
+ assert cs.uint32("5") == 5 # Like int("5")
215
+ assert cs.uint32(b"\x05\x00\x00\x00") == 5 # Parsed
216
+ assert cs.uint8[4]([1, 2]) == [1, 2, 0, 0] # Padded to the number of entries
217
+ ```
218
+
219
+ Some types don't accept all the values of their Python base type:
220
+ - `char` and `char` arrays don't accept a `str`, encode it to bytes first. An `int` gives a single character, e.g. `cs.char(0x41)` is `b"A"`.
221
+ - `wchar` and `wchar` arrays only accept a `str`.
222
+ - Other arrays don't accept a `str` or an `int`.
223
+
224
+ A structure or union converts the values of its fields in the same way. A `char` field takes bytes as its value, and a structure field keeps a structure as it is. More bytes than a field needs raise a `ValueError`. Values that are set as attributes aren't converted for performance reasons.
225
+
226
+ ```python
227
+ cs.load("""
228
+ struct example {
229
+ uint16 values[2];
230
+ char name[4];
231
+ };
232
+ """)
233
+
234
+ obj = cs.example(values=b"\x01\x00\x02\x00", name=b"ab")
235
+ assert obj.values == [1, 2] # Parsed
236
+ assert obj.name == b"ab\x00\x00" # Padded
237
+ ```
238
+
239
+ Writing doesn't convert values. E.g. `cs.uint8[2].dumps(b"\x01\x02")` raises a `WriteError`. Use `cs.uint8[2].dumps([1, 2])` instead.
240
+
208
241
  ### Unions and nested structures
209
242
  Unions and nested structures are supported, both anonymous and named.
210
243
 
@@ -248,7 +281,7 @@ assert a.c.a.a == 0x64616564
248
281
  assert a.c.a.b == 0x66656562
249
282
  assert a.c.b.b == b"deadbeef"
250
283
 
251
- assert a.dumps() == b"ohaideadbeef"
284
+ assert bytes(a) == b"ohaideadbeef"
252
285
 
253
286
  b = c.test_anonymous(b"ohai\x39\x05\x00\x00\x28\x23\x00\x00deadbeef")
254
287
  assert b.magic == b"ohai"
@@ -283,7 +316,7 @@ assert a.b == 0b1
283
316
  assert a.c == 0xFF
284
317
  assert a.d == 0b11
285
318
  assert a.e == 0b111
286
- assert a.dumps() == d
319
+ assert bytes(a) == d
287
320
  ```
288
321
 
289
322
  ### Enums and Flags