From c566d01180a0de2d2b059aaf8f05b49c0eb1f19c Mon Sep 17 00:00:00 2001 From: nickyoung-github Date: Sun, 29 Nov 2026 21:32:48 +0000 Subject: [PATCH] Write and read JSON in Rust by serde: the generated structs are Serialize and Deserialize, as JSON_FORMAT.md has it --- DESIGN.md | 15 +- JSON_FORMAT.md | 10 +- README.md | 28 +- WIRE_FORMAT.md | 4 + src/dataclass_native/backends/pyo3.py | 24 +- src/dataclass_native/backends/rust.py | 286 ++++++- src/dataclass_native/rust/Cargo.toml | 11 +- src/dataclass_native/rust/src/json.rs | 1016 +++++++++++++++++++++++ src/dataclass_native/rust/src/lib.rs | 38 + src/dataclass_native/rust/src/python.rs | 42 +- tests/test_json.py | 8 +- tests/test_pyo3.py | 11 +- tests/test_rust.py | 182 +++- 13 files changed, 1627 insertions(+), 48 deletions(-) create mode 100644 src/dataclass_native/rust/src/json.rs diff --git a/DESIGN.md b/DESIGN.md index 0bb7a90..2856154 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -268,7 +268,16 @@ the structs, by [pyo3](https://pyo3.rs), as nanobind does in those of C++. bundle, which the schema tells. It reads where C++ does: a struct's map in one pass, in whatever order, and a bundle's shared objects from where they are when first referred to. -Not yet in Rust, so done by Python for what is held in it: JSON and Arrow. +- JSON is by [serde](https://serde.rs), with the crate's feature `json`: so the structs are also what a Rust + program gives any other format of serde's. The generated code is within the crate's macro `json!`, which is + of nothing without the feature, so that the crate still depends on nothing without it. It implements the + crate's `Form` for each struct, enum and union, and serde's `Serialize` and `Deserialize` by that: not by + serde's `derive`, as what the format has of a float which is not finite, or of bytes, it has wherever one is, + as within a tuple. A plain union is read by the kind of value serde says is next, and of a string by which of + its members reads it. serde_json is given a formatter which writes a float as Python does, so the text is + that of Python and C++, though it need not be. What is rejected is said as serde says it. + +Not yet in Rust, so done by Python for what is held in it: Arrow. ## Python runtime @@ -430,8 +439,8 @@ what an object is made from, before the native class checks it. depends on nothing; and Python's objects stored in the structs, as they are in those of C++, by an extension generated for pyo3, with arrays which share their numbers with numpy; and functions written in Rust, called as those of C++ are, and fields read and set by descriptors of the extension's own, as those of - C++ are; and msgpack. To come: JSON and Arrow in Rust, which Python does until then; and an example built - with maturin. + C++ are; and msgpack, and JSON by serde. To come: Arrow in Rust, which Python does until then; and an + example built with maturin. 6. **Done:** classes which are not frozen, whose fields may be set, held by reference, and whose arrays may be written to. To come: lists. 7. JSON. The aim is that pydantic's `TypeAdapter` reads what this writes, and this reads what it writes: not that diff --git a/JSON_FORMAT.md b/JSON_FORMAT.md index 4334885..d0fd83f 100644 --- a/JSON_FORMAT.md +++ b/JSON_FORMAT.md @@ -1,9 +1,10 @@ # dataclass-native: JSON format How a value of a schema type is written as JSON. The aim is that [pydantic](https://docs.pydantic.dev) reads what -this writes, and that this reads what pydantic writes: not that the two write the same text. Python and C++ -implement it, and do write the same text as each other. The Python one is the reference: where this document and -it disagree, one of them has a bug. +this writes, and that this reads what pydantic writes: not that the two write the same text. Python, C++ and +Rust implement it, Rust by [serde](https://serde.rs). What is asked of them is likewise that each reads what the +others write: they do also write the same text as each other, but need not. The Python one is the reference: +where this document and it disagree, one of them has a bug. A reader is given the type it is to read, as with [msgpack](WIRE_FORMAT.md). @@ -94,6 +95,9 @@ others. field's if no digit but a zero is lost. - An array of a `frozenset` with an element twice is rejected, and the elements may be in any order. +Rust reads as serde does, which is otherwise of what none of them writes: `-0` is not an integer to it, and is +the float `-0.0`; and the text of a number which is a key may have no spaces about it, as Python allows. + ## With pydantic Written by this, and read by pydantic's `TypeAdapter` of the same type, or the reverse: diff --git a/README.md b/README.md index e7bc221..a5c33c3 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,19 @@ let data: Vec = to_msgpack(&trade)?; let trade: Trade = from_msgpack(&data)?; ``` +With the crate's feature `json` they are also [serde](https://serde.rs)'s: each is `Serialize` and +`Deserialize`, as [JSON_FORMAT.md](JSON_FORMAT.md) has it, so is written as the JSON which Python and C++ read: + +```rust +use dataclass_native::json::{from_json, to_json}; + +let data: Vec = to_json(&trade)?; +let trade: Trade = from_json(&data)?; +``` + +`serde_json::to_string(&trade)` writes the same, but for the exponent of a float, which it has as `1e-5` where +Python has `1e-05`: either is read. The crate depends on nothing without the feature. + To store Python's objects in them, as in the structs of C++ below, generate for [pyo3](https://pyo3.rs) instead, which also writes `src/my_schemas_native.rs`: @@ -173,7 +186,8 @@ fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> { Built as an extension module (`crate-type = ["cdylib"]`) and placed in the package as `_native`, the classes of `my_schemas` are then bound to the Rust structs as they would be to those of C++. Rust writes and reads them -as msgpack: JSON and Arrow Python does for it, until Rust has its own. An example built with maturin is to come. +as msgpack and as JSON: Arrow Python does for it, until Rust has its own. An example built with maturin is to +come. ## Storing Python objects in the structs @@ -390,14 +404,14 @@ here is of two customers, each with two addresses: 15 values, in 7 objects. Arro | Microseconds, for each `Order`, to | `pure` | C++ | Rust | |---|---:|---:|---:| -| Write msgpack | 8.8 | 2.0 | 1.8 | -| Read msgpack | 24.2 | 2.6 | 2.7 | -| Write JSON | 10.7 | 2.3 | 17.1 | -| Read JSON | 13.6 | 3.1 | 20.5 | -| Write Arrow | 11.1 | 0.4 | 16.2 | +| Write msgpack | 8.9 | 1.9 | 1.8 | +| Read msgpack | 24.4 | 2.6 | 2.8 | +| Write JSON | 10.7 | 2.3 | 2.1 | +| Read JSON | 13.6 | 3.1 | 2.8 | +| Write Arrow | 11.2 | 0.4 | 16.2 | | Read Arrow | 9.3 | 0.7 | 14.3 | -C++ writes and reads the structs itself, as Rust does msgpack. JSON and Arrow Rust does not yet, so Python +C++ writes and reads the structs itself, as Rust does msgpack and JSON. Arrow Rust does not yet, so Python does, reading each field from the struct: which is slower than `pure`, until Rust has its own. ## Examples diff --git a/WIRE_FORMAT.md b/WIRE_FORMAT.md index 074af38..3293397 100644 --- a/WIRE_FORMAT.md +++ b/WIRE_FORMAT.md @@ -7,6 +7,10 @@ this document and it disagree, one of them has a bug. A reader is given the type it is to read. The data does not describe itself, beyond what a reader needs to tell the members of a union apart and to skip a field it does not know. +What is asked of the implementations is that each reads what any of them writes: not that they write the same +bytes. Where this says how a value is written, which a reader need not rely on, as that an integer is in its +shortest form or a set in ascending order, a writer should write it so, and the three now do. + ## Values | Type | Written as | diff --git a/src/dataclass_native/backends/pyo3.py b/src/dataclass_native/backends/pyo3.py index 198c695..0b7be07 100644 --- a/src/dataclass_native/backends/pyo3.py +++ b/src/dataclass_native/backends/pyo3.py @@ -13,6 +13,7 @@ from collections import defaultdict from .. import schema as s +from .cpp import in_json from .rust import KEYWORDS, RUNTIME, _ModuleGenerator, identifier from .rust import generate as generate_structs @@ -65,7 +66,8 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str: f"//! them to an extension module, which is to be {package}._native\n" "#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, clippy::all)]\n\n" f"use {RUNTIME}::python::{{\n" - " from_msgpack, maker, member, to_msgpack, Changing, Fields, Frozen, Held, Native, Told,\n" + " from_json, from_msgpack, maker, member, to_json, to_msgpack, Changing, Fields, Frozen, Held, Native,\n" + " Told,\n" "};\n" f"use {RUNTIME}::Mutable;\n" "use pyo3::exceptions::PyTypeError;\n" @@ -85,7 +87,7 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str: for name, (variants, members) in generator.unions.items(): parts.append(_union(_plain(module.name, name), variants, members)) for struct in module.structs: - parts.append(_struct(struct)) + parts.append(_struct(struct, in_json(schema, struct.ref))) added.append(_class(struct.module, struct.name)) hashes.append((struct.name, s.schema_hash(struct))) structs.append((struct.name, added[-1])) @@ -204,7 +206,7 @@ def _union(plain: str, variants: list[str], members: tuple[s.Type, ...]) -> str: ) -def _struct(struct: s.Struct) -> str: +def _struct(struct: s.Struct, in_json: bool) -> str: plain, name = _plain(struct.module, struct.name), _class(struct.module, struct.name) if struct.mutable: held, trait, read, written = ( @@ -256,6 +258,21 @@ def _struct(struct: s.Struct) -> str: registered.append( f' fields.{kind}::<{plain}, _>("{f.name}", |held| &held.{field}, |held| &mut held.{field})?;\n' ) + # Not if a union it may hold has members which cannot be told apart in JSON + json = ( + ( + " /// As JSON, and one read from it: by serde, as the crate's json has it\n" + " fn __json__<'py>(&self, py: Python<'py>) -> PyResult> {\n" + f" to_json(py, &*{read})\n" + " }\n\n" + " #[staticmethod]\n" + " fn __from_json__(data: &[u8]) -> PyResult {\n" + f' Ok(Self({held.partition("<")[0]}::new(from_json("{struct.name}", data)?)))\n' + " }\n\n" + ) + if in_json + else "" + ) write = ( "" if struct.mutable @@ -304,6 +321,7 @@ def _struct(struct: s.Struct) -> str: " fn __from_msgpack__(data: &[u8]) -> PyResult {\n" f" Ok(Self({held.partition('<')[0]}::new(from_msgpack(data)?)))\n" " }\n\n" + f"{json}" " /// As what it holds is: so that one made anew for the same struct is found to be of it\n" " fn __hash__(&self) -> usize {\n" " self.0.address()\n" diff --git a/src/dataclass_native/backends/rust.py b/src/dataclass_native/backends/rust.py index 8f3b841..5ebcb21 100644 --- a/src/dataclass_native/backends/rust.py +++ b/src/dataclass_native/backends/rust.py @@ -17,6 +17,7 @@ from .._wire import _reaches from ..introspect import _tag from ..schema import SchemaError +from .cpp import in_json RUNTIME = "dataclass_native" @@ -118,6 +119,275 @@ def _described(name: str) -> str: ) +JSON = f"{RUNTIME}::json" +_SER = f" fn ser(&self, serializer: S) -> Result {{\n" +_DE = f" fn de<'de, D: {JSON}::serde::Deserializer<'de>>(deserializer: D) -> Result {{\n" +_DE_ERROR = f"{JSON}::serde::de::Error" +_VALUE = f"{JSON}::serde::de::value" + + +def _json(name: str, items: str) -> str: + """What is of serde, and so of JSON: which is there only if the crate has its feature json""" + body = "".join(f" {line}\n" if line else "\n" for line in items.splitlines()) + return ( + f"{RUNTIME}::json! {{\n{body}\n {RUNTIME}::serde_by_form!([] {name});\n}}\n" + ) + + +def _expecting(what: str) -> str: + return ( + " fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n" + f" formatter.write_str({_string(what)})\n" + " }\n\n" + ) + + +def _json_enum(enum: s.Enum, name: str) -> str: + """How an enum is written as JSON, and read: as each member's value, or its name, which the schema tells""" + members = [(identifier(m.name), m) for m in enum.members] + written = "".join( + f" Self::{member} => serializer.serialize_str({_string(m.text)}),\n" + if m.quoted + else f" Self::{member} => serializer.serialize_i64({m.text}),\n" + for member, m in members + ) + # One which is written as a number is read from its text only as a key, which is always a string + by_text = "".join( + f" {_string(m.text)}{'' if m.quoted else ' if self.0'} => Ok({name}::{member}),\n" + for member, m in members + ) + by_value = "".join( + f" {m.text} => Ok({name}::{member}),\n" + for member, m in members + if not m.quoted + ) + unexpected = f"{JSON}::serde::de::Unexpected" + numbered = ( + ( + f"\n fn visit_i64(self, value: i64) -> Result<{name}, E> {{\n" + " match value {\n" + f"{by_value}" + f" _ => Err(E::invalid_value({unexpected}::Signed(value), &self)),\n" + " }\n" + " }\n\n" + f" fn visit_u64(self, value: u64) -> Result<{name}, E> {{\n" + " match i64::try_from(value) {\n" + f" Ok(value) => {JSON}::serde::de::Visitor::visit_i64(self, value),\n" + f" Err(_) => Err(E::invalid_value({unexpected}::Unsigned(value), &self)),\n" + " }\n" + " }\n" + ) + if by_value + else "" + ) + return _json( + name, + f"impl {JSON}::Form for {name} {{\n" + f"{_SER}" + f" match self {{\n{written} }}\n" + " }\n\n" + f"{_DE}" + f" deserializer.deserialize_any({name}Member(false))\n" + " }\n\n" + f" fn de_key<'de, D: {JSON}::serde::Deserializer<'de>>(deserializer: D) -> Result {{\n" + f" deserializer.deserialize_any({name}Member(true))\n" + " }\n" + "}\n\n" + "/// Reads a member: as a key, if it is one\n" + f"struct {name}Member(bool);\n\n" + f"impl {JSON}::serde::de::Visitor<'_> for {name}Member {{\n" + f" type Value = {name};\n\n" + " fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n" + f" formatter.write_str({_string('a ' + enum.name)})\n" + " }\n\n" + f" fn visit_str(self, text: &str) -> Result<{name}, E> {{\n" + " match text {\n" + f"{by_text}" + f" _ => Err(E::invalid_value({unexpected}::Str(text), &self)),\n" + " }\n" + " }\n" + f"{numbered}" + "}\n", + ) + + +def _json_struct(struct: s.Struct, name: str) -> str: + """How a struct is written as JSON, and read: as an object of its fields""" + keys = [_string(f.name) for f in struct.fields] + written = "".join( + f" map.serialize_entry({key}, &{JSON}::Ser(&self.{identifier(f.name)}))?;\n" + for key, f in zip(keys, struct.fields, strict=True) + ) + held = "".join( + f" let mut field{index} = None;\n" for index in range(len(keys)) + ) + taken = "".join( + f" Some({index}) => {JSON}::field(&mut map, {key}, &mut field{index})?,\n" + for index, key in enumerate(keys) + ) + made = "".join( + f" {identifier(f.name)}: match field{index} {{\n" + " Some(read) => read,\n" + f" None => {name}::default().{identifier(f.name)},\n" + " },\n" + if f.has_default + else f" {identifier(f.name)}: {JSON}::required({key}, field{index})?,\n" + for index, (key, f) in enumerate(zip(keys, struct.fields, strict=True)) + ) + return _json( + name, + f"impl {JSON}::Form for {name} {{\n" + f"{_SER}" + f" use {JSON}::serde::ser::SerializeMap;\n" + f" let mut map = serializer.serialize_map(Some({len(keys)}))?;\n" + f"{written}" + " map.end()\n" + " }\n\n" + f"{_DE}" + " struct Fields;\n\n" + f" impl<'de> {JSON}::serde::de::Visitor<'de> for Fields {{\n" + f" type Value = {name};\n\n" + f"{_expecting('a ' + struct.name)}" + f" fn visit_map>(self, mut map: A) -> Result<{name}, A::Error> {{\n" + f"{held}" + f" while let Some(key) = map.next_key_seed({JSON}::Named(&[{', '.join(keys)}]))? {{\n" + " match key {\n" + f"{taken}" + f" _ => {JSON}::ignored(&mut map)?,\n" + " }\n" + " }\n" + f" Ok({name} {{\n{made} }})\n" + " }\n" + " }\n\n" + " deserializer.deserialize_map(Fields)\n" + " }\n" + "}\n", + ) + + +def _json_union( + t: s.Union, members: tuple[s.Type, ...], name: str, variants: list[str] +) -> str: + """How a union is written as JSON, and read: as its member, which is told by its tag, or by the kind of value + and the form of string it is written as""" + written = "".join( + f" Self::{variant}(value) => {JSON}::Form::ser(value, serializer),\n" + for variant in variants + ) + if t.discriminated: + tags = [_string(_member_tag(member)) for member in members] + tagged = "".join( + f" Self::{variant}(_) => {tag},\n" + for variant, tag in zip(variants, tags, strict=True) + ) + by_tag = "".join( + f" {tag} => Ok(Self::{variant}({JSON}::Form::de(deserializer)?)),\n" + for variant, tag in zip(variants, tags, strict=True) + ) + return _json( + name, + f"impl {JSON}::Tagged for {name} {{\n" + " fn tag(&self) -> &'static str {\n" + f" match self {{\n{tagged} }}\n" + " }\n\n" + f" fn value(&self, serializer: S) -> Result {{\n" + f" match self {{\n{written} }}\n" + " }\n\n" + f" fn member<'de, D: {JSON}::serde::Deserializer<'de>>(tag: &str, deserializer: D) -> Result {{\n" + " match tag {\n" + f"{by_tag}" + f' _ => Err({_DE_ERROR}::custom("not the tag of a member of the union")),\n' + " }\n" + " }\n" + "}\n\n" + f"impl {JSON}::Form for {name} {{\n" + f"{_SER}" + f" {JSON}::ser_tagged(self, serializer)\n" + " }\n\n" + f"{_DE}" + f" {JSON}::de_tagged(deserializer)\n" + " }\n" + "}\n", + ) + + kinds = [s.json_kinds(member) for member in members] + + def of(kind: str) -> str | None: + return next( + (v for v, k in zip(variants, kinds, strict=True) if kind in k), None + ) + + def given(method: str, typ: str, source: str, variant: str | None) -> str: + """What is read of a value of a kind, as the member which is written as it""" + if variant is None: + return "" + return ( + f" fn {method}(self, value: {typ}) -> Result<{name}, E> {{\n" + f" Ok({name}::{variant}({JSON}::Form::de({_VALUE}::{source}::::new(value))?))\n" + " }\n\n" + ) + + # A whole number is of the int, if there is one: else of the float, which may be written as one by another + whole = of("int") or of("float") + # Each which is a string of a form of its own, then the one which may be any string: then a float, which is + # one if it is not finite + texts = [ + v + for v, k in zip(variants, kinds, strict=True) + if any(kind.startswith("str:") for kind in k) + ] + texts += [v for v in (of("str") or of("float"),) if v] + by_text = "".join( + f" if let Ok(value) = {JSON}::Form::de({_VALUE}::StrDeserializer::<{_VALUE}::Error>::new(text)) {{\n" + f" return Ok({name}::{variant}(value));\n" + " }\n" + for variant in texts + ) + text = ( + ( + f" fn visit_str(self, text: &str) -> Result<{name}, E> {{\n" + f"{by_text}" + f" Err(E::invalid_value({JSON}::serde::de::Unexpected::Str(text), &self))\n" + " }\n\n" + ) + if texts + else "" + ) + + def held(method: str, access: str, source: str, variant: str | None) -> str: + if variant is None: + return "" + return ( + f" fn {method}>(self, held: A) -> Result<{name}, A::Error> {{\n" + f" Ok({name}::{variant}({JSON}::Form::de({_VALUE}::{source}::new(held))?))\n" + " }\n\n" + ) + + return _json( + name, + f"impl {JSON}::Form for {name} {{\n" + f"{_SER}" + f" match self {{\n{written} }}\n" + " }\n\n" + f"{_DE}" + " struct Member;\n\n" + f" impl<'de> {JSON}::serde::de::Visitor<'de> for Member {{\n" + f" type Value = {name};\n\n" + f"{_expecting('a member of the union')}" + f"{given('visit_bool', 'bool', 'BoolDeserializer', of('bool'))}" + f"{given('visit_i64', 'i64', 'I64Deserializer', whole)}" + f"{given('visit_u64', 'u64', 'U64Deserializer', whole)}" + f"{given('visit_f64', 'f64', 'F64Deserializer', of('float'))}" + f"{text}" + f"{held('visit_seq', 'SeqAccess', 'SeqAccessDeserializer', of('array'))}" + f"{held('visit_map', 'MapAccess', 'MapAccessDeserializer', of('object'))}" + " }\n\n" + " deserializer.deserialize_any(Member)\n" + " }\n" + "}\n", + ) + + def _member_tag(member: s.Type) -> str: """The tag of a union's member: that of what it is, if it is held out of line""" return _tag(member.target if isinstance(member, s.Indirect) else member) or "" @@ -276,7 +546,7 @@ def __enum(self, enum: s.Enum) -> str: f" _ => Err({WIRE}::Fault::Mismatch),\n" " }\n" " }\n" - "}\n" + "}\n\n" + _json_enum(enum, name) ) def __struct(self, struct: s.Struct) -> str: @@ -355,6 +625,12 @@ def __struct(self, struct: s.Struct) -> str: " }\n" "}\n" f"{record}" + # Not if a union it may hold has members which cannot be told apart in it + + ( + "\n" + _json_struct(struct, name) + if in_json(self.__schema, struct.ref) + else "" + ) ) def __path(self, module: str, name: str) -> str: @@ -439,7 +715,13 @@ def __union(self, t: s.Union, members: tuple[s.Type, ...], name: str) -> str: " fn default() -> Self {\n" f" Self::{variants[0]}(Default::default())\n" " }\n" - "}\n\n" + _wire_union(t, members, name, variants) + "}\n\n" + + _wire_union(t, members, name, variants) + + ( + "\n" + _json_union(t, members, name, variants) + if in_json(self.__schema, t) + else "" + ) ) return name diff --git a/src/dataclass_native/rust/Cargo.toml b/src/dataclass_native/rust/Cargo.toml index 0efe178..c3cd80f 100644 --- a/src/dataclass_native/rust/Cargo.toml +++ b/src/dataclass_native/rust/Cargo.toml @@ -1,5 +1,5 @@ # The types used by the Rust which dataclass-native generates. A crate to depend on by path, which -# `dataclass-native rust-dir` prints: it depends on nothing itself, but for its feature python. +# `dataclass-native rust-dir` prints: it depends on nothing itself, but for its features json and python. [package] name = "dataclass_native" version = "0.0.0" @@ -11,9 +11,14 @@ publish = false [lib] path = "src/lib.rs" -# With python, also what a Python extension needs to hold Python's objects in the generated structs: by pyo3 +# With json, the generated structs are serde's, by which they are written as JSON and read from it. With python, +# also what a Python extension needs to hold Python's objects in them: by pyo3 [features] -python = ["dep:pyo3"] +json = ["dep:serde", "dep:serde_json"] +python = ["dep:pyo3", "json"] [dependencies] pyo3 = { version = "0.30", optional = true } +serde = { version = "1", optional = true } +# Which reads a float as exactly what was written +serde_json = { version = "1", optional = true, features = ["float_roundtrip"] } diff --git a/src/dataclass_native/rust/src/json.rs b/src/dataclass_native/rust/src/json.rs new file mode 100644 index 0000000..f75ca43 --- /dev/null +++ b/src/dataclass_native/rust/src/json.rs @@ -0,0 +1,1016 @@ +//! The generated structs as serde has them, by which they are written as JSON and read from it: as JSON_FORMAT.md +//! has it, which Python and C++ write and read. The generated code implements `Form` for each struct, enum and +//! union, and serde's `Serialize` and `Deserialize` by it: so they are also what any other format of serde's is of, +//! which says what kind of value is next, as JSON does. + +use crate::{ + date_of, days_of, Array, Bytes, Date, DateTime, Decimal, Indirect, Mutable, MutableArray, NaiveDateTime, Ordered, + TimeDelta, TimeOfDay, Uuid, +}; +pub use serde; +use serde::de::{self, DeserializeSeed, Deserializer, IgnoredAny, MapAccess, SeqAccess, Unexpected, Visitor}; +use serde::ser::{self, SerializeMap, SerializeSeq, SerializeTuple, Serializer}; +use serde::{Deserialize, Serialize}; +use std::cell::Cell; +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; +use std::io; +use std::marker::PhantomData; +use std::sync::Arc; + +/// A type which is written and read as JSON_FORMAT.md has it: which is not always as serde itself would, as with a +/// float which is not finite. Of a field, and of what is within one +pub trait Form: Sized { + fn ser(&self, serializer: S) -> Result; + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result; + + /// As de, of the key of an object: which is always a string, so a number is read from its text + fn de_key<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Self::de(deserializer) + } +} + +/// A value as JSON +pub fn to_json(value: &T) -> Result, serde_json::Error> { + let mut out = Vec::new(); + value.ser(&mut serde_json::Serializer::with_formatter(&mut out, AsPython))?; + Ok(out) +} + +/// The value which JSON is of +pub fn from_json(data: &[u8]) -> Result { + // All of it, as what is ignored is not otherwise found not to be text + let text = std::str::from_utf8(data).map_err(|error| serde_json::Error::io(io::Error::other(error)))?; + let mut deserializer = serde_json::Deserializer::from_str(text); + let value = T::de(&mut deserializer)?; + deserializer.end()?; + Ok(value) +} + +/// Writes a float as Python does, which is also in the fewest digits which read back as it: `1e-05`, not `1e-5` +struct AsPython; + +impl serde_json::ser::Formatter for AsPython { + fn write_f64(&mut self, writer: &mut W, value: f64) -> io::Result<()> { + let text = format!("{value:?}"); + match text.split_once('e') { + Some((digits, exponent)) => { + let (sign, exponent) = exponent.strip_prefix('-').map_or(('+', exponent), |rest| ('-', rest)); + write!(writer, "{digits}e{sign}{exponent:0>2}") + } + None => writer.write_all(text.as_bytes()), + } + } +} + +/// A value to be written as its Form is +pub struct Ser<'a, T>(pub &'a T); + +impl Serialize for Ser<'_, T> { + fn serialize(&self, serializer: S) -> Result { + self.0.ser(serializer) + } +} + +/// A value read as its Form is +pub struct De(pub T); + +impl<'de, T: Form> Deserialize<'de> for De { + fn deserialize>(deserializer: D) -> Result { + T::de(deserializer).map(De) + } +} + +/// serde's Serialize and Deserialize of types which have a Form, by it +#[macro_export] +macro_rules! serde_by_form { + ($([$($generics:tt)*] $of:ty),* $(,)?) => {$( + impl<$($generics)*> $crate::json::serde::Serialize for $of { + fn serialize(&self, serializer: S) -> Result { + $crate::json::Form::ser(self, serializer) + } + } + + impl<'de, $($generics)*> $crate::json::serde::Deserialize<'de> for $of { + fn deserialize>(deserializer: D) -> Result { + $crate::json::Form::de(deserializer) + } + } + )*}; +} + +serde_by_form!( + [] Bytes, + [] Date, + [] TimeOfDay, + [] DateTime, + [] NaiveDateTime, + [] TimeDelta, + [] Uuid, + [const PLACES: u32] Decimal, + [T: Form] Indirect, + [T: Form] Mutable, + [T: Numbers, const N: usize] Array, + [T: Numbers, const N: usize] MutableArray, +); + +macro_rules! as_serde { + ($($of:ty),*) => {$( + impl Form for $of { + fn ser(&self, serializer: S) -> Result { + self.serialize(serializer) + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Self::deserialize(deserializer) + } + } + )*}; +} + +as_serde!(bool, i8, i16, i32, i64, u8, u16, u32, u64, String); + +const NOT_FINITE: [(&str, f64); 3] = [("NaN", f64::NAN), ("Infinity", f64::INFINITY), ("-Infinity", f64::NEG_INFINITY)]; + +/// Reads a float: from a number of either kind, or the name of one which is not finite. As a key, which is always +/// a string, also from the text of a number +struct Float { + key: bool, +} + +impl Visitor<'_> for Float { + type Value = f64; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a number, or \"NaN\", \"Infinity\" or \"-Infinity\"") + } + + fn visit_f64(self, value: f64) -> Result { + Ok(value) + } + + fn visit_i64(self, value: i64) -> Result { + Ok(value as f64) + } + + fn visit_u64(self, value: u64) -> Result { + Ok(value as f64) + } + + fn visit_str(self, text: &str) -> Result { + let named = NOT_FINITE.iter().find(|(name, _)| *name == text).map(|(_, value)| *value); + // Not one too great to be a float, which is not what its name is of + let parsed = || text.parse().ok().filter(|value: &f64| self.key && value.is_finite()); + named.or_else(parsed).ok_or_else(|| E::invalid_value(Unexpected::Str(text), &self)) + } +} + +fn float(value: f64, serializer: S) -> Result { + if value.is_finite() { + serializer.serialize_f64(value) + } else if value.is_nan() { + serializer.serialize_str("NaN") + } else { + serializer.serialize_str(if value > 0.0 { "Infinity" } else { "-Infinity" }) + } +} + +/// A float which is not finite is a string, as it is not JSON +impl Form for f64 { + fn ser(&self, serializer: S) -> Result { + float(*self, serializer) + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_any(Float { key: false }) + } +} + +/// Written as the float of the same value +impl Form for f32 { + fn ser(&self, serializer: S) -> Result { + float(f64::from(*self), serializer) + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let value = f64::de(deserializer)?; + if value.is_finite() && (value as f32).is_infinite() { + return Err(de::Error::custom("a number too great to be a Float32")); + } + Ok(value as f32) + } +} + +macro_rules! ordered { + ($($float:ty),*) => {$( + impl Form for Ordered<$float> { + fn ser(&self, serializer: S) -> Result { + self.0.ser(serializer) + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Form::de(deserializer).map(Ordered) + } + + fn de_key<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Ok(Ordered(deserializer.deserialize_any(Float { key: true })? as $float)) + } + } + )*}; +} + +ordered!(f64, f32); + +/// A type which is written as a string, of its own form +pub trait Text: Sized { + const EXPECTED: &'static str; + + /// Or why it cannot be written + fn text(&self) -> Result; + + fn parse(text: &str) -> Option; +} + +struct Parsed(PhantomData); + +impl Visitor<'_> for Parsed { + type Value = T; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(T::EXPECTED) + } + + fn visit_str(self, text: &str) -> Result { + T::parse(text).ok_or_else(|| E::invalid_value(Unexpected::Str(text), &self)) + } +} + +macro_rules! text { + ($([$($generics:tt)*] $of:ty),*) => {$( + impl<$($generics)*> Form for $of { + fn ser(&self, serializer: S) -> Result { + serializer.serialize_str(&self.text().map_err(ser::Error::custom)?) + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_str(Parsed(PhantomData)) + } + } + )*}; +} + +text!([] Bytes, [] Date, [] TimeOfDay, [] DateTime, [] NaiveDateTime, [] TimeDelta, [] Uuid); +text!([const PLACES: u32] Decimal); + +const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + +fn encoded(bytes: &[u8]) -> String { + let mut text = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let group = chunk.iter().fold(0u32, |group, byte| group << 8 | u32::from(*byte)) << (8 * (3 - chunk.len())); + for index in 0..4 { + let sextet = (group >> (18 - 6 * index)) & 0x3f; + text.push(if index <= chunk.len() { char::from(BASE64[sextet as usize]) } else { '=' }); + } + } + text +} + +/// Of either alphabet, and padded +fn decoded(text: &str) -> Option> { + let text = text.as_bytes(); + if text.len() % 4 != 0 { + return None; + } + let padding = text.iter().rev().take(2).take_while(|byte| **byte == b'=').count(); + let mut bytes = Vec::with_capacity(text.len() / 4 * 3); + for (index, chunk) in text.chunks(4).enumerate() { + let last = (index + 1) * 4 == text.len(); + let digits = if last { 4 - padding } else { 4 }; + let mut group = 0u32; + for (place, byte) in chunk.iter().enumerate() { + let sextet = match *byte { + b'=' if place >= digits => 0, + b'+' | b'-' => 62, + b'/' | b'_' => 63, + byte => BASE64.iter().position(|digit| *digit == byte).filter(|_| byte.is_ascii_alphanumeric())? as u32, + }; + group = group << 6 | sextet; + } + bytes.extend(&group.to_be_bytes()[1..digits]); + } + Some(bytes) +} + +/// As base64, of the alphabet which is safe in a URL +impl Text for Bytes { + const EXPECTED: &'static str = "bytes, as base64"; + + fn text(&self) -> Result { + Ok(encoded(&self.0)) + } + + fn parse(text: &str) -> Option { + decoded(text).map(Bytes) + } +} + +const DAY: i64 = 86_400_000_000; + +/// So many digits, and no more, as a number +fn digits(text: &str, count: usize) -> Option { + (text.len() == count && text.bytes().all(|digit| digit.is_ascii_digit())).then(|| text.parse().ok())? +} + +/// A date as `2026-01-02`, of the years 1 to 9999: and the days since 1970-01-01 which that is of +fn date_text(days: i64) -> Result { + let (year, month, day) = date_of(days); + if !(1..=9999).contains(&year) { + return Err("A date which is not of the years 1 to 9999 cannot be written"); + } + Ok(format!("{year:04}-{month:02}-{day:02}")) +} + +fn date_parsed(text: &str) -> Option { + let (year, month, day) = (digits(text.get(..4)?, 4)?, digits(text.get(5..7)?, 2)?, digits(text.get(8..)?, 2)?); + let valid = text.as_bytes()[4] == b'-' && text.as_bytes()[7] == b'-' && year >= 1 && (1..=12).contains(&month); + let days = days_of(year, month, day); + // Which is the day it says, if there is such a day + (valid && day >= 1 && date_of(days) == (year, month, day)).then_some(days) +} + +/// A time as `03:04:05`, or `03:04:05.000006` if it has microseconds: and the microseconds since midnight +fn time_text(micros: i64) -> String { + let (seconds, fraction) = (micros / 1_000_000, micros % 1_000_000); + let text = format!("{:02}:{:02}:{:02}", seconds / 3600, seconds / 60 % 60, seconds % 60); + if fraction == 0 { + text + } else { + format!("{text}.{fraction:06}") + } +} + +fn time_parsed(text: &str) -> Option { + let (whole, fraction) = text.split_once('.').map_or((text, None), |(whole, fraction)| (whole, Some(fraction))); + let (hour, minute, second) = (digits(whole.get(..2)?, 2)?, digits(whole.get(3..5)?, 2)?, digits(whole.get(6..)?, 2)?); + let separated = whole.as_bytes()[2] == b':' && whole.as_bytes()[5] == b':'; + if !separated || hour > 23 || minute > 59 || second > 59 { + return None; + } + let fraction = match fraction { + Some(places) if (1..=6).contains(&places.len()) => digits(places, places.len())? * 10i64.pow(6 - places.len() as u32), + Some(_) => return None, + None => 0, + }; + Some(((hour * 60 + minute) * 60 + second) * 1_000_000 + fraction) +} + +/// A date and a time, with `T` between them, as microseconds since 1970-01-01T00:00 +fn moment_text(micros: i64) -> Result { + Ok(format!("{}T{}", date_text(micros.div_euclid(DAY))?, time_text(micros.rem_euclid(DAY)))) +} + +fn moment_parsed(text: &str) -> Option { + let (date, time) = (text.get(..10)?, text.get(11..)?); + (text.as_bytes()[10] == b'T').then_some(())?; + Some(date_parsed(date)? * DAY + time_parsed(time)?) +} + +impl Text for Date { + const EXPECTED: &'static str = "a date, as 2026-01-02"; + + fn text(&self) -> Result { + date_text(i64::from(self.0)) + } + + fn parse(text: &str) -> Option { + (text.len() == 10).then(|| date_parsed(text))?.map(|days| Date(days as i32)) + } +} + +impl Text for TimeOfDay { + const EXPECTED: &'static str = "a time, as 03:04:05"; + + fn text(&self) -> Result { + if !(0..DAY).contains(&self.0) { + return Err("A time which is not within a day cannot be written"); + } + Ok(time_text(self.0)) + } + + fn parse(text: &str) -> Option { + time_parsed(text).map(TimeOfDay) + } +} + +impl Text for NaiveDateTime { + const EXPECTED: &'static str = "a datetime with no timezone, as 2026-01-02T03:04:05"; + + fn text(&self) -> Result { + moment_text(self.0) + } + + fn parse(text: &str) -> Option { + moment_parsed(text).map(NaiveDateTime) + } +} + +/// In UTC, which it is read as from whatever offset it was written with +impl Text for DateTime { + const EXPECTED: &'static str = "a datetime with a timezone, as 2026-01-02T03:04:05Z"; + + fn text(&self) -> Result { + Ok(moment_text(self.0)? + "Z") + } + + fn parse(text: &str) -> Option { + let (local, offset) = match text.strip_suffix('Z') { + Some(local) => (local, 0), + None => { + let (local, offset) = text.split_at_checked(text.len().checked_sub(6)?)?; + let (hours, minutes) = (digits(offset.get(1..3)?, 2)?, digits(offset.get(4..)?, 2)?); + let sign = match offset.as_bytes()[0] { + b'+' => 1, + b'-' => -1, + _ => return None, + }; + (offset.as_bytes()[3] == b':' && hours <= 23 && minutes <= 59).then_some(())?; + (local, sign * (hours * 60 + minutes) * 60_000_000) + } + }; + let micros = moment_parsed(local)? - offset; + // Of the years 1 to 9999 in UTC, too + date_text(micros.div_euclid(DAY)).ok().map(|_| DateTime(micros)) + } +} + +/// As an ISO 8601 duration of days, hours, minutes and seconds: read also with years, each of 365 days +impl Text for TimeDelta { + const EXPECTED: &'static str = "a duration, as P1DT2H3M4.000005S"; + + fn text(&self) -> Result { + let whole = self.0.unsigned_abs(); + let (days, rest) = (whole / DAY as u64, whole % DAY as u64); + let (hours, minutes) = (rest / 3_600_000_000, rest / 60_000_000 % 60); + let (seconds, micros) = (rest / 1_000_000 % 60, rest % 1_000_000); + let mut time = String::new(); + for (count, unit) in [(hours, 'H'), (minutes, 'M')] { + if count != 0 { + time += &format!("{count}{unit}"); + } + } + match (seconds, micros) { + (0, 0) => {} + (_, 0) => time += &format!("{seconds}S"), + _ => time += &format!("{seconds}.{micros:06}S"), + } + if days == 0 && time.is_empty() { + time += "0S"; + } + let mut text = String::from(if self.0 < 0 { "-P" } else { "P" }); + if days != 0 { + text += &format!("{days}D"); + } + if !time.is_empty() { + text = text + "T" + &time; + } + Ok(text) + } + + fn parse(text: &str) -> Option { + let (negative, text) = text.strip_prefix('-').map_or((false, text), |rest| (true, rest)); + let text = text.strip_prefix('P')?; + let (date, time) = text.split_once('T').map_or((text, None), |(date, time)| (date, Some(time))); + // Each part in its order, if it is there: a number, then its unit + fn part<'a>(rest: &mut &'a str, unit: char) -> Option> { + let end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?; + if !rest[end..].starts_with(unit) { + return Some(None); + } + let number = &rest[..end]; + *rest = &rest[end + 1..]; + Some(Some(number)) + } + let whole = |number: Option<&str>| match number { + Some(number) => digits(number, number.len()).filter(|_| !number.is_empty()), + None => Some(0), + }; + let (mut date, mut any) = (date, false); + let mut micros: i64 = 0; + for (unit, each) in [('Y', 365 * DAY), ('D', DAY)] { + let number = if date.is_empty() { None } else { part(&mut date, unit)? }; + any |= number.is_some(); + micros = micros.checked_add(whole(number)?.checked_mul(each)?)?; + } + if let Some(mut time) = time { + (!time.is_empty()).then_some(())?; + for (unit, each) in [('H', 3_600_000_000), ('M', 60_000_000)] { + let number = if time.is_empty() { None } else { part(&mut time, unit)? }; + any |= number.is_some(); + micros = micros.checked_add(whole(number)?.checked_mul(each)?)?; + } + if let Some(seconds) = if time.is_empty() { None } else { part(&mut time, 'S')? } { + any = true; + let (seconds, fraction) = seconds.split_once('.').map_or((seconds, "0"), |(seconds, fraction)| (seconds, fraction)); + (1..=6).contains(&fraction.len()).then_some(())?; + let fraction = digits(fraction, fraction.len())? * 10i64.pow(6 - fraction.len() as u32); + micros = micros.checked_add(whole(Some(seconds))?.checked_mul(1_000_000)?)?.checked_add(fraction)?; + } + time.is_empty().then_some(())?; + } + (any && date.is_empty()).then(|| TimeDelta(if negative { -micros } else { micros })) + } +} + +/// As `12345678-1234-5678-1234-567812345678` +impl Text for Uuid { + const EXPECTED: &'static str = "a UUID, as 12345678-1234-5678-1234-567812345678"; + + fn text(&self) -> Result { + let hex: String = self.0.iter().map(|byte| format!("{byte:02x}")).collect(); + Ok(format!("{}-{}-{}-{}-{}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..])) + } + + fn parse(text: &str) -> Option { + let bytes = text.as_bytes(); + if bytes.len() != 36 || [8, 13, 18, 23].iter().any(|at| bytes[*at] != b'-') { + return None; + } + let hex: Vec = bytes.iter().filter(|byte| **byte != b'-').copied().collect(); + let mut uuid = [0; 16]; + for (byte, pair) in uuid.iter_mut().zip(hex.chunks(2)) { + *byte = u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok().filter(|_| pair.len() == 2 && pair[0] != b'+')?; + } + (hex.len() == 32).then_some(Uuid(uuid)) + } +} + +/// As its digits, with a point before its decimal places +impl Text for Decimal { + const EXPECTED: &'static str = "a Decimal, as its digits"; + + fn text(&self) -> Result { + if !self.fits() { + return Err("A Decimal of more than 18 digits cannot be written"); + } + Ok(self.to_string()) + } + + fn parse(text: &str) -> Option { + Decimal::parse(text) + } +} + +struct Maybe(PhantomData); + +impl<'de, T: Form> Visitor<'de> for Maybe { + type Value = Option; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a value, or null") + } + + fn visit_none(self) -> Result, E> { + Ok(None) + } + + fn visit_unit(self) -> Result, E> { + Ok(None) + } + + fn visit_some>(self, deserializer: D) -> Result, D::Error> { + T::de(deserializer).map(Some) + } +} + +/// null, or its T +impl Form for Option { + fn ser(&self, serializer: S) -> Result { + match self { + Some(value) => value.ser(serializer), + None => serializer.serialize_none(), + } + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_option(Maybe(PhantomData)) + } +} + +fn sequence<'a, T: Form + 'a, S: Serializer>( + items: impl ExactSizeIterator, + serializer: S, +) -> Result { + let mut sequence = serializer.serialize_seq(Some(items.len()))?; + for item in items { + sequence.serialize_element(&Ser(item))?; + } + sequence.end() +} + +/// What an array is read into: which says whether it took each of what the array holds +trait Gathered: Default { + fn add(&mut self, item: T) -> bool; +} + +impl Gathered for Vec { + fn add(&mut self, item: T) -> bool { + self.push(item); + true + } +} + +/// Not what it has already +impl Gathered for BTreeSet { + fn add(&mut self, item: T) -> bool { + self.insert(item) + } +} + +struct Each(PhantomData<(T, C)>); + +impl<'de, T: Form, C: Gathered> Visitor<'de> for Each { + type Value = C; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("an array") + } + + fn visit_seq>(self, mut sequence: A) -> Result { + let mut read = C::default(); + while let Some(De(item)) = sequence.next_element()? { + if !read.add(item) { + return Err(de::Error::custom("an array of a frozenset has an element twice")); + } + } + Ok(read) + } +} + +impl Form for Vec { + fn ser(&self, serializer: S) -> Result { + sequence(self.iter(), serializer) + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_seq(Each(PhantomData)) + } +} + +/// An array, in ascending order: read whatever its order +impl Form for BTreeSet { + fn ser(&self, serializer: S) -> Result { + sequence(self.iter(), serializer) + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_seq(Each(PhantomData)) + } +} + +struct Key(PhantomData); + +impl<'de, K: Form> DeserializeSeed<'de> for Key { + type Value = K; + + fn deserialize>(self, deserializer: D) -> Result { + K::de_key(deserializer) + } +} + +struct Keyed(PhantomData<(K, V)>); + +impl<'de, K: Form + Ord, V: Form> Visitor<'de> for Keyed { + type Value = BTreeMap; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("an object") + } + + fn visit_map>(self, mut map: A) -> Result { + let mut read = BTreeMap::new(); + while let Some(key) = map.next_key_seed(Key(PhantomData))? { + let De(value) = map.next_value()?; + if read.insert(key, value).is_some() { + return Err(de::Error::custom("an object has a key twice")); + } + } + Ok(read) + } +} + +/// An object, in ascending order of key: whose keys are the strings they are written as, or of their text +impl Form for BTreeMap { + fn ser(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(Some(self.len()))?; + for (key, value) in self { + map.serialize_entry(&Ser(key), &Ser(value))?; + } + map.end() + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_map(Keyed(PhantomData)) + } +} + +macro_rules! tuple { + ($count:literal: $($name:ident $index:tt),+) => { + impl<$($name: Form),+> Form for ($($name,)+) { + fn ser<__S: Serializer>(&self, serializer: __S) -> Result<__S::Ok, __S::Error> { + let mut tuple = serializer.serialize_tuple($count)?; + $(tuple.serialize_element(&Ser(&self.$index))?;)+ + tuple.end() + } + + fn de<'de, __D: Deserializer<'de>>(deserializer: __D) -> Result { + struct Fixed<$($name),+>(PhantomData<($($name,)+)>); + + impl<'de, $($name: Form),+> Visitor<'de> for Fixed<$($name),+> { + type Value = ($($name,)+); + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "an array of {}", $count) + } + + fn visit_seq<__S: SeqAccess<'de>>(self, mut sequence: __S) -> Result { + let read = ($( + sequence.next_element::>()?.ok_or_else(|| de::Error::invalid_length($index, &self))?.0, + )+); + match sequence.next_element::()? { + Some(_) => Err(de::Error::invalid_length($count + 1, &self)), + None => Ok(read), + } + } + } + + deserializer.deserialize_tuple($count, Fixed(PhantomData)) + } + } + }; +} + +tuple!(1: A 0); +tuple!(2: A 0, B 1); +tuple!(3: A 0, B 1, C 2); +tuple!(4: A 0, B 1, C 2, D 3); +tuple!(5: A 0, B 1, C 2, D 3, E 4); +tuple!(6: A 0, B 1, C 2, D 3, E 4, F 5); +tuple!(7: A 0, B 1, C 2, D 3, E 4, F 5, G 6); +tuple!(8: A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7); + +/// As its T +impl Form for Indirect { + fn ser(&self, serializer: S) -> Result { + match self.get() { + Some(value) => value.ser(serializer), + None => Err(ser::Error::custom("An empty Indirect cannot be written")), + } + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + T::de(deserializer).map(Indirect::new) + } +} + +/// As its T, wherever it is held: so that it is shared is lost +impl Form for Arc { + fn ser(&self, serializer: S) -> Result { + T::ser(self, serializer) + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + T::de(deserializer).map(Arc::new) + } +} + +thread_local! { + /// How many objects which are not frozen the one being written is within + static DEPTH: Cell = const { Cell::new(0) }; +} + +/// As its T: which may hold itself, so is not written if it is within more than 256 others +impl Form for Mutable { + fn ser(&self, serializer: S) -> Result { + if DEPTH.get() == 256 { + return Err(ser::Error::custom("An object which holds itself, or is too deeply nested, cannot be written")); + } + DEPTH.set(DEPTH.get() + 1); + let written = self.read().ser(serializer); + DEPTH.set(DEPTH.get() - 1); + written + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + T::de(deserializer).map(Mutable::new) + } +} + +/// What an array may be of: its numbers are written as a tuple of them is, which is base64 if they are bytes +pub trait Numbers: Form + Copy { + fn ser_all(numbers: &[Self], serializer: S) -> Result { + sequence(numbers.iter(), serializer) + } + + fn de_all<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + Form::de(deserializer) + } +} + +impl Numbers for u8 { + fn ser_all(numbers: &[Self], serializer: S) -> Result { + serializer.serialize_str(&encoded(numbers)) + } + + fn de_all<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + Bytes::de(deserializer).map(|bytes| bytes.0) + } +} + +macro_rules! numbers { + ($($number:ty),*) => {$(impl Numbers for $number {})*}; +} + +numbers!(i8, i16, i32, i64, u16, u32, u64, f32, f64); + +struct All<'a, T>(&'a [T]); + +impl Serialize for All<'_, T> { + fn serialize(&self, serializer: S) -> Result { + T::ser_all(self.0, serializer) + } +} + +struct AllOf(Vec); + +impl<'de, T: Numbers> Deserialize<'de> for AllOf { + fn deserialize>(deserializer: D) -> Result { + T::de_all(deserializer).map(AllOf) + } +} + +/// The numbers of an array, after its shape if it is of more than one dimension +fn ser_array( + shape: &[usize; N], + numbers: &[T], + serializer: S, +) -> Result { + if N == 1 { + return T::ser_all(numbers, serializer); + } + let mut both = serializer.serialize_tuple(2)?; + both.serialize_element(&shape[..])?; + both.serialize_element(&All(numbers))?; + both.end() +} + +fn de_array<'de, T: Numbers, const N: usize, D: Deserializer<'de>>( + deserializer: D, +) -> Result<([usize; N], Vec), D::Error> { + if N == 1 { + let numbers = T::de_all(deserializer)?; + return Ok(([numbers.len(); N], numbers)); + } + let (shape, AllOf(numbers)): (Vec, AllOf) = Deserialize::deserialize(deserializer)?; + let shape = <[usize; N]>::try_from(shape).map_err(|_| de::Error::custom("an array of other dimensions"))?; + Ok((shape, numbers)) +} + +impl Form for Array { + fn ser(&self, serializer: S) -> Result { + ser_array(self.shape(), self.as_slice(), serializer) + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let (shape, numbers) = de_array(deserializer)?; + Array::new(numbers, shape).ok_or_else(|| de::Error::custom("an array whose shape is not of its numbers")) + } +} + +impl Form for MutableArray { + fn ser(&self, serializer: S) -> Result { + ser_array(self.shape(), &self.read(), serializer) + } + + fn de<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let (shape, numbers) = de_array(deserializer)?; + MutableArray::new(numbers, shape).ok_or_else(|| de::Error::custom("an array whose shape is not of its numbers")) + } +} + +/// Reads the key of an entry of an object, as which of some names it is: or None, if it is none of them +pub struct Named<'a>(pub &'a [&'static str]); + +impl<'de> DeserializeSeed<'de> for Named<'_> { + type Value = Option; + + fn deserialize>(self, deserializer: D) -> Result { + deserializer.deserialize_identifier(self) + } +} + +impl Visitor<'_> for Named<'_> { + type Value = Option; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a key") + } + + fn visit_str(self, key: &str) -> Result { + Ok(self.0.iter().position(|name| *name == key)) + } +} + +/// Reads a field of a struct, which must not have been read +pub fn field<'de, A: MapAccess<'de>, T: Form>( + map: &mut A, + name: &'static str, + held: &mut Option, +) -> Result<(), A::Error> { + if held.is_some() { + return Err(de::Error::duplicate_field(name)); + } + *held = Some(map.next_value::>()?.0); + Ok(()) +} + +/// Reads past an entry which is not of a field +pub fn ignored<'de, A: MapAccess<'de>>(map: &mut A) -> Result<(), A::Error> { + map.next_value::().map(drop) +} + +/// A field which was read: or if not, which has no default, so must be +pub fn required(name: &'static str, held: Option) -> Result { + held.ok_or_else(|| E::missing_field(name)) +} + +/// A discriminated union, which is written as `{"t": tag, "v": value}`: the generated code says what its tags are +pub trait Tagged: Sized { + fn tag(&self) -> &'static str; + + /// Its member, as that is written + fn value(&self, serializer: S) -> Result; + + /// Reads the member which a tag is of + fn member<'de, D: Deserializer<'de>>(tag: &str, deserializer: D) -> Result; +} + +struct Value<'a, T>(&'a T); + +impl Serialize for Value<'_, T> { + fn serialize(&self, serializer: S) -> Result { + self.0.value(serializer) + } +} + +pub fn ser_tagged(value: &T, serializer: S) -> Result { + let mut map = serializer.serialize_map(Some(2))?; + map.serialize_entry("t", value.tag())?; + map.serialize_entry("v", &Value(value))?; + map.end() +} + +struct Member<'a, T>(&'a str, PhantomData); + +impl<'de, T: Tagged> DeserializeSeed<'de> for Member<'_, T> { + type Value = T; + + fn deserialize>(self, deserializer: D) -> Result { + T::member(self.0, deserializer) + } +} + +struct TaggedVisitor(PhantomData); + +impl<'de, T: Tagged> Visitor<'de> for TaggedVisitor { + type Value = T; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("an object of \"t\", a tag, and \"v\", its value") + } + + fn visit_map>(self, mut map: A) -> Result { + let (mut tag, mut value, mut early) = (None::, None, None::); + while let Some(key) = map.next_key_seed(Named(&["t", "v"]))? { + match key { + Some(0) if tag.is_none() => tag = Some(map.next_value()?), + Some(1) if value.is_none() && early.is_none() => match &tag { + Some(tag) => value = Some(map.next_value_seed(Member(tag, PhantomData))?), + // Its tag is to follow: so it is kept until it is known what it is + None => early = Some(map.next_value()?), + }, + _ => return Err(de::Error::custom("an object of other than \"t\" and \"v\", once each")), + } + } + match (value, tag, early) { + (Some(value), ..) => Ok(value), + (None, Some(tag), Some(early)) => T::member(&tag, early).map_err(de::Error::custom), + _ => Err(de::Error::custom("an object without both \"t\" and \"v\"")), + } + } +} + +pub fn de_tagged<'de, T: Tagged, D: Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_map(TaggedVisitor(PhantomData)) +} diff --git a/src/dataclass_native/rust/src/lib.rs b/src/dataclass_native/rust/src/lib.rs index 56b5588..f0b28d7 100644 --- a/src/dataclass_native/rust/src/lib.rs +++ b/src/dataclass_native/rust/src/lib.rs @@ -7,7 +7,45 @@ use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; #[cfg(feature = "python")] mod fields; +#[cfg(feature = "json")] +pub mod json; pub mod msgpack; + +/// What the generated code has of serde, and so of JSON: which is there only with the feature json, as it is the +/// feature which has serde +#[cfg(feature = "json")] +#[macro_export] +macro_rules! json { + ($($items:tt)*) => { $($items)* }; +} + +#[cfg(not(feature = "json"))] +#[macro_export] +macro_rules! json { + ($($items:tt)*) => {}; +} + +/// The days since 1970-01-01 of a date, and the year, month and day of that many +#[cfg(feature = "json")] +pub(crate) fn days_of(year: i64, month: i64, day: i64) -> i64 { + let year = year - i64::from(month <= 2); + let era = year.div_euclid(400); + let of_era = year - era * 400; + let of_year = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day - 1; + era * 146_097 + of_era * 365 + of_era / 4 - of_era / 100 + of_year - 719_468 +} + +#[cfg(feature = "json")] +pub(crate) fn date_of(days: i64) -> (i64, i64, i64) { + let days = days + 719_468; + let era = days.div_euclid(146_097); + let of_era = days - era * 146_097; + let year = (of_era - of_era / 1460 + of_era / 36_524 - of_era / 146_096) / 365; + let of_year = of_era - (365 * year + year / 4 - year / 100); + let shifted = (5 * of_year + 2) / 153; + let month = if shifted < 10 { shifted + 3 } else { shifted - 9 }; + (year + era * 400 + i64::from(month <= 2), month, of_year - (153 * shifted + 2) / 5 + 1) +} #[cfg(feature = "python")] pub mod python; diff --git a/src/dataclass_native/rust/src/python.rs b/src/dataclass_native/rust/src/python.rs index 3b48247..fb9e079 100644 --- a/src/dataclass_native/rust/src/python.rs +++ b/src/dataclass_native/rust/src/python.rs @@ -1,7 +1,7 @@ //! Between the types of this crate and what a Python extension gives of them to Python: as nanobind does of those //! of C++. The generated bindings use it for each field of a struct. -use crate::msgpack; +use crate::{date_of, days_of, json, msgpack}; use crate::{ Array, Bytes, Date, DateTime, Decimal, Indirect, Mutable, MutableArray, NaiveDateTime, Ordered, TimeDelta, TimeOfDay, Uuid, @@ -274,26 +274,6 @@ impl Native for Bytes { const DAY: i64 = 86_400_000_000; -/// The days since 1970-01-01 of a date, and the year, month and day of that many -fn days_of(year: i64, month: i64, day: i64) -> i64 { - let year = year - i64::from(month <= 2); - let era = year.div_euclid(400); - let of_era = year - era * 400; - let of_year = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day - 1; - era * 146_097 + of_era * 365 + of_era / 4 - of_era / 100 + of_year - 719_468 -} - -fn date_of(days: i64) -> (i64, i64, i64) { - let days = days + 719_468; - let era = days.div_euclid(146_097); - let of_era = days - era * 146_097; - let year = (of_era - of_era / 1460 + of_era / 36_524 - of_era / 146_096) / 365; - let of_year = of_era - (365 * year + year / 4 - year / 100); - let shifted = (5 * of_year + 2) / 153; - let month = if shifted < 10 { shifted + 3 } else { shifted - 9 }; - (year + era * 400 + i64::from(month <= 2), month, of_year - (153 * shifted + 2) / 5 + 1) -} - /// A date and a time of day, as microseconds since 1970-01-01T00:00: and Python's datetime of that, in a timezone /// or none fn datetime<'py>( @@ -942,3 +922,23 @@ pub fn to_msgpack<'py, T: msgpack::Wire>(py: Python<'py>, value: &T) -> PyResult pub fn from_msgpack(data: &[u8]) -> PyResult { msgpack::from_msgpack(data).map_err(|error| PyValueError::new_err(error.0)) } + +/// A struct as JSON, and one read from it: what the class of each has as `__json__` and `__from_json__`, which +/// dataclass_native's to_json and from_json call +pub fn to_json<'py, T: json::Form>(py: Python<'py>, value: &T) -> PyResult> { + match json::to_json(value) { + Ok(data) => Ok(PyBytes::new(py, &data)), + Err(error) => Err(PyValueError::new_err(error.to_string())), + } +} + +pub fn from_json(of: &str, data: &[u8]) -> PyResult { + json::from_json(data).map_err(|error| { + // Whether it is what was read which is wrong, or that it is not of the type: as serde says which + PyValueError::new_err(if error.is_data() { + format!("The data is not a {of}, as written: {error}") + } else { + format!("The data is not JSON: {error}") + }) + }) +} diff --git a/tests/test_json.py b/tests/test_json.py index 9f787a8..e793ba5 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -221,7 +221,9 @@ def test_arrays(): # As what it is read into may be written to, or not assert from_json(Path, to_json(path)).points.flags.writeable assert not from_json(Curve, to_json(curve)).points.flags.writeable - with pytest.raises(ValueError, match="Surface.values cannot be read"): + with pytest.raises( + ValueError, match="Surface.values cannot be read|The data is not a Surface" + ): from_json(Surface, '{"values": [[2, 2], [1.0, 2.0]]}') @@ -253,7 +255,9 @@ def test_reading(): assert from_json(Money, ' {\n"currency" : 3 , "amount":1e2}\t') == Money( 100.0, Currency.GBP ) - with pytest.raises(ValueError, match="Money cannot be read: "): + with pytest.raises( + ValueError, match="Money cannot be read: |The data is not a Money" + ): from_json(Money, '{"currency": 3}') # A float from a number of either kind, but not an int from one with a fraction assert from_json(tuple[float, ...], '[1, -0, 2.5, 1E2, "NaN"]')[:4] == ( diff --git a/tests/test_pyo3.py b/tests/test_pyo3.py index 28b456e..e141cfa 100644 --- a/tests/test_pyo3.py +++ b/tests/test_pyo3.py @@ -30,6 +30,15 @@ ] # What an extension in Rust is yet to do, so the test of it is not run: Arrow TO_COME = ["test_arrow.py::test_bound_objects_are_held_natively"] +# What serde reads otherwise than Python and C++ do, of JSON which none of them writes: -0, which is not an int +# to it, and is the float -0.0, and a key which is a number with spaces about it +OTHERWISE = [ + "test_json.py::test_both_read_the_same[whole--0]", + "test_json.py::test_both_read_the_same[big--0]", + "test_json.py::test_both_read_the_same[real--0]", + 'test_json.py::test_both_read_the_same[by_whole-{"-0": true}]', + 'test_json.py::test_both_read_the_same[by_real-{"1.5": 1, "1": 2, "1e2": 3, "Infinity": 4, " 2.0 ": 5, "-0": 6}]', +] _MANIFEST = """\ [package] @@ -226,7 +235,7 @@ def test_runtime_with_the_extension(built, mode): result = subprocess.run( [sys.executable, "-m", "pytest", "-q", "--no-cov", "-p", "no:cacheprovider"] + [f"tests/{file}" for file in files] - + [f"--deselect=tests/{test}" for test in TO_COME] + + [f"--deselect=tests/{test}" for test in TO_COME + OTHERWISE] # Not prepending tests to the path, where the schemas have no extension + ["--import-mode=importlib", "-o", f"pythonpath={built.as_posix()}"], cwd=TESTS.parent, diff --git a/tests/test_rust.py b/tests/test_rust.py index 00f82bd..c9666c2 100644 --- a/tests/test_rust.py +++ b/tests/test_rust.py @@ -105,6 +105,64 @@ def test_common(sources): } } + dataclass_native::json! { + impl dataclass_native::json::Form for Currency { + fn ser(&self, serializer: S) -> Result { + match self { + Self::USD => serializer.serialize_i64(1), + Self::EUR => serializer.serialize_i64(2), + Self::GBP => serializer.serialize_i64(3), + } + } + + fn de<'de, D: dataclass_native::json::serde::Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_any(CurrencyMember(false)) + } + + fn de_key<'de, D: dataclass_native::json::serde::Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_any(CurrencyMember(true)) + } + } + + /// Reads a member: as a key, if it is one + struct CurrencyMember(bool); + + impl dataclass_native::json::serde::de::Visitor<'_> for CurrencyMember { + type Value = Currency; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("a Currency") + } + + fn visit_str(self, text: &str) -> Result { + match text { + "1" if self.0 => Ok(Currency::USD), + "2" if self.0 => Ok(Currency::EUR), + "3" if self.0 => Ok(Currency::GBP), + _ => Err(E::invalid_value(dataclass_native::json::serde::de::Unexpected::Str(text), &self)), + } + } + + fn visit_i64(self, value: i64) -> Result { + match value { + 1 => Ok(Currency::USD), + 2 => Ok(Currency::EUR), + 3 => Ok(Currency::GBP), + _ => Err(E::invalid_value(dataclass_native::json::serde::de::Unexpected::Signed(value), &self)), + } + } + + fn visit_u64(self, value: u64) -> Result { + match i64::try_from(value) { + Ok(value) => dataclass_native::json::serde::de::Visitor::visit_i64(self, value), + Err(_) => Err(E::invalid_value(dataclass_native::json::serde::de::Unexpected::Unsigned(value), &self)), + } + } + } + + dataclass_native::serde_by_form!([] Currency); + } + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(i8)] @@ -137,6 +195,46 @@ def test_common(sources): } } + dataclass_native::json! { + impl dataclass_native::json::Form for Side { + fn ser(&self, serializer: S) -> Result { + match self { + Self::BUY => serializer.serialize_str("buy"), + Self::SELL => serializer.serialize_str("sell"), + } + } + + fn de<'de, D: dataclass_native::json::serde::Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_any(SideMember(false)) + } + + fn de_key<'de, D: dataclass_native::json::serde::Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_any(SideMember(true)) + } + } + + /// Reads a member: as a key, if it is one + struct SideMember(bool); + + impl dataclass_native::json::serde::de::Visitor<'_> for SideMember { + type Value = Side; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("a Side") + } + + fn visit_str(self, text: &str) -> Result { + match text { + "buy" => Ok(Side::BUY), + "sell" => Ok(Side::SELL), + _ => Err(E::invalid_value(dataclass_native::json::serde::de::Unexpected::Str(text), &self)), + } + } + } + + dataclass_native::serde_by_form!([] Side); + } + #[derive(Debug, Clone, PartialEq)] pub struct Money { pub amount: f64, @@ -195,6 +293,53 @@ def test_common(sources): impl dataclass_native::msgpack::Record for Money { const TAG: &'static str = "schemas.common.Money"; } + + dataclass_native::json! { + impl dataclass_native::json::Form for Money { + fn ser(&self, serializer: S) -> Result { + use dataclass_native::json::serde::ser::SerializeMap; + let mut map = serializer.serialize_map(Some(2))?; + map.serialize_entry("amount", &dataclass_native::json::Ser(&self.amount))?; + map.serialize_entry("currency", &dataclass_native::json::Ser(&self.currency))?; + map.end() + } + + fn de<'de, D: dataclass_native::json::serde::Deserializer<'de>>(deserializer: D) -> Result { + struct Fields; + + impl<'de> dataclass_native::json::serde::de::Visitor<'de> for Fields { + type Value = Money; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("a Money") + } + + fn visit_map>(self, mut map: A) -> Result { + let mut field0 = None; + let mut field1 = None; + while let Some(key) = map.next_key_seed(dataclass_native::json::Named(&["amount", "currency"]))? { + match key { + Some(0) => dataclass_native::json::field(&mut map, "amount", &mut field0)?, + Some(1) => dataclass_native::json::field(&mut map, "currency", &mut field1)?, + _ => dataclass_native::json::ignored(&mut map)?, + } + } + Ok(Money { + amount: dataclass_native::json::required("amount", field0)?, + currency: match field1 { + Some(read) => read, + None => Money::default().currency, + }, + }) + } + } + + deserializer.deserialize_map(Fields) + } + } + + dataclass_native::serde_by_form!([] Money); + } """ ) ) @@ -405,14 +550,42 @@ def test_cli(tmp_path, capsys): let read: (Shared, Shared) = from_msgpack(&to_msgpack(&both).unwrap()).unwrap(); assert!(read == both && Shared::ptr_eq(read.0.next.as_ref().unwrap(), &read.1)); + #[cfg(feature = "json")] + json(&keyed, &curve, &surface, &path, &first); println!("ok"); } + +/// As JSON, by serde: as JSON_FORMAT.md has it, and read back as what was written +#[cfg(feature = "json")] +fn json(keyed: &Everything, curve: &Curve, surface: &Surface, path: &Path, link: &Link) { + use dataclass_native::json::{from_json, to_json}; + + let money = Money { amount: 1.5, currency: Currency::EUR }; + assert_eq!(to_json(&money).unwrap(), br#"{"amount":1.5,"currency":2}"#); + assert_eq!(from_json::(br#" {"currency": 2, "other": [1], "amount": 15e-1} "#).unwrap(), money); + assert!(from_json::(br#"{"currency": 2}"#).unwrap_err().to_string().contains("missing field `amount`")); + // A float as Python writes it, and one which is not finite as a string + let floats = (1e-5, 1e16, 1.5e300, 100.0, f64::NAN, f64::NEG_INFINITY); + assert_eq!(to_json(&floats).unwrap(), br#"[1e-05,1e+16,1.5e+300,100.0,"NaN","-Infinity"]"#); + for kinds in [Kinds::default(), Kinds { number: KindsNumber::Str("x".to_string()), ..Kinds::default() }] { + assert_eq!(from_json::(&to_json(&kinds).unwrap()).unwrap(), kinds); + } + assert_eq!(from_json::(&to_json(keyed).unwrap()).unwrap(), *keyed); + assert_eq!(from_json::(&to_json(curve).unwrap()).unwrap(), *curve); + assert_eq!(from_json::(&to_json(surface).unwrap()).unwrap(), *surface); + assert_eq!(from_json::(&to_json(path).unwrap()).unwrap(), *path); + // What is shared is written where it is held, so is not shared when it is read + assert_eq!(to_json(link).unwrap(), br#"{"name":"a","next":{"name":"b","next":null}}"#); + assert_eq!(from_json::(&to_json(link).unwrap()).unwrap(), *link); +} """ @needs_cargo -def test_cargo_compiles_it(sources): - """With warnings as errors, and it holds what it is to: with no crate but dataclass-native's own""" +@pytest.mark.parametrize("features", [(), ("--features", "json")]) +def test_cargo_compiles_it(sources, features): + """With warnings as errors, and it holds what it is to: with no crate but dataclass-native's own, which has + serde only with its feature json""" # Kept between runs, so that only what has changed is built crate = BUILD / "crate" shutil.rmtree(crate / "src", ignore_errors=True) @@ -429,6 +602,9 @@ def test_cargo_compiles_it(sources): version = "0.0.0" edition = "2021" + [features] + json = ["dataclass_native/json"] + [dependencies] dataclass_native = {{ path = "{rust_dir().as_posix()}" }} """ @@ -436,7 +612,7 @@ def test_cargo_compiles_it(sources): encoding="utf-8", ) result = subprocess.run( - ["cargo", "run", "--quiet"], + ["cargo", "run", "--quiet", *features], cwd=crate, capture_output=True, text=True,