dataclass-native 1.0.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.
- dataclass_native/__init__.py +60 -0
- dataclass_native/__main__.py +5 -0
- dataclass_native/_arrow.py +822 -0
- dataclass_native/_json.py +783 -0
- dataclass_native/_mode.py +57 -0
- dataclass_native/_msgpack.py +207 -0
- dataclass_native/_native.py +234 -0
- dataclass_native/_runtime.py +607 -0
- dataclass_native/_version.py +24 -0
- dataclass_native/_wire.py +901 -0
- dataclass_native/arrays.py +13 -0
- dataclass_native/backends/__init__.py +0 -0
- dataclass_native/backends/bindings.py +74 -0
- dataclass_native/backends/cpp.py +574 -0
- dataclass_native/backends/templates/bindings.cpp.j2 +58 -0
- dataclass_native/backends/templates/extensions.cmake.j2 +12 -0
- dataclass_native/backends/templates/header.hpp.j2 +75 -0
- dataclass_native/cli.py +125 -0
- dataclass_native/cmake/dataclass_native-config.cmake +67 -0
- dataclass_native/include/dataclass_native/arrow.hpp +2022 -0
- dataclass_native/include/dataclass_native/json.hpp +1903 -0
- dataclass_native/include/dataclass_native/msgpack.hpp +1513 -0
- dataclass_native/include/dataclass_native/python.hpp +594 -0
- dataclass_native/include/dataclass_native/reflect.hpp +63 -0
- dataclass_native/include/dataclass_native/types.hpp +417 -0
- dataclass_native/introspect.py +811 -0
- dataclass_native/py.typed +0 -0
- dataclass_native/schema.py +553 -0
- dataclass_native/types.py +103 -0
- dataclass_native-1.0.0.dist-info/METADATA +339 -0
- dataclass_native-1.0.0.dist-info/RECORD +35 -0
- dataclass_native-1.0.0.dist-info/WHEEL +5 -0
- dataclass_native-1.0.0.dist-info/entry_points.txt +2 -0
- dataclass_native-1.0.0.dist-info/licenses/LICENSE +21 -0
- dataclass_native-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,901 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reads and writes values of the schema's types as msgpack, in the wire format of WIRE_FORMAT.md.
|
|
3
|
+
|
|
4
|
+
write() and read() are the reference implementation of that format, in Python alone: they get and set the fields of
|
|
5
|
+
@native objects as any Python code does, so work in every mode. to_msgpack() and from_msgpack() use them, unless the
|
|
6
|
+
object is stored natively: then the C++ of dataclass_native/msgpack.hpp writes and reads the native object itself.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import datetime as dt
|
|
10
|
+
import decimal
|
|
11
|
+
import math
|
|
12
|
+
import re
|
|
13
|
+
import struct
|
|
14
|
+
import sys
|
|
15
|
+
import uuid
|
|
16
|
+
from collections.abc import Callable, Mapping
|
|
17
|
+
from typing import Any, overload
|
|
18
|
+
from weakref import WeakKeyDictionary
|
|
19
|
+
|
|
20
|
+
from . import _msgpack as m
|
|
21
|
+
from . import schema as s
|
|
22
|
+
from ._mode import Mode, mode
|
|
23
|
+
from ._native import is_native, native_info
|
|
24
|
+
from .introspect import _tag, describe, resolve, walk
|
|
25
|
+
|
|
26
|
+
REF = 1
|
|
27
|
+
"""The extension type of a reference to a shared object: the index of its table, and its row in it"""
|
|
28
|
+
TIMESTAMP = -1
|
|
29
|
+
|
|
30
|
+
_EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.UTC)
|
|
31
|
+
_EPOCH_DAY = dt.date(1970, 1, 1).toordinal()
|
|
32
|
+
# What a Decimal is written as: digits, with no exponent
|
|
33
|
+
_DECIMAL = re.compile(r"-?[0-9]+(\.[0-9]+)?", re.ASCII)
|
|
34
|
+
# Of a datetime with no timezone
|
|
35
|
+
_LOCAL_EPOCH = dt.datetime(1970, 1, 1)
|
|
36
|
+
_MICROSECOND = dt.timedelta(microseconds=1)
|
|
37
|
+
_SECOND = dt.timedelta(seconds=1)
|
|
38
|
+
_DAY_MICROSECONDS = 86_400_000_000
|
|
39
|
+
# As deeply as what is read may be nested
|
|
40
|
+
_MAX_DEPTH = 256
|
|
41
|
+
_BYTE = s.Int(8, signed=False)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _Invalid(Exception):
|
|
45
|
+
"""A value is not of the type being written, or what is being read is not that type as written"""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _Writer:
|
|
49
|
+
"""The shared objects of what is being written"""
|
|
50
|
+
|
|
51
|
+
def __init__(self):
|
|
52
|
+
self.tables: dict[str, list[bytes]] = {}
|
|
53
|
+
"""By tag, in the order first used: the objects, as written"""
|
|
54
|
+
self.references: dict[int, tuple[int, int]] = {}
|
|
55
|
+
"""By id of a shared object, the index of its table and its row"""
|
|
56
|
+
self.shared: list[Any] = []
|
|
57
|
+
"""The shared objects, kept so that no other object comes to have an id of theirs"""
|
|
58
|
+
self.depth = 0
|
|
59
|
+
"""How many objects which are not frozen what is being written is within"""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _Reader:
|
|
63
|
+
"""The shared objects of what is being read"""
|
|
64
|
+
|
|
65
|
+
def __init__(self, tables: list[tuple[str, list[Any]]]):
|
|
66
|
+
self.tables = tables
|
|
67
|
+
self.objects: dict[tuple[int, int], Any] = {}
|
|
68
|
+
"""By reference, the objects read so far: _READING while one is being read"""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
_READING = object()
|
|
72
|
+
|
|
73
|
+
type _Encode = Callable[[Any, bytearray, _Writer], None]
|
|
74
|
+
type _Decode = Callable[[Any, _Reader], Any]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@overload
|
|
78
|
+
def from_msgpack[T](tp: type[T], data: bytes) -> T: ...
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@overload
|
|
82
|
+
def from_msgpack(tp: Any, data: bytes) -> Any: ...
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def to_msgpack(value: Any, tp: Any = None) -> bytes:
|
|
86
|
+
"""
|
|
87
|
+
A value as msgpack, in the wire format. An object stored natively is written natively.
|
|
88
|
+
|
|
89
|
+
:param tp: Its type, if not a @native class: any type a field may have, e.g. tuple[Trade, ...]
|
|
90
|
+
"""
|
|
91
|
+
cls = type(value)
|
|
92
|
+
if tp in (None, cls) and _native_class(cls) is not None:
|
|
93
|
+
from ._runtime import native_object
|
|
94
|
+
|
|
95
|
+
return native_object(value).__msgpack__()
|
|
96
|
+
return write(value, tp)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def from_msgpack(tp: Any, data: bytes) -> Any:
|
|
100
|
+
"""
|
|
101
|
+
The value of a type, read from msgpack in the wire format. Raises ValueError if the data is not that.
|
|
102
|
+
|
|
103
|
+
:param tp: A @native class, or any type a field may have
|
|
104
|
+
"""
|
|
105
|
+
native = _native_class(tp)
|
|
106
|
+
# A pydantic dataclass is made in Python, so that pydantic validates it
|
|
107
|
+
if native is not None and not _codec(tp).validated:
|
|
108
|
+
from ._runtime import wrap
|
|
109
|
+
|
|
110
|
+
return wrap(tp, native.__from_msgpack__(bytes(data)))
|
|
111
|
+
return read(tp, data)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _native_class(cls: Any) -> type | None:
|
|
115
|
+
"""The native class of a @native class which is bound to one"""
|
|
116
|
+
if mode() is Mode.PURE or not (isinstance(cls, type) and is_native(cls)):
|
|
117
|
+
return None
|
|
118
|
+
from ._runtime import bind
|
|
119
|
+
|
|
120
|
+
return bind(cls, required=mode() is Mode.STRICT)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def write(value: Any, tp: Any = None) -> bytes:
|
|
124
|
+
"""As to_msgpack, in Python alone"""
|
|
125
|
+
encode, _, bundled = _root(type(value) if tp is None else tp)
|
|
126
|
+
writer = _Writer()
|
|
127
|
+
root = bytearray()
|
|
128
|
+
try:
|
|
129
|
+
encode(value, root, writer)
|
|
130
|
+
except _Invalid:
|
|
131
|
+
raise TypeError(
|
|
132
|
+
f"{value!r} cannot be written as {_name(tp or type(value))}"
|
|
133
|
+
) from None
|
|
134
|
+
if not bundled:
|
|
135
|
+
return bytes(root)
|
|
136
|
+
|
|
137
|
+
out = bytearray()
|
|
138
|
+
m.pack_map(out, 2)
|
|
139
|
+
m.pack_str(out, "root")
|
|
140
|
+
out += root
|
|
141
|
+
m.pack_str(out, "shared")
|
|
142
|
+
m.pack_array(out, len(writer.tables))
|
|
143
|
+
for tag, rows in writer.tables.items():
|
|
144
|
+
m.pack_array(out, 2)
|
|
145
|
+
m.pack_str(out, tag)
|
|
146
|
+
m.pack_array(out, len(rows))
|
|
147
|
+
for row in rows:
|
|
148
|
+
out += row
|
|
149
|
+
return bytes(out)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def read(tp: Any, data: bytes) -> Any:
|
|
153
|
+
"""As from_msgpack, in Python alone"""
|
|
154
|
+
_, decode, bundled = _root(tp)
|
|
155
|
+
wire = m.unpack(data)
|
|
156
|
+
reader = _Reader([])
|
|
157
|
+
try:
|
|
158
|
+
if bundled:
|
|
159
|
+
wire, reader = _unbundle(wire)
|
|
160
|
+
return decode(wire, reader)
|
|
161
|
+
except _Invalid:
|
|
162
|
+
raise ValueError(
|
|
163
|
+
f"The data is not a {_name(tp)}, as written: {_brief(wire)}"
|
|
164
|
+
) from None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _name(tp: Any) -> str:
|
|
168
|
+
return tp.__qualname__ if isinstance(tp, type) else str(tp)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _brief(wire: Any) -> str:
|
|
172
|
+
text = repr(wire)
|
|
173
|
+
return text if len(text) <= 80 else f"{text[:77]}..."
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _unbundle(wire: Any) -> tuple[Any, _Reader]:
|
|
177
|
+
if (
|
|
178
|
+
type(wire) is not dict
|
|
179
|
+
or "root" not in wire
|
|
180
|
+
or type(wire.get("shared")) is not list
|
|
181
|
+
):
|
|
182
|
+
raise _Invalid
|
|
183
|
+
tables = []
|
|
184
|
+
for table in wire["shared"]:
|
|
185
|
+
if type(table) is not list or len(table) != 2:
|
|
186
|
+
raise _Invalid
|
|
187
|
+
tag, rows = table
|
|
188
|
+
if type(tag) is not str or type(rows) is not list:
|
|
189
|
+
raise _Invalid
|
|
190
|
+
tables.append((tag, rows))
|
|
191
|
+
return wire["root"], _Reader(tables)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _root(tp: Any) -> tuple[_Encode, _Decode, bool]:
|
|
195
|
+
"""To write and to read a type, and whether it is written as a bundle: with the objects it shares"""
|
|
196
|
+
if isinstance(tp, type) and is_native(tp):
|
|
197
|
+
codec = _codec(tp)
|
|
198
|
+
return codec.encode, codec.decode, codec.bundled
|
|
199
|
+
t = resolve(tp, _name(tp))
|
|
200
|
+
return _encoder(t), _decoder(t), _reaches(t, set())
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _reaches(t: s.Type, classes: set[type]) -> bool:
|
|
204
|
+
"""Whether a value of the type may hold, however deeply, a Shared one: adds the classes it may hold to classes"""
|
|
205
|
+
shared = False
|
|
206
|
+
for inner in walk(t):
|
|
207
|
+
if isinstance(inner, s.Shared):
|
|
208
|
+
shared = True
|
|
209
|
+
if isinstance(inner, s.StructRef) and inner.cls not in classes:
|
|
210
|
+
classes.add(inner.cls)
|
|
211
|
+
struct = describe(inner.cls)
|
|
212
|
+
assert isinstance(struct, s.Struct)
|
|
213
|
+
for f in struct.fields:
|
|
214
|
+
shared |= _reaches(f.type, classes)
|
|
215
|
+
return shared
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class _Codec:
|
|
219
|
+
"""Writes and reads a struct"""
|
|
220
|
+
|
|
221
|
+
def __init__(self, cls: type):
|
|
222
|
+
struct = describe(cls)
|
|
223
|
+
assert isinstance(struct, s.Struct)
|
|
224
|
+
self.cls = cls
|
|
225
|
+
self.tag = struct.tag
|
|
226
|
+
classes: set[type] = set()
|
|
227
|
+
self.bundled = _reaches(struct.ref, classes)
|
|
228
|
+
self.validated = any(hasattr(c, "__pydantic_validator__") for c in classes)
|
|
229
|
+
"""Whether it, or a class it may hold, is a pydantic dataclass"""
|
|
230
|
+
self.header = _packed(m.pack_map, len(struct.fields))
|
|
231
|
+
# Of each field: its name, that as written, and how to write and read it
|
|
232
|
+
self.fields = [
|
|
233
|
+
(f.name, _packed(m.pack_str, f.name), _encoder(f.type), _decoder(f.type))
|
|
234
|
+
for f in struct.fields
|
|
235
|
+
]
|
|
236
|
+
|
|
237
|
+
def encode(self, value: Any, out: bytearray, writer: _Writer):
|
|
238
|
+
# Exactly, as a subclass is another struct
|
|
239
|
+
if type(value) is not self.cls:
|
|
240
|
+
raise _Invalid
|
|
241
|
+
out += self.header
|
|
242
|
+
for name, key, encode, _ in self.fields:
|
|
243
|
+
out += key
|
|
244
|
+
item = getattr(value, name)
|
|
245
|
+
try:
|
|
246
|
+
encode(item, out, writer)
|
|
247
|
+
except _Invalid:
|
|
248
|
+
raise TypeError(
|
|
249
|
+
f"{self.cls.__qualname__}.{name} cannot be {item!r}"
|
|
250
|
+
) from None
|
|
251
|
+
|
|
252
|
+
def decode(self, wire: Any, reader: _Reader) -> Any:
|
|
253
|
+
if type(wire) is not dict:
|
|
254
|
+
raise _Invalid
|
|
255
|
+
# Those written: one which is not takes its default, and one which is not a field is ignored
|
|
256
|
+
fields = {}
|
|
257
|
+
for name, _, _, decode in self.fields:
|
|
258
|
+
if name in wire:
|
|
259
|
+
try:
|
|
260
|
+
fields[name] = decode(wire[name], reader)
|
|
261
|
+
except _Invalid:
|
|
262
|
+
raise ValueError(
|
|
263
|
+
f"{self.cls.__qualname__}.{name} cannot be read from {_brief(wire[name])}"
|
|
264
|
+
) from None
|
|
265
|
+
try:
|
|
266
|
+
return self.cls(**fields)
|
|
267
|
+
except TypeError as e:
|
|
268
|
+
# A field with no default was not written, or a native field rejects what was
|
|
269
|
+
raise ValueError(f"{self.cls.__qualname__} cannot be read: {e}") from None
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
_codecs: WeakKeyDictionary[type, _Codec] = WeakKeyDictionary()
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _codec(cls: type) -> _Codec:
|
|
276
|
+
try:
|
|
277
|
+
return _codecs[cls]
|
|
278
|
+
except KeyError:
|
|
279
|
+
codec = _codecs[cls] = _Codec(cls)
|
|
280
|
+
return codec
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _packed(pack: Callable[[bytearray, Any], None], value: Any) -> bytes:
|
|
284
|
+
out = bytearray()
|
|
285
|
+
pack(out, value)
|
|
286
|
+
return bytes(out)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _struct_class(t: s.Type) -> type | None:
|
|
290
|
+
match t:
|
|
291
|
+
case (
|
|
292
|
+
s.StructRef(cls=cls)
|
|
293
|
+
| s.Shared(s.StructRef(cls=cls))
|
|
294
|
+
| s.Indirect(s.StructRef(cls=cls))
|
|
295
|
+
):
|
|
296
|
+
return cls
|
|
297
|
+
case _:
|
|
298
|
+
return None
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _order(t: s.Type) -> Callable[[Any], Any] | None:
|
|
302
|
+
"""The key by which the elements of a set, or the keys of a map, are ordered when written"""
|
|
303
|
+
if not isinstance(t, s.EnumRef):
|
|
304
|
+
# As they are natively: numbers and times by value, str by code point and bytes by byte
|
|
305
|
+
return None
|
|
306
|
+
enum = describe(t.cls)
|
|
307
|
+
assert isinstance(enum, s.Enum)
|
|
308
|
+
order = {member.name: member.value for member in enum.members}
|
|
309
|
+
return {
|
|
310
|
+
value: order[member.name] for value, member in s.enum_members(t.cls).items()
|
|
311
|
+
}.__getitem__
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _ordered(values: Any, key: Callable[[Any], Any] | None) -> list[Any]:
|
|
315
|
+
try:
|
|
316
|
+
ordered = sorted(values, key=key)
|
|
317
|
+
except (TypeError, KeyError):
|
|
318
|
+
# Not all of the type, so they have no order
|
|
319
|
+
raise _Invalid from None
|
|
320
|
+
if key and len({key(value) for value in ordered}) < len(ordered):
|
|
321
|
+
# An enum's member, and its value too
|
|
322
|
+
raise _Invalid
|
|
323
|
+
return ordered
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# Each size of an array's shape
|
|
327
|
+
_SHAPE = s.Sequence(s.Int(64, signed=False))
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _numbers(t: s.Array) -> Callable[[Any], tuple[Any, ...]]:
|
|
331
|
+
"""Gives the numbers of an array of the type, the last of its dimensions varying fastest: it is written as the
|
|
332
|
+
tuple of them is, after its shape if it is of more than one dimension"""
|
|
333
|
+
np = sys.modules["numpy"]
|
|
334
|
+
dtype = np.dtype(t.dtype)
|
|
335
|
+
|
|
336
|
+
def numbers(value: Any) -> tuple[Any, ...]:
|
|
337
|
+
if (
|
|
338
|
+
type(value) is not np.ndarray
|
|
339
|
+
or value.dtype != dtype
|
|
340
|
+
or value.ndim != t.dimensions
|
|
341
|
+
):
|
|
342
|
+
raise _Invalid
|
|
343
|
+
return tuple(value.ravel().tolist())
|
|
344
|
+
|
|
345
|
+
return numbers
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _array(t: s.Array) -> Callable[..., Any]:
|
|
349
|
+
"""Gives the array of the type which holds some numbers, of a shape if it is of more than one dimension: one
|
|
350
|
+
which can be written to only if the type's can, as natively"""
|
|
351
|
+
np = sys.modules["numpy"]
|
|
352
|
+
dtype = np.dtype(t.dtype)
|
|
353
|
+
|
|
354
|
+
def array(numbers: tuple[Any, ...], shape: tuple[int, ...] | None = None) -> Any:
|
|
355
|
+
value = np.array(numbers, dtype)
|
|
356
|
+
if shape is not None:
|
|
357
|
+
if (
|
|
358
|
+
len(shape) != t.dimensions
|
|
359
|
+
or min(shape) < 0
|
|
360
|
+
or math.prod(shape) != len(numbers)
|
|
361
|
+
):
|
|
362
|
+
raise _Invalid
|
|
363
|
+
value = value.reshape(shape)
|
|
364
|
+
value.flags.writeable = t.writeable
|
|
365
|
+
return value
|
|
366
|
+
|
|
367
|
+
return array
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _exactly(typ: type, pack: Callable[[bytearray, Any], None]) -> _Encode:
|
|
371
|
+
def encode(value: Any, out: bytearray, writer: _Writer):
|
|
372
|
+
if type(value) is not typ:
|
|
373
|
+
raise _Invalid
|
|
374
|
+
pack(out, value)
|
|
375
|
+
|
|
376
|
+
return encode
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _encoder(t: s.Type) -> _Encode:
|
|
380
|
+
"""Writes a value of the type, raising _Invalid if it is not one"""
|
|
381
|
+
if cls := _struct_class(t):
|
|
382
|
+
if isinstance(t, s.StructRef) and t.mutable:
|
|
383
|
+
|
|
384
|
+
def nested(value: Any, out: bytearray, writer: _Writer):
|
|
385
|
+
# Which only an object that is not frozen may do
|
|
386
|
+
if writer.depth == _MAX_DEPTH:
|
|
387
|
+
raise ValueError(
|
|
388
|
+
"An object which holds itself, or is too deeply nested, cannot be written"
|
|
389
|
+
)
|
|
390
|
+
writer.depth += 1
|
|
391
|
+
_codec(cls).encode(value, out, writer)
|
|
392
|
+
writer.depth -= 1
|
|
393
|
+
|
|
394
|
+
return nested
|
|
395
|
+
|
|
396
|
+
if not isinstance(t, s.Shared):
|
|
397
|
+
# Its codec is found when used, not now, as the type may be recursive
|
|
398
|
+
return lambda value, out, writer: _codec(cls).encode(value, out, writer)
|
|
399
|
+
|
|
400
|
+
def share(value: Any, out: bytearray, writer: _Writer):
|
|
401
|
+
codec = _codec(cls)
|
|
402
|
+
if type(value) is not cls:
|
|
403
|
+
raise _Invalid
|
|
404
|
+
reference = writer.references.get(id(value))
|
|
405
|
+
if reference is None:
|
|
406
|
+
rows = writer.tables.setdefault(codec.tag, [])
|
|
407
|
+
reference = (list(writer.tables).index(codec.tag), len(rows))
|
|
408
|
+
writer.references[id(value)] = reference
|
|
409
|
+
writer.shared.append(value)
|
|
410
|
+
# Its row is taken before it is written, as it may share objects of its own type
|
|
411
|
+
rows.append(b"")
|
|
412
|
+
row = bytearray()
|
|
413
|
+
codec.encode(value, row, writer)
|
|
414
|
+
rows[reference[1]] = bytes(row)
|
|
415
|
+
m.pack_ext(out, REF, struct.pack(">II", *reference))
|
|
416
|
+
|
|
417
|
+
return share
|
|
418
|
+
|
|
419
|
+
match t:
|
|
420
|
+
case s.Bool():
|
|
421
|
+
return _exactly(bool, m.pack_bool)
|
|
422
|
+
|
|
423
|
+
case s.Int(min=low, max=high):
|
|
424
|
+
|
|
425
|
+
def integer(value: Any, out: bytearray, writer: _Writer):
|
|
426
|
+
if type(value) is not int or not low <= value <= high:
|
|
427
|
+
raise _Invalid
|
|
428
|
+
m.pack_int(out, value)
|
|
429
|
+
|
|
430
|
+
return integer
|
|
431
|
+
|
|
432
|
+
case s.Float(bits=bits):
|
|
433
|
+
|
|
434
|
+
def number(value: Any, out: bytearray, writer: _Writer):
|
|
435
|
+
if type(value) not in (float, int):
|
|
436
|
+
raise _Invalid
|
|
437
|
+
try:
|
|
438
|
+
m.pack_float(out, value, bits)
|
|
439
|
+
except (OverflowError, struct.error):
|
|
440
|
+
raise _Invalid from None
|
|
441
|
+
|
|
442
|
+
return number
|
|
443
|
+
|
|
444
|
+
case s.Str():
|
|
445
|
+
|
|
446
|
+
def text(value: Any, out: bytearray, writer: _Writer):
|
|
447
|
+
if type(value) is not str:
|
|
448
|
+
raise _Invalid
|
|
449
|
+
try:
|
|
450
|
+
m.pack_str(out, value)
|
|
451
|
+
except UnicodeEncodeError:
|
|
452
|
+
raise _Invalid from None
|
|
453
|
+
|
|
454
|
+
return text
|
|
455
|
+
|
|
456
|
+
case s.Bytes():
|
|
457
|
+
return _exactly(bytes, m.pack_bin)
|
|
458
|
+
|
|
459
|
+
case s.Decimal():
|
|
460
|
+
|
|
461
|
+
def number(value: Any, out: bytearray, writer: _Writer):
|
|
462
|
+
if type(value) is not decimal.Decimal:
|
|
463
|
+
raise _Invalid
|
|
464
|
+
try:
|
|
465
|
+
m.pack_str(out, format(t.value(t.unscaled(value)), "f"))
|
|
466
|
+
except ValueError:
|
|
467
|
+
raise _Invalid from None
|
|
468
|
+
|
|
469
|
+
return number
|
|
470
|
+
|
|
471
|
+
case s.Uuid():
|
|
472
|
+
return _exactly(uuid.UUID, lambda out, value: m.pack_bin(out, value.bytes))
|
|
473
|
+
|
|
474
|
+
case s.Date():
|
|
475
|
+
return _exactly(
|
|
476
|
+
dt.date,
|
|
477
|
+
lambda out, value: m.pack_int(out, value.toordinal() - _EPOCH_DAY),
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
case s.Time():
|
|
481
|
+
|
|
482
|
+
def time(value: Any, out: bytearray, writer: _Writer):
|
|
483
|
+
if type(value) is not dt.time or value.tzinfo is not None:
|
|
484
|
+
raise _Invalid
|
|
485
|
+
seconds = (value.hour * 60 + value.minute) * 60 + value.second
|
|
486
|
+
m.pack_int(out, seconds * 1_000_000 + value.microsecond)
|
|
487
|
+
|
|
488
|
+
return time
|
|
489
|
+
|
|
490
|
+
case s.NaiveDateTime():
|
|
491
|
+
|
|
492
|
+
def local(value: Any, out: bytearray, writer: _Writer):
|
|
493
|
+
if type(value) is not dt.datetime or value.tzinfo is not None:
|
|
494
|
+
raise _Invalid
|
|
495
|
+
m.pack_int(out, (value - _LOCAL_EPOCH) // _MICROSECOND)
|
|
496
|
+
|
|
497
|
+
return local
|
|
498
|
+
|
|
499
|
+
case s.DateTime():
|
|
500
|
+
|
|
501
|
+
def instant(value: Any, out: bytearray, writer: _Writer):
|
|
502
|
+
if type(value) is not dt.datetime or value.utcoffset() is None:
|
|
503
|
+
raise _Invalid
|
|
504
|
+
seconds, rest = divmod(value - _EPOCH, _SECOND)
|
|
505
|
+
nanoseconds = rest // _MICROSECOND * 1000
|
|
506
|
+
# The shortest of msgpack's three timestamps which holds it
|
|
507
|
+
if not 0 <= seconds < 1 << 34:
|
|
508
|
+
data = struct.pack(">Iq", nanoseconds, seconds)
|
|
509
|
+
elif nanoseconds or seconds >= 1 << 32:
|
|
510
|
+
data = struct.pack(">Q", nanoseconds << 34 | seconds)
|
|
511
|
+
else:
|
|
512
|
+
data = struct.pack(">I", seconds)
|
|
513
|
+
m.pack_ext(out, TIMESTAMP, data)
|
|
514
|
+
|
|
515
|
+
return instant
|
|
516
|
+
|
|
517
|
+
case s.TimeDelta():
|
|
518
|
+
return _exactly(
|
|
519
|
+
dt.timedelta, lambda out, value: m.pack_int(out, value // _MICROSECOND)
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
case s.EnumRef(cls=enum):
|
|
523
|
+
names = {
|
|
524
|
+
value: _packed(m.pack_str, member.name)
|
|
525
|
+
for value, member in s.enum_members(enum).items()
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
def member(value: Any, out: bytearray, writer: _Writer):
|
|
529
|
+
try:
|
|
530
|
+
out += names[value]
|
|
531
|
+
except (KeyError, TypeError):
|
|
532
|
+
raise _Invalid from None
|
|
533
|
+
|
|
534
|
+
return member
|
|
535
|
+
|
|
536
|
+
case s.Optional(inner):
|
|
537
|
+
encode = _encoder(inner)
|
|
538
|
+
|
|
539
|
+
def optional(value: Any, out: bytearray, writer: _Writer):
|
|
540
|
+
if value is None:
|
|
541
|
+
m.pack_nil(out)
|
|
542
|
+
else:
|
|
543
|
+
encode(value, out, writer)
|
|
544
|
+
|
|
545
|
+
return optional
|
|
546
|
+
|
|
547
|
+
case s.Sequence(element) if element == _BYTE:
|
|
548
|
+
|
|
549
|
+
def octets(value: Any, out: bytearray, writer: _Writer):
|
|
550
|
+
if type(value) is not tuple:
|
|
551
|
+
raise _Invalid
|
|
552
|
+
try:
|
|
553
|
+
m.pack_bin(out, bytes(value))
|
|
554
|
+
except (TypeError, ValueError):
|
|
555
|
+
raise _Invalid from None
|
|
556
|
+
|
|
557
|
+
return octets
|
|
558
|
+
|
|
559
|
+
case s.Sequence(element) | s.Set(element):
|
|
560
|
+
encode = _encoder(element)
|
|
561
|
+
typ, key = (
|
|
562
|
+
(frozenset, _order(element)) if isinstance(t, s.Set) else (tuple, None)
|
|
563
|
+
)
|
|
564
|
+
|
|
565
|
+
def array(value: Any, out: bytearray, writer: _Writer):
|
|
566
|
+
if type(value) is not typ:
|
|
567
|
+
raise _Invalid
|
|
568
|
+
m.pack_array(out, len(value))
|
|
569
|
+
for item in _ordered(value, key) if typ is frozenset else value:
|
|
570
|
+
encode(item, out, writer)
|
|
571
|
+
|
|
572
|
+
return array
|
|
573
|
+
|
|
574
|
+
case s.Array(element, dimensions):
|
|
575
|
+
numbers, encode = _numbers(t), _encoder(s.Sequence(element))
|
|
576
|
+
if dimensions == 1:
|
|
577
|
+
return lambda value, out, writer: encode(numbers(value), out, writer)
|
|
578
|
+
encode_shape = _encoder(_SHAPE)
|
|
579
|
+
|
|
580
|
+
def shaped(value: Any, out: bytearray, writer: _Writer):
|
|
581
|
+
flat = numbers(value)
|
|
582
|
+
m.pack_array(out, 2)
|
|
583
|
+
encode_shape(value.shape, out, writer)
|
|
584
|
+
encode(flat, out, writer)
|
|
585
|
+
|
|
586
|
+
return shaped
|
|
587
|
+
|
|
588
|
+
case s.Tuple(elements):
|
|
589
|
+
encoders = [_encoder(e) for e in elements]
|
|
590
|
+
|
|
591
|
+
def fixed(value: Any, out: bytearray, writer: _Writer):
|
|
592
|
+
if type(value) is not tuple or len(value) != len(encoders):
|
|
593
|
+
raise _Invalid
|
|
594
|
+
m.pack_array(out, len(value))
|
|
595
|
+
for encode, item in zip(encoders, value, strict=True):
|
|
596
|
+
encode(item, out, writer)
|
|
597
|
+
|
|
598
|
+
return fixed
|
|
599
|
+
|
|
600
|
+
case s.Map(key_type, value_type):
|
|
601
|
+
encode_key, encode_value = _encoder(key_type), _encoder(value_type)
|
|
602
|
+
key = _order(key_type)
|
|
603
|
+
|
|
604
|
+
def mapping(value: Any, out: bytearray, writer: _Writer):
|
|
605
|
+
if not isinstance(value, Mapping):
|
|
606
|
+
raise _Invalid
|
|
607
|
+
m.pack_map(out, len(value))
|
|
608
|
+
for k in _ordered(value, key):
|
|
609
|
+
encode_key(k, out, writer)
|
|
610
|
+
encode_value(value[k], out, writer)
|
|
611
|
+
|
|
612
|
+
return mapping
|
|
613
|
+
|
|
614
|
+
case s.Union(members, discriminated):
|
|
615
|
+
encoders = [_encoder(member) for member in members]
|
|
616
|
+
tags = [_packed(m.pack_str, _tag(member) or "") for member in members]
|
|
617
|
+
|
|
618
|
+
def union(value: Any, out: bytearray, writer: _Writer):
|
|
619
|
+
index = _member(members, value)
|
|
620
|
+
if discriminated:
|
|
621
|
+
m.pack_map(out, 2)
|
|
622
|
+
out += _T + tags[index] + _V
|
|
623
|
+
encoders[index](value, out, writer)
|
|
624
|
+
|
|
625
|
+
return union
|
|
626
|
+
|
|
627
|
+
case _:
|
|
628
|
+
raise AssertionError(t)
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
_T, _V = _packed(m.pack_str, "t"), _packed(m.pack_str, "v")
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def _member(members: tuple[s.Type, ...], value: Any) -> int:
|
|
635
|
+
"""The member of a union which a value is of: by its exact type, so an int is a float only if not an int"""
|
|
636
|
+
whole = type(value) is int
|
|
637
|
+
for as_float in (False, True):
|
|
638
|
+
for index, member in enumerate(members):
|
|
639
|
+
if (whole and isinstance(member, s.Float)) is as_float and s.conforms(
|
|
640
|
+
member, value
|
|
641
|
+
):
|
|
642
|
+
return index
|
|
643
|
+
raise _Invalid
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def _decoder(t: s.Type) -> _Decode:
|
|
647
|
+
"""Reads a value of the type from what msgpack holds, raising _Invalid if that is not one as written"""
|
|
648
|
+
if cls := _struct_class(t):
|
|
649
|
+
if not isinstance(t, s.Shared):
|
|
650
|
+
return lambda wire, reader: _codec(cls).decode(wire, reader)
|
|
651
|
+
|
|
652
|
+
def shared(wire: Any, reader: _Reader) -> Any:
|
|
653
|
+
codec = _codec(cls)
|
|
654
|
+
if _reference(wire, reader) != codec.tag:
|
|
655
|
+
raise _Invalid
|
|
656
|
+
reference = struct.unpack(">II", wire.data)
|
|
657
|
+
obj = reader.objects.get(reference)
|
|
658
|
+
if obj is None:
|
|
659
|
+
reader.objects[reference] = _READING
|
|
660
|
+
row = reader.tables[reference[0]][1][reference[1]]
|
|
661
|
+
obj = reader.objects[reference] = codec.decode(row, reader)
|
|
662
|
+
elif obj is _READING:
|
|
663
|
+
# It shares itself, which no object written could
|
|
664
|
+
raise _Invalid
|
|
665
|
+
return obj
|
|
666
|
+
|
|
667
|
+
return shared
|
|
668
|
+
|
|
669
|
+
match t:
|
|
670
|
+
case s.Bool():
|
|
671
|
+
return _of(bool)
|
|
672
|
+
|
|
673
|
+
case s.Int(min=low, max=high):
|
|
674
|
+
|
|
675
|
+
def integer(wire: Any, reader: _Reader) -> Any:
|
|
676
|
+
if type(wire) is not int or not low <= wire <= high:
|
|
677
|
+
raise _Invalid
|
|
678
|
+
return wire
|
|
679
|
+
|
|
680
|
+
return integer
|
|
681
|
+
|
|
682
|
+
case s.Float():
|
|
683
|
+
# Of either size
|
|
684
|
+
return _of(float)
|
|
685
|
+
|
|
686
|
+
case s.Str():
|
|
687
|
+
return _of(str)
|
|
688
|
+
|
|
689
|
+
case s.Bytes():
|
|
690
|
+
return _of(bytes)
|
|
691
|
+
|
|
692
|
+
case s.Decimal():
|
|
693
|
+
|
|
694
|
+
def number(wire: Any, reader: _Reader) -> Any:
|
|
695
|
+
if type(wire) is not str or not _DECIMAL.fullmatch(wire):
|
|
696
|
+
raise _Invalid
|
|
697
|
+
try:
|
|
698
|
+
return t.value(t.unscaled(decimal.Decimal(wire)))
|
|
699
|
+
except ValueError:
|
|
700
|
+
raise _Invalid from None
|
|
701
|
+
|
|
702
|
+
return number
|
|
703
|
+
|
|
704
|
+
case s.Uuid():
|
|
705
|
+
# Which raises ValueError unless there are 16
|
|
706
|
+
return _of(bytes, lambda octets: uuid.UUID(bytes=octets))
|
|
707
|
+
|
|
708
|
+
case s.Date():
|
|
709
|
+
return _of(int, lambda days: dt.date.fromordinal(_EPOCH_DAY + days))
|
|
710
|
+
|
|
711
|
+
case s.Time():
|
|
712
|
+
|
|
713
|
+
def time(wire: Any, reader: _Reader) -> Any:
|
|
714
|
+
if type(wire) is not int or not 0 <= wire < _DAY_MICROSECONDS:
|
|
715
|
+
raise _Invalid
|
|
716
|
+
return (dt.datetime.min + wire * _MICROSECOND).time()
|
|
717
|
+
|
|
718
|
+
return time
|
|
719
|
+
|
|
720
|
+
case s.NaiveDateTime():
|
|
721
|
+
# Which raises OverflowError if beyond the years a datetime may be of
|
|
722
|
+
return _of(
|
|
723
|
+
int, lambda microseconds: _LOCAL_EPOCH + microseconds * _MICROSECOND
|
|
724
|
+
)
|
|
725
|
+
|
|
726
|
+
case s.DateTime():
|
|
727
|
+
|
|
728
|
+
def instant(wire: Any, reader: _Reader) -> Any:
|
|
729
|
+
if type(wire) is not m.Ext or wire.code != TIMESTAMP:
|
|
730
|
+
raise _Invalid
|
|
731
|
+
match len(wire.data):
|
|
732
|
+
case 4:
|
|
733
|
+
nanoseconds, seconds = 0, struct.unpack(">I", wire.data)[0]
|
|
734
|
+
case 8:
|
|
735
|
+
both = struct.unpack(">Q", wire.data)[0]
|
|
736
|
+
nanoseconds, seconds = both >> 34, both & ((1 << 34) - 1)
|
|
737
|
+
case 12:
|
|
738
|
+
nanoseconds, seconds = struct.unpack(">Iq", wire.data)
|
|
739
|
+
case _:
|
|
740
|
+
raise _Invalid
|
|
741
|
+
# A whole number of microseconds, as that is what a datetime holds
|
|
742
|
+
if nanoseconds >= 1_000_000_000 or nanoseconds % 1000:
|
|
743
|
+
raise _Invalid
|
|
744
|
+
try:
|
|
745
|
+
return _EPOCH + dt.timedelta(
|
|
746
|
+
seconds=seconds, microseconds=nanoseconds // 1000
|
|
747
|
+
)
|
|
748
|
+
except OverflowError:
|
|
749
|
+
raise _Invalid from None
|
|
750
|
+
|
|
751
|
+
return instant
|
|
752
|
+
|
|
753
|
+
case s.TimeDelta():
|
|
754
|
+
return _of(int, lambda microseconds: microseconds * _MICROSECOND)
|
|
755
|
+
|
|
756
|
+
case s.EnumRef(cls=enum):
|
|
757
|
+
members = {member.name: member for member in enum}
|
|
758
|
+
|
|
759
|
+
def member(wire: Any, reader: _Reader) -> Any:
|
|
760
|
+
try:
|
|
761
|
+
return members[wire]
|
|
762
|
+
except (KeyError, TypeError):
|
|
763
|
+
raise _Invalid from None
|
|
764
|
+
|
|
765
|
+
return member
|
|
766
|
+
|
|
767
|
+
case s.Optional(inner):
|
|
768
|
+
decode = _decoder(inner)
|
|
769
|
+
return lambda wire, reader: None if wire is None else decode(wire, reader)
|
|
770
|
+
|
|
771
|
+
case s.Sequence(element) if element == _BYTE:
|
|
772
|
+
return _of(bytes, tuple)
|
|
773
|
+
|
|
774
|
+
case s.Sequence(element) | s.Set(element):
|
|
775
|
+
decode = _decoder(element)
|
|
776
|
+
container = frozenset if isinstance(t, s.Set) else tuple
|
|
777
|
+
|
|
778
|
+
def array(wire: Any, reader: _Reader) -> Any:
|
|
779
|
+
if type(wire) is not list:
|
|
780
|
+
raise _Invalid
|
|
781
|
+
return container(decode(item, reader) for item in wire)
|
|
782
|
+
|
|
783
|
+
return array
|
|
784
|
+
|
|
785
|
+
case s.Array(element, dimensions):
|
|
786
|
+
held, decode = _array(t), _decoder(s.Sequence(element))
|
|
787
|
+
if dimensions == 1:
|
|
788
|
+
return lambda wire, reader: held(decode(wire, reader))
|
|
789
|
+
decode_shape = _decoder(_SHAPE)
|
|
790
|
+
|
|
791
|
+
def shaped(wire: Any, reader: _Reader) -> Any:
|
|
792
|
+
if type(wire) is not list or len(wire) != 2:
|
|
793
|
+
raise _Invalid
|
|
794
|
+
return held(decode(wire[1], reader), decode_shape(wire[0], reader))
|
|
795
|
+
|
|
796
|
+
return shaped
|
|
797
|
+
|
|
798
|
+
case s.Tuple(elements):
|
|
799
|
+
decoders = [_decoder(e) for e in elements]
|
|
800
|
+
|
|
801
|
+
def fixed(wire: Any, reader: _Reader) -> Any:
|
|
802
|
+
if type(wire) is not list or len(wire) != len(decoders):
|
|
803
|
+
raise _Invalid
|
|
804
|
+
return tuple(
|
|
805
|
+
decode(item, reader)
|
|
806
|
+
for decode, item in zip(decoders, wire, strict=True)
|
|
807
|
+
)
|
|
808
|
+
|
|
809
|
+
return fixed
|
|
810
|
+
|
|
811
|
+
case s.Map(key_type, value_type):
|
|
812
|
+
decode_key, decode_value = _decoder(key_type), _decoder(value_type)
|
|
813
|
+
|
|
814
|
+
def mapping(wire: Any, reader: _Reader) -> Any:
|
|
815
|
+
if type(wire) is not dict:
|
|
816
|
+
raise _Invalid
|
|
817
|
+
return {
|
|
818
|
+
decode_key(k, reader): decode_value(v, reader)
|
|
819
|
+
for k, v in wire.items()
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
return mapping
|
|
823
|
+
|
|
824
|
+
case s.Union(members, discriminated=True):
|
|
825
|
+
by_tag = {_tag(member): _decoder(member) for member in members}
|
|
826
|
+
|
|
827
|
+
def tagged(wire: Any, reader: _Reader) -> Any:
|
|
828
|
+
if type(wire) is not dict or wire.keys() != {"t", "v"}:
|
|
829
|
+
raise _Invalid
|
|
830
|
+
try:
|
|
831
|
+
decode = by_tag[wire["t"]]
|
|
832
|
+
except (KeyError, TypeError):
|
|
833
|
+
raise _Invalid from None
|
|
834
|
+
return decode(wire["v"], reader)
|
|
835
|
+
|
|
836
|
+
return tagged
|
|
837
|
+
|
|
838
|
+
case s.Union(members):
|
|
839
|
+
# No two are written as the same kind of msgpack value, or with the same tag if shared
|
|
840
|
+
by_kind = {_kind(member): _decoder(member) for member in members}
|
|
841
|
+
|
|
842
|
+
def union(wire: Any, reader: _Reader) -> Any:
|
|
843
|
+
kind = _KINDS.get(type(wire)) or _extension_kind(wire, reader)
|
|
844
|
+
try:
|
|
845
|
+
decode = by_kind[kind]
|
|
846
|
+
except KeyError:
|
|
847
|
+
raise _Invalid from None
|
|
848
|
+
return decode(wire, reader)
|
|
849
|
+
|
|
850
|
+
return union
|
|
851
|
+
|
|
852
|
+
case _:
|
|
853
|
+
raise AssertionError(t)
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _of(typ: type, convert: Callable[[Any], Any] | None = None) -> _Decode:
|
|
857
|
+
def decode(wire: Any, reader: _Reader) -> Any:
|
|
858
|
+
if type(wire) is not typ:
|
|
859
|
+
raise _Invalid
|
|
860
|
+
if convert is None:
|
|
861
|
+
return wire
|
|
862
|
+
try:
|
|
863
|
+
return convert(wire)
|
|
864
|
+
except (OverflowError, ValueError):
|
|
865
|
+
raise _Invalid from None
|
|
866
|
+
|
|
867
|
+
return decode
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
def _reference(wire: Any, reader: _Reader) -> str:
|
|
871
|
+
"""The tag of the shared object which a reference is to"""
|
|
872
|
+
if type(wire) is not m.Ext or wire.code != REF or len(wire.data) != 8:
|
|
873
|
+
raise _Invalid
|
|
874
|
+
table, row = struct.unpack(">II", wire.data)
|
|
875
|
+
if table >= len(reader.tables) or row >= len(reader.tables[table][1]):
|
|
876
|
+
raise _Invalid
|
|
877
|
+
return reader.tables[table][0]
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
_KINDS: dict[type, tuple[str, ...]] = {
|
|
881
|
+
bool: ("bool",),
|
|
882
|
+
int: ("int",),
|
|
883
|
+
float: ("float",),
|
|
884
|
+
str: ("str",),
|
|
885
|
+
bytes: ("bin",),
|
|
886
|
+
list: ("array",),
|
|
887
|
+
dict: ("map",),
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
|
|
891
|
+
def _kind(member: s.Type) -> tuple[str, ...]:
|
|
892
|
+
"""As schema.wire_kind, but a shared struct by its tag, which is what a reference to one gives"""
|
|
893
|
+
if isinstance(member, s.Shared):
|
|
894
|
+
return ("ref", native_info(member.target.cls).tag)
|
|
895
|
+
return s.wire_kind(member)
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def _extension_kind(wire: Any, reader: _Reader) -> tuple[str, ...]:
|
|
899
|
+
if type(wire) is m.Ext and wire.code == TIMESTAMP:
|
|
900
|
+
return ("timestamp",)
|
|
901
|
+
return ("ref", _reference(wire, reader))
|