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
20 changes: 16 additions & 4 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,19 @@ the structs, by [pyo3](https://pyo3.rs), as nanobind does in those of C++.
- pyo3 says an int which is too great for its field is an `OverflowError`: the runtime makes of it the
`TypeError` which any value a field cannot be is.

Not yet in Rust, so done by Python for what is held in it: msgpack, JSON and Arrow. Nor are the descriptors of
fields which C++ has, so a field is read and set by way of Python.
- The extension has the `__fields__` and `__maker__` which one of C++ has, in each of its modules, so a field
is read and set, and an object made, without Python: by the crate's `Field`, which the generated code gives
what reads and writes the field of a struct. A type says how it is made as Python itself is to have it, and
taken from that, with what the field is told: an enum by its members, a frozen struct by its class, and a
tuple or a frozenset of what is as Python has it. The rest, Python's converters do, as for C++.

- msgpack is written and read by the crate's `msgpack`, which depends on nothing: so by Rust alone, as by an
extension, whose classes have the `__msgpack__` and `__from_msgpack__` which those of C++ have. The generated
code implements its `Wire` for each struct, enum and union, and says of each whether it is written as a
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.

## Python runtime

Expand Down Expand Up @@ -418,8 +429,9 @@ what an object is made from, before the native class checks it.
and their defaults, generated as modules which cargo compiles, with a crate of the types they use which
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. To come: msgpack, JSON and Arrow in Rust, which Python does until then; the
descriptors of fields which C++ has; and an example built with maturin.
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.
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
74 changes: 42 additions & 32 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,15 @@ pub struct Trade {
}
```

They are written as msgpack, and read from it, as Python and C++ write and read them, with no Python:

```rust
use dataclass_native::msgpack::{from_msgpack, to_msgpack};

let data: Vec<u8> = to_msgpack(&trade)?;
let trade: Trade = from_msgpack(&data)?;
```

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 @@ -163,8 +172,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 does not yet serialise
them, which Python does for it, and an example built with maturin is to come.
`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.

## Storing Python objects in the structs

Expand Down Expand Up @@ -351,44 +360,45 @@ Apple M1 with Python 3.14, of extensions built for release: `uv run python tests
tables, of the classes of [tests/schemas](tests/schemas).

- `pure`: plain dataclasses, as Python has them.
- C++: bound to the C++ structs, whose extension reads and sets fields itself, as of 1.1.0.
- C++, Python's descriptors: the same, read and set by way of Python, as an extension built by 1.0.0 is.
- Rust: bound to the Rust structs. Its extension does not yet read and set fields itself, so Python does.

| Nanoseconds to | `pure` | C++ | C++, Python's descriptors | Rust |
|---|---:|---:|---:|---:|
| Make `Money(1.5, Currency.EUR)` | 156 | 293 | 840 | 891 |
| Make a `Trade`, of 19 fields | 1,113 | 3,537 | 6,129 | 6,771 |
| Make a `Customer`, which is not frozen | 103 | 339 | 1,436 | 1,542 |
| Read a float | 9 | 29 | 113 | 111 |
| Read an enum | 17 | 25 | 176 | 186 |
| Read a str | 9 | 37 | 121 | 120 |
| Read a nested object | 17 | 147 | 295 | 320 |
| Read a `Shared` object | 9 | 139 | 215 | 258 |
| Read a tuple of 3 strs | 9 | 104 | 210 | 247 |
| Read an array of 1,000 floats | 9 | 301 | 394 | 723 |
| Set an int | 17 | 24 | 139 | 134 |
| Set a str | 9 | 30 | 147 | 150 |
| Set a nested object | 9 | 58 | 195 | 233 |
- C++ and Rust: bound to the structs of each, whose extension reads and sets fields itself. C++'s does as of
1.1.0.
- Python's descriptors: the same, read and set by way of Python, as an extension built before it did so is.

| Nanoseconds to | `pure` | C++ | Rust | C++, Python's descriptors | Rust, Python's descriptors |
|---|---:|---:|---:|---:|---:|
| Make `Money(1.5, Currency.EUR)` | 159 | 300 | 431 | 838 | 904 |
| Make a `Trade`, of 19 fields | 1,126 | 3,568 | 4,006 | 6,293 | 6,705 |
| Make a `Customer`, which is not frozen | 104 | 338 | 563 | 1,447 | 1,566 |
| Read a float | 9 | 29 | 46 | 113 | 112 |
| Read an enum | 18 | 25 | 40 | 174 | 187 |
| Read a str | 9 | 39 | 56 | 121 | 119 |
| Read a nested object | 18 | 153 | 169 | 298 | 312 |
| Read a `Shared` object | 9 | 149 | 203 | 217 | 262 |
| Read a tuple of 3 strs | 9 | 104 | 154 | 210 | 262 |
| Read an array of 1,000 floats | 9 | 299 | 418 | 400 | 485 |
| Set an int | 17 | 24 | 41 | 132 | 134 |
| Set a str | 9 | 30 | 60 | 139 | 152 |
| Set a nested object | 9 | 58 | 107 | 190 | 235 |

A bound object is slower to make and to read than a plain dataclass, as each field is converted to and from what
the struct holds, where Python only keeps a reference: by some three times for a number, and more for what
Python must make an object of each time it is read. An array is not copied, whatever its size.
the struct holds, where Python only keeps a reference: by some three times for a number in C++, and five in
Rust, and more for what Python must make an object of each time it is read. An array is not copied, whatever
its size.

What is gained is in what native code then does with the structs, without Python: as in serialising. An `Order`
here is of two customers, each with two addresses: 15 values, in 7 objects. Arrow is of 10,000 of them.

| Microseconds, for each `Order`, to | `pure` | C++ | Rust |
|---|---:|---:|---:|
| Write msgpack | 8.8 | 1.9 | 18.1 |
| Read msgpack | 24.3 | 2.6 | 36.5 |
| Write JSON | 10.7 | 2.3 | 20.1 |
| Read JSON | 13.5 | 3.1 | 25.8 |
| Write Arrow | 11.2 | 0.4 | 19.0 |
| Read Arrow | 9.3 | 0.7 | 19.6 |

C++ writes and reads the structs itself. Rust does not yet, so Python does, reading each field from the struct:
which is slower than `pure`, until Rust has its own.
| 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 |
| 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
does, reading each field from the struct: which is slower than `pure`, until Rust has its own.

## Examples

Expand Down
2 changes: 1 addition & 1 deletion WIRE_FORMAT.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# dataclass-native: msgpack wire format

How a value of a schema type is written as [msgpack](https://github.com/msgpack/msgpack/blob/master/spec.md). Every
implementation (Python and C++ now, Rust to come) writes and reads this. The Python one is the reference: where
implementation (Python, C++ and Rust) writes and reads this. 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. The data does not describe itself, beyond what a reader needs to tell
Expand Down
93 changes: 71 additions & 22 deletions src/dataclass_native/backends/pyo3.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,21 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str:
f"// Generated by dataclass-native from {package}: do not edit\n"
f"//! The classes which hold Python's objects of {package} in the structs generated for it. `register` adds\n"
f"//! them to an extension module, which is to be {package}._native\n"
"#![allow(non_camel_case_types, non_snake_case, clippy::all)]\n\n"
f"use {RUNTIME}::python::{{member, Changing, Frozen, Held, 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"
"};\n"
f"use {RUNTIME}::Mutable;\n"
"use pyo3::exceptions::PyTypeError;\n"
"use pyo3::prelude::*;\n"
"use pyo3::types::{PyDict, PyModule};\n"
"use pyo3::types::{PyBytes, PyDict, PyModule};\n"
)
]
registered = []
for module in modules:
generator = _ModuleGenerator(schema, module)
generator.generate()
added, hashes = [], []
added, hashes, structs = [], [], []
for enum in module.enums:
parts.append(_enum(enum))
added.append(_class(enum.module, enum.name))
Expand All @@ -86,7 +88,8 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str:
parts.append(_struct(struct))
added.append(_class(struct.module, struct.name))
hashes.append((struct.name, s.schema_hash(struct)))
registered.append(_registered(package, module.name, added, hashes))
structs.append((struct.name, added[-1]))
registered.append(_registered(module.name, added, hashes, structs))

parts.append(
f"/// Adds a module for each schema module of {package} to an extension module, which is to be\n"
Expand All @@ -98,7 +101,10 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str:


def _registered(
package: str, module: str, classes: list[str], hashes: list[tuple[str, str]]
module: str,
classes: list[str],
hashes: list[tuple[str, str]],
structs: list[tuple[str, str]],
) -> str:
within = module.split(".")[1:]
lines = [
Expand All @@ -123,7 +129,18 @@ def _registered(
lines += [
f' schema.set_item("{name}", "{digest}")?;\n' for name, digest in hashes
]
lines += [' module.add("__schema__", schema)?;\n', " }\n"]
lines.append(' module.add("__schema__", schema)?;\n')
# What reads, sets and makes the objects of its classes without Python
lines.append(" let fields = PyDict::new(py);\n")
lines += [
f' fields.set_item("{name}", {cls}::fields(py)?)?;\n'
for name, cls in structs
]
lines += [
' module.add("__fields__", fields)?;\n',
' module.add("__maker__", maker(py)?)?;\n',
" }\n",
]
return "".join(lines)


Expand All @@ -149,8 +166,18 @@ def _enum(enum: s.Enum) -> str:
f" let held = value.cast_exact::<{name}>()\n"
f' .map_err(|_| PyTypeError::new_err("not a {enum.name}"))?;\n'
f" Ok(match held.get() {{\n{back} }})\n"
" }\n\n"
" fn to_python<'py>(&self, _py: Python<'py>, told: &Told<'_, 'py>) -> PyResult<Option<Bound<'py, PyAny>>> {\n"
f" told.member({name}__MEMBERS.iter().position(|member| member == self))\n"
" }\n\n"
" fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult<Option<Self>> {\n"
f" Ok(told.place(value).and_then(|at| {name}__MEMBERS.get(at).copied()))\n"
" }\n"
"}\n"
"}\n\n"
"/// In the order of Python's\n"
f"const {name}__MEMBERS: [{plain}; {len(members)}] = [\n"
+ "".join(f" {plain}::{m},\n" for m in members)
+ "];\n"
)


Expand Down Expand Up @@ -217,22 +244,28 @@ def _struct(struct: s.Struct) -> str:
" }\n"
)

by_value = (
# What reads and sets each field without Python
registered = []
for f in struct.fields:
match f.type:
case s.StructRef(mutable=False) if not struct.mutable:
kind = "within"
case _:
kind = "changing" if struct.mutable else "frozen"
field = identifier(f.name)
registered.append(
f' fields.{kind}::<{plain}, _>("{f.name}", |held| &held.{field}, |held| &mut held.{field})?;\n'
)
write = (
""
if struct.mutable
else (
"\n/// Held by value: so a copy of it\n"
f"impl Native for {plain} {{\n"
" fn to_native<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {\n"
f" <{plain} as Frozen>::wrap(py, Held::new(self.clone()))\n"
" }\n\n"
" fn from_native(value: &Bound<'_, PyAny>) -> PyResult<Self> {\n"
f" Ok((*<{plain} as Frozen>::unwrap(value)?).clone())\n"
" }\n\n"
" fn into_native<'py>(self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {\n"
f" <{plain} as Frozen>::wrap(py, Held::new(self))\n"
"\n fn write<R>(value: &Bound<'_, PyAny>, write: impl FnOnce(&mut Self) -> R) -> PyResult<R> {\n"
f" let held = value.cast_exact::<{name}>()\n"
f' .map_err(|_| PyTypeError::new_err("not a {struct.name}"))?;\n'
" let mut held = held.try_borrow_mut()?;\n"
" Ok(write(held.0.make_mut()))\n"
" }\n"
"}\n"
)
)
return (
Expand All @@ -247,14 +280,30 @@ def _struct(struct: s.Struct) -> str:
f' .map_err(|_| PyTypeError::new_err("not a {struct.name}"))?;\n'
" Ok(held.borrow().0.clone())\n"
" }\n"
"}\n"
f"{by_value}\n"
f"{write}"
"}\n\n"
f"impl {name} {{\n"
" fn fields(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {\n"
" let fields = Fields::new(py.get_type::<Self>());\n"
+ "".join(registered)
+ ""
" Ok(fields.into_dict())\n"
" }\n"
"}\n\n"
"#[pymethods]\n"
f"impl {name} {{\n"
" #[new]\n"
" fn new() -> Self {\n"
f" Self({held.partition('<')[0]}::new({plain}::default()))\n"
" }\n\n" + "\n".join(methods) + "\n"
" /// As msgpack, and one read from it: see the crate's msgpack\n"
" fn __msgpack__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {\n"
f" to_msgpack(py, &*{read})\n"
" }\n\n"
" #[staticmethod]\n"
" fn __from_msgpack__(data: &[u8]) -> PyResult<Self> {\n"
f" Ok(Self({held.partition('<')[0]}::new(from_msgpack(data)?)))\n"
" }\n\n"
" /// 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