dissect.cstruct 5.0.dev18__tar.gz → 5.0.dev20__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.
Files changed (86) hide show
  1. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/CHANGELOG.md +3 -0
  2. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/PKG-INFO +33 -1
  3. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/README.md +32 -0
  4. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/__init__.py +4 -0
  5. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/compiler.py +2 -5
  6. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/dump.py +4 -1
  7. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/enum.py +7 -9
  8. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/structure.py +90 -1
  9. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect.cstruct.egg-info/PKG-INFO +33 -1
  10. dissect_cstruct-5.0.dev20/dissect.cstruct.egg-info/scm_version.json +8 -0
  11. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_bitfield.py +3 -0
  12. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_compiler.py +5 -6
  13. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_declarative.py +17 -1
  14. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_dump.py +15 -2
  15. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_enum.py +9 -1
  16. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_structure.py +145 -1
  17. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_union.py +45 -1
  18. dissect_cstruct-5.0.dev18/dissect.cstruct.egg-info/scm_version.json +0 -8
  19. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/.git-blame-ignore-revs +0 -0
  20. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/.gitattributes +0 -0
  21. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/COPYRIGHT +0 -0
  22. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/LICENSE +0 -0
  23. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/MANIFEST.in +0 -0
  24. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/bitbuffer.py +0 -0
  25. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/cstruct.py +0 -0
  26. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/declarative.py +0 -0
  27. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/exception.py +0 -0
  28. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/expression.py +0 -0
  29. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/lexer.py +0 -0
  30. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/parser.py +0 -0
  31. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/tools/__init__.py +0 -0
  32. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/tools/stubgen.py +0 -0
  33. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/__init__.py +0 -0
  34. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/base.py +0 -0
  35. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/char.py +0 -0
  36. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/flag.py +0 -0
  37. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/int.py +0 -0
  38. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/leb128.py +0 -0
  39. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/packed.py +0 -0
  40. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/pointer.py +0 -0
  41. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/void.py +0 -0
  42. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/types/wchar.py +0 -0
  43. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect/cstruct/util.py +0 -0
  44. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect.cstruct.egg-info/SOURCES.txt +0 -0
  45. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect.cstruct.egg-info/dependency_links.txt +0 -0
  46. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect.cstruct.egg-info/entry_points.txt +0 -0
  47. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect.cstruct.egg-info/requires.txt +0 -0
  48. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect.cstruct.egg-info/scm_file_list.json +0 -0
  49. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/dissect.cstruct.egg-info/top_level.txt +0 -0
  50. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/examples/disk.py +0 -0
  51. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/examples/mirai.py +0 -0
  52. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/examples/pe.py +0 -0
  53. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/examples/protobuf.py +0 -0
  54. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/examples/secdesc.py +0 -0
  55. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/pyproject.toml +0 -0
  56. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/setup.cfg +0 -0
  57. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/__init__.py +0 -0
  58. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/_data/testdef.txt +0 -0
  59. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/_docs/Makefile +0 -0
  60. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/_docs/__init__.py +0 -0
  61. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/_docs/conf.py +0 -0
  62. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/_docs/index.rst +0 -0
  63. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/conftest.py +0 -0
  64. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_align.py +0 -0
  65. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_annotations.py +0 -0
  66. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_basic.py +0 -0
  67. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_benchmark.py +0 -0
  68. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_bitbuffer.py +0 -0
  69. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_ctypes.py +0 -0
  70. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_expression.py +0 -0
  71. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_lexer.py +0 -0
  72. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_parser.py +0 -0
  73. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_tools_stubgen.py +0 -0
  74. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_base.py +0 -0
  75. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_char.py +0 -0
  76. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_custom.py +0 -0
  77. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_flag.py +0 -0
  78. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_int.py +0 -0
  79. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_leb128.py +0 -0
  80. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_packed.py +0 -0
  81. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_pointer.py +0 -0
  82. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_void.py +0 -0
  83. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_types_wchar.py +0 -0
  84. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/test_util.py +0 -0
  85. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tests/util.py +0 -0
  86. {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev20}/tox.ini +0 -0
@@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
9
9
  ### Added
10
10
 
11
11
  - Declarative syntax for structures and unions in `dissect.cstruct.declarative`, using classes with type annotations.
12
+ - `asdict()` and the `_asdict()` method return the field values of a structure or union as a dict, with nested structures as dicts and arrays as lists. `asjson()` returns them as a JSON string, with bytes as base64 and enum members as numbers. `JSONEncoder` encodes structures as part of other data with `json.dumps()`.
12
13
 
13
14
  ### Changed
14
15
 
@@ -42,6 +43,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
42
43
  - A surrogate pair takes up two entries of a `wchar` array, so writing it no longer writes more bytes than the size of the array.
43
44
  - A `wchar` string can hold a lone surrogate, instead of raising an error for the whole structure when reading or writing it. Bytes are written back as they were stored.
44
45
  - Writing more than a single character to a `char` or `wchar` raises a `ValueError`, instead of writing all of it and moving the fields after it. An empty value is padded.
46
+ - A plain integer can be written to an enum or flag field, including a bit field.
47
+ - `dumpstruct` shows the fields of a structure in a union in a union, instead of only its `repr`.
45
48
 
46
49
  ## [4.5] - 20-05-2025
47
50
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev18
3
+ Version: 5.0.dev20
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
@@ -312,6 +312,38 @@ assert example.magic == 1337
312
312
  assert example.data == b"arbitrary length data"
313
313
  ```
314
314
 
315
+ ### Converting to dicts and JSON
316
+ `asdict()` returns the field values of a structure or union as a dict, like `dataclasses.asdict()`. The method `_asdict()` does the same, like `namedtuple`. Nested structures and unions become dicts and arrays become lists. Other values are returned as they are, so enum members stay enum members and pointers are not dereferenced.
317
+
318
+ `asjson()` returns the same values as a JSON string. Bytes are encoded as base64 strings, and enum and flag members and pointers as numbers. To encode structures as part of other data, use `JSONEncoder` with `json.dumps()`.
319
+
320
+ ```python
321
+ import json
322
+
323
+ from dissect.cstruct import JSONEncoder, asdict, asjson, cstruct
324
+
325
+ c_def = """
326
+ enum Type : uint8 {
327
+ FILE = 1,
328
+ DIRECTORY = 2
329
+ };
330
+
331
+ struct entry {
332
+ Type type;
333
+ char name[4];
334
+ uint32 sizes[2];
335
+ };
336
+ """
337
+
338
+ c = cstruct().load(c_def)
339
+
340
+ entry = c.entry(b"\x01test\x01\x00\x00\x00\x02\x00\x00\x00")
341
+ assert asdict(entry) == {"type": c.Type.FILE, "name": b"test", "sizes": [1, 2]}
342
+ assert entry._asdict() == asdict(entry)
343
+ assert asjson(entry) == '{"type": 1, "name": "dGVzdA==", "sizes": [1, 2]}'
344
+ assert json.dumps({"entries": [entry]}, cls=JSONEncoder) == f'{{"entries": [{asjson(entry)}]}}'
345
+ ```
346
+
315
347
  ### Custom definition parsers
316
348
  Don't like the C-like definition syntax? Write your own syntax parser!
317
349
 
@@ -284,6 +284,38 @@ assert example.magic == 1337
284
284
  assert example.data == b"arbitrary length data"
285
285
  ```
286
286
 
287
+ ### Converting to dicts and JSON
288
+ `asdict()` returns the field values of a structure or union as a dict, like `dataclasses.asdict()`. The method `_asdict()` does the same, like `namedtuple`. Nested structures and unions become dicts and arrays become lists. Other values are returned as they are, so enum members stay enum members and pointers are not dereferenced.
289
+
290
+ `asjson()` returns the same values as a JSON string. Bytes are encoded as base64 strings, and enum and flag members and pointers as numbers. To encode structures as part of other data, use `JSONEncoder` with `json.dumps()`.
291
+
292
+ ```python
293
+ import json
294
+
295
+ from dissect.cstruct import JSONEncoder, asdict, asjson, cstruct
296
+
297
+ c_def = """
298
+ enum Type : uint8 {
299
+ FILE = 1,
300
+ DIRECTORY = 2
301
+ };
302
+
303
+ struct entry {
304
+ Type type;
305
+ char name[4];
306
+ uint32 sizes[2];
307
+ };
308
+ """
309
+
310
+ c = cstruct().load(c_def)
311
+
312
+ entry = c.entry(b"\x01test\x01\x00\x00\x00\x02\x00\x00\x00")
313
+ assert asdict(entry) == {"type": c.Type.FILE, "name": b"test", "sizes": [1, 2]}
314
+ assert entry._asdict() == asdict(entry)
315
+ assert asjson(entry) == '{"type": 1, "name": "dGVzdA==", "sizes": [1, 2]}'
316
+ assert json.dumps({"entries": [entry]}, cls=JSONEncoder) == f'{{"entries": [{asjson(entry)}]}}'
317
+ ```
318
+
287
319
  ### Custom definition parsers
288
320
  Don't like the C-like definition syntax? Write your own syntax parser!
289
321
 
@@ -29,6 +29,7 @@ from dissect.cstruct.types import (
29
29
  Wchar,
30
30
  WcharArray,
31
31
  )
32
+ from dissect.cstruct.types.structure import JSONEncoder, asdict, asjson
32
33
  from dissect.cstruct.util import (
33
34
  f16,
34
35
  f32,
@@ -65,6 +66,7 @@ __all__ = [
65
66
  "Field",
66
67
  "Flag",
67
68
  "Int",
69
+ "JSONEncoder",
68
70
  "MetaType",
69
71
  "NullPointerDereference",
70
72
  "Packed",
@@ -76,6 +78,8 @@ __all__ = [
76
78
  "Void",
77
79
  "Wchar",
78
80
  "WcharArray",
81
+ "asdict",
82
+ "asjson",
79
83
  "cstruct",
80
84
  "ctypes",
81
85
  "ctypes_type",
@@ -948,9 +948,8 @@ class _WriteSourceGenerator(_SourceGenerator):
948
948
  other = []
949
949
  remaining = type_.__size__ * 8
950
950
  for field in fields:
951
+ # Enum members and plain integers are shifted the same way
951
952
  value = self._load_value(field, _get_attribute("data", field._name), pack)
952
- if issubclass(field.type, (Enum, Flag)):
953
- value += "._value_"
954
953
 
955
954
  remaining -= field.bits
956
955
  little.append(f"{value} << {type_.__size__ * 8 - remaining - field.bits}")
@@ -1069,9 +1068,7 @@ class _WriteSourceGenerator(_SourceGenerator):
1069
1068
 
1070
1069
  pack.add(count, "s", var)
1071
1070
 
1072
- elif issubclass(field_type, (Enum, Flag)):
1073
- self._pack_number(read_type, f"{self._load_value(field, value, pack)}._value_", pack)
1074
-
1071
+ # Enum members and plain integers are packed the same way, as the integer type of the enum
1075
1072
  elif issubclass(read_type, Packed):
1076
1073
  pack.add(1, read_type.__fmt__, value, f"_or_default({value}, {type_})")
1077
1074
 
@@ -318,7 +318,7 @@ def _describe_value(
318
318
  Structures and unions, and arrays of them, get their fields or elements as child nodes. Other values, including
319
319
  arrays of other types, are formatted as a human-readable ``display``.
320
320
  """
321
- if isinstance(value, UnionProxy):
321
+ while isinstance(value, UnionProxy):
322
322
  # Nested Structure members inside a Union are proxied; unwrap to the real Structure
323
323
  value = value.__target__
324
324
 
@@ -428,6 +428,9 @@ def dumpstruct(
428
428
 
429
429
  Prints a colorized hexdump and parsed structure output.
430
430
 
431
+ Note that this is different from :func:`asdict` and :func:`asjson`: those functions return the field values of a
432
+ structure or union, while this function describes the layout of the structure (hex bytes, offsets, display strings).
433
+
431
434
  The ``dict`` and ``json`` output formats describe the structure as a tree:
432
435
  - bytes: hex string of the raw data
433
436
  - type: type name of the structure
@@ -1,7 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import sys
4
- from enum import Enum as _Enum
5
4
  from enum import EnumMeta, IntEnum, IntFlag
6
5
  from typing import TYPE_CHECKING, Any, BinaryIO, TypeVar, overload
7
6
 
@@ -100,16 +99,15 @@ class EnumMetaType(EnumMeta, MetaType):
100
99
  def _read_0(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> list[Self]:
101
100
  return list(map(cls, cls.__type__._read_0(stream, context=context, endian=endian)))
102
101
 
103
- def _write(cls, stream: BinaryIO, data: Enum, *, endian: Endianness) -> int:
104
- return cls.__type__._write(stream, data.value, endian=endian)
102
+ def _write(cls, stream: BinaryIO, data: Enum | int, *, endian: Endianness) -> int:
103
+ # Enum members are integers, so the integer type writes them like plain integers
104
+ return cls.__type__._write(stream, data, endian=endian)
105
105
 
106
- def _write_array(cls, stream: BinaryIO, array: list[BaseType | int], *, endian: Endianness) -> int:
107
- data = [entry.value if isinstance(entry, _Enum) else entry for entry in array]
108
- return cls.__type__._write_array(stream, data, endian=endian)
106
+ def _write_array(cls, stream: BinaryIO, array: list[Enum | int], *, endian: Endianness) -> int:
107
+ return cls.__type__._write_array(stream, array, endian=endian)
109
108
 
110
- def _write_0(cls, stream: BinaryIO, array: list[BaseType | int], *, endian: Endianness) -> int:
111
- data = [entry.value if isinstance(entry, _Enum) else entry for entry in array]
112
- return cls._write_array(stream, [*data, cls.__type__.__default__()], endian=endian)
109
+ def _write_0(cls, stream: BinaryIO, array: list[Enum | int], *, endian: Endianness) -> int:
110
+ return cls.__type__._write_0(stream, array, endian=endian)
113
111
 
114
112
  def cdef(cls) -> str:
115
113
  """Render this enum (or flag) back to its C-style definition.
@@ -1,6 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import base64
3
4
  import io
5
+ import json
4
6
  import warnings
5
7
  from collections import ChainMap
6
8
  from collections.abc import MutableMapping
@@ -26,6 +28,7 @@ from dissect.cstruct.types.base import (
26
28
  )
27
29
  from dissect.cstruct.types.enum import EnumMetaType
28
30
  from dissect.cstruct.types.pointer import Pointer
31
+ from dissect.cstruct.types.void import Void
29
32
 
30
33
  if TYPE_CHECKING:
31
34
  from collections.abc import Callable, Iterator, Mapping
@@ -339,7 +342,8 @@ class StructureMetaType(MetaType):
339
342
  bit_buffer = BitBuffer(stream, endian=endian)
340
343
 
341
344
  if isinstance(field_type, EnumMetaType):
342
- bit_buffer.write(field_type.__type__, value.value, field.bits)
345
+ # Enum members and plain integers are shifted into the buffer the same way
346
+ bit_buffer.write(field_type.__type__, value, field.bits)
343
347
  else:
344
348
  bit_buffer.write(field_type, value, field.bits)
345
349
  else:
@@ -808,6 +812,91 @@ class UnionProxy:
808
812
  self.__union__._rebuild(self.__attr__)
809
813
 
810
814
 
815
+ def asdict(obj: Structure | UnionProxy) -> dict[str, Any]:
816
+ """Return the field values of a structure or union as a dict, like :func:`dataclasses.asdict`.
817
+
818
+ The keys are the field names in :attr:`StructureMetaType.__members__`, so the fields of anonymous structures and
819
+ unions are part of the parent, and a union has all of its fields. Nested structures and unions become dicts and
820
+ arrays become lists. Other values are returned as they are: enum members stay enum members, and pointers are not
821
+ dereferenced.
822
+
823
+ Note that this is different from :func:`dumpstruct` called with ``output="dict"``: this function returns a
824
+ dictionary with pairs of field names and values, rather than a dictionary that describes the layout of the
825
+ structure (hex bytes, offsets, display strings).
826
+
827
+ Args:
828
+ obj: The structure or union to convert.
829
+
830
+ Raises:
831
+ TypeError: If ``obj`` is not a structure or union instance.
832
+ """
833
+ while isinstance(obj, UnionProxy):
834
+ obj = obj.__target__
835
+
836
+ if not isinstance(obj, Structure):
837
+ raise TypeError("asdict() should be called on Structure instances")
838
+
839
+ return _asdict_value(obj)
840
+
841
+
842
+ def _asdict_value(value: Any) -> Any:
843
+ # Structures in a union are proxied
844
+ while isinstance(value, UnionProxy):
845
+ value = value.__target__
846
+
847
+ if isinstance(value, Structure):
848
+ return {name: _asdict_value(getattr(value, name)) for name in value.__class__.__members__}
849
+
850
+ if isinstance(value, (list, tuple)):
851
+ # The entries of an array of other types are returned as they are, copying them is much faster
852
+ if isinstance(value, BaseArray) and not issubclass(value.__type__, (Structure, BaseArray)):
853
+ return list(value)
854
+ return [_asdict_value(item) for item in value]
855
+
856
+ return value
857
+
858
+
859
+ class JSONEncoder(json.JSONEncoder):
860
+ """JSON encoder for structures and unions, and the values of their fields.
861
+
862
+ Structures and unions are encoded as objects with the fields of :func:`asdict`. Bytes, such as the values of
863
+ ``char`` arrays, are encoded as base64 strings and ``void`` values as ``null``. Enum and flag members and pointers
864
+ are integers, which :mod:`json` encodes as numbers.
865
+
866
+ Example:
867
+ >>> json.dumps({"header": header}, cls=JSONEncoder)
868
+ """
869
+
870
+ def default(self, o: Any) -> Any:
871
+ if isinstance(o, (Structure, UnionProxy)):
872
+ return asdict(o)
873
+
874
+ if isinstance(o, _BUFFER_TYPES):
875
+ return base64.b64encode(o).decode()
876
+
877
+ if isinstance(o, Void):
878
+ return None
879
+
880
+ return super().default(o)
881
+
882
+
883
+ def asjson(obj: Structure | UnionProxy, **kwargs) -> str:
884
+ """Return the field values of a structure or union as a JSON string, encoded with :class:`JSONEncoder`.
885
+
886
+ Note that this is different from :func:`dumpstruct` called with ``output="json"``: this function returns a
887
+ JSON string with pairs of field names and values, rather than a JSON string that describes the layout of the
888
+ structure (hex bytes, offsets, display strings).
889
+
890
+ Args:
891
+ obj: The structure or union to convert.
892
+ **kwargs: Keyword arguments for :func:`json.dumps`, e.g. ``indent``.
893
+
894
+ Raises:
895
+ TypeError: If ``obj`` is not a structure or union instance.
896
+ """
897
+ return json.dumps(asdict(obj), cls=JSONEncoder, **kwargs)
898
+
899
+
811
900
  def attrsetter(path: str) -> Callable[[Any], Any]:
812
901
  path, _, attr = path.rpartition(".")
813
902
  path = path.split(".")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev18
3
+ Version: 5.0.dev20
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
@@ -312,6 +312,38 @@ assert example.magic == 1337
312
312
  assert example.data == b"arbitrary length data"
313
313
  ```
314
314
 
315
+ ### Converting to dicts and JSON
316
+ `asdict()` returns the field values of a structure or union as a dict, like `dataclasses.asdict()`. The method `_asdict()` does the same, like `namedtuple`. Nested structures and unions become dicts and arrays become lists. Other values are returned as they are, so enum members stay enum members and pointers are not dereferenced.
317
+
318
+ `asjson()` returns the same values as a JSON string. Bytes are encoded as base64 strings, and enum and flag members and pointers as numbers. To encode structures as part of other data, use `JSONEncoder` with `json.dumps()`.
319
+
320
+ ```python
321
+ import json
322
+
323
+ from dissect.cstruct import JSONEncoder, asdict, asjson, cstruct
324
+
325
+ c_def = """
326
+ enum Type : uint8 {
327
+ FILE = 1,
328
+ DIRECTORY = 2
329
+ };
330
+
331
+ struct entry {
332
+ Type type;
333
+ char name[4];
334
+ uint32 sizes[2];
335
+ };
336
+ """
337
+
338
+ c = cstruct().load(c_def)
339
+
340
+ entry = c.entry(b"\x01test\x01\x00\x00\x00\x02\x00\x00\x00")
341
+ assert asdict(entry) == {"type": c.Type.FILE, "name": b"test", "sizes": [1, 2]}
342
+ assert entry._asdict() == asdict(entry)
343
+ assert asjson(entry) == '{"type": 1, "name": "dGVzdA==", "sizes": [1, 2]}'
344
+ assert json.dumps({"entries": [entry]}, cls=JSONEncoder) == f'{{"entries": [{asjson(entry)}]}}'
345
+ ```
346
+
315
347
  ### Custom definition parsers
316
348
  Don't like the C-like definition syntax? Write your own syntax parser!
317
349
 
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "5.0.dev0",
3
+ "distance": 20,
4
+ "node": "g3e19cdfe0c0489ef470a41791188d4939a3a87f0",
5
+ "dirty": true,
6
+ "branch": "main",
7
+ "node_date": "2026-11-16"
8
+ }
@@ -243,6 +243,9 @@ def test_bitfield_with_enum_or_flag(cs: cstruct, compiled: bool) -> None:
243
243
 
244
244
  assert obj.dumps() == buf
245
245
 
246
+ # Plain integers are written like flag members
247
+ assert cs.test(a=1, b=1, c=3, d=3).dumps() == buf
248
+
246
249
 
247
250
  def test_bitfield_char(cs: cstruct, compiled: bool) -> None:
248
251
  cdef = """
@@ -749,12 +749,11 @@ def test_generate_packed_write_numbers(cs: cstruct, TestEnum: type[Enum]) -> Non
749
749
  code = next(gen._generate_packed_source(fields))
750
750
 
751
751
  expected = """
752
- if (_value0 := data.a) is None: _value0 = _type0.__default__()
753
- if (_value1 := data.c) is None: _value1 = _type2.__default__()
752
+ if (_value0 := data.c) is None: _value0 = _type2.__default__()
754
753
  try:
755
- buf = _pack0[endian](_value0._value_, data.b, _value1.to_bytes(3, _byteorder[endian], signed=False))
754
+ buf = _pack0[endian](data.a, data.b, _value0.to_bytes(3, _byteorder[endian], signed=False))
756
755
  except _struct_error:
757
- buf = _pack0[endian](_value0._value_, _or_default(data.b, _type1), _value1.to_bytes(3, _byteorder[endian], signed=False))
756
+ buf = _pack0[endian](_or_default(data.a, _type0), _or_default(data.b, _type1), _value0.to_bytes(3, _byteorder[endian], signed=False))
758
757
  stream.write(buf)
759
758
  """ # noqa: E501
760
759
 
@@ -784,8 +783,8 @@ def test_generate_bits_write(cs: cstruct, TestEnum: type[Enum]) -> None:
784
783
  expected = """
785
784
  if (_value0 := data.a) is None: _value0 = _type0.__default__()
786
785
  if (_value1 := data.b) is None: _value1 = _type1.__default__()
787
- stream.write(_pack0[endian]((_value0 << 0 | _value1._value_ << 2 if endian == '<' else _value0 << 6 | _value1._value_ << 0)))
788
- """ # noqa: E501
786
+ stream.write(_pack0[endian]((_value0 << 0 | _value1 << 2 if endian == '<' else _value0 << 6 | _value1 << 0)))
787
+ """
789
788
 
790
789
  assert code == dedent(expected)
791
790
 
@@ -22,7 +22,7 @@ from dissect.cstruct.declarative import (
22
22
  uint64,
23
23
  )
24
24
  from dissect.cstruct.types.pointer import Pointer
25
- from dissect.cstruct.types.structure import Structure, StructureMetaType, UnionMetaType
25
+ from dissect.cstruct.types.structure import Structure, StructureMetaType, UnionMetaType, asdict
26
26
  from dissect.cstruct.types.structure import Union as CUnion
27
27
 
28
28
  # Module level cstruct instance to exercise bound-type inference through stringified annotations
@@ -418,6 +418,22 @@ def test_char_and_bytes(cs: cstruct) -> None:
418
418
  assert obj.value == 1
419
419
 
420
420
 
421
+ def test_asdict(cs: cstruct) -> None:
422
+ """Test that asdict has the fields of a structure, not its other attributes."""
423
+
424
+ class Header(Struct, cs=cs):
425
+ magic: char[4]
426
+ size: uint32
427
+
428
+ @property
429
+ def total_size(self) -> int:
430
+ return self.size + 8
431
+
432
+ obj = Header(b"test\x01\x00\x00\x00")
433
+ assert obj.total_size == 9
434
+ assert asdict(obj) == {"magic": b"test", "size": 1}
435
+
436
+
421
437
  def test_endian(cs: cstruct) -> None:
422
438
  big = cstruct(endian=">")
423
439
 
@@ -993,7 +993,7 @@ def test_dumpstruct_union_root(cs: cstruct, compiled: bool) -> None:
993
993
 
994
994
 
995
995
  def test_dumpstruct_union_nested_struct(cs: cstruct, compiled: bool) -> None:
996
- """Nested Structure members inside a Union are proxied via UnionProxy; verify unwrap."""
996
+ """Nested Structure members inside a Union are proxied via UnionProxy, twice in nested unions; verify unwrap."""
997
997
  cdef = """
998
998
  struct inner {
999
999
  uint32 a;
@@ -1004,6 +1004,11 @@ def test_dumpstruct_union_nested_struct(cs: cstruct, compiled: bool) -> None:
1004
1004
  uint8 raw[8];
1005
1005
  };
1006
1006
 
1007
+ union outer_outer {
1008
+ outer nested;
1009
+ uint8 raw[8];
1010
+ };
1011
+
1007
1012
  union anon_outer {
1008
1013
  struct {
1009
1014
  uint32 a;
@@ -1022,9 +1027,17 @@ def test_dumpstruct_union_nested_struct(cs: cstruct, compiled: bool) -> None:
1022
1027
  ]
1023
1028
  raw = {"name": "raw[8]", "type": "uint8", "offset": 0, "size": 8, "display": "[1, 0, 0, 0, 2, 0, 0, 0]"}
1024
1029
 
1030
+ outer_fields = [
1031
+ {"name": "nested", "type": "inner", "offset": 0, "size": 8, "kind": "struct", "fields": inner_fields},
1032
+ raw,
1033
+ ]
1034
+
1025
1035
  result = dumpstruct(cs.outer, buf, output="dict")
1036
+ assert result["fields"] == outer_fields
1037
+
1038
+ result = dumpstruct(cs.outer_outer, buf, output="dict")
1026
1039
  assert result["fields"] == [
1027
- {"name": "nested", "type": "inner", "offset": 0, "size": 8, "kind": "struct", "fields": inner_fields},
1040
+ {"name": "nested", "type": "outer", "offset": 0, "size": 8, "kind": "union", "fields": outer_fields},
1028
1041
  raw,
1029
1042
  ]
1030
1043
 
@@ -59,6 +59,7 @@ def test_enum_read(TestEnum: type[Enum]) -> None:
59
59
  def test_enum_write(TestEnum: type[Enum]) -> None:
60
60
  assert TestEnum.B.dumps() == b"\x02"
61
61
  assert TestEnum(b"\x02").dumps() == b"\x02"
62
+ assert TestEnum.dumps(2) == b"\x02"
62
63
 
63
64
 
64
65
  def test_enum_array_read(TestEnum: type[Enum]) -> None:
@@ -69,6 +70,8 @@ def test_enum_array_read(TestEnum: type[Enum]) -> None:
69
70
  def test_enum_array_write(TestEnum: type[Enum]) -> None:
70
71
  assert TestEnum[2]([TestEnum.B, TestEnum.C]).dumps() == b"\x02\x03"
71
72
  assert TestEnum[None]([TestEnum.B, TestEnum.C]).dumps() == b"\x02\x03\x00"
73
+ assert TestEnum[2]([2, 3]).dumps() == b"\x02\x03"
74
+ assert TestEnum[None]([2, 3]).dumps() == b"\x02\x03\x00"
72
75
 
73
76
 
74
77
  def test_enum_alias(cs: cstruct) -> None:
@@ -366,7 +369,12 @@ def test_enum_struct_write(cs: cstruct, compiled: bool) -> None:
366
369
  obj.b32 = cs.Test32.B
367
370
  obj.list = [cs.Test16.A, cs.Test16.B]
368
371
 
369
- assert obj.dumps() == b"\x01\x00\x02\x00\x01\x00\x00\x02\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x01\x00\x02\x00"
372
+ buf = b"\x01\x00\x02\x00\x01\x00\x00\x02\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x01\x00\x02\x00"
373
+ assert obj.dumps() == buf
374
+
375
+ # Plain integers are written like enum members
376
+ obj = cs.test(a16=1, b16=2, a24=1, b24=2, a32=1, b32=2, list=[1, 2])
377
+ assert obj.dumps() == buf
370
378
 
371
379
 
372
380
  def test_enum_anonymous(cs: cstruct, compiled: bool) -> None:
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import inspect
4
+ import json
4
5
  from io import BytesIO
5
6
  from textwrap import dedent
6
7
  from types import MethodType
@@ -13,7 +14,7 @@ from dissect.cstruct.exception import ArraySizeError, ResolveError
13
14
  from dissect.cstruct.types import structure
14
15
  from dissect.cstruct.types.base import Array, BaseType
15
16
  from dissect.cstruct.types.pointer import Pointer
16
- from dissect.cstruct.types.structure import Field, Structure, StructureMetaType
17
+ from dissect.cstruct.types.structure import Field, JSONEncoder, Structure, StructureMetaType, asdict, asjson
17
18
  from tests.util import verify_compiled
18
19
 
19
20
 
@@ -308,6 +309,149 @@ def test_structure_values_dict(cs: cstruct, compiled: bool) -> None:
308
309
  assert values.keys() == {"magic", "wmagic", "a", "b", "c", "string", "wstring"}
309
310
 
310
311
 
312
+ def test_structure_asdict(cs: cstruct, compiled: bool) -> None:
313
+ """Test that asdict converts nested structures and arrays, and returns other values as they are."""
314
+ cdef = """
315
+ enum Color : uint8 {
316
+ RED = 1
317
+ };
318
+
319
+ struct inner {
320
+ uint8 x;
321
+ };
322
+
323
+ struct test {
324
+ uint32 a;
325
+ Color color;
326
+ char magic[4];
327
+ wchar wmagic[2];
328
+ inner nested;
329
+ inner arr[2];
330
+ uint8 matrix[2][2];
331
+ char names[2][2];
332
+ struct {
333
+ uint8 anon;
334
+ };
335
+ uint8 class;
336
+ uint8 _;
337
+ uint8 _;
338
+ uint8 bits : 4;
339
+ Color color_bits : 4;
340
+ };
341
+ """
342
+ cs.load(cdef, compiled=compiled)
343
+
344
+ assert verify_compiled(cs.test, compiled)
345
+
346
+ buf = b"\x01\x00\x00\x00\x01testh\x00i\x00\x07\x08\x09\x01\x02\x03\x04abcd\x05\x06\xaa\xbb\x12"
347
+ obj = cs.test(buf)
348
+
349
+ result = asdict(obj)
350
+ assert result == {
351
+ "a": 1,
352
+ "color": cs.Color.RED,
353
+ "magic": b"test",
354
+ "wmagic": "hi",
355
+ "nested": {"x": 7},
356
+ "arr": [{"x": 8}, {"x": 9}],
357
+ "matrix": [[1, 2], [3, 4]],
358
+ "names": [b"ab", b"cd"],
359
+ "anon": 5,
360
+ "class": 6,
361
+ "_": 0xBB,
362
+ "bits": 2,
363
+ "color_bits": cs.Color.RED,
364
+ }
365
+ assert list(result) == list(cs.test.__members__)
366
+ assert result["color"] is cs.Color.RED
367
+
368
+ # The dicts and lists are new
369
+ result["arr"][0]["x"] = 0
370
+ result["matrix"][0][0] = 0
371
+ assert obj.arr[0].x == 8
372
+ assert obj.matrix[0][0] == 1
373
+
374
+
375
+ def test_structure_asdict_pointer(cs: cstruct, compiled: bool) -> None:
376
+ """Test that asdict doesn't dereference pointers, which may be null."""
377
+ cdef = """
378
+ struct node {
379
+ uint32 value;
380
+ struct node *next;
381
+ };
382
+ """
383
+ cs.pointer = cs.uint32
384
+ cs.load(cdef, compiled=compiled)
385
+
386
+ assert verify_compiled(cs.node, compiled)
387
+
388
+ obj = cs.node(b"\x01\x00\x00\x00\x08\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00")
389
+
390
+ result = asdict(obj)
391
+ assert result == {"value": 1, "next": 8}
392
+ assert result["next"] is obj.next
393
+
394
+ assert asdict(obj.next.dereference()) == {"value": 2, "next": 0}
395
+
396
+
397
+ def test_structure_asdict_invalid(cs: cstruct) -> None:
398
+ """Test that asdict and asjson only accept structure instances."""
399
+ cs.load("struct test { uint8 a; };")
400
+
401
+ with pytest.raises(TypeError, match=r"^asdict\(\) should be called on Structure instances$"):
402
+ asdict(cs.test)
403
+
404
+ with pytest.raises(TypeError, match=r"^asdict\(\) should be called on Structure instances$"):
405
+ asjson(1)
406
+
407
+
408
+ def test_structure_asjson(cs: cstruct, compiled: bool) -> None:
409
+ """Test that bytes are encoded as base64, void as null, and enums, flags and pointers as integers."""
410
+ cdef = """
411
+ enum Color : uint8 {
412
+ RED = 1
413
+ };
414
+
415
+ flag Perm : uint8 {
416
+ R = 1,
417
+ W = 2
418
+ };
419
+
420
+ struct inner {
421
+ uint8 x;
422
+ };
423
+
424
+ struct test {
425
+ Color color;
426
+ Perm perm;
427
+ char magic[4];
428
+ wchar wmagic[2];
429
+ float f;
430
+ void nothing;
431
+ inner nested;
432
+ char *name;
433
+ };
434
+ """
435
+ cs.pointer = cs.uint32
436
+ cs.load(cdef, compiled=compiled)
437
+
438
+ assert verify_compiled(cs.test, compiled)
439
+
440
+ obj = cs.test(b"\x01\x03\x00\xffabh\x00i\x00\x00\x00\xc0\x3f\x07\x10\x00\x00\x00")
441
+
442
+ expected = (
443
+ '{"color": 1, "perm": 3, "magic": "AP9hYg==", "wmagic": "hi", "f": 1.5, "nothing": null, '
444
+ '"nested": {"x": 7}, "name": 16}'
445
+ )
446
+ assert asjson(obj) == expected
447
+ assert json.dumps({"header": obj, "nested": [obj.nested]}, cls=JSONEncoder) == (
448
+ f'{{"header": {expected}, "nested": [{{"x": 7}}]}}'
449
+ )
450
+
451
+ assert asjson(obj.nested, indent=1) == '{\n "x": 7\n}'
452
+ assert json.dumps(bytearray(b"\x00\xff"), cls=JSONEncoder) == '"AP8="'
453
+
454
+
311
455
  def test_structure_definition_simple_be(cs: cstruct, compiled: bool) -> None:
312
456
  cdef = """
313
457
  struct test {
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import inspect
4
4
  import io
5
+ import json
5
6
  from textwrap import dedent
6
7
 
7
8
  import pytest
@@ -10,7 +11,7 @@ from dissect.cstruct import compiler
10
11
  from dissect.cstruct.cstruct import cstruct
11
12
  from dissect.cstruct.types import structure
12
13
  from dissect.cstruct.types.base import Array, BaseType
13
- from dissect.cstruct.types.structure import Field, Union, UnionProxy
14
+ from dissect.cstruct.types.structure import Field, JSONEncoder, Union, UnionProxy, asdict
14
15
  from tests.util import parsed_state, source_lines, verify_compiled
15
16
 
16
17
 
@@ -885,6 +886,49 @@ def test_union_in_union(cs: cstruct, compiled: bool) -> None:
885
886
  assert obj.dumps() == b"\x02"
886
887
 
887
888
 
889
+ def test_union_asdict(cs: cstruct, compiled: bool) -> None:
890
+ """Test that asdict has all fields of a union, and unwraps the proxies of structures in (nested) unions."""
891
+ cdef = """
892
+ struct inner {
893
+ uint8 x;
894
+ uint8 y;
895
+ };
896
+
897
+ union test {
898
+ inner nested;
899
+ uint16 raw;
900
+ struct {
901
+ uint8 lo;
902
+ uint8 hi;
903
+ };
904
+ };
905
+
906
+ union outer {
907
+ test u;
908
+ uint16 raw;
909
+ };
910
+
911
+ struct holder {
912
+ uint8 a;
913
+ test u;
914
+ };
915
+ """
916
+ cs.load(cdef, compiled=compiled)
917
+
918
+ assert verify_compiled(cs.test, compiled)
919
+ assert verify_compiled(cs.holder, compiled)
920
+
921
+ test = {"nested": {"x": 1, "y": 2}, "raw": 0x0201, "lo": 1, "hi": 2}
922
+ assert asdict(cs.test(b"\x01\x02")) == test
923
+ assert asdict(cs.holder(b"\x00\x01\x02")) == {"a": 0, "u": test}
924
+
925
+ obj = cs.outer(b"\x01\x02")
926
+ assert isinstance(obj.u.nested.__target__, UnionProxy)
927
+ assert asdict(obj) == {"u": test, "raw": 0x0201}
928
+ assert asdict(obj.u.nested) == {"x": 1, "y": 2}
929
+ assert json.dumps(obj.u.nested, cls=JSONEncoder) == '{"x": 1, "y": 2}'
930
+
931
+
888
932
  def test_union_write_largest_field(cs: cstruct, compiled: bool) -> None:
889
933
  """Test that a union is written by its largest field, and raises errors for invalid and missing values."""
890
934
  cdef = """
@@ -1,8 +0,0 @@
1
- {
2
- "tag": "5.0.dev0",
3
- "distance": 18,
4
- "node": "g65eeecb47a4c88d43217ef8f68631e8ac3322446",
5
- "dirty": true,
6
- "branch": "main",
7
- "node_date": "2026-11-06"
8
- }