dissect.cstruct 5.0.dev18__py3-none-any.whl → 5.0.dev20__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.
@@ -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
 
dissect/cstruct/dump.py CHANGED
@@ -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
 
@@ -1,9 +1,9 @@
1
- dissect/cstruct/__init__.py,sha256=eO8ddn6U2EA_ta2QNKe8jYNgDVYC3gDBrafZ9Qqq4UM,1528
1
+ dissect/cstruct/__init__.py,sha256=ti1VYFx1MtZuDcMks14haNvUw0IZYjRo346ChzhqPls,1647
2
2
  dissect/cstruct/bitbuffer.py,sha256=aNzY4lkWe8ffAc8j7FODXzwZc8gZwbey77UosyoYCsw,2711
3
- dissect/cstruct/compiler.py,sha256=0u58J5pB4izosBj8G4wiBI1JSAAgHFMLM63IaSG4YO4,54509
3
+ dissect/cstruct/compiler.py,sha256=3dlVVzU8-i-G5PKti8sMTKLF3BdQ9g6_tHaKn0KDqJA,54440
4
4
  dissect/cstruct/cstruct.py,sha256=mJerzPouWV29RdK5LqjGitDDMvNKcadoT2hj1zpExnM,26551
5
5
  dissect/cstruct/declarative.py,sha256=5ubPtOyy6L5gJMFaPcbW3xYbTijZGMp0XJGxBeed1nE,14505
6
- dissect/cstruct/dump.py,sha256=4PS4h9R9bmDveYMFBdkM1Nw1_wZy0UUES1CDc4qxtrA,18774
6
+ dissect/cstruct/dump.py,sha256=W5ISbaZ-1YmWXKzh-x6pDt5_SlpFRDhD9GGNyv1MnLw,19016
7
7
  dissect/cstruct/exception.py,sha256=box-mw6FoP6c3vndvYLcTeJCZVgIG8IQVPEAg4zW0C8,380
8
8
  dissect/cstruct/expression.py,sha256=SbZRv7ueasYU4k-4k2eV1fjwL3JTAgF2UBaBvNjwiv4,10736
9
9
  dissect/cstruct/lexer.py,sha256=N7eqCOlcaQriUUIswJv16i-CE_sahYXGO-YdFO0IKKY,20421
@@ -14,19 +14,19 @@ dissect/cstruct/tools/stubgen.py,sha256=MeZkLmSeNSLNcAEwlAdIGv1lKvlvK3UQ4WN85ovs
14
14
  dissect/cstruct/types/__init__.py,sha256=6P71Pu94Dv7RNjZpDZ19pqzx-G0QzmQw4q0-3zWALso,911
15
15
  dissect/cstruct/types/base.py,sha256=NdCP9dJk6lrKPERYjR9qeD2gFzWd6krVSN4tAOqqkvI,18357
16
16
  dissect/cstruct/types/char.py,sha256=N19R7Zzn2uMuG-ULW5X2UgmgkLvjaBj1Td7AQQI93Fg,3417
17
- dissect/cstruct/types/enum.py,sha256=nOdI6vGtqTfPMhOBkKuiuOriIB2YHSt8Q9ruri37s3U,9177
17
+ dissect/cstruct/types/enum.py,sha256=VICmKWRuzTicq6pNKpAG_xfFzC5pVLp48qe9lFyXqoc,9029
18
18
  dissect/cstruct/types/flag.py,sha256=YxQHix8ZhK1qQX3J_Og7GJp_4JAxCwzUbUibuJeDaWQ,3479
19
19
  dissect/cstruct/types/int.py,sha256=9RbdrkvAI28zATM97VVORQnras0XhLaVMtdPjJwpTH4,2089
20
20
  dissect/cstruct/types/leb128.py,sha256=V97XTJT_Xbw1LpTwTN1OkjPHuQQAQUxd8OGuA6yEDmE,2387
21
21
  dissect/cstruct/types/packed.py,sha256=NgCX0YWX8SH8z47atq0f39w9MBjU_eBFJtUisUWdO-M,3867
22
22
  dissect/cstruct/types/pointer.py,sha256=FNuB9bfENWRebbKX-R6Vs6xWPMHepjvOhhomeUhr7I8,3985
23
- dissect/cstruct/types/structure.py,sha256=DHsdtRfhcEPB4W9aBfctLflDH6xaBvxKuOtDWhSO7iQ,39675
23
+ dissect/cstruct/types/structure.py,sha256=cwLzetR0AEDBVqOIeOxo6viWxbTRvt5tYDkbZEISk_U,43165
24
24
  dissect/cstruct/types/void.py,sha256=fV4hKk50uop_EKbR1nfy1cdtAzvUYrSymXsdakCyFk8,1222
25
25
  dissect/cstruct/types/wchar.py,sha256=VrnPXsP_lsyA-1xr4D2aSIVijumMhUuZWNlDHcn12-s,3964
26
- dissect_cstruct-5.0.dev18.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
27
- dissect_cstruct-5.0.dev18.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
28
- dissect_cstruct-5.0.dev18.dist-info/METADATA,sha256=cY4cQa56JsEILbAzrcmeh5M_akYena2rAgkg0SvxGWY,11448
29
- dissect_cstruct-5.0.dev18.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
- dissect_cstruct-5.0.dev18.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
31
- dissect_cstruct-5.0.dev18.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
32
- dissect_cstruct-5.0.dev18.dist-info/RECORD,,
26
+ dissect_cstruct-5.0.dev20.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
27
+ dissect_cstruct-5.0.dev20.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
28
+ dissect_cstruct-5.0.dev20.dist-info/METADATA,sha256=PTh5qmB9Hrn-h2yQbC1r_V3eZjE_iit0oL9mKRErugo,12661
29
+ dissect_cstruct-5.0.dev20.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
+ dissect_cstruct-5.0.dev20.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
31
+ dissect_cstruct-5.0.dev20.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
32
+ dissect_cstruct-5.0.dev20.dist-info/RECORD,,