binal 0.1.0__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.
@@ -0,0 +1,364 @@
1
+ """Decoding: binary -> Python objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ..errors import DecodeError, ValidationError
8
+ from ..types import IntegerCodec
9
+ from .buffer import Reader
10
+ from .compiler import FieldSpec, split_annotated
11
+ from .encoder import check_constraints, derived_length
12
+
13
+
14
+ def _prefix_int_spec(prefix_type: Any) -> IntegerCodec:
15
+ _base, meta = split_annotated(prefix_type)
16
+ for m in meta:
17
+ if isinstance(m, IntegerCodec):
18
+ return m
19
+ return IntegerCodec(bits=16, signed=False)
20
+
21
+
22
+ def decode_into(
23
+ cls: Any,
24
+ reader: Reader,
25
+ byte_order: str,
26
+ path: str = "",
27
+ ) -> Any:
28
+ specs = cls._binal_specs() # type: ignore[attr-defined]
29
+ specs_by_name = {s.name: s for s in specs}
30
+ values: dict[str, Any] = {}
31
+ offsets: dict[str, tuple[int, int]] = {}
32
+ checksum_specs: list[FieldSpec] = []
33
+
34
+ for spec in specs:
35
+ field_path = f"{path}.{spec.name}" if path else spec.name
36
+ if spec.when is not None:
37
+ cond = values.get(spec.when.field)
38
+ if cond != spec.when.equals:
39
+ values[spec.name] = None
40
+ continue
41
+ if spec.align is not None:
42
+ reader.align_byte()
43
+ while reader.pos % spec.align.alignment != 0:
44
+ reader.read_bytes(1, field_path)
45
+ start = reader.pos
46
+
47
+ if spec.magic is not None:
48
+ raw = reader.read_bytes(len(spec.magic.value), field_path)
49
+ if raw != spec.magic.value:
50
+ raise DecodeError(
51
+ "Magic bytes mismatch",
52
+ path=field_path,
53
+ offset=start,
54
+ expected=spec.magic.value,
55
+ reason="Magic bytes mismatch",
56
+ )
57
+ values[spec.name] = spec.magic.value
58
+ offsets[spec.name] = (start, reader.pos)
59
+ continue
60
+ if spec.padding is not None:
61
+ raw = reader.read_bytes(spec.padding.length, field_path)
62
+ values[spec.name] = raw
63
+ offsets[spec.name] = (start, reader.pos)
64
+ continue
65
+ if spec.checksum is not None:
66
+ if spec.int_spec is None:
67
+ raise DecodeError(
68
+ "Checksum field needs an integer type", path=field_path
69
+ )
70
+ raw_val = reader.read_int(
71
+ spec.int_spec.bits,
72
+ spec.int_spec.signed,
73
+ spec.int_spec.byte_order or byte_order,
74
+ field_path,
75
+ )
76
+ values[spec.name] = raw_val
77
+ offsets[spec.name] = (start, reader.pos)
78
+ checksum_specs.append(spec)
79
+ continue
80
+ if spec.length_of is not None or spec.count_of is not None:
81
+ if spec.int_spec is None:
82
+ raise DecodeError(
83
+ "Derived length field needs an integer type", path=field_path
84
+ )
85
+ raw_val = reader.read_int(
86
+ spec.int_spec.bits,
87
+ spec.int_spec.signed,
88
+ spec.int_spec.byte_order or byte_order,
89
+ field_path,
90
+ )
91
+ values[spec.name] = raw_val
92
+ offsets[spec.name] = (start, reader.pos)
93
+ continue
94
+
95
+ value = _decode_field(
96
+ spec, reader, byte_order, field_path, values, specs_by_name
97
+ )
98
+ values[spec.name] = value
99
+ offsets[spec.name] = (start, reader.pos)
100
+
101
+ # Verify derived lengths.
102
+ for spec in specs:
103
+ if spec.length_of is not None:
104
+ target = values.get(spec.length_of.field)
105
+ target_spec = specs_by_name.get(spec.length_of.field)
106
+ expected = derived_length(target, target_spec)
107
+ if values.get(spec.name) != expected:
108
+ raise DecodeError(
109
+ "Derived length mismatch",
110
+ path=spec.name,
111
+ offset=None,
112
+ expected=expected,
113
+ available=values.get(spec.name),
114
+ reason="Derived length mismatch",
115
+ )
116
+ if spec.count_of is not None:
117
+ target = values.get(spec.count_of.field)
118
+ expected = len(target) if target is not None else 0
119
+ if values.get(spec.name) != expected:
120
+ raise DecodeError(
121
+ "Derived count mismatch",
122
+ path=spec.name,
123
+ expected=expected,
124
+ available=values.get(spec.name),
125
+ reason="Derived count mismatch",
126
+ )
127
+
128
+ # Verify checksums.
129
+ for spec in checksum_specs:
130
+ assert spec.checksum is not None
131
+ parts = b"".join(
132
+ reader.data[s:e]
133
+ for name in spec.checksum.fields
134
+ for (s, e) in [offsets[name]]
135
+ )
136
+ expected = spec.checksum.algorithm(parts)
137
+ if values.get(spec.name) != expected:
138
+ raise DecodeError(
139
+ "Checksum mismatch",
140
+ path=spec.name,
141
+ expected=expected,
142
+ available=values.get(spec.name),
143
+ reason="Checksum mismatch",
144
+ )
145
+
146
+ # Validate constraints on decoded values.
147
+ for spec in specs:
148
+ if spec.name in values and values[spec.name] is not None:
149
+ if spec.magic is not None or spec.padding is not None:
150
+ continue
151
+ check_constraints(spec, values[spec.name], spec.name)
152
+
153
+ instance = object.__new__(cls)
154
+ instance.__dict__.update(values)
155
+ return instance
156
+
157
+
158
+ def _decode_field(
159
+ spec: FieldSpec,
160
+ reader: Reader,
161
+ byte_order: str,
162
+ path: str,
163
+ values: dict[str, Any],
164
+ specs_by_name: dict[str, FieldSpec],
165
+ ) -> Any:
166
+ # Custom codec.
167
+ if spec.codec is not None:
168
+ codec = spec.codec if not isinstance(spec.codec, type) else spec.codec()
169
+ storage_spec = spec.codec_storage_spec
170
+ if storage_spec is None:
171
+ raise DecodeError(f"Codec for {path} has no storage type", path=path)
172
+ storage_value = _decode_storage(storage_spec, reader, byte_order, path)
173
+ return codec.decode(storage_value)
174
+
175
+ if spec.kind == "int" and spec.int_spec is not None:
176
+ value = reader.read_int(
177
+ spec.int_spec.bits,
178
+ spec.int_spec.signed,
179
+ spec.int_spec.byte_order or byte_order,
180
+ path,
181
+ )
182
+ _check_int_range(spec, value, path)
183
+ return value
184
+ if spec.kind == "varint" and spec.varint_spec is not None:
185
+ return reader.read_varint(spec.varint_spec.kind, spec.varint_spec.zigzag, path)
186
+ if spec.kind == "float" and spec.float_spec is not None:
187
+ return reader.read_float(spec.float_spec.bits, byte_order, path)
188
+ if spec.kind == "bool":
189
+ raw = reader.read_bytes(1, path)
190
+ if raw[0] not in (0, 1):
191
+ raise DecodeError(
192
+ "Invalid boolean byte", path=path, expected="0 or 1", available=raw[0]
193
+ )
194
+ return bool(raw[0])
195
+ if spec.kind == "bit":
196
+ width = spec.bits.width if spec.bits else 1
197
+ raw = reader.read_bits(width, path)
198
+ # bool bit fields decode to bool.
199
+ if spec.origin is bool:
200
+ return bool(raw)
201
+ return raw
202
+ if spec.kind == "bytes":
203
+ if spec.prefixed is not None:
204
+ prefix = _prefix_int_spec(spec.prefixed.prefix_type)
205
+ length = reader.read_int(prefix.bits, prefix.signed, byte_order, path)
206
+ return reader.read_bytes(length, path)
207
+ if spec.fixed is not None:
208
+ return reader.read_bytes(spec.fixed.length, path)
209
+ if spec.sized is not None:
210
+ length = values.get(spec.sized.field)
211
+ if length is None:
212
+ raise DecodeError(f"Sized field {path} has no length", path=path)
213
+ return reader.read_bytes(int(length), path)
214
+ # Greedy: read remaining bytes.
215
+ remaining = reader.remaining()
216
+ return reader.read_bytes(remaining, path)
217
+ if spec.kind == "str":
218
+ encoding = (
219
+ (spec.fixed.encoding if spec.fixed else None)
220
+ or (spec.prefixed.encoding if spec.prefixed else None)
221
+ or (spec.null_terminated.encoding if spec.null_terminated else None)
222
+ or "utf-8"
223
+ )
224
+ if spec.prefixed is not None:
225
+ prefix = _prefix_int_spec(spec.prefixed.prefix_type)
226
+ length = reader.read_int(prefix.bits, prefix.signed, byte_order, path)
227
+ raw = reader.read_bytes(length, path)
228
+ return raw.decode(encoding)
229
+ if spec.fixed is not None:
230
+ raw = reader.read_bytes(spec.fixed.length, path)
231
+ return raw.split(b"\x00", 1)[0].decode(encoding)
232
+ if spec.null_terminated is not None:
233
+ buf = bytearray()
234
+ while True:
235
+ byte = reader.read_bytes(1, path)
236
+ if byte == b"\x00":
237
+ break
238
+ buf.extend(byte)
239
+ return bytes(buf).decode(encoding)
240
+ if spec.sized is not None:
241
+ length = values.get(spec.sized.field)
242
+ if length is None:
243
+ raise DecodeError(f"Sized field {path} has no length", path=path)
244
+ raw = reader.read_bytes(int(length), path)
245
+ return raw.decode(encoding)
246
+ raise DecodeError(f"String field {path} needs a length mechanism", path=path)
247
+ if spec.kind == "list":
248
+ if spec.array is not None and spec.array.count_prefix is not None:
249
+ prefix = _prefix_int_spec(spec.array.count_prefix)
250
+ count = reader.read_int(prefix.bits, prefix.signed, byte_order, path)
251
+ elif spec.array is not None and isinstance(spec.array.count, int):
252
+ count = spec.array.count
253
+ elif spec.array is not None and isinstance(spec.array.count, str):
254
+ count_val = values.get(spec.array.count)
255
+ if count_val is None:
256
+ raise DecodeError(f"Array {path} has no count", path=path)
257
+ count = int(count_val)
258
+ else:
259
+ raise DecodeError(f"Array {path} has no count mechanism", path=path)
260
+ elem_spec = spec.element_spec
261
+ if elem_spec is None:
262
+ raise DecodeError(f"No element spec for {path}", path=path)
263
+ items: list[Any] = []
264
+ for i in range(count):
265
+ items.append(_decode_element(elem_spec, reader, byte_order, f"{path}[{i}]"))
266
+ return items
267
+ if spec.kind == "model" and spec.nested is not None:
268
+ return decode_into(spec.nested, reader, byte_order, path)
269
+ if spec.kind == "enum" and spec.enum_type is not None:
270
+ underlying = spec.int_spec or IntegerCodec(bits=8, signed=False)
271
+ raw = reader.read_int(underlying.bits, underlying.signed, byte_order, path)
272
+ try:
273
+ return spec.enum_type(raw)
274
+ except ValueError:
275
+ on_unknown = spec.enum_field.on_unknown if spec.enum_field else "raise"
276
+ if on_unknown == "keep":
277
+ return raw
278
+ raise DecodeError(
279
+ f"Unknown enum value {raw} for {spec.enum_type.__name__}",
280
+ path=path,
281
+ expected=f"a value of {spec.enum_type.__name__}",
282
+ available=raw,
283
+ reason="Unknown enum value",
284
+ ) from None
285
+ if spec.kind == "union":
286
+ if spec.tagged_union is not None:
287
+ discriminator = values.get(spec.tagged_union.discriminator)
288
+ variant = spec.tagged_union.variants.get(discriminator)
289
+ if variant is None:
290
+ raise DecodeError(
291
+ f"No union variant for discriminator {discriminator!r}",
292
+ path=path,
293
+ reason="Unknown discriminator",
294
+ )
295
+ return decode_into(variant, reader, byte_order, path)
296
+ raise DecodeError(
297
+ f"Unsupported union field {path} (needs TaggedUnion)", path=path
298
+ )
299
+ raise DecodeError(f"Unsupported field kind {spec.kind!r} for {path}", path=path)
300
+
301
+
302
+ def _decode_storage(
303
+ storage_spec: FieldSpec, reader: Reader, byte_order: str, path: str
304
+ ) -> Any:
305
+ if storage_spec.kind == "model" and storage_spec.nested is not None:
306
+ return decode_into(storage_spec.nested, reader, byte_order, path)
307
+ if storage_spec.int_spec is not None:
308
+ return reader.read_int(
309
+ storage_spec.int_spec.bits,
310
+ storage_spec.int_spec.signed,
311
+ storage_spec.int_spec.byte_order or byte_order,
312
+ path,
313
+ )
314
+ if storage_spec.float_spec is not None:
315
+ return reader.read_float(storage_spec.float_spec.bits, byte_order, path)
316
+ raise DecodeError(f"Unsupported codec storage type for {path}", path=path)
317
+
318
+
319
+ def _decode_element(
320
+ elem_spec: FieldSpec, reader: Reader, byte_order: str, path: str
321
+ ) -> Any:
322
+ if elem_spec.kind == "model" and elem_spec.nested is not None:
323
+ return decode_into(elem_spec.nested, reader, byte_order, path)
324
+ if elem_spec.kind == "enum" and elem_spec.enum_type is not None:
325
+ underlying = elem_spec.int_spec or IntegerCodec(bits=8, signed=False)
326
+ raw = reader.read_int(underlying.bits, underlying.signed, byte_order, path)
327
+ try:
328
+ return elem_spec.enum_type(raw)
329
+ except ValueError as exc:
330
+ raise DecodeError(f"Unknown enum value {raw}", path=path) from exc
331
+ if elem_spec.int_spec is not None:
332
+ return reader.read_int(
333
+ elem_spec.int_spec.bits,
334
+ elem_spec.int_spec.signed,
335
+ elem_spec.int_spec.byte_order or byte_order,
336
+ path,
337
+ )
338
+ if elem_spec.float_spec is not None:
339
+ return reader.read_float(elem_spec.float_spec.bits, byte_order, path)
340
+ if elem_spec.kind == "bool":
341
+ return bool(reader.read_bytes(1, path)[0])
342
+ if elem_spec.kind == "bytes":
343
+ # Greedy element not supported; treat as error.
344
+ raise DecodeError(f"Unsupported bytes array element for {path}", path=path)
345
+ if elem_spec.kind == "str":
346
+ raise DecodeError(f"Unsupported str array element for {path}", path=path)
347
+ raise DecodeError(f"Unsupported array element type for {path}", path=path)
348
+
349
+
350
+ def _check_int_range(spec: FieldSpec, value: Any, path: str) -> None:
351
+ if spec.int_spec is None:
352
+ return
353
+ bits = spec.int_spec.bits
354
+ signed = spec.int_spec.signed
355
+ lo, hi = (
356
+ (-(1 << (bits - 1)), (1 << (bits - 1)) - 1) if signed else (0, (1 << bits) - 1)
357
+ )
358
+ if not (lo <= int(value) <= hi):
359
+ raise ValidationError(
360
+ "", path=path, expected=f"integer between {lo} and {hi}", received=value
361
+ )
362
+
363
+
364
+ __all__ = ["decode_into"]