dissect.cstruct 5.0.dev25__tar.gz → 5.0.dev26__tar.gz
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-5.0.dev25 → dissect_cstruct-5.0.dev26}/CHANGELOG.md +20 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/PKG-INFO +41 -8
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/README.md +40 -7
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/bitbuffer.py +8 -1
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/compiler.py +39 -17
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/dump.py +1 -1
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/tools/stubgen.py +9 -2
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/base.py +125 -17
- dissect_cstruct-5.0.dev26/dissect/cstruct/types/char.py +210 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/enum.py +2 -1
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/int.py +7 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/packed.py +18 -1
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/pointer.py +16 -12
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/structure.py +104 -26
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/void.py +9 -0
- dissect_cstruct-5.0.dev26/dissect/cstruct/types/wchar.py +201 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/PKG-INFO +41 -8
- dissect_cstruct-5.0.dev26/dissect.cstruct.egg-info/scm_version.json +8 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/examples/protobuf.py +1 -1
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_align.py +13 -13
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_annotations.py +1 -1
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_basic.py +39 -23
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_benchmark.py +1 -1
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_bitfield.py +25 -36
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_compiler.py +30 -26
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_declarative.py +3 -3
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_expression.py +16 -15
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_tools_stubgen.py +39 -18
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_types_base.py +152 -16
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_types_char.py +100 -38
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_types_custom.py +6 -3
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_types_enum.py +17 -17
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_types_flag.py +8 -7
- dissect_cstruct-5.0.dev26/tests/test_types_int.py +324 -0
- dissect_cstruct-5.0.dev26/tests/test_types_leb128.py +134 -0
- dissect_cstruct-5.0.dev26/tests/test_types_packed.py +219 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_types_pointer.py +40 -18
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_types_structure.py +353 -63
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_types_union.py +74 -41
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_types_void.py +6 -6
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_types_wchar.py +106 -55
- dissect_cstruct-5.0.dev26/tests/test_util.py +171 -0
- dissect_cstruct-5.0.dev25/dissect/cstruct/types/char.py +0 -103
- dissect_cstruct-5.0.dev25/dissect/cstruct/types/wchar.py +0 -116
- dissect_cstruct-5.0.dev25/dissect.cstruct.egg-info/scm_version.json +0 -8
- dissect_cstruct-5.0.dev25/tests/test_types_int.py +0 -452
- dissect_cstruct-5.0.dev25/tests/test_types_leb128.py +0 -205
- dissect_cstruct-5.0.dev25/tests/test_types_packed.py +0 -276
- dissect_cstruct-5.0.dev25/tests/test_util.py +0 -157
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/.git-blame-ignore-revs +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/.gitattributes +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/COPYRIGHT +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/LICENSE +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/MANIFEST.in +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/__init__.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/cstruct.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/declarative.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/exception.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/expression.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/lexer.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/parser.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/tools/__init__.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/__init__.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/flag.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/leb128.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect/cstruct/util.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/SOURCES.txt +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/dependency_links.txt +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/entry_points.txt +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/requires.txt +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/scm_file_list.json +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/top_level.txt +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/examples/disk.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/examples/mirai.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/examples/pe.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/examples/secdesc.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/pyproject.toml +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/setup.cfg +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/__init__.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/_data/testdef.txt +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/_docs/Makefile +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/_docs/__init__.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/_docs/conf.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/_docs/index.rst +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/conftest.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_bitbuffer.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_ctypes.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_dump.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_exception.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_lexer.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/test_parser.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tests/util.py +0 -0
- {dissect_cstruct-5.0.dev25 → dissect_cstruct-5.0.dev26}/tox.ini +0 -0
|
@@ -45,6 +45,25 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
45
45
|
- Errors that `load` raises include the line of the definition.
|
|
46
46
|
- `ArraySizeError` is removed. A value that is longer than its static array raises a `WriteError`.
|
|
47
47
|
- `write()` raises a `TypeError` for an object that can't be written to, like `read()` does.
|
|
48
|
+
- `bytes(obj)` works on instances of all types. It gives the byte representation of the value.
|
|
49
|
+
- For null-terminated arrays, it does not include the null terminator. Use `cls.dumps(obj)` to include the null terminator.
|
|
50
|
+
- For integer types, `bytearray(obj)` gives as many zero bytes as its value, e.g. `bytearray(cs.uint32(5))` gives 5 zero bytes. Use `bytearray(bytes(obj))` instead.
|
|
51
|
+
- `char` and `char` arrays no longer accept a string, when they're created or written. Encode the string to bytes first.
|
|
52
|
+
- Writing doesn't convert values anymore (e.g. `type.write(stream, value)`, or manually setting an attribute on a structure instance): a `char` doesn't accept an int, and `uint8` arrays don't accept bytes. Convert the value first, e.g. `cs.char(0x41)` or `cs.uint8[2](b"\x01\x02")`, or pass it as an argument when the structure is created.
|
|
53
|
+
- Creating a `char`, a `wchar` or an array from a value instead of from data:
|
|
54
|
+
- An int creates a `char` with that byte, e.g. `cs.char(0x41)` is `b"A"`.
|
|
55
|
+
- Arrays of all types with a fixed number of entries add default entries to a value with fewer entries, e.g. `cs.char[4]([0x41])` is `b"A\x00\x00\x00"`, `cs.wchar[4]("A")` is `"A\x00\x00\x00"` and `cs.uint8[4]([1])` and `cs.uleb128[4]([1])` are `[1, 0, 0, 0]`.
|
|
56
|
+
- A value with more entries than the array, or more than one character for a `char` or `wchar`, raises a `ValueError`.
|
|
57
|
+
- Without a value, the result is the default value, e.g. `cs.char()` is `b"\x00"` and `cs.uint8[4]()` is `[0, 0, 0, 0]`.
|
|
58
|
+
- `TypeError` is raised for unsupported values.
|
|
59
|
+
- On Python 3.12 and newer, instances of all types support the buffer protocol, so that e.g. `fh.write(obj)` works.
|
|
60
|
+
- Values that are given when a structure or union is created are converted to the types of their fields, like the type does. E.g. in `struct test { uint16 values[2]; }`, `cs.test(values=[1, 2]).values` is a `uint16[2]` and `cs.test(values=b"\x01\x00\x02\x00").values` is `[1, 2]`.
|
|
61
|
+
- More bytes than a field needs raise a `ValueError`, e.g. `cs.test(values=b"\x01\x00\x02\x00\x03\x00")`.
|
|
62
|
+
- Values that are set as attributes aren't converted, e.g. `cs.test().values = [1, 2]`. For performance reasons this is impractical.
|
|
63
|
+
|
|
64
|
+
### Deprecated
|
|
65
|
+
|
|
66
|
+
- `obj.dumps()` and `obj.write(fh)` on instances. Use `cls.dumps(obj)` and `cls.write(fh, obj)` instead.
|
|
48
67
|
|
|
49
68
|
### Fixed
|
|
50
69
|
|
|
@@ -64,6 +83,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
64
83
|
- An `Expression` is parsed when it's created. An invalid array size that refers to a field, e.g. `char a[n +]`, raises a `ParserError` during `load`, instead of an `ExpressionParserError` on every read.
|
|
65
84
|
- `offsetof` gives the offsets of C for the fields of a union and the fields of an anonymous nested structure or union, instead of an error or the offset in the nested type.
|
|
66
85
|
- An empty expression raises "not enough operands" instead of "too many operands".
|
|
86
|
+
- Writing an array with a fixed number of entries of a dynamic size, e.g. `uleb128 a[4]` or an array of structures with a dynamic size, pads it to its number of entries or raises a `WriteError` if it's too long, instead of writing as many entries as the value has.
|
|
67
87
|
|
|
68
88
|
## [4.5] - 20-05-2025
|
|
69
89
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: dissect.cstruct
|
|
3
|
-
Version: 5.0.
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
319
|
+
assert bytes(a) == d
|
|
287
320
|
```
|
|
288
321
|
|
|
289
322
|
### Enums and Flags
|
|
@@ -90,14 +90,13 @@ assert c_parser.Example.A == 0
|
|
|
90
90
|
assert c_parser.Example.C == 6
|
|
91
91
|
assert c_parser.Example(5) == c_parser.Example.B
|
|
92
92
|
|
|
93
|
-
assert result
|
|
93
|
+
assert bytes(result) == data
|
|
94
94
|
|
|
95
95
|
# You can also instantiate structures from Python by using kwargs
|
|
96
|
-
# Note that array sizes are not enforced
|
|
97
96
|
instance = c_parser.some_struct(
|
|
98
|
-
field_1=5, field_2="lorem", field_3="ipsum", field_4=[c_parser.Example.B, c_parser.Example.A]
|
|
97
|
+
field_1=5, field_2=b"lorem", field_3=b"ipsum", field_4=[c_parser.Example.B, c_parser.Example.A]
|
|
99
98
|
)
|
|
100
|
-
assert instance
|
|
99
|
+
assert bytes(instance) == b"\x05loremipsum\x05\x00\x00\x00"
|
|
101
100
|
|
|
102
101
|
```
|
|
103
102
|
|
|
@@ -132,7 +131,7 @@ header = Header(data)
|
|
|
132
131
|
assert header.data == b"KUSJESVANSRT"
|
|
133
132
|
assert header.flags == 5
|
|
134
133
|
assert header.trailer == b"<3"
|
|
135
|
-
assert header
|
|
134
|
+
assert bytes(header) == data
|
|
136
135
|
|
|
137
136
|
cs = cstruct(endian=">")
|
|
138
137
|
|
|
@@ -177,6 +176,40 @@ assert cs.uint24[2](b"\x01\x00\x00\x02\x00\x00") == [1, 2] # You can also parse
|
|
|
177
176
|
assert cs.char[None](b"hello world!\x00") == b"hello world!" # A list index of None means null terminated
|
|
178
177
|
```
|
|
179
178
|
|
|
179
|
+
### Creating values
|
|
180
|
+
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.
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
from dissect.cstruct import cstruct
|
|
184
|
+
|
|
185
|
+
cs = cstruct()
|
|
186
|
+
assert cs.uint32("5") == 5 # Like int("5")
|
|
187
|
+
assert cs.uint32(b"\x05\x00\x00\x00") == 5 # Parsed
|
|
188
|
+
assert cs.uint8[4]([1, 2]) == [1, 2, 0, 0] # Padded to the number of entries
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Some types don't accept all the values of their Python base type:
|
|
192
|
+
- `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"`.
|
|
193
|
+
- `wchar` and `wchar` arrays only accept a `str`.
|
|
194
|
+
- Other arrays don't accept a `str` or an `int`.
|
|
195
|
+
|
|
196
|
+
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.
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
cs.load("""
|
|
200
|
+
struct example {
|
|
201
|
+
uint16 values[2];
|
|
202
|
+
char name[4];
|
|
203
|
+
};
|
|
204
|
+
""")
|
|
205
|
+
|
|
206
|
+
obj = cs.example(values=b"\x01\x00\x02\x00", name=b"ab")
|
|
207
|
+
assert obj.values == [1, 2] # Parsed
|
|
208
|
+
assert obj.name == b"ab\x00\x00" # Padded
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
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.
|
|
212
|
+
|
|
180
213
|
### Unions and nested structures
|
|
181
214
|
Unions and nested structures are supported, both anonymous and named.
|
|
182
215
|
|
|
@@ -220,7 +253,7 @@ assert a.c.a.a == 0x64616564
|
|
|
220
253
|
assert a.c.a.b == 0x66656562
|
|
221
254
|
assert a.c.b.b == b"deadbeef"
|
|
222
255
|
|
|
223
|
-
assert a
|
|
256
|
+
assert bytes(a) == b"ohaideadbeef"
|
|
224
257
|
|
|
225
258
|
b = c.test_anonymous(b"ohai\x39\x05\x00\x00\x28\x23\x00\x00deadbeef")
|
|
226
259
|
assert b.magic == b"ohai"
|
|
@@ -255,7 +288,7 @@ assert a.b == 0b1
|
|
|
255
288
|
assert a.c == 0xFF
|
|
256
289
|
assert a.d == 0b11
|
|
257
290
|
assert a.e == 0b111
|
|
258
|
-
assert a
|
|
291
|
+
assert bytes(a) == d
|
|
259
292
|
```
|
|
260
293
|
|
|
261
294
|
### Enums and Flags
|
|
@@ -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
|
|
@@ -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:
|
|
@@ -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:
|
|
@@ -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)
|
|
@@ -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))
|