Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
10 changes: 7 additions & 3 deletions JSON_FORMAT.md
Original file line number Diff line number Diff line change
@@ -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).

Expand Down Expand Up @@ -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:
Expand Down
28 changes: 21 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,19 @@ let data: Vec<u8> = 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<u8> = 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`:

Expand All @@ -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

Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions WIRE_FORMAT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
24 changes: 21 additions & 3 deletions src/dataclass_native/backends/pyo3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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"
Expand All @@ -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]))
Expand Down Expand Up @@ -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 = (
Expand Down Expand Up @@ -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<Bound<'py, PyBytes>> {\n"
f" to_json(py, &*{read})\n"
" }\n\n"
" #[staticmethod]\n"
" fn __from_json__(data: &[u8]) -> PyResult<Self> {\n"
f' Ok(Self({held.partition("<")[0]}::new(from_json("{struct.name}", data)?)))\n'
" }\n\n"
)
if in_json
else ""
)
write = (
""
if struct.mutable
Expand Down Expand Up @@ -304,6 +321,7 @@ def _struct(struct: s.Struct) -> str:
" fn __from_msgpack__(data: &[u8]) -> PyResult<Self> {\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"
Expand Down
Loading
Loading