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,783 @@
|
|
|
1
|
+
"""
|
|
2
|
+
JSON of @native objects, in the format of JSON_FORMAT.md: such that pydantic reads what this writes, and this reads
|
|
3
|
+
what pydantic writes. In Python alone, in every mode.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import base64
|
|
7
|
+
import binascii
|
|
8
|
+
import datetime as dt
|
|
9
|
+
import decimal
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
import re
|
|
13
|
+
import struct
|
|
14
|
+
import uuid
|
|
15
|
+
from collections.abc import Callable, Mapping
|
|
16
|
+
from typing import Any, overload
|
|
17
|
+
from weakref import WeakKeyDictionary
|
|
18
|
+
|
|
19
|
+
from . import schema as s
|
|
20
|
+
from ._native import is_native
|
|
21
|
+
from ._wire import (
|
|
22
|
+
_DECIMAL,
|
|
23
|
+
_EPOCH,
|
|
24
|
+
_LOCAL_EPOCH,
|
|
25
|
+
_MAX_DEPTH,
|
|
26
|
+
_MICROSECOND,
|
|
27
|
+
_array,
|
|
28
|
+
_brief,
|
|
29
|
+
_Invalid,
|
|
30
|
+
_member,
|
|
31
|
+
_name,
|
|
32
|
+
_native_class,
|
|
33
|
+
_numbers,
|
|
34
|
+
_order,
|
|
35
|
+
_ordered,
|
|
36
|
+
_struct_class,
|
|
37
|
+
)
|
|
38
|
+
from ._wire import _codec as _wire_codec
|
|
39
|
+
from .introspect import _tag, describe, resolve
|
|
40
|
+
from .schema import SchemaError
|
|
41
|
+
|
|
42
|
+
# Makes a value of a type plain: what the json module writes. Given how many objects which are not frozen it is within
|
|
43
|
+
type _Plain = Callable[[Any, int], Any]
|
|
44
|
+
# Makes a value of a type from what the json module read
|
|
45
|
+
type _Object = Callable[[Any], Any]
|
|
46
|
+
|
|
47
|
+
_DATE = r"\d{4}-\d\d-\d\d"
|
|
48
|
+
_TIME = r"([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d{1,6})?"
|
|
49
|
+
_FORMS = {
|
|
50
|
+
s.Date: re.compile(_DATE, re.ASCII),
|
|
51
|
+
s.Time: re.compile(_TIME, re.ASCII),
|
|
52
|
+
s.DateTime: re.compile(
|
|
53
|
+
rf"{_DATE}T{_TIME}(Z|[+-]([01]\d|2[0-3]):[0-5]\d)", re.ASCII
|
|
54
|
+
),
|
|
55
|
+
s.NaiveDateTime: re.compile(rf"{_DATE}T{_TIME}", re.ASCII),
|
|
56
|
+
s.Uuid: re.compile(
|
|
57
|
+
r"[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}", re.ASCII | re.IGNORECASE
|
|
58
|
+
),
|
|
59
|
+
}
|
|
60
|
+
# As ISO 8601 has a duration, of days and less: and of years of 365 days, which pydantic writes
|
|
61
|
+
_DURATION = re.compile(
|
|
62
|
+
r"(-)?P(?:(\d+)Y)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d{1,6}))?S)?)?",
|
|
63
|
+
re.ASCII,
|
|
64
|
+
)
|
|
65
|
+
_NOT_FINITE = {"NaN": math.nan, "Infinity": math.inf, "-Infinity": -math.inf}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _is_bytes(t: s.Type) -> bool:
|
|
69
|
+
"""Whether a type is a tuple of UInt8, which is written as bytes are"""
|
|
70
|
+
return isinstance(t, s.Sequence) and t.element == s.Int(8, signed=False)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@overload
|
|
74
|
+
def from_json[T](tp: type[T], data: str | bytes) -> T: ...
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@overload
|
|
78
|
+
def from_json(tp: Any, data: str | bytes) -> Any: ...
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def to_json(value: Any, tp: Any = None) -> bytes:
|
|
82
|
+
"""
|
|
83
|
+
A value as JSON, in the format of JSON_FORMAT.md: as UTF-8, which is what is stored or sent. An object stored
|
|
84
|
+
natively is written natively.
|
|
85
|
+
|
|
86
|
+
:param tp: Its type, if not a @native class: any type a field may have, e.g. tuple[Trade, ...]
|
|
87
|
+
"""
|
|
88
|
+
cls = type(value)
|
|
89
|
+
native = _native_class(cls) if tp in (None, cls) else None
|
|
90
|
+
# Which has no JSON if a union it holds cannot be told apart: as the Python then says
|
|
91
|
+
if native is not None and hasattr(native, "__json__"):
|
|
92
|
+
from ._runtime import native_object
|
|
93
|
+
|
|
94
|
+
return native_object(value).__json__()
|
|
95
|
+
return write(value, tp)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def from_json(tp: Any, data: str | bytes) -> Any:
|
|
99
|
+
"""
|
|
100
|
+
The value of a type, read from JSON in the format of JSON_FORMAT.md. Raises ValueError if the data is not that.
|
|
101
|
+
|
|
102
|
+
:param tp: A @native class, or any type a field may have
|
|
103
|
+
"""
|
|
104
|
+
native = _native_class(tp)
|
|
105
|
+
# A pydantic dataclass is made in Python, so that pydantic validates it
|
|
106
|
+
if (
|
|
107
|
+
native is not None
|
|
108
|
+
and hasattr(native, "__from_json__")
|
|
109
|
+
and not _wire_codec(tp).validated
|
|
110
|
+
):
|
|
111
|
+
from ._runtime import wrap
|
|
112
|
+
|
|
113
|
+
return wrap(
|
|
114
|
+
tp,
|
|
115
|
+
native.__from_json__(
|
|
116
|
+
data.encode() if isinstance(data, str) else bytes(data)
|
|
117
|
+
),
|
|
118
|
+
)
|
|
119
|
+
return read(tp, data)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def write(value: Any, tp: Any = None) -> bytes:
|
|
123
|
+
"""As to_json, in Python alone"""
|
|
124
|
+
plain, _ = _root(type(value) if tp is None else tp)
|
|
125
|
+
try:
|
|
126
|
+
made = plain(value, 0)
|
|
127
|
+
except _Invalid:
|
|
128
|
+
raise TypeError(
|
|
129
|
+
f"{value!r} cannot be written as {_name(tp or type(value))}"
|
|
130
|
+
) from None
|
|
131
|
+
text = json.dumps(made, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
|
|
132
|
+
return text.encode()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def read(tp: Any, data: str | bytes) -> Any:
|
|
136
|
+
"""As from_json, in Python alone"""
|
|
137
|
+
_, make = _root(tp)
|
|
138
|
+
try:
|
|
139
|
+
read = json.loads(data, object_pairs_hook=_once, parse_constant=_constant)
|
|
140
|
+
except (ValueError, RecursionError) as e:
|
|
141
|
+
raise ValueError(f"The data is not JSON: {e}") from None
|
|
142
|
+
try:
|
|
143
|
+
return make(read)
|
|
144
|
+
except _Invalid:
|
|
145
|
+
raise ValueError(
|
|
146
|
+
f"The data is not a {_name(tp)}, as written: {_brief(read)}"
|
|
147
|
+
) from None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _once(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
151
|
+
made = dict(pairs)
|
|
152
|
+
if len(made) != len(pairs):
|
|
153
|
+
raise ValueError("an object has a key twice")
|
|
154
|
+
return made
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _constant(name: str) -> Any:
|
|
158
|
+
raise ValueError(f"{name} is not JSON")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _root(tp: Any) -> tuple[_Plain, _Object]:
|
|
162
|
+
if isinstance(tp, type) and is_native(tp):
|
|
163
|
+
codec = _codec(tp)
|
|
164
|
+
return codec.plain, codec.object
|
|
165
|
+
t = resolve(tp, _name(tp))
|
|
166
|
+
return _plain(t, _name(tp)), _object(t, _name(tp))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class _Codec:
|
|
170
|
+
"""Writes and reads a struct, as an object of its fields"""
|
|
171
|
+
|
|
172
|
+
def __init__(self, cls: type):
|
|
173
|
+
struct_ = describe(cls)
|
|
174
|
+
assert isinstance(struct_, s.Struct)
|
|
175
|
+
self.cls = cls
|
|
176
|
+
self.fields: list[tuple[str, _Plain, _Object]] | None = None
|
|
177
|
+
self.struct = struct_
|
|
178
|
+
|
|
179
|
+
def __fields(self) -> list[tuple[str, _Plain, _Object]]:
|
|
180
|
+
# When used, not when made, as a field may be of its own class
|
|
181
|
+
if self.fields is None:
|
|
182
|
+
self.fields = [
|
|
183
|
+
(f.name, _plain(f.type, where), _object(f.type, where))
|
|
184
|
+
for f in self.struct.fields
|
|
185
|
+
for where in [f"{self.cls.__qualname__}.{f.name}"]
|
|
186
|
+
]
|
|
187
|
+
return self.fields
|
|
188
|
+
|
|
189
|
+
def plain(self, value: Any, depth: int) -> dict[str, Any]:
|
|
190
|
+
# Exactly, as a subclass is another struct
|
|
191
|
+
if type(value) is not self.cls:
|
|
192
|
+
raise _Invalid
|
|
193
|
+
made = {}
|
|
194
|
+
for name, plain, _ in self.__fields():
|
|
195
|
+
item = getattr(value, name)
|
|
196
|
+
try:
|
|
197
|
+
made[name] = plain(item, depth)
|
|
198
|
+
except _Invalid:
|
|
199
|
+
raise TypeError(
|
|
200
|
+
f"{self.cls.__qualname__}.{name} cannot be {item!r}"
|
|
201
|
+
) from None
|
|
202
|
+
return made
|
|
203
|
+
|
|
204
|
+
def object(self, read: Any) -> Any:
|
|
205
|
+
if type(read) is not dict:
|
|
206
|
+
raise _Invalid
|
|
207
|
+
# Those written: one which is not takes its default, and one which is not a field is ignored
|
|
208
|
+
fields = {}
|
|
209
|
+
for name, _, make in self.__fields():
|
|
210
|
+
if name in read:
|
|
211
|
+
try:
|
|
212
|
+
fields[name] = make(read[name])
|
|
213
|
+
except _Invalid:
|
|
214
|
+
raise ValueError(
|
|
215
|
+
f"{self.cls.__qualname__}.{name} cannot be read from {_brief(read[name])}"
|
|
216
|
+
) from None
|
|
217
|
+
try:
|
|
218
|
+
return self.cls(**fields)
|
|
219
|
+
except TypeError as e:
|
|
220
|
+
# A field with no default was not written, or a native field rejects what was
|
|
221
|
+
raise ValueError(f"{self.cls.__qualname__} cannot be read: {e}") from None
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
_codecs: WeakKeyDictionary[type, _Codec] = WeakKeyDictionary()
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _codec(cls: type) -> _Codec:
|
|
228
|
+
try:
|
|
229
|
+
return _codecs[cls]
|
|
230
|
+
except KeyError:
|
|
231
|
+
codec = _codecs[cls] = _Codec(cls)
|
|
232
|
+
return codec
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _text(t: s.Type) -> tuple[Callable[[Any], str], Callable[[str], Any]]:
|
|
236
|
+
"""Writes a value of a type which is written as a string, and reads it: _Invalid if it is not one"""
|
|
237
|
+
|
|
238
|
+
def checked(typ: type, write: Callable[[Any], str]) -> Callable[[Any], str]:
|
|
239
|
+
def text(value: Any) -> str:
|
|
240
|
+
if type(value) is not typ or not s.conforms(t, value):
|
|
241
|
+
raise _Invalid
|
|
242
|
+
try:
|
|
243
|
+
return write(value)
|
|
244
|
+
except (OverflowError, ValueError):
|
|
245
|
+
raise _Invalid from None
|
|
246
|
+
|
|
247
|
+
return text
|
|
248
|
+
|
|
249
|
+
def formed(read: Callable[[str], Any]) -> Callable[[str], Any]:
|
|
250
|
+
form = _FORMS[type(t)]
|
|
251
|
+
|
|
252
|
+
def value(text: str) -> Any:
|
|
253
|
+
if not form.fullmatch(text):
|
|
254
|
+
raise _Invalid
|
|
255
|
+
try:
|
|
256
|
+
return read(text)
|
|
257
|
+
except (OverflowError, ValueError):
|
|
258
|
+
raise _Invalid from None
|
|
259
|
+
|
|
260
|
+
return value
|
|
261
|
+
|
|
262
|
+
match t:
|
|
263
|
+
case s.Str():
|
|
264
|
+
|
|
265
|
+
def text(value: Any) -> str:
|
|
266
|
+
if type(value) is not str:
|
|
267
|
+
raise _Invalid
|
|
268
|
+
try:
|
|
269
|
+
value.encode()
|
|
270
|
+
except UnicodeEncodeError:
|
|
271
|
+
raise _Invalid from None
|
|
272
|
+
return value
|
|
273
|
+
|
|
274
|
+
# Nor read: half of a character, which an escape may be of, is not text
|
|
275
|
+
return text, text
|
|
276
|
+
|
|
277
|
+
case s.Bytes() | s.Sequence(s.Int(bits=8, signed=False)):
|
|
278
|
+
typ = bytes if isinstance(t, s.Bytes) else tuple
|
|
279
|
+
|
|
280
|
+
def encoded(value: Any) -> str:
|
|
281
|
+
if type(value) is not typ:
|
|
282
|
+
raise _Invalid
|
|
283
|
+
try:
|
|
284
|
+
return base64.urlsafe_b64encode(bytes(value)).decode()
|
|
285
|
+
except (TypeError, ValueError):
|
|
286
|
+
raise _Invalid from None
|
|
287
|
+
|
|
288
|
+
def decoded(read: str) -> Any:
|
|
289
|
+
if len(read) % 4:
|
|
290
|
+
raise _Invalid
|
|
291
|
+
try:
|
|
292
|
+
# Of either alphabet
|
|
293
|
+
data = base64.b64decode(
|
|
294
|
+
read.replace("+", "-").replace("/", "_"), b"-_", validate=True
|
|
295
|
+
)
|
|
296
|
+
except (binascii.Error, ValueError):
|
|
297
|
+
raise _Invalid from None
|
|
298
|
+
return typ(data)
|
|
299
|
+
|
|
300
|
+
return encoded, decoded
|
|
301
|
+
|
|
302
|
+
case s.Date():
|
|
303
|
+
return checked(dt.date, dt.date.isoformat), formed(dt.date.fromisoformat)
|
|
304
|
+
|
|
305
|
+
case s.Time():
|
|
306
|
+
return checked(dt.time, dt.time.isoformat), formed(dt.time.fromisoformat)
|
|
307
|
+
|
|
308
|
+
case s.DateTime():
|
|
309
|
+
# As UTC, which it is read back as: it is an instant
|
|
310
|
+
return (
|
|
311
|
+
checked(
|
|
312
|
+
dt.datetime,
|
|
313
|
+
lambda v: (_LOCAL_EPOCH + (v - _EPOCH)).isoformat() + "Z",
|
|
314
|
+
),
|
|
315
|
+
formed(lambda read: dt.datetime.fromisoformat(read).astimezone(dt.UTC)),
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
case s.NaiveDateTime():
|
|
319
|
+
return checked(dt.datetime, dt.datetime.isoformat), formed(
|
|
320
|
+
dt.datetime.fromisoformat
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
case s.Uuid():
|
|
324
|
+
return checked(uuid.UUID, str), formed(uuid.UUID)
|
|
325
|
+
|
|
326
|
+
case s.TimeDelta():
|
|
327
|
+
|
|
328
|
+
def duration(value: dt.timedelta) -> str:
|
|
329
|
+
whole = value // _MICROSECOND
|
|
330
|
+
days, rest = divmod(abs(whole), 86_400_000_000)
|
|
331
|
+
hours, rest = divmod(rest, 3_600_000_000)
|
|
332
|
+
minutes, rest = divmod(rest, 60_000_000)
|
|
333
|
+
seconds, micros = divmod(rest, 1_000_000)
|
|
334
|
+
parts = [(hours, "H"), (minutes, "M")]
|
|
335
|
+
time = "".join(f"{n}{unit}" for n, unit in parts if n)
|
|
336
|
+
if seconds or micros:
|
|
337
|
+
time += f"{seconds}.{micros:06}S" if micros else f"{seconds}S"
|
|
338
|
+
if not days and not time:
|
|
339
|
+
time = "0S"
|
|
340
|
+
return (
|
|
341
|
+
("-" if whole < 0 else "")
|
|
342
|
+
+ "P"
|
|
343
|
+
+ (f"{days}D" if days else "")
|
|
344
|
+
+ (f"T{time}" if time else "")
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
def elapsed(read: str) -> dt.timedelta:
|
|
348
|
+
found = _DURATION.fullmatch(read)
|
|
349
|
+
if (
|
|
350
|
+
not found
|
|
351
|
+
or not any(found.groups()[1:6])
|
|
352
|
+
or read.endswith(("T", "P"))
|
|
353
|
+
):
|
|
354
|
+
raise _Invalid
|
|
355
|
+
sign, years, days, hours, minutes, seconds, fraction = found.groups()
|
|
356
|
+
try:
|
|
357
|
+
value = dt.timedelta(
|
|
358
|
+
days=int(years or 0) * 365 + int(days or 0),
|
|
359
|
+
hours=int(hours or 0),
|
|
360
|
+
minutes=int(minutes or 0),
|
|
361
|
+
seconds=int(seconds or 0),
|
|
362
|
+
microseconds=int((fraction or "0").ljust(6, "0")),
|
|
363
|
+
)
|
|
364
|
+
except OverflowError:
|
|
365
|
+
raise _Invalid from None
|
|
366
|
+
return -value if sign else value
|
|
367
|
+
|
|
368
|
+
return checked(dt.timedelta, duration), elapsed
|
|
369
|
+
|
|
370
|
+
case s.Decimal():
|
|
371
|
+
|
|
372
|
+
def number(read: str) -> decimal.Decimal:
|
|
373
|
+
if not _DECIMAL.fullmatch(read):
|
|
374
|
+
raise _Invalid
|
|
375
|
+
try:
|
|
376
|
+
return t.value(t.unscaled(decimal.Decimal(read)))
|
|
377
|
+
except ValueError:
|
|
378
|
+
raise _Invalid from None
|
|
379
|
+
|
|
380
|
+
return (
|
|
381
|
+
checked(decimal.Decimal, lambda v: format(t.value(t.unscaled(v)), "f")),
|
|
382
|
+
number,
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
case s.EnumRef(cls=enum):
|
|
386
|
+
by_value = s.json_values(enum)
|
|
387
|
+
members = (
|
|
388
|
+
{str(value): member for value, member in by_value.items()}
|
|
389
|
+
if by_value
|
|
390
|
+
else {member.name: member for member in enum}
|
|
391
|
+
)
|
|
392
|
+
names = {member: name for name, member in members.items()}
|
|
393
|
+
|
|
394
|
+
def name(value: Any) -> str:
|
|
395
|
+
try:
|
|
396
|
+
return names[s.enum_members(enum)[value]]
|
|
397
|
+
except (KeyError, TypeError):
|
|
398
|
+
raise _Invalid from None
|
|
399
|
+
|
|
400
|
+
def member(read: str) -> Any:
|
|
401
|
+
try:
|
|
402
|
+
return members[read]
|
|
403
|
+
except KeyError:
|
|
404
|
+
raise _Invalid from None
|
|
405
|
+
|
|
406
|
+
return name, member
|
|
407
|
+
|
|
408
|
+
case s.Bool():
|
|
409
|
+
return (
|
|
410
|
+
checked(bool, lambda v: "true" if v else "false"),
|
|
411
|
+
lambda read: _of({"true": True, "false": False}, read),
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
case s.Int(min=low, max=high):
|
|
415
|
+
|
|
416
|
+
def whole(read: str) -> int:
|
|
417
|
+
if not re.fullmatch(r"-?(0|[1-9][0-9]*)", read, re.ASCII):
|
|
418
|
+
raise _Invalid
|
|
419
|
+
if not low <= (value := int(read)) <= high:
|
|
420
|
+
raise _Invalid
|
|
421
|
+
return value
|
|
422
|
+
|
|
423
|
+
return checked(int, str), whole
|
|
424
|
+
|
|
425
|
+
case s.Float():
|
|
426
|
+
write, read = _float(t)
|
|
427
|
+
return lambda value: str(write(value)), lambda text: read(_parsed(text))
|
|
428
|
+
|
|
429
|
+
case _:
|
|
430
|
+
raise AssertionError(t)
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _of(values: dict[str, Any], read: str) -> Any:
|
|
434
|
+
try:
|
|
435
|
+
return values[read]
|
|
436
|
+
except KeyError:
|
|
437
|
+
raise _Invalid from None
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _parsed(text: str) -> Any:
|
|
441
|
+
"""A number which is a key, so was written as text"""
|
|
442
|
+
if text in _NOT_FINITE:
|
|
443
|
+
return text
|
|
444
|
+
try:
|
|
445
|
+
return json.loads(text, parse_constant=_constant)
|
|
446
|
+
except ValueError:
|
|
447
|
+
raise _Invalid from None
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _float(t: s.Float) -> tuple[Callable[[Any], Any], Callable[[Any], float]]:
|
|
451
|
+
"""Writes a float as a number, or as text if it is not finite, which JSON has no number for: and reads it"""
|
|
452
|
+
|
|
453
|
+
def write(value: Any) -> Any:
|
|
454
|
+
if type(value) not in (float, int):
|
|
455
|
+
raise _Invalid
|
|
456
|
+
try:
|
|
457
|
+
number = float(value)
|
|
458
|
+
if t.bits == 32 and math.isfinite(number):
|
|
459
|
+
# As it is held natively
|
|
460
|
+
number = struct.unpack("f", struct.pack("f", number))[0]
|
|
461
|
+
except (OverflowError, struct.error):
|
|
462
|
+
raise _Invalid from None
|
|
463
|
+
if math.isfinite(number):
|
|
464
|
+
return number
|
|
465
|
+
return (
|
|
466
|
+
"NaN" if math.isnan(number) else "Infinity" if number > 0 else "-Infinity"
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
def read(plain: Any) -> float:
|
|
470
|
+
if type(plain) is str and plain in _NOT_FINITE:
|
|
471
|
+
return _NOT_FINITE[plain]
|
|
472
|
+
# Of either kind of number: another may write a float which is whole as an integer
|
|
473
|
+
if type(plain) not in (float, int):
|
|
474
|
+
raise _Invalid
|
|
475
|
+
try:
|
|
476
|
+
number = float(plain)
|
|
477
|
+
if t.bits == 32:
|
|
478
|
+
struct.pack("f", number)
|
|
479
|
+
except (OverflowError, struct.error):
|
|
480
|
+
raise _Invalid from None
|
|
481
|
+
if not math.isfinite(number):
|
|
482
|
+
# Too great to be written as a number
|
|
483
|
+
raise _Invalid
|
|
484
|
+
return number
|
|
485
|
+
|
|
486
|
+
return write, read
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _plain(t: s.Type, where: str) -> _Plain:
|
|
490
|
+
"""Makes a value of the type plain, raising _Invalid if it is not one"""
|
|
491
|
+
if cls := _struct_class(t):
|
|
492
|
+
if isinstance(t, s.StructRef) and t.mutable:
|
|
493
|
+
|
|
494
|
+
def nested(value: Any, depth: int) -> Any:
|
|
495
|
+
# Which only an object that is not frozen may do
|
|
496
|
+
if depth == _MAX_DEPTH:
|
|
497
|
+
raise ValueError(
|
|
498
|
+
"An object which holds itself, or is too deeply nested, cannot be written"
|
|
499
|
+
)
|
|
500
|
+
return _codec(cls).plain(value, depth + 1)
|
|
501
|
+
|
|
502
|
+
return nested
|
|
503
|
+
|
|
504
|
+
# Its codec is found when used, not now, as the type may be recursive. One which is Shared is written
|
|
505
|
+
# wherever it is held
|
|
506
|
+
return lambda value, depth: _codec(cls).plain(value, depth)
|
|
507
|
+
|
|
508
|
+
match t:
|
|
509
|
+
case s.Bool():
|
|
510
|
+
return lambda value, depth: _exactly(bool, value)
|
|
511
|
+
|
|
512
|
+
case s.Int(min=low, max=high):
|
|
513
|
+
|
|
514
|
+
def integer(value: Any, depth: int) -> int:
|
|
515
|
+
if type(value) is not int or not low <= value <= high:
|
|
516
|
+
raise _Invalid
|
|
517
|
+
return value
|
|
518
|
+
|
|
519
|
+
return integer
|
|
520
|
+
|
|
521
|
+
case s.Float():
|
|
522
|
+
write, _ = _float(t)
|
|
523
|
+
return lambda value, depth: write(value)
|
|
524
|
+
|
|
525
|
+
case s.EnumRef(cls=enum) if (by_value := s.json_values(enum)) is not None:
|
|
526
|
+
values = {member: value for value, member in by_value.items()}
|
|
527
|
+
members = s.enum_members(enum)
|
|
528
|
+
|
|
529
|
+
def valued(value: Any, depth: int) -> Any:
|
|
530
|
+
try:
|
|
531
|
+
return values[members[value]]
|
|
532
|
+
except (KeyError, TypeError):
|
|
533
|
+
raise _Invalid from None
|
|
534
|
+
|
|
535
|
+
return valued
|
|
536
|
+
|
|
537
|
+
case s.Optional(inner):
|
|
538
|
+
plain = _plain(inner, where)
|
|
539
|
+
return lambda value, depth: None if value is None else plain(value, depth)
|
|
540
|
+
|
|
541
|
+
case s.Sequence(element) | s.Set(element) if not _is_bytes(t):
|
|
542
|
+
plain = _plain(element, where)
|
|
543
|
+
typ, key = (
|
|
544
|
+
(frozenset, _order(element)) if isinstance(t, s.Set) else (tuple, None)
|
|
545
|
+
)
|
|
546
|
+
|
|
547
|
+
def array(value: Any, depth: int) -> list[Any]:
|
|
548
|
+
if type(value) is not typ:
|
|
549
|
+
raise _Invalid
|
|
550
|
+
items = _ordered(value, key) if typ is frozenset else value
|
|
551
|
+
return [plain(item, depth) for item in items]
|
|
552
|
+
|
|
553
|
+
return array
|
|
554
|
+
|
|
555
|
+
case s.Array(element, dimensions):
|
|
556
|
+
numbers, plain = _numbers(t), _plain(s.Sequence(element), where)
|
|
557
|
+
if dimensions == 1:
|
|
558
|
+
return lambda value, depth: plain(numbers(value), depth)
|
|
559
|
+
return lambda value, depth: [
|
|
560
|
+
list(value.shape),
|
|
561
|
+
plain(numbers(value), depth),
|
|
562
|
+
]
|
|
563
|
+
|
|
564
|
+
case s.Tuple(elements):
|
|
565
|
+
plains = [_plain(e, where) for e in elements]
|
|
566
|
+
|
|
567
|
+
def fixed(value: Any, depth: int) -> list[Any]:
|
|
568
|
+
if type(value) is not tuple or len(value) != len(plains):
|
|
569
|
+
raise _Invalid
|
|
570
|
+
return [
|
|
571
|
+
plain(item, depth)
|
|
572
|
+
for plain, item in zip(plains, value, strict=True)
|
|
573
|
+
]
|
|
574
|
+
|
|
575
|
+
return fixed
|
|
576
|
+
|
|
577
|
+
case s.Map(key_type, value_type):
|
|
578
|
+
name, _ = _text(key_type)
|
|
579
|
+
plain, key = _plain(value_type, where), _order(key_type)
|
|
580
|
+
|
|
581
|
+
def mapping(value: Any, depth: int) -> dict[str, Any]:
|
|
582
|
+
if not isinstance(value, Mapping):
|
|
583
|
+
raise _Invalid
|
|
584
|
+
return {name(k): plain(value[k], depth) for k in _ordered(value, key)}
|
|
585
|
+
|
|
586
|
+
return mapping
|
|
587
|
+
|
|
588
|
+
case s.Union(members, discriminated):
|
|
589
|
+
_told_apart(t, where)
|
|
590
|
+
plains = [_plain(member, where) for member in members]
|
|
591
|
+
tags = [_tag(member) for member in members]
|
|
592
|
+
any_string = any("str" in s.json_kinds(m) for m in members)
|
|
593
|
+
|
|
594
|
+
def union(value: Any, depth: int) -> Any:
|
|
595
|
+
index = _member(members, value)
|
|
596
|
+
made = plains[index](value, depth)
|
|
597
|
+
if discriminated:
|
|
598
|
+
return {"t": tags[index], "v": made}
|
|
599
|
+
if (
|
|
600
|
+
any_string
|
|
601
|
+
and isinstance(members[index], s.Float)
|
|
602
|
+
and type(made) is str
|
|
603
|
+
):
|
|
604
|
+
# Which would be read as the string it is written as
|
|
605
|
+
raise _Invalid
|
|
606
|
+
return made
|
|
607
|
+
|
|
608
|
+
return union
|
|
609
|
+
|
|
610
|
+
case _:
|
|
611
|
+
text, _ = _text(t)
|
|
612
|
+
return lambda value, depth: text(value)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _exactly(typ: type, value: Any) -> Any:
|
|
616
|
+
if type(value) is not typ:
|
|
617
|
+
raise _Invalid
|
|
618
|
+
return value
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def _told_apart(t: s.Union, where: str):
|
|
622
|
+
"""Raises if a union's members are not written as different kinds of JSON, unless it says which each is"""
|
|
623
|
+
if pair := s.json_collision(t):
|
|
624
|
+
# Which are written where they are held, so as their classes are
|
|
625
|
+
shared = all(isinstance(member, s.Shared) for member in pair)
|
|
626
|
+
raise SchemaError(
|
|
627
|
+
f"{where}: cannot be written as JSON, as union members {pair[0]} and {pair[1]} cannot be told "
|
|
628
|
+
f"apart in it: use {'Shared[DiscriminatedUnion[A, B]]' if shared else 'DiscriminatedUnion'}"
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def _object(t: s.Type, where: str) -> _Object:
|
|
633
|
+
"""Makes a value of the type from what was read, raising _Invalid if that is not one"""
|
|
634
|
+
if cls := _struct_class(t):
|
|
635
|
+
return lambda read: _codec(cls).object(read)
|
|
636
|
+
|
|
637
|
+
match t:
|
|
638
|
+
case s.Bool():
|
|
639
|
+
return lambda read: _exactly(bool, read)
|
|
640
|
+
|
|
641
|
+
case s.Int(min=low, max=high):
|
|
642
|
+
|
|
643
|
+
def integer(read: Any) -> int:
|
|
644
|
+
if type(read) is not int or not low <= read <= high:
|
|
645
|
+
raise _Invalid
|
|
646
|
+
return read
|
|
647
|
+
|
|
648
|
+
return integer
|
|
649
|
+
|
|
650
|
+
case s.Float():
|
|
651
|
+
_, read_float = _float(t)
|
|
652
|
+
return read_float
|
|
653
|
+
|
|
654
|
+
case s.EnumRef(cls=enum) if (by_value := s.json_values(enum)) is not None:
|
|
655
|
+
|
|
656
|
+
def valued(read: Any) -> Any:
|
|
657
|
+
# Of its type too: 1 is not True
|
|
658
|
+
if type(read) not in (str, int):
|
|
659
|
+
raise _Invalid
|
|
660
|
+
try:
|
|
661
|
+
return by_value[read]
|
|
662
|
+
except KeyError:
|
|
663
|
+
raise _Invalid from None
|
|
664
|
+
|
|
665
|
+
return valued
|
|
666
|
+
|
|
667
|
+
case s.Optional(inner):
|
|
668
|
+
make = _object(inner, where)
|
|
669
|
+
return lambda read: None if read is None else make(read)
|
|
670
|
+
|
|
671
|
+
case s.Sequence(element) | s.Set(element) if not _is_bytes(t):
|
|
672
|
+
make = _object(element, where)
|
|
673
|
+
container = frozenset if isinstance(t, s.Set) else tuple
|
|
674
|
+
|
|
675
|
+
def array(read: Any) -> Any:
|
|
676
|
+
if type(read) is not list:
|
|
677
|
+
raise _Invalid
|
|
678
|
+
made = container(make(item) for item in read)
|
|
679
|
+
if len(made) != len(read):
|
|
680
|
+
# An element twice
|
|
681
|
+
raise _Invalid
|
|
682
|
+
return made
|
|
683
|
+
|
|
684
|
+
return array
|
|
685
|
+
|
|
686
|
+
case s.Array(element, dimensions):
|
|
687
|
+
held, make = _array(t), _object(s.Sequence(element), where)
|
|
688
|
+
if dimensions == 1:
|
|
689
|
+
return lambda read: held(make(read))
|
|
690
|
+
make_shape = _object(s.Sequence(s.Int(64, signed=False)), where)
|
|
691
|
+
|
|
692
|
+
def shaped(read: Any) -> Any:
|
|
693
|
+
if type(read) is not list or len(read) != 2:
|
|
694
|
+
raise _Invalid
|
|
695
|
+
return held(make(read[1]), make_shape(read[0]))
|
|
696
|
+
|
|
697
|
+
return shaped
|
|
698
|
+
|
|
699
|
+
case s.Tuple(elements):
|
|
700
|
+
makes = [_object(e, where) for e in elements]
|
|
701
|
+
|
|
702
|
+
def fixed(read: Any) -> tuple[Any, ...]:
|
|
703
|
+
if type(read) is not list or len(read) != len(makes):
|
|
704
|
+
raise _Invalid
|
|
705
|
+
return tuple(make(item) for make, item in zip(makes, read, strict=True))
|
|
706
|
+
|
|
707
|
+
return fixed
|
|
708
|
+
|
|
709
|
+
case s.Map(key_type, value_type):
|
|
710
|
+
_, key = _text(key_type)
|
|
711
|
+
make = _object(value_type, where)
|
|
712
|
+
|
|
713
|
+
def mapping(read: Any) -> dict[Any, Any]:
|
|
714
|
+
if type(read) is not dict:
|
|
715
|
+
raise _Invalid
|
|
716
|
+
made = {key(k): make(v) for k, v in read.items()}
|
|
717
|
+
if len(made) != len(read):
|
|
718
|
+
# A key twice, though written differently
|
|
719
|
+
raise _Invalid
|
|
720
|
+
return made
|
|
721
|
+
|
|
722
|
+
return mapping
|
|
723
|
+
|
|
724
|
+
case s.Union(members, discriminated=True):
|
|
725
|
+
by_tag = {_tag(member): _object(member, where) for member in members}
|
|
726
|
+
|
|
727
|
+
def tagged(read: Any) -> Any:
|
|
728
|
+
if type(read) is not dict or read.keys() != {"t", "v"}:
|
|
729
|
+
raise _Invalid
|
|
730
|
+
try:
|
|
731
|
+
make = by_tag[read["t"]]
|
|
732
|
+
except (KeyError, TypeError):
|
|
733
|
+
raise _Invalid from None
|
|
734
|
+
return make(read["v"])
|
|
735
|
+
|
|
736
|
+
return tagged
|
|
737
|
+
|
|
738
|
+
case s.Union(members):
|
|
739
|
+
_told_apart(t, where)
|
|
740
|
+
# Each kind of JSON value is of one member: but a string, which is of whichever reads it
|
|
741
|
+
by_kind: dict[str, list[_Object]] = {}
|
|
742
|
+
any_string = any("str" in s.json_kinds(m) for m in members)
|
|
743
|
+
for member in members:
|
|
744
|
+
make = _object(member, where)
|
|
745
|
+
kinds = set(s.json_kinds(member))
|
|
746
|
+
if isinstance(member, s.Float) and not any_string:
|
|
747
|
+
# One which is not finite, which is written as a string
|
|
748
|
+
kinds.add("str")
|
|
749
|
+
for kind in kinds:
|
|
750
|
+
by_kind.setdefault(kind.partition(":")[0], []).append(make)
|
|
751
|
+
if "float" in by_kind and "int" not in by_kind:
|
|
752
|
+
by_kind["int"] = by_kind["float"]
|
|
753
|
+
|
|
754
|
+
def union(read: Any) -> Any:
|
|
755
|
+
kind = _JSON_KINDS.get(type(read))
|
|
756
|
+
for make in by_kind.get(kind or "", ()):
|
|
757
|
+
try:
|
|
758
|
+
return make(read)
|
|
759
|
+
except _Invalid:
|
|
760
|
+
pass
|
|
761
|
+
raise _Invalid
|
|
762
|
+
|
|
763
|
+
return union
|
|
764
|
+
|
|
765
|
+
case _:
|
|
766
|
+
_, value = _text(t)
|
|
767
|
+
|
|
768
|
+
def text(read: Any) -> Any:
|
|
769
|
+
if type(read) is not str:
|
|
770
|
+
raise _Invalid
|
|
771
|
+
return value(read)
|
|
772
|
+
|
|
773
|
+
return text
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
_JSON_KINDS: dict[type, str] = {
|
|
777
|
+
bool: "bool",
|
|
778
|
+
int: "int",
|
|
779
|
+
float: "float",
|
|
780
|
+
str: "str",
|
|
781
|
+
list: "array",
|
|
782
|
+
dict: "object",
|
|
783
|
+
}
|