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,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.dev24
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
@@ -0,0 +1,32 @@
1
+ dissect/cstruct/__init__.py,sha256=6WCBCk9iTJiKjzfkYCZAwWkIh3FnxEuCe_y2TSUJ2bU,1905
2
+ dissect/cstruct/bitbuffer.py,sha256=9s7xZAwcLTLG_ZdBKSEseO1NR7NM-WZjaKzxoroFo7c,3066
3
+ dissect/cstruct/compiler.py,sha256=ztNEdgDDNO51qs0qLggMkNZcBTe30zhzAkDMit78_44,55605
4
+ dissect/cstruct/cstruct.py,sha256=PLGbkE01Hse9ODAoxGkrcuKo7_vMHDBJ8QvL52MD_mM,29432
5
+ dissect/cstruct/declarative.py,sha256=8yyQeP22BoZh6Gy3TASQ1HrVkecMNb3BVKj7oBdb0QU,14714
6
+ dissect/cstruct/dump.py,sha256=qlQydCynnG9JSrhEfcSlE-6wmon8hvD2Pw2ndz9sWFw,19015
7
+ dissect/cstruct/exception.py,sha256=8b_nLXacWGdQ3BhZN-DOOEr4gp5Vacni6etwDKqYHis,988
8
+ dissect/cstruct/expression.py,sha256=HMDKuZmPElZF88dC6FdEpUO_yUTCSw-WU7wI_XsgYEY,13592
9
+ dissect/cstruct/lexer.py,sha256=INbr9yEVua43VvPmmnWUy392jLgTeLv2-k2M22Pe1zE,20838
10
+ dissect/cstruct/parser.py,sha256=9e1R027YqZw3mhAEORdEzdAUWcifNR3youChwJ_momU,24610
11
+ dissect/cstruct/util.py,sha256=-qBoVSK_uwJ_tFt7bELS-EtipFQ6ebkRZBHAD3iYy5Q,9099
12
+ dissect/cstruct/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ dissect/cstruct/tools/stubgen.py,sha256=dRv2DBT1r6V6ZBTzsGeJeFuEjc7vbX4i3wnb4MkcWEE,7884
14
+ dissect/cstruct/types/__init__.py,sha256=6P71Pu94Dv7RNjZpDZ19pqzx-G0QzmQw4q0-3zWALso,911
15
+ dissect/cstruct/types/base.py,sha256=r0coM74Istu5vqOyPHKIOtyiyo_QmKw1nd293bNxLa8,24162
16
+ dissect/cstruct/types/char.py,sha256=Xq9Jg6ITod9EgXGLN93TJ_V76VeatX_iYp2JrPlf0tc,7708
17
+ dissect/cstruct/types/enum.py,sha256=dDqG-mRxikRan5e2phL5OCOCWe-8J6gn-kmHlrto8q4,9206
18
+ dissect/cstruct/types/flag.py,sha256=YxQHix8ZhK1qQX3J_Og7GJp_4JAxCwzUbUibuJeDaWQ,3479
19
+ dissect/cstruct/types/int.py,sha256=JjiMQs0ZFLiVsEITUA8gn25YEbn3g09uGG9Yl0Naux0,2842
20
+ dissect/cstruct/types/leb128.py,sha256=WJ7FQXRsmsdDZJWm2lOe3SEkEJqXfQTIFYpmOajXv0s,2835
21
+ dissect/cstruct/types/packed.py,sha256=5kfIdBKTD664hT1wyjSDkMRmcNnk_g8JJNf5Gj2ikAc,4721
22
+ dissect/cstruct/types/pointer.py,sha256=lEWSTJMN-hbzddhtHXIUAxhKfiygRSMWNAMNU59ivuk,4437
23
+ dissect/cstruct/types/structure.py,sha256=d7H4GfAGPcm4VZR-FemGhjxhP_mURZUiPn3StA29-3k,46859
24
+ dissect/cstruct/types/void.py,sha256=Cgw_Y5Jg3YlO4rdA6F6mhN-FeWf0Sb-Kv3Po_h-Inz4,1439
25
+ dissect/cstruct/types/wchar.py,sha256=76-6Irt__4oQRtDD_iFtZQRjfdg6k40c51JA4KxoiVE,7588
26
+ dissect_cstruct-5.0.dev26.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
27
+ dissect_cstruct-5.0.dev26.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
28
+ dissect_cstruct-5.0.dev26.dist-info/METADATA,sha256=RfpkMA8_W1LEF-tLqM7v0Cq7Kp3LJaqG0J4itjdJPjA,14005
29
+ dissect_cstruct-5.0.dev26.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
+ dissect_cstruct-5.0.dev26.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
31
+ dissect_cstruct-5.0.dev26.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
32
+ dissect_cstruct-5.0.dev26.dist-info/RECORD,,
@@ -1,32 +0,0 @@
1
- dissect/cstruct/__init__.py,sha256=6WCBCk9iTJiKjzfkYCZAwWkIh3FnxEuCe_y2TSUJ2bU,1905
2
- dissect/cstruct/bitbuffer.py,sha256=FpvyoDuio0hLfUtyqb2OUg1SpDVnblxMVNtAbYLPzVk,2781
3
- dissect/cstruct/compiler.py,sha256=6mK2CdUnfWdQIu0_1qIL1NCaaqlv5eJcvlamMsGfEAg,54781
4
- dissect/cstruct/cstruct.py,sha256=quHzIZoM6ADQrfrMPsQ-QzxJ-9D2glYHWwSQXn7cysM,27645
5
- dissect/cstruct/declarative.py,sha256=GPU208IsslegjFug9udduu-6fhmV2CIfIf6oY76ycEw,14571
6
- dissect/cstruct/dump.py,sha256=W5ISbaZ-1YmWXKzh-x6pDt5_SlpFRDhD9GGNyv1MnLw,19016
7
- dissect/cstruct/exception.py,sha256=8b_nLXacWGdQ3BhZN-DOOEr4gp5Vacni6etwDKqYHis,988
8
- dissect/cstruct/expression.py,sha256=HMDKuZmPElZF88dC6FdEpUO_yUTCSw-WU7wI_XsgYEY,13592
9
- dissect/cstruct/lexer.py,sha256=INbr9yEVua43VvPmmnWUy392jLgTeLv2-k2M22Pe1zE,20838
10
- dissect/cstruct/parser.py,sha256=9e1R027YqZw3mhAEORdEzdAUWcifNR3youChwJ_momU,24610
11
- dissect/cstruct/util.py,sha256=-qBoVSK_uwJ_tFt7bELS-EtipFQ6ebkRZBHAD3iYy5Q,9099
12
- dissect/cstruct/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
- dissect/cstruct/tools/stubgen.py,sha256=MeZkLmSeNSLNcAEwlAdIGv1lKvlvK3UQ4WN85ovsxTM,7672
14
- dissect/cstruct/types/__init__.py,sha256=6P71Pu94Dv7RNjZpDZ19pqzx-G0QzmQw4q0-3zWALso,911
15
- dissect/cstruct/types/base.py,sha256=tMwLBArs-lsrjr-gyGP4oRKivhF9PFZER8mC92WsFAc,19292
16
- dissect/cstruct/types/char.py,sha256=CA9-xVA2UbwV3CnfjYOrCIl-Y41QjhJVU4VFn2ZXe3s,3543
17
- dissect/cstruct/types/enum.py,sha256=H67ACZM3svwySAW4IgstcnqeuGCzmuKIL2IbQV3RgSk,9089
18
- dissect/cstruct/types/flag.py,sha256=YxQHix8ZhK1qQX3J_Og7GJp_4JAxCwzUbUibuJeDaWQ,3479
19
- dissect/cstruct/types/int.py,sha256=DBTpQjF6R2zEy0ItXPfO5OHTUwaJqEMTOu7kxuzMGho,2615
20
- dissect/cstruct/types/leb128.py,sha256=WJ7FQXRsmsdDZJWm2lOe3SEkEJqXfQTIFYpmOajXv0s,2835
21
- dissect/cstruct/types/packed.py,sha256=sLMrUjRLzlTR4FzRLsPnnAJANhunhUBzbvcMRnGe94A,4181
22
- dissect/cstruct/types/pointer.py,sha256=pIxiDGosRu1jhchdcA3Zm7yIXkPUh2UKnIt8kxUygf0,4138
23
- dissect/cstruct/types/structure.py,sha256=T28ZncDWG2QtkQcpKNwfpNmk5_77IgW0idDxHINzcFY,43638
24
- dissect/cstruct/types/void.py,sha256=fV4hKk50uop_EKbR1nfy1cdtAzvUYrSymXsdakCyFk8,1222
25
- dissect/cstruct/types/wchar.py,sha256=eJyOWdT8Y3k8gM9QNE0NeXBwcAGRcp4aUkIBezAYe0c,4225
26
- dissect_cstruct-5.0.dev24.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
27
- dissect_cstruct-5.0.dev24.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
28
- dissect_cstruct-5.0.dev24.dist-info/METADATA,sha256=TwINfkCJixnZO2mCLvYnMw5DvUJxNIOfdIbf4o7wMeI,12661
29
- dissect_cstruct-5.0.dev24.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
- dissect_cstruct-5.0.dev24.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
31
- dissect_cstruct-5.0.dev24.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
32
- dissect_cstruct-5.0.dev24.dist-info/RECORD,,