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.
- binal/__init__.py +111 -0
- binal/_internal/__init__.py +5 -0
- binal/_internal/buffer.py +244 -0
- binal/_internal/compiler.py +474 -0
- binal/_internal/decoder.py +364 -0
- binal/_internal/encoder.py +426 -0
- binal/bits.py +8 -0
- binal/checksum.py +55 -0
- binal/codecs.py +39 -0
- binal/collections.py +7 -0
- binal/constraints.py +101 -0
- binal/errors.py +141 -0
- binal/fields.py +202 -0
- binal/io.py +5 -0
- binal/model.py +310 -0
- binal/py.typed +0 -0
- binal/schema.py +49 -0
- binal/types.py +125 -0
- binal-0.1.0.dist-info/METADATA +84 -0
- binal-0.1.0.dist-info/RECORD +21 -0
- binal-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
"""Encoding: Python objects -> binary."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import enum
|
|
6
|
+
from typing import Any, Literal, cast
|
|
7
|
+
|
|
8
|
+
from ..errors import EncodeError, ValidationError
|
|
9
|
+
from ..types import IntegerCodec
|
|
10
|
+
from .buffer import Writer
|
|
11
|
+
from .compiler import FieldSpec
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def check_constraints(spec: FieldSpec, value: Any, path: str) -> None:
|
|
15
|
+
for constraint in spec.constraints:
|
|
16
|
+
try:
|
|
17
|
+
ok = constraint.check(value)
|
|
18
|
+
except (TypeError, ValueError):
|
|
19
|
+
ok = False
|
|
20
|
+
if not ok:
|
|
21
|
+
raise ValidationError(
|
|
22
|
+
"",
|
|
23
|
+
path=path,
|
|
24
|
+
expected=constraint.describe(),
|
|
25
|
+
received=value,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def int_range(spec: FieldSpec) -> tuple[int, int]:
|
|
30
|
+
bits = spec.int_spec.bits if spec.int_spec else 8 # type: ignore[union-attr]
|
|
31
|
+
signed = spec.int_spec.signed if spec.int_spec else False # type: ignore[union-attr]
|
|
32
|
+
if signed:
|
|
33
|
+
return -(1 << (bits - 1)), (1 << (bits - 1)) - 1
|
|
34
|
+
return 0, (1 << bits) - 1
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def derived_length(target_value: Any, target_spec: FieldSpec | None) -> int:
|
|
38
|
+
if isinstance(target_value, (bytes, bytearray)):
|
|
39
|
+
return len(target_value)
|
|
40
|
+
if isinstance(target_value, str):
|
|
41
|
+
encoding = "utf-8"
|
|
42
|
+
if target_spec is not None:
|
|
43
|
+
if target_spec.fixed is not None and target_spec.fixed.encoding:
|
|
44
|
+
encoding = target_spec.fixed.encoding
|
|
45
|
+
elif target_spec.prefixed is not None and target_spec.prefixed.encoding:
|
|
46
|
+
encoding = target_spec.prefixed.encoding
|
|
47
|
+
elif target_spec.null_terminated is not None:
|
|
48
|
+
encoding = target_spec.null_terminated.encoding
|
|
49
|
+
return len(target_value.encode(encoding))
|
|
50
|
+
if isinstance(target_value, (list, tuple)):
|
|
51
|
+
return len(cast(Any, target_value))
|
|
52
|
+
if target_value is None:
|
|
53
|
+
return 0
|
|
54
|
+
# Nested model: encoded size.
|
|
55
|
+
if hasattr(target_value, "encoded_size"):
|
|
56
|
+
return int(target_value.encoded_size())
|
|
57
|
+
return int(target_value) if isinstance(target_value, int) else len(target_value) # type: ignore[arg-type]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _encode_storage(
|
|
61
|
+
value: Any,
|
|
62
|
+
storage_spec: FieldSpec,
|
|
63
|
+
writer: Writer,
|
|
64
|
+
byte_order: str,
|
|
65
|
+
path: str,
|
|
66
|
+
offsets: dict[str, tuple[int, int]],
|
|
67
|
+
specs_by_name: dict[str, FieldSpec],
|
|
68
|
+
values: dict[str, Any],
|
|
69
|
+
) -> None:
|
|
70
|
+
"""Encode a storage value (for codecs) using a storage spec."""
|
|
71
|
+
if storage_spec.kind == "model" and storage_spec.nested is not None:
|
|
72
|
+
encode_into(value, writer, byte_order, path, offsets)
|
|
73
|
+
return
|
|
74
|
+
if storage_spec.int_spec is not None:
|
|
75
|
+
checkint_range(storage_spec, value, path)
|
|
76
|
+
writer.write_int(
|
|
77
|
+
int(value),
|
|
78
|
+
storage_spec.int_spec.bits,
|
|
79
|
+
storage_spec.int_spec.signed,
|
|
80
|
+
storage_spec.int_spec.byte_order or byte_order,
|
|
81
|
+
)
|
|
82
|
+
return
|
|
83
|
+
if storage_spec.float_spec is not None:
|
|
84
|
+
writer.write_float(float(value), storage_spec.float_spec.bits, byte_order)
|
|
85
|
+
return
|
|
86
|
+
raise EncodeError(f"Unsupported codec storage type for {path}", path=path)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def checkint_range(spec: FieldSpec, value: Any, path: str) -> None:
|
|
90
|
+
if spec.int_spec is None:
|
|
91
|
+
return
|
|
92
|
+
lo, hi = int_range(spec)
|
|
93
|
+
if not (lo <= int(value) <= hi):
|
|
94
|
+
raise ValidationError(
|
|
95
|
+
"",
|
|
96
|
+
path=path,
|
|
97
|
+
expected=f"integer between {lo} and {hi}",
|
|
98
|
+
received=value,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _encode_element(
|
|
103
|
+
value: Any,
|
|
104
|
+
elem_spec: FieldSpec,
|
|
105
|
+
writer: Writer,
|
|
106
|
+
byte_order: str,
|
|
107
|
+
path: str,
|
|
108
|
+
) -> None:
|
|
109
|
+
if elem_spec.kind == "model" and elem_spec.nested is not None:
|
|
110
|
+
encode_into(value, writer, byte_order, path, {})
|
|
111
|
+
return
|
|
112
|
+
if elem_spec.kind == "enum" and elem_spec.enum_type is not None:
|
|
113
|
+
raw = value.value if isinstance(value, enum.Enum) else int(value)
|
|
114
|
+
underlying = elem_spec.int_spec or IntegerCodec(bits=8, signed=False)
|
|
115
|
+
writer.write_int(raw, underlying.bits, underlying.signed, byte_order)
|
|
116
|
+
return
|
|
117
|
+
if elem_spec.int_spec is not None:
|
|
118
|
+
checkint_range(elem_spec, value, path)
|
|
119
|
+
writer.write_int(
|
|
120
|
+
int(value),
|
|
121
|
+
elem_spec.int_spec.bits,
|
|
122
|
+
elem_spec.int_spec.signed,
|
|
123
|
+
elem_spec.int_spec.byte_order or byte_order,
|
|
124
|
+
)
|
|
125
|
+
return
|
|
126
|
+
if elem_spec.float_spec is not None:
|
|
127
|
+
writer.write_float(float(value), elem_spec.float_spec.bits, byte_order)
|
|
128
|
+
return
|
|
129
|
+
if elem_spec.kind == "bool":
|
|
130
|
+
writer.write_bytes(b"\x01" if value else b"\x00")
|
|
131
|
+
return
|
|
132
|
+
if elem_spec.kind == "bytes":
|
|
133
|
+
writer.write_bytes(bytes(value))
|
|
134
|
+
return
|
|
135
|
+
if elem_spec.kind == "str":
|
|
136
|
+
writer.write_bytes(str(value).encode("utf-8"))
|
|
137
|
+
return
|
|
138
|
+
raise EncodeError(f"Unsupported array element type for {path}", path=path)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def encode_into(
|
|
142
|
+
instance: Any,
|
|
143
|
+
writer: Writer,
|
|
144
|
+
byte_order: str,
|
|
145
|
+
path: str = "",
|
|
146
|
+
offsets: dict[str, tuple[int, int]] | None = None,
|
|
147
|
+
) -> dict[str, tuple[int, int]]:
|
|
148
|
+
"""Encode ``instance`` into ``writer``. Returns field byte offsets."""
|
|
149
|
+
|
|
150
|
+
specs = instance.__class__._binal_specs() # type: ignore[attr-defined]
|
|
151
|
+
specs_by_name = {s.name: s for s in specs}
|
|
152
|
+
values: dict[str, Any] = {}
|
|
153
|
+
for spec in specs:
|
|
154
|
+
if spec.is_derived and spec.magic is None and spec.padding is None:
|
|
155
|
+
# Derived values are computed below from target fields.
|
|
156
|
+
values[spec.name] = getattr(instance, spec.name, None)
|
|
157
|
+
else:
|
|
158
|
+
values[spec.name] = getattr(instance, spec.name, None)
|
|
159
|
+
if offsets is None:
|
|
160
|
+
offsets = {}
|
|
161
|
+
checksum_placeholders: list[tuple[FieldSpec, int, int]] = []
|
|
162
|
+
|
|
163
|
+
for spec in specs:
|
|
164
|
+
field_path = f"{path}.{spec.name}" if path else spec.name
|
|
165
|
+
if spec.when is not None:
|
|
166
|
+
cond = values.get(spec.when.field)
|
|
167
|
+
if cond != spec.when.equals:
|
|
168
|
+
continue
|
|
169
|
+
if spec.align is not None:
|
|
170
|
+
writer.align(spec.align.alignment)
|
|
171
|
+
start = writer.tell()
|
|
172
|
+
|
|
173
|
+
if spec.magic is not None:
|
|
174
|
+
writer.write_bytes(spec.magic.value)
|
|
175
|
+
offsets[spec.name] = (start, writer.tell())
|
|
176
|
+
continue
|
|
177
|
+
if spec.padding is not None:
|
|
178
|
+
writer.write_bytes(b"\x00" * spec.padding.length)
|
|
179
|
+
offsets[spec.name] = (start, writer.tell())
|
|
180
|
+
continue
|
|
181
|
+
if spec.checksum is not None:
|
|
182
|
+
size = spec.fixed_size or 4
|
|
183
|
+
placeholder_pos = writer.tell()
|
|
184
|
+
writer.write_bytes(b"\x00" * size)
|
|
185
|
+
offsets[spec.name] = (start, writer.tell())
|
|
186
|
+
checksum_placeholders.append((spec, placeholder_pos, size))
|
|
187
|
+
continue
|
|
188
|
+
if spec.length_of is not None or spec.count_of is not None:
|
|
189
|
+
target_name = (
|
|
190
|
+
spec.length_of.field if spec.length_of else spec.count_of.field
|
|
191
|
+
) # type: ignore[union-attr]
|
|
192
|
+
target_spec = specs_by_name.get(target_name)
|
|
193
|
+
target_value = values.get(target_name)
|
|
194
|
+
derived = derived_length(target_value, target_spec)
|
|
195
|
+
# Keep the instance attribute in sync.
|
|
196
|
+
object.__setattr__(instance, spec.name, derived)
|
|
197
|
+
values[spec.name] = derived
|
|
198
|
+
if spec.int_spec is not None:
|
|
199
|
+
checkint_range(spec, derived, field_path)
|
|
200
|
+
writer.write_int(
|
|
201
|
+
derived,
|
|
202
|
+
spec.int_spec.bits,
|
|
203
|
+
spec.int_spec.signed,
|
|
204
|
+
spec.int_spec.byte_order or byte_order,
|
|
205
|
+
)
|
|
206
|
+
offsets[spec.name] = (start, writer.tell())
|
|
207
|
+
continue
|
|
208
|
+
|
|
209
|
+
value = values.get(spec.name)
|
|
210
|
+
_encode_field(
|
|
211
|
+
spec,
|
|
212
|
+
value,
|
|
213
|
+
writer,
|
|
214
|
+
byte_order,
|
|
215
|
+
field_path,
|
|
216
|
+
offsets,
|
|
217
|
+
specs_by_name,
|
|
218
|
+
values,
|
|
219
|
+
instance,
|
|
220
|
+
)
|
|
221
|
+
offsets[spec.name] = (start, writer.tell())
|
|
222
|
+
|
|
223
|
+
# Patch checksums now that all target fields are encoded.
|
|
224
|
+
data = writer.data
|
|
225
|
+
for spec, pos, size in checksum_placeholders:
|
|
226
|
+
assert spec.checksum is not None
|
|
227
|
+
parts = b"".join(
|
|
228
|
+
data[s:e] for name in spec.checksum.fields for (s, e) in [offsets[name]]
|
|
229
|
+
)
|
|
230
|
+
digest = spec.checksum.algorithm(parts)
|
|
231
|
+
order = byte_order
|
|
232
|
+
if spec.int_spec is not None and spec.int_spec.byte_order:
|
|
233
|
+
order = spec.int_spec.byte_order
|
|
234
|
+
digest_bytes = int(digest).to_bytes(
|
|
235
|
+
size, cast(Literal["big", "little"], order), signed=False
|
|
236
|
+
)
|
|
237
|
+
data[pos : pos + size] = digest_bytes
|
|
238
|
+
object.__setattr__(instance, spec.name, digest)
|
|
239
|
+
values[spec.name] = digest
|
|
240
|
+
return offsets
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _encode_field(
|
|
244
|
+
spec: FieldSpec,
|
|
245
|
+
value: Any,
|
|
246
|
+
writer: Writer,
|
|
247
|
+
byte_order: str,
|
|
248
|
+
path: str,
|
|
249
|
+
offsets: dict[str, tuple[int, int]],
|
|
250
|
+
specs_by_name: dict[str, FieldSpec],
|
|
251
|
+
values: dict[str, Any],
|
|
252
|
+
instance: Any,
|
|
253
|
+
) -> None:
|
|
254
|
+
if value is None:
|
|
255
|
+
# Optional / conditional-absent field.
|
|
256
|
+
return
|
|
257
|
+
check_constraints(spec, value, path)
|
|
258
|
+
|
|
259
|
+
# Custom codec.
|
|
260
|
+
if spec.codec is not None:
|
|
261
|
+
codec = spec.codec if not isinstance(spec.codec, type) else spec.codec()
|
|
262
|
+
storage_value = codec.encode(value)
|
|
263
|
+
storage_spec = spec.codec_storage_spec
|
|
264
|
+
if storage_spec is None:
|
|
265
|
+
raise EncodeError(f"Codec for {path} has no storage type", path=path)
|
|
266
|
+
_encode_storage(
|
|
267
|
+
storage_value,
|
|
268
|
+
storage_spec,
|
|
269
|
+
writer,
|
|
270
|
+
byte_order,
|
|
271
|
+
path,
|
|
272
|
+
offsets,
|
|
273
|
+
specs_by_name,
|
|
274
|
+
values,
|
|
275
|
+
)
|
|
276
|
+
return
|
|
277
|
+
|
|
278
|
+
if spec.kind == "int" and spec.int_spec is not None:
|
|
279
|
+
checkint_range(spec, value, path)
|
|
280
|
+
writer.write_int(
|
|
281
|
+
int(value),
|
|
282
|
+
spec.int_spec.bits,
|
|
283
|
+
spec.int_spec.signed,
|
|
284
|
+
spec.int_spec.byte_order or byte_order,
|
|
285
|
+
)
|
|
286
|
+
return
|
|
287
|
+
if spec.kind == "varint" and spec.varint_spec is not None:
|
|
288
|
+
writer.write_varint(int(value), spec.varint_spec.kind, spec.varint_spec.zigzag)
|
|
289
|
+
return
|
|
290
|
+
if spec.kind == "float" and spec.float_spec is not None:
|
|
291
|
+
writer.write_float(float(value), spec.float_spec.bits, byte_order)
|
|
292
|
+
return
|
|
293
|
+
if spec.kind == "bool":
|
|
294
|
+
writer.write_bytes(b"\x01" if value else b"\x00")
|
|
295
|
+
return
|
|
296
|
+
if spec.kind == "bit":
|
|
297
|
+
width = spec.bits.width if spec.bits else 1
|
|
298
|
+
if spec.origin is bool:
|
|
299
|
+
bit_value = 1 if value else 0
|
|
300
|
+
else:
|
|
301
|
+
bit_value = int(value)
|
|
302
|
+
writer.write_bits(bit_value, width)
|
|
303
|
+
return
|
|
304
|
+
if spec.kind == "bytes":
|
|
305
|
+
raw = bytes(value)
|
|
306
|
+
if spec.prefixed is not None:
|
|
307
|
+
prefix_base, _prefix_meta = _prefix_int_spec(spec.prefixed.prefix_type)
|
|
308
|
+
writer.write_int(len(raw), prefix_base.bits, prefix_base.signed, byte_order)
|
|
309
|
+
writer.write_bytes(raw)
|
|
310
|
+
elif spec.fixed is not None:
|
|
311
|
+
if len(raw) > spec.fixed.length:
|
|
312
|
+
raise ValidationError(
|
|
313
|
+
"",
|
|
314
|
+
path=path,
|
|
315
|
+
expected=f"length at most {spec.fixed.length}",
|
|
316
|
+
received=len(raw),
|
|
317
|
+
)
|
|
318
|
+
writer.write_bytes(raw + b"\x00" * (spec.fixed.length - len(raw)))
|
|
319
|
+
elif spec.sized is not None:
|
|
320
|
+
expected_len = values.get(spec.sized.field)
|
|
321
|
+
if expected_len is not None and len(raw) != expected_len:
|
|
322
|
+
raise ValidationError(
|
|
323
|
+
"", path=path, expected=f"length {expected_len}", received=len(raw)
|
|
324
|
+
)
|
|
325
|
+
writer.write_bytes(raw)
|
|
326
|
+
else:
|
|
327
|
+
writer.write_bytes(raw)
|
|
328
|
+
return
|
|
329
|
+
if spec.kind == "str":
|
|
330
|
+
encoding = (
|
|
331
|
+
(spec.fixed.encoding if spec.fixed else None)
|
|
332
|
+
or (spec.prefixed.encoding if spec.prefixed else None)
|
|
333
|
+
or (spec.null_terminated.encoding if spec.null_terminated else None)
|
|
334
|
+
or "utf-8"
|
|
335
|
+
)
|
|
336
|
+
raw = str(value).encode(encoding)
|
|
337
|
+
if spec.prefixed is not None:
|
|
338
|
+
prefix_base, _ = _prefix_int_spec(spec.prefixed.prefix_type)
|
|
339
|
+
writer.write_int(len(raw), prefix_base.bits, prefix_base.signed, byte_order)
|
|
340
|
+
writer.write_bytes(raw)
|
|
341
|
+
elif spec.fixed is not None:
|
|
342
|
+
if len(raw) > spec.fixed.length:
|
|
343
|
+
raise ValidationError(
|
|
344
|
+
"",
|
|
345
|
+
path=path,
|
|
346
|
+
expected=f"length at most {spec.fixed.length}",
|
|
347
|
+
received=len(raw),
|
|
348
|
+
)
|
|
349
|
+
writer.write_bytes(raw + b"\x00" * (spec.fixed.length - len(raw)))
|
|
350
|
+
elif spec.null_terminated is not None:
|
|
351
|
+
writer.write_bytes(raw + b"\x00")
|
|
352
|
+
elif spec.sized is not None:
|
|
353
|
+
expected_len = values.get(spec.sized.field)
|
|
354
|
+
if expected_len is not None and len(raw) != expected_len:
|
|
355
|
+
raise ValidationError(
|
|
356
|
+
"", path=path, expected=f"length {expected_len}", received=len(raw)
|
|
357
|
+
)
|
|
358
|
+
writer.write_bytes(raw)
|
|
359
|
+
else:
|
|
360
|
+
writer.write_bytes(raw)
|
|
361
|
+
return
|
|
362
|
+
if spec.kind == "list":
|
|
363
|
+
items = list(value)
|
|
364
|
+
if spec.array is not None and spec.array.count_prefix is not None:
|
|
365
|
+
prefix_base, _ = _prefix_int_spec(spec.array.count_prefix)
|
|
366
|
+
writer.write_int(
|
|
367
|
+
len(items), prefix_base.bits, prefix_base.signed, byte_order
|
|
368
|
+
)
|
|
369
|
+
elif spec.array is not None and isinstance(spec.array.count, int):
|
|
370
|
+
if len(items) != spec.array.count:
|
|
371
|
+
raise ValidationError(
|
|
372
|
+
"",
|
|
373
|
+
path=path,
|
|
374
|
+
expected=f"length {spec.array.count}",
|
|
375
|
+
received=len(items),
|
|
376
|
+
)
|
|
377
|
+
elif spec.array is not None and isinstance(spec.array.count, str):
|
|
378
|
+
expected = values.get(spec.array.count)
|
|
379
|
+
if expected is not None and len(items) != expected:
|
|
380
|
+
raise ValidationError(
|
|
381
|
+
"", path=path, expected=f"length {expected}", received=len(items)
|
|
382
|
+
)
|
|
383
|
+
elem_spec = spec.element_spec
|
|
384
|
+
if elem_spec is None:
|
|
385
|
+
raise EncodeError(f"No element spec for {path}", path=path)
|
|
386
|
+
for i, item in enumerate(items):
|
|
387
|
+
_encode_element(item, elem_spec, writer, byte_order, f"{path}[{i}]")
|
|
388
|
+
return
|
|
389
|
+
if spec.kind == "model" and spec.nested is not None:
|
|
390
|
+
encode_into(value, writer, byte_order, path, {})
|
|
391
|
+
return
|
|
392
|
+
if spec.kind == "enum" and spec.enum_type is not None:
|
|
393
|
+
raw = value.value if isinstance(value, enum.Enum) else int(value)
|
|
394
|
+
underlying = spec.int_spec or IntegerCodec(bits=8, signed=False)
|
|
395
|
+
writer.write_int(raw, underlying.bits, underlying.signed, byte_order)
|
|
396
|
+
return
|
|
397
|
+
if spec.kind == "union":
|
|
398
|
+
if spec.tagged_union is not None:
|
|
399
|
+
discriminator = values.get(spec.tagged_union.discriminator)
|
|
400
|
+
variant = spec.tagged_union.variants.get(discriminator)
|
|
401
|
+
if variant is None:
|
|
402
|
+
raise EncodeError(
|
|
403
|
+
f"No union variant for discriminator {discriminator!r}", path=path
|
|
404
|
+
)
|
|
405
|
+
# value should already be an instance of the variant.
|
|
406
|
+
encode_into(value, writer, byte_order, path, {})
|
|
407
|
+
return
|
|
408
|
+
raise EncodeError(
|
|
409
|
+
f"Unsupported union field {path} (needs TaggedUnion)", path=path
|
|
410
|
+
)
|
|
411
|
+
raise EncodeError(f"Unsupported field kind {spec.kind!r} for {path}", path=path)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _prefix_int_spec(prefix_type: Any) -> tuple[IntegerCodec, Any]:
|
|
415
|
+
from ..types import IntegerCodec as _IC
|
|
416
|
+
from .compiler import split_annotated
|
|
417
|
+
|
|
418
|
+
base, meta = split_annotated(prefix_type)
|
|
419
|
+
for m in meta:
|
|
420
|
+
if isinstance(m, _IC):
|
|
421
|
+
return m, base
|
|
422
|
+
# Plain int type as prefix defaults to UInt16? Caller passes a type alias.
|
|
423
|
+
return _IC(bits=16, signed=False), base
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
__all__ = ["encode_into"]
|
binal/bits.py
ADDED
binal/checksum.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Checksum algorithms and the Checksum field marker."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import zlib
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def CRC32(data: bytes) -> int:
|
|
10
|
+
"""CRC-32 (IEEE) checksum, as an unsigned 32-bit integer."""
|
|
11
|
+
return zlib.crc32(data) & 0xFFFFFFFF
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def CRC16(data: bytes) -> int:
|
|
15
|
+
"""CRC-16/CCITT-FALSE checksum, as an unsigned 16-bit integer."""
|
|
16
|
+
crc = 0xFFFF
|
|
17
|
+
for byte in data:
|
|
18
|
+
crc ^= byte << 8
|
|
19
|
+
for _ in range(8):
|
|
20
|
+
crc = (
|
|
21
|
+
((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
|
|
22
|
+
)
|
|
23
|
+
return crc
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def Adler32(data: bytes) -> int:
|
|
27
|
+
"""Adler-32 checksum, as an unsigned 32-bit integer."""
|
|
28
|
+
return zlib.adler32(data) & 0xFFFFFFFF
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
ChecksumAlgorithm = Callable[[bytes], int]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Checksum:
|
|
35
|
+
"""Mark a field as a checksum over the encoded bytes of other fields.
|
|
36
|
+
|
|
37
|
+
Example::
|
|
38
|
+
|
|
39
|
+
checksum: Annotated[UInt32, Checksum(CRC32, fields=("content",))]
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
algorithm: ChecksumAlgorithm,
|
|
45
|
+
fields: tuple[str, ...] | list[str] = (),
|
|
46
|
+
) -> None:
|
|
47
|
+
self.algorithm = algorithm
|
|
48
|
+
self.fields = tuple(fields)
|
|
49
|
+
|
|
50
|
+
def __repr__(self) -> str:
|
|
51
|
+
name = getattr(self.algorithm, "__name__", repr(self.algorithm))
|
|
52
|
+
return f"Checksum({name}, fields={self.fields!r})"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
__all__ = ["CRC16", "CRC32", "Adler32", "Checksum", "ChecksumAlgorithm"]
|
binal/codecs.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Custom codecs: separate a Python representation from its binary storage."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Generic, TypeVar
|
|
6
|
+
|
|
7
|
+
PyT = TypeVar("PyT")
|
|
8
|
+
StorageT = TypeVar("StorageT")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Codec(Generic[PyT, StorageT]):
|
|
12
|
+
"""Base class for custom codecs.
|
|
13
|
+
|
|
14
|
+
Subclasses declare ``storage`` (the binary type used on the wire) and
|
|
15
|
+
implement :meth:`encode` (Python -> storage) and :meth:`decode`
|
|
16
|
+
(storage -> Python).
|
|
17
|
+
|
|
18
|
+
Example::
|
|
19
|
+
|
|
20
|
+
class TimestampCodec(Codec[datetime, int]):
|
|
21
|
+
storage = UInt64
|
|
22
|
+
|
|
23
|
+
def encode(self, value: datetime) -> int:
|
|
24
|
+
return int(value.timestamp())
|
|
25
|
+
|
|
26
|
+
def decode(self, value: int) -> datetime:
|
|
27
|
+
return datetime.fromtimestamp(value, tz=timezone.utc)
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
storage: Any = None
|
|
31
|
+
|
|
32
|
+
def encode(self, value: PyT) -> StorageT:
|
|
33
|
+
raise NotImplementedError
|
|
34
|
+
|
|
35
|
+
def decode(self, value: StorageT) -> PyT:
|
|
36
|
+
raise NotImplementedError
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
__all__ = ["Codec", "PyT", "StorageT"]
|
binal/collections.py
ADDED
binal/constraints.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Value constraints usable in ``Annotated`` field metadata."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Range:
|
|
11
|
+
"""Require a numeric value to lie within ``[minimum, maximum]``."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, minimum: float, maximum: float) -> None:
|
|
14
|
+
self.minimum = minimum
|
|
15
|
+
self.maximum = maximum
|
|
16
|
+
|
|
17
|
+
def __repr__(self) -> str:
|
|
18
|
+
return f"Range({self.minimum!r}, {self.maximum!r})"
|
|
19
|
+
|
|
20
|
+
def describe(self) -> str:
|
|
21
|
+
return f"integer between {self.minimum} and {self.maximum}"
|
|
22
|
+
|
|
23
|
+
def check(self, value: Any) -> bool:
|
|
24
|
+
return self.minimum <= value <= self.maximum
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MaxLength:
|
|
28
|
+
"""Require ``len(value) <= maximum``."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, maximum: int) -> None:
|
|
31
|
+
self.maximum = maximum
|
|
32
|
+
|
|
33
|
+
def __repr__(self) -> str:
|
|
34
|
+
return f"MaxLength({self.maximum!r})"
|
|
35
|
+
|
|
36
|
+
def describe(self) -> str:
|
|
37
|
+
return f"length at most {self.maximum}"
|
|
38
|
+
|
|
39
|
+
def check(self, value: Any) -> bool:
|
|
40
|
+
try:
|
|
41
|
+
return len(value) <= self.maximum
|
|
42
|
+
except TypeError:
|
|
43
|
+
return False
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class MinLength:
|
|
47
|
+
"""Require ``len(value) >= minimum``."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, minimum: int) -> None:
|
|
50
|
+
self.minimum = minimum
|
|
51
|
+
|
|
52
|
+
def __repr__(self) -> str:
|
|
53
|
+
return f"MinLength({self.minimum!r})"
|
|
54
|
+
|
|
55
|
+
def describe(self) -> str:
|
|
56
|
+
return f"length at least {self.minimum}"
|
|
57
|
+
|
|
58
|
+
def check(self, value: Any) -> bool:
|
|
59
|
+
try:
|
|
60
|
+
return len(value) >= self.minimum
|
|
61
|
+
except TypeError:
|
|
62
|
+
return False
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Pattern:
|
|
66
|
+
"""Require a string value to match a regular expression."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, pattern: str) -> None:
|
|
69
|
+
self.pattern = pattern
|
|
70
|
+
self._compiled = re.compile(pattern)
|
|
71
|
+
|
|
72
|
+
def __repr__(self) -> str:
|
|
73
|
+
return f"Pattern({self.pattern!r})"
|
|
74
|
+
|
|
75
|
+
def describe(self) -> str:
|
|
76
|
+
return f"string matching {self.pattern!r}"
|
|
77
|
+
|
|
78
|
+
def check(self, value: Any) -> bool:
|
|
79
|
+
return isinstance(value, str) and self._compiled.search(value) is not None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Custom:
|
|
83
|
+
"""Require a value to satisfy a user-supplied predicate."""
|
|
84
|
+
|
|
85
|
+
def __init__(self, validator: Callable[[Any], bool], description: str = "") -> None:
|
|
86
|
+
self.validator = validator
|
|
87
|
+
self.description = description or getattr(
|
|
88
|
+
validator, "__name__", "custom validation"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def __repr__(self) -> str:
|
|
92
|
+
return f"Custom({self.description!r})"
|
|
93
|
+
|
|
94
|
+
def describe(self) -> str:
|
|
95
|
+
return self.description
|
|
96
|
+
|
|
97
|
+
def check(self, value: Any) -> bool:
|
|
98
|
+
return bool(self.validator(value))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
__all__ = ["Custom", "MaxLength", "MinLength", "Pattern", "Range"]
|