diff --git a/DESIGN.md b/DESIGN.md index 094a557..0bb7a90 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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 @@ -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 diff --git a/README.md b/README.md index 0d75710..e7bc221 100644 --- a/README.md +++ b/README.md @@ -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 = 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`: @@ -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 @@ -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 diff --git a/WIRE_FORMAT.md b/WIRE_FORMAT.md index 2deccfa..074af38 100644 --- a/WIRE_FORMAT.md +++ b/WIRE_FORMAT.md @@ -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 diff --git a/src/dataclass_native/backends/pyo3.py b/src/dataclass_native/backends/pyo3.py index e2d6ea9..198c695 100644 --- a/src/dataclass_native/backends/pyo3.py +++ b/src/dataclass_native/backends/pyo3.py @@ -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)) @@ -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" @@ -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 = [ @@ -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) @@ -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>> {\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> {\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" ) @@ -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> {\n" - f" <{plain} as Frozen>::wrap(py, Held::new(self.clone()))\n" - " }\n\n" - " fn from_native(value: &Bound<'_, PyAny>) -> PyResult {\n" - f" Ok((*<{plain} as Frozen>::unwrap(value)?).clone())\n" - " }\n\n" - " fn into_native<'py>(self, py: Python<'py>) -> PyResult> {\n" - f" <{plain} as Frozen>::wrap(py, Held::new(self))\n" + "\n fn write(value: &Bound<'_, PyAny>, write: impl FnOnce(&mut Self) -> R) -> PyResult {\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 ( @@ -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> {\n" + " let fields = Fields::new(py.get_type::());\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> {\n" + f" to_msgpack(py, &*{read})\n" + " }\n\n" + " #[staticmethod]\n" + " fn __from_msgpack__(data: &[u8]) -> PyResult {\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" diff --git a/src/dataclass_native/backends/rust.py b/src/dataclass_native/backends/rust.py index 4e97ee5..8f3b841 100644 --- a/src/dataclass_native/backends/rust.py +++ b/src/dataclass_native/backends/rust.py @@ -14,6 +14,8 @@ from typing import Any from .. import schema as s +from .._wire import _reaches +from ..introspect import _tag from ..schema import SchemaError RUNTIME = "dataclass_native" @@ -86,6 +88,109 @@ def identifier(name: str) -> str: return f"{name}_" if name in KEYWORDS else name +WIRE = f"{RUNTIME}::msgpack" +_WRITE = f" fn write(&self, writer: &mut {WIRE}::Writer) -> Result<(), {WIRE}::Error> {{\n" +_READ = f" fn read(reader: &mut {WIRE}::Reader<'_>) -> {WIRE}::Read {{\n" +# Of a union's member, by how it is written: what tells it, of what is next to be read +_KINDS = { + "bool": "Bool", + "int": "Int", + "float": "Float", + "str": "Str", + "bin": "Bin", + "timestamp": "Timestamp", + "map": "Map", + "array": "Array", + "ref": "Reference", +} + + +def _bool(value: bool) -> str: + return "true" if value else "false" + + +def _described(name: str) -> str: + """What data which is not one is said not to be: as Python names it""" + return ( + " fn described() -> String {\n" + f" {_string(name)}.to_string()\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 "" + + +def _wire_union( + t: s.Union, members: tuple[s.Type, ...], name: str, variants: list[str] +) -> str: + """How a union is written as msgpack, and read: as its member, which is told by its tag or by its kind""" + read = f"{WIRE}::Wire::read(reader)?" + mismatch = f"Err({WIRE}::Fault::Mismatch)" + if t.discriminated: + written = "".join( + f" Self::{variant}(value) => {{\n" + " writer.map(2);\n" + ' writer.str("t");\n' + f" writer.str({_string(_member_tag(member))});\n" + ' writer.str("v");\n' + f" {WIRE}::Wire::write(value, writer)\n" + " }\n" + for variant, member in zip(variants, members, strict=True) + ) + by_tag = "".join( + f" {_string(_member_tag(member))} => Ok(Self::{variant}({read})),\n" + for variant, member in zip(variants, members, strict=True) + ) + reading = ( + " reader.tagged(|reader, tag| match tag {\n" + f"{by_tag}" + f" _ => {mismatch},\n" + " })\n" + ) + else: + written = "".join( + f" Self::{variant}(value) => {WIRE}::Wire::write(value, writer),\n" + for variant in variants + ) + # No two are written as the same kind of value, but those which are shared: which are told by their tags + by_kind = "".join( + f" {WIRE}::Kind::{_KINDS[s.wire_kind(member)[0]]} => Ok(Self::{variant}({read})),\n" + for variant, member in zip(variants, members, strict=True) + if not isinstance(member, s.Shared) + ) + by_tag = "".join( + f" {_string(_member_tag(member))} => Ok(Self::{variant}({read})),\n" + for variant, member in zip(variants, members, strict=True) + if isinstance(member, s.Shared) + ) + if by_tag: + by_kind += ( + f" {WIRE}::Kind::Reference => match reader.referred()? {{\n" + f"{by_tag}" + f" _ => {mismatch},\n" + " },\n" + ) + reading = ( + " match reader.kind()? {\n" + f"{by_kind}" + f" _ => {mismatch},\n" + " }\n" + ) + return ( + f"impl {WIRE}::Wire for {name} {{\n" + f" const BUNDLED: bool = {_bool(_reaches(t, set()))};\n\n" + f"{_WRITE}" + f" match self {{\n{written} }}\n" + " }\n\n" + f"{_READ}{reading}" + " }\n" + "}\n" + ) + + def generate(schema: s.Schema) -> dict[str, str]: """The source of each module of the schema, and of each package they are in: by path from the output directory""" modules = set(schema.modules) @@ -150,11 +255,28 @@ def __enum(self, enum: s.Enum) -> str: f"{' #[default]\n' if index == 0 else ''} {identifier(m.name)} = {m.value},\n" for index, m in enumerate(enum.members) ) + name = identifier(enum.name) + names = [(identifier(m.name), _string(m.name)) for m in enum.members] + written = "".join(f" Self::{m} => {text},\n" for m, text in names) + read = "".join(f" {text} => Ok(Self::{m}),\n" for m, text in names) return ( "#[allow(non_camel_case_types, clippy::upper_case_acronyms)]\n" "#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]\n" f"#[repr({repr_})]\n" - f"pub enum {identifier(enum.name)} {{\n{members}}}\n" + f"pub enum {name} {{\n{members}}}\n\n" + "/// By the name of its member\n" + f"impl {WIRE}::Wire for {name} {{\n" + f"{_described(enum.name)}" + f"{_WRITE}" + f" writer.str(match self {{\n{written} }});\n" + " Ok(())\n" + " }\n\n" + f"{_READ}" + f" match reader.str()? {{\n{read}" + f" _ => Err({WIRE}::Fault::Mismatch),\n" + " }\n" + " }\n" + "}\n" ) def __struct(self, struct: s.Struct) -> str: @@ -172,6 +294,36 @@ def __struct(self, struct: s.Struct) -> str: else "Default::default()" ) defaults.append(f" {identifier(f.name)}: {value},\n") + of = _string(struct.name) + written, held, taken, made = [], [], [], [] + for index, f in enumerate(struct.fields): + field, key = identifier(f.name), _string(f.name) + written.append( + f" writer.str({key});\n" + f" {WIRE}::Wire::write(&self.{field}, writer)?;\n" + ) + held.append(f" let mut field{index} = None;\n") + taken.append( + f" Some({key}) => reader.field({of}, {key}, &mut field{index})?,\n" + ) + made.append( + f" {field}: match field{index} {{\n" + " Some(read) => read,\n" + f" None => Self::default().{field},\n" + " },\n" + if f.has_default + else f" {field}: {WIRE}::Reader::required({of}, {key}, field{index})?,\n" + ) + # One which is not frozen is not shared + record = ( + "" + if struct.mutable + else ( + f"\nimpl {WIRE}::Record for {name} {{\n" + f" const TAG: &'static str = {_string(struct.tag)};\n" + "}\n" + ) + ) return ( "#[derive(Debug, Clone, PartialEq)]\n" f"pub struct {name} {{\n{''.join(fields)}}}\n\n" @@ -180,7 +332,29 @@ def __struct(self, struct: s.Struct) -> str: " fn default() -> Self {\n" f" Self {{\n{''.join(defaults)} }}\n" " }\n" + "}\n\n" + "/// A map of its fields, by name: read in any order, one which is not written taking its default\n" + f"impl {WIRE}::Wire for {name} {{\n" + f" const BUNDLED: bool = {_bool(_reaches(struct.ref, set()))};\n\n" + f"{_described(struct.name)}" + f"{_WRITE}" + f" writer.map({len(struct.fields)});\n{''.join(written)}" + " Ok(())\n" + " }\n\n" + f"{_READ}" + " reader.nested(|reader| {\n" + f"{''.join(held)}" + " for _ in 0..reader.map()? {\n" + " match reader.key()? {\n" + f"{''.join(taken)}" + " _ => reader.skip()?,\n" + " }\n" + " }\n" + f" Ok(Self {{\n{''.join(made)} }})\n" + " })\n" + " }\n" "}\n" + f"{record}" ) def __path(self, module: str, name: str) -> str: @@ -265,7 +439,7 @@ 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\n" + _wire_union(t, members, name, variants) ) return name diff --git a/src/dataclass_native/rust/src/fields.rs b/src/dataclass_native/rust/src/fields.rs new file mode 100644 index 0000000..c164ec7 --- /dev/null +++ b/src/dataclass_native/rust/src/fields.rs @@ -0,0 +1,423 @@ +//! What reads, sets and makes Python's objects of the bound classes without Python: the descriptor of each field, +//! which an extension gives as its `__fields__`, and what makes an object, its `__maker__`. As those of C++ are, +//! by dataclass_native/python.hpp: dataclass_native._runtime binds either alike. + +use crate::python::{Changing, Frozen, Native}; +use pyo3::exceptions::{PyAttributeError, PyOverflowError, PyTypeError, PyValueError}; +use pyo3::prelude::*; +use pyo3::types::{PyCFunction, PyDict, PyString, PyTuple, PyType}; +use pyo3::{ffi, intern, PyTraverseError, PyVisit}; +use std::sync::Arc; + +/// What a field is told by dataclass_native._runtime, of what it could not know: with which a value is made as +/// Python is to have it, not as Python would convert it +pub struct Told<'a, 'py> { + /// The members of the enum the field is of, in their order + pub members: Option<&'a Bound<'py, PyTuple>>, + /// The class of the struct which the field is by value, or is a tuple of + pub wraps: Option<&'a Bound<'py, PyType>>, + /// Whether what a container holds is as Python has it + pub direct: bool, +} + +impl<'py> Told<'_, 'py> { + /// The member of the enum which is at a place among them + pub fn member(&self, at: Option) -> PyResult>> { + match (self.members, at) { + (Some(members), Some(at)) => members.get_item(at).map(Some), + _ => Ok(None), + } + } + + /// The place of a member of the enum: not of its value, which Python is left to find the member of + pub fn place(&self, value: &Bound<'py, PyAny>) -> Option { + self.members?.iter().position(|member| member.is(value)) + } + + /// An object of the class which the field is of, holding a native object + pub fn wrapped(&self, handle: Bound<'py, PyAny>) -> PyResult>> { + self.wraps.map(|class| instance(class, &handle)).transpose() + } + + /// The native object of an object of exactly the class which the field is of, if it has one + pub fn unwrapped(&self, value: &Bound<'py, PyAny>) -> Option> { + self.wraps.filter(|class| value.get_type().is(*class)).and_then(|_| handle_of(value)) + } +} + +/// The native object of a Python one, if it has one +fn handle_of<'py>(obj: &Bound<'py, PyAny>) -> Option> { + let py = obj.py(); + let attributes = unsafe { + let attributes = ffi::PyObject_GenericGetDict(obj.as_ptr(), std::ptr::null_mut()); + if attributes.is_null() { + ffi::PyErr_Clear(); + return None; + } + Bound::from_owned_ptr(py, attributes).cast_into_unchecked::() + }; + attributes.get_item(intern!(py, "__native__")).ok().flatten() +} + +/// An object of a bound class, which holds a native object: as dataclass_native._runtime.wrap makes +fn instance<'py>(class: &Bound<'py, PyType>, handle: &Bound<'py, PyAny>) -> PyResult> { + let py = class.py(); + let (obj, attributes) = unsafe { + let obj = Bound::from_owned_ptr_or_err(py, ffi::PyType_GenericAlloc(class.as_type_ptr(), 0))?; + let attributes = ffi::PyObject_GenericGetDict(obj.as_ptr(), std::ptr::null_mut()); + (obj, Bound::from_owned_ptr_or_err(py, attributes)?.cast_into_unchecked::()) + }; + attributes.set_item(intern!(py, "__native__"), handle)?; + Ok(obj) +} + +/// What reads and sets a field of a native object, of the class it is of +trait Member: Send + Sync { + /// As the extension gives it + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult>; + + /// As Python is to have it, if that can be made with what was told + fn give<'py>(&self, handle: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult>>; + + /// From what the extension is given + fn set(&self, handle: &Bound<'_, PyAny>, value: &Bound<'_, PyAny>) -> PyResult<()>; + + /// From what Python has, if it can be taken with what was told: giving whether it was + fn take<'py>(&self, handle: &Bound<'py, PyAny>, value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) + -> PyResult; +} + +/// A field of a frozen struct +struct OfFrozen { + read: fn(&T) -> &M, + written: fn(&mut T) -> &mut M, +} + +impl Member for OfFrozen { + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult> { + (self.read)(&*T::unwrap(handle)?).to_native(handle.py()) + } + + fn give<'py>(&self, handle: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult>> { + (self.read)(&*T::unwrap(handle)?).to_python(handle.py(), told) + } + + fn set(&self, handle: &Bound<'_, PyAny>, value: &Bound<'_, PyAny>) -> PyResult<()> { + // Read before the struct is written to, as it may be of the struct itself + let value = M::from_native(value)?; + T::write(handle, |held| *(self.written)(held) = value) + } + + fn take<'py>( + &self, + handle: &Bound<'py, PyAny>, + value: &Bound<'py, PyAny>, + told: &Told<'_, 'py>, + ) -> PyResult { + let Some(value) = M::from_python(value, told)? else { return Ok(false) }; + T::write(handle, |held| *(self.written)(held) = value)?; + Ok(true) + } +} + +/// A field of a frozen struct which is itself one: read where it is, not copied +struct Within(OfFrozen); + +impl Member for Within { + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult> { + M::wrap(handle.py(), T::unwrap(handle)?.member(self.0.read)) + } + + fn give<'py>(&self, handle: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult>> { + if told.wraps.is_none() { + return Ok(None); + } + told.wrapped(self.get(handle)?) + } + + fn set(&self, handle: &Bound<'_, PyAny>, value: &Bound<'_, PyAny>) -> PyResult<()> { + self.0.set(handle, value) + } + + fn take<'py>( + &self, + handle: &Bound<'py, PyAny>, + value: &Bound<'py, PyAny>, + told: &Told<'_, 'py>, + ) -> PyResult { + self.0.take(handle, value, told) + } +} + +/// A field of a struct which is not frozen +struct OfChanging { + read: fn(&T) -> &M, + written: fn(&mut T) -> &mut M, +} + +impl Member for OfChanging { + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult> { + (self.read)(&T::unwrap(handle)?.read()).to_native(handle.py()) + } + + fn give<'py>(&self, handle: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult>> { + (self.read)(&T::unwrap(handle)?.read()).to_python(handle.py(), told) + } + + fn set(&self, handle: &Bound<'_, PyAny>, value: &Bound<'_, PyAny>) -> PyResult<()> { + let value = M::from_native(value)?; + *(self.written)(&mut T::unwrap(handle)?.write()) = value; + Ok(()) + } + + fn take<'py>( + &self, + handle: &Bound<'py, PyAny>, + value: &Bound<'py, PyAny>, + told: &Told<'_, 'py>, + ) -> PyResult { + let Some(value) = M::from_python(value, told)? else { return Ok(false) }; + *(self.written)(&mut T::unwrap(handle)?.write()) = value; + Ok(true) + } +} + +/// The descriptors of a native class's fields, by name: what an extension's `__fields__` has for it +pub struct Fields<'py> { + native: Bound<'py, PyType>, + fields: Bound<'py, PyDict>, +} + +impl<'py> Fields<'py> { + pub fn new(native: Bound<'py, PyType>) -> Self { + let fields = PyDict::new(native.py()); + Self { native, fields } + } + + pub fn into_dict(self) -> Bound<'py, PyDict> { + self.fields + } + + fn add(&self, name: &str, member: impl Member + 'static) -> PyResult<()> { + let py = self.native.py(); + let field = Field { + name: PyString::intern(py, name).unbind(), + native: self.native.clone().unbind(), + member: Arc::new(member), + bound: None, + }; + self.fields.set_item(name, Bound::new(py, field)?) + } + + /// A field of a frozen struct, by what gives it of one + pub fn frozen( + &self, + name: &str, + read: fn(&T) -> &M, + written: fn(&mut T) -> &mut M, + ) -> PyResult<()> { + self.add(name, OfFrozen { read, written }) + } + + /// A field of a frozen struct which is itself a frozen struct + pub fn within( + &self, + name: &str, + read: fn(&T) -> &M, + written: fn(&mut T) -> &mut M, + ) -> PyResult<()> { + self.add(name, Within(OfFrozen { read, written })) + } + + /// A field of a struct which is not frozen + pub fn changing( + &self, + name: &str, + read: fn(&T) -> &M, + written: fn(&mut T) -> &mut M, + ) -> PyResult<()> { + self.add(name, OfChanging { read, written }) + } +} + +/// What bound() gave a field: the Python descriptor it is in place of, with what that has, and what it was told +struct Bound_ { + fallback: Py, + default: Option>, + to_native: Option>, + from_native: Option>, + members: Option>, + wraps: Option>, + direct: bool, +} + +/// The descriptor of a field of a bound class: reads and sets the member of the native object of an instance +#[pyclass(frozen, module = "dataclass_native", name = "Field")] +pub struct Field { + name: Py, + native: Py, + member: Arc, + bound: Option, +} + +/// An attribute, or None if it is +fn held(from: &Bound<'_, PyAny>, name: &str) -> PyResult>> { + let value = from.getattr(name)?; + Ok((!value.is_none()).then(|| value.unbind())) +} + +#[pymethods] +impl Field { + /// A descriptor as this, in place of the Python one of the field: which it is as, for what has no native + /// object. The rest is what it is told, by which it need not call Python's converters + fn bound<'py>( + &self, + py: Python<'py>, + fallback: Bound<'py, PyAny>, + missing: Bound<'py, PyAny>, + members: Option>, + wraps: Option>, + direct: bool, + ) -> PyResult { + let default = fallback.getattr("default")?; + Ok(Field { + name: self.name.clone_ref(py), + native: self.native.clone_ref(py), + member: Arc::clone(&self.member), + bound: Some(Bound_ { + // A default which is None is one: only what is missing is not + default: (!default.is(&missing)).then(|| default.unbind()), + to_native: held(&fallback, "to_native")?, + from_native: held(&fallback, "from_native")?, + fallback: fallback.unbind(), + members: members.map(Bound::unbind), + wraps: wraps.map(Bound::unbind), + direct, + }), + }) + } + + fn __get__<'py>( + &self, + py: Python<'py>, + obj: Option<&Bound<'py, PyAny>>, + owner: Option<&Bound<'py, PyAny>>, + ) -> PyResult> { + let bound = self.bound.as_ref(); + let Some(obj) = obj else { + // As the dataclass's own attribute: its default, if any + return match bound.and_then(|bound| bound.default.as_ref()) { + Some(default) => Ok(default.bind(py).clone()), + None => Err(PyAttributeError::new_err(self.name.clone_ref(py))), + }; + }; + let Some(bound) = bound else { return Err(PyAttributeError::new_err(self.name.clone_ref(py))) }; + let Some(handle) = handle_of(obj) else { + // Made by pydantic, or of a subclass which is not bound: as the Python has it + return bound.fallback.bind(py).call_method1(intern!(py, "__get__"), (obj, owner)); + }; + + let from_native = bound.from_native.as_ref().map(|convert| convert.bind(py)); + let value = if !handle.get_type().is(&self.native) { + handle.getattr(&self.name)? + } else if from_native.is_none() { + return self.member.get(&handle); + } else { + match self.member.give(&handle, &bound.told(py))? { + Some(given) => return Ok(given), + None => self.member.get(&handle)?, + } + }; + match from_native { + Some(convert) => convert.call1((value,)), + None => Ok(value), + } + } + + fn __set__<'py>(&self, py: Python<'py>, obj: &Bound<'py, PyAny>, value: &Bound<'py, PyAny>) -> PyResult<()> { + let Some(bound) = self.bound.as_ref() else { return Err(PyAttributeError::new_err(self.name.clone_ref(py))) }; + let Some(handle) = handle_of(obj) else { + return bound.fallback.bind(py).call_method1(intern!(py, "__set__"), (obj, value)).map(drop); + }; + + let of_native = handle.get_type().is(&self.native); + let set = || -> PyResult<()> { + let Some(to_native) = bound.to_native.as_ref() else { + return if of_native { self.member.set(&handle, value) } else { handle.setattr(&self.name, value) }; + }; + // What it does not itself take, Python converts: and says why it cannot be, if it cannot + if of_native && self.member.take(&handle, value, &bound.told(py)).unwrap_or(false) { + return Ok(()); + } + let converted = to_native.bind(py).call1((value,))?; + if of_native { + self.member.set(&handle, &converted) + } else { + handle.setattr(&self.name, converted) + } + }; + set().map_err(|error| { + // A ValueError from bytes(), of ints which are not bytes: and an OverflowError of an int + let rejected = error.is_instance_of::(py) + || error.is_instance_of::(py) + || error.is_instance_of::(py); + match (rejected, obj.get_type().qualname(), value.repr()) { + (true, Ok(class), Ok(value)) => { + PyTypeError::new_err(format!("{class}.{} cannot be {value}", self.name.bind(py))) + } + _ => error, + } + }) + } + + fn __delete__(&self, _obj: &Bound<'_, PyAny>) -> PyResult<()> { + Err(PyAttributeError::new_err("__delete__")) + } + + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + visit.call(&self.native)?; + if let Some(bound) = &self.bound { + visit.call(&bound.fallback)?; + for held in [&bound.default, &bound.to_native, &bound.from_native].into_iter().flatten() { + visit.call(held)?; + } + if let Some(members) = &bound.members { + visit.call(members)?; + } + if let Some(wraps) = &bound.wraps { + visit.call(wraps)?; + } + } + Ok(()) + } +} + +impl Bound_ { + fn told<'a, 'py>(&'a self, py: Python<'py>) -> Told<'a, 'py> { + Told { + members: self.members.as_ref().map(|members| members.bind(py)), + wraps: self.wraps.as_ref().map(|wraps| wraps.bind(py)), + direct: self.direct, + } + } +} + +/// What an extension's `__maker__` is: maker(cls, native, new) gives the `__new__` of a bound class, which makes an +/// object with its native object. As the Python `__new__` which it is in place of, and which it calls for a +/// subclass: which is not of its native class +pub fn maker(py: Python<'_>) -> PyResult> { + PyCFunction::new_closure(py, Some(c"maker"), None, |given: &Bound<'_, PyTuple>, _: Option<&Bound<'_, PyDict>>| { + let (class, native, new): (Bound<'_, PyType>, Bound<'_, PyAny>, Bound<'_, PyAny>) = given.extract()?; + let (class, native, new) = (class.unbind(), native.unbind(), new.unbind()); + let made = move |taken: &Bound<'_, PyTuple>, named: Option<&Bound<'_, PyDict>>| -> PyResult> { + let py = taken.py(); + let class = class.bind(py); + let is_abstract = unsafe { ffi::PyType_GetFlags(class.as_type_ptr()) } & ffi::Py_TPFLAGS_IS_ABSTRACT != 0; + if is_abstract || !taken.get_item(0).is_ok_and(|first| first.is(class)) { + return Ok(new.bind(py).call(taken, named)?.unbind()); + } + Ok(instance(class, &native.bind(py).call0()?)?.unbind()) + }; + PyCFunction::new_closure(given.py(), Some(c"__new__"), None, made).map(Bound::unbind) + }) +} diff --git a/src/dataclass_native/rust/src/lib.rs b/src/dataclass_native/rust/src/lib.rs index a6558ef..56b5588 100644 --- a/src/dataclass_native/rust/src/lib.rs +++ b/src/dataclass_native/rust/src/lib.rs @@ -5,6 +5,9 @@ use std::cmp::Ordering; use std::fmt; use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; +#[cfg(feature = "python")] +mod fields; +pub mod msgpack; #[cfg(feature = "python")] pub mod python; @@ -68,6 +71,38 @@ impl Decimal { pub fn fits(&self) -> bool { self.0 > -Self::LIMIT && self.0 < Self::LIMIT } + + /// That of digits alone, with a point or not: of no more places than its own but for zeros, nor more than + /// 18 digits + pub fn parse(text: &str) -> Option { + let (negative, text) = match text.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, text), + }; + let (whole, fraction) = match text.split_once('.') { + Some((whole, fraction)) if !fraction.is_empty() => (whole, fraction), + Some(_) => return None, + None => (text, ""), + }; + if whole.is_empty() { + return None; + } + let places = PLACES as usize; + // As many places as its own, of zeros if there are not so many: and no more, but of zeros + let kept = fraction.bytes().chain(std::iter::repeat(b'0')).take(places); + let mut unscaled: i64 = 0; + for digit in whole.bytes().chain(kept) { + // Before it is of another digit, which may be more than an integer holds + if !digit.is_ascii_digit() || unscaled >= Self::LIMIT / 10 { + return None; + } + unscaled = unscaled * 10 + i64::from(digit - b'0'); + } + if fraction.bytes().skip(places).any(|digit| digit != b'0') { + return None; + } + Some(Self(if negative { -unscaled } else { unscaled })) + } } /// Its digits, with a point before the last PLACES of them: as it is written diff --git a/src/dataclass_native/rust/src/msgpack.rs b/src/dataclass_native/rust/src/msgpack.rs new file mode 100644 index 0000000..de686b6 --- /dev/null +++ b/src/dataclass_native/rust/src/msgpack.rs @@ -0,0 +1,992 @@ +//! The generated structs as msgpack, as WIRE_FORMAT.md has it: what Python and C++ write, and read. The generated +//! code implements `Wire` for each struct, enum and union. + +use crate::{ + Array, Bytes, Date, DateTime, Decimal, Indirect, Mutable, MutableArray, NaiveDateTime, Ordered, TimeDelta, + TimeOfDay, Uuid, +}; +use std::any::Any; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt; +use std::sync::Arc; + +/// What is read is not msgpack, or not the type being read, as written: or a value cannot be written +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(pub String); + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for Error {} + +/// Why a value was not read: it is not of its type, as written, which what is reading it says of what it is +/// reading. Or what says for itself what is wrong +#[derive(Debug)] +pub enum Fault { + Mismatch, + Error(String), +} + +pub type Read = Result; + +fn error(message: &str) -> Read { + Err(Fault::Error(message.to_string())) +} + +/// As deeply as what is read or written may be nested +const MAX_DEPTH: usize = 256; +const TIMESTAMP: i8 = -1; +const REFERENCE: i8 = 1; + +/// A type which is written as msgpack, and read from it +pub trait Wire: Sized { + /// Whether a Shared may be reached from it, however deeply: so that it is written as a bundle + const BUNDLED: bool = false; + + /// What it is said to be, of data which is not one + fn described() -> String { + std::any::type_name::().to_string() + } + + fn write(&self, writer: &mut Writer) -> Result<(), Error>; + + fn read(reader: &mut Reader<'_>) -> Read; +} + +/// A struct, which may be shared: by the tag which its table has +pub trait Record: Wire + Send + Sync + 'static { + const TAG: &'static str; +} + +/// A value as msgpack +pub fn to_msgpack(value: &T) -> Result, Error> { + let mut writer = Writer::default(); + value.write(&mut writer)?; + if !T::BUNDLED { + return Ok(writer.out); + } + let root = std::mem::take(&mut writer.out); + let tables = std::mem::take(&mut writer.tables); + writer.map(2); + writer.str("root"); + writer.out.extend(root); + writer.str("shared"); + writer.array(tables.len()); + for (tag, rows) in tables { + writer.array(2); + writer.str(tag); + writer.array(rows.len()); + rows.iter().for_each(|row| writer.out.extend(row)); + } + Ok(writer.out) +} + +/// The value which msgpack is of +pub fn from_msgpack(data: &[u8]) -> Result { + let mut reader = Reader { data, at: 0, depth: 0, tables: Vec::new() }; + let read = if T::BUNDLED { + reader.bundle().and_then(|root| reader.finish().and_then(|()| reader.at(root, T::read))) + } else { + T::read(&mut reader).and_then(|value| reader.finish().map(|()| value)) + }; + read.map_err(|fault| match fault { + Fault::Mismatch => Error(format!("The data is not a {}, as written", T::described())), + Fault::Error(message) => Error(message), + }) +} + +/// What is written, and the objects it shares +#[derive(Default)] +pub struct Writer { + out: Vec, + /// By tag, in the order first used: the objects, as written + tables: Vec<(&'static str, Vec>)>, + /// By where a shared object is, its table and its row + references: HashMap, + depth: usize, +} + +impl Writer { + pub fn nil(&mut self) { + self.out.push(0xc0); + } + + pub fn bool(&mut self, value: bool) { + self.out.push(if value { 0xc3 } else { 0xc2 }); + } + + /// In the shortest form which holds it + pub fn integer(&mut self, value: i128) { + let out = &mut self.out; + match value { + 0..=0x7f => out.push(value as u8), + -32..=-1 => out.push(value as i8 as u8), + 0x80..=0xff => out.extend([0xcc, value as u8]), + 0x100..=0xffff => Self::sized(out, 0xcd, &(value as u16).to_be_bytes()), + 0x1_0000..=0xffff_ffff => Self::sized(out, 0xce, &(value as u32).to_be_bytes()), + -0x80..=-33 => out.extend([0xd0, value as i8 as u8]), + -0x8000..=-0x81 => Self::sized(out, 0xd1, &(value as i16).to_be_bytes()), + -0x8000_0000..=-0x8001 => Self::sized(out, 0xd2, &(value as i32).to_be_bytes()), + _ if value < 0 => Self::sized(out, 0xd3, &(value as i64).to_be_bytes()), + _ => Self::sized(out, 0xcf, &(value as u64).to_be_bytes()), + } + } + + fn sized(out: &mut Vec, form: u8, bytes: &[u8]) { + out.push(form); + out.extend(bytes); + } + + /// A length, in the form of the least of three sizes which holds it + fn length(&mut self, length: usize, forms: [Option; 3]) { + match (length, forms) { + (0..=0xff, [Some(form), ..]) => self.out.extend([form, length as u8]), + (0..=0xffff, [_, Some(form), _]) => Self::sized(&mut self.out, form, &(length as u16).to_be_bytes()), + (_, [.., Some(form)]) => Self::sized(&mut self.out, form, &(length as u32).to_be_bytes()), + _ => unreachable!(), + } + } + + pub fn str(&mut self, value: &str) { + match value.len() { + length @ 0..=31 => self.out.push(0xa0 | length as u8), + length => self.length(length, [Some(0xd9), Some(0xda), Some(0xdb)]), + } + self.out.extend(value.as_bytes()); + } + + pub fn bin(&mut self, value: &[u8]) { + self.length(value.len(), [Some(0xc4), Some(0xc5), Some(0xc6)]); + self.out.extend(value); + } + + pub fn array(&mut self, length: usize) { + match length { + 0..=15 => self.out.push(0x90 | length as u8), + _ => self.length(length, [None, Some(0xdc), Some(0xdd)]), + } + } + + pub fn map(&mut self, length: usize) { + match length { + 0..=15 => self.out.push(0x80 | length as u8), + _ => self.length(length, [None, Some(0xde), Some(0xdf)]), + } + } + + fn extension(&mut self, code: i8, data: &[u8]) { + match data.len() { + 4 => self.out.push(0xd6), + 8 => self.out.push(0xd7), + length => self.out.extend([0xc7, length as u8]), + } + self.out.push(code as u8); + self.out.extend(data); + } + + /// A reference to a shared object, which is written if it has not been + pub fn share(&mut self, shared: &Arc) -> Result<(), Error> { + let address = Arc::as_ptr(shared) as usize; + let (table, row) = match self.references.get(&address) { + Some(reference) => *reference, + None => { + let table = match self.tables.iter().position(|(tag, _)| *tag == T::TAG) { + Some(table) => table, + None => { + self.tables.push((T::TAG, Vec::new())); + self.tables.len() - 1 + } + }; + // Its row is taken before it is written, as it may share objects of its own type + let row = self.tables[table].1.len(); + self.tables[table].1.push(Vec::new()); + self.references.insert(address, (table as u32, row as u32)); + let outer = std::mem::take(&mut self.out); + // Itself, not a reference to it + let written = T::write(shared, self); + self.tables[table].1[row] = std::mem::replace(&mut self.out, outer); + written?; + (table as u32, row as u32) + } + }; + let mut reference = [0; 8]; + reference[..4].copy_from_slice(&table.to_be_bytes()); + reference[4..].copy_from_slice(&row.to_be_bytes()); + self.extension(REFERENCE, &reference); + Ok(()) + } + + /// Writes what is within an object which is not frozen: which may hold itself, and so never end + pub fn nested(&mut self, write: impl FnOnce(&mut Self) -> Result<(), Error>) -> Result<(), Error> { + if self.depth == MAX_DEPTH { + return Err(Error("An object which holds itself, or is too deeply nested, cannot be written".to_string())); + } + self.depth += 1; + let written = write(self); + self.depth -= 1; + written + } +} + +/// Which kind of msgpack value is next: by which the member of a union is told +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Nil, + Bool, + Int, + Float, + Str, + Bin, + Array, + Map, + Timestamp, + Reference, + Extension, +} + +enum Slot { + Unread, + Reading, + Read(Arc), +} + +struct Table<'a> { + tag: &'a str, + /// Where each row is, and the object read from it + rows: Vec<(usize, Slot)>, +} + +/// What is read, and the objects it shares +pub struct Reader<'a> { + data: &'a [u8], + at: usize, + depth: usize, + tables: Vec>, +} + +impl<'a> Reader<'a> { + fn take(&mut self, count: usize) -> Read<&'a [u8]> { + let data = self.data; + match self.at.checked_add(count).and_then(|end| data.get(self.at..end)) { + Some(taken) => { + self.at += count; + Ok(taken) + } + None => error("msgpack data is truncated"), + } + } + + fn byte(&mut self) -> Read { + Ok(self.take(1)?[0]) + } + + fn peek(&self, ahead: usize) -> Read { + match self.data.get(self.at + ahead) { + Some(byte) => Ok(*byte), + None => error("msgpack data is truncated"), + } + } + + fn unsigned(&mut self, bytes: usize) -> Read { + Ok(self.take(bytes)?.iter().fold(0, |value, byte| value << 8 | u64::from(*byte))) + } + + fn finish(&self) -> Read<()> { + if self.at == self.data.len() { + Ok(()) + } else { + error("msgpack data has more than one value") + } + } + + /// Reads from somewhere else in the data, then goes on from where it was + fn at(&mut self, position: usize, read: impl FnOnce(&mut Self) -> Read) -> Read { + let after = std::mem::replace(&mut self.at, position); + let value = read(self); + self.at = after; + value + } + + pub fn kind(&self) -> Read { + let extension = |ahead| { + Ok(match self.peek(ahead)? as i8 { + TIMESTAMP => Kind::Timestamp, + REFERENCE => Kind::Reference, + _ => Kind::Extension, + }) + }; + match self.peek(0)? { + 0x00..=0x7f | 0xe0..=0xff | 0xcc..=0xd3 => Ok(Kind::Int), + 0x80..=0x8f | 0xde | 0xdf => Ok(Kind::Map), + 0x90..=0x9f | 0xdc | 0xdd => Ok(Kind::Array), + 0xa0..=0xbf | 0xd9..=0xdb => Ok(Kind::Str), + 0xc0 => Ok(Kind::Nil), + 0xc1 => error("msgpack data has the unused byte 0xc1"), + 0xc2 | 0xc3 => Ok(Kind::Bool), + 0xc4..=0xc6 => Ok(Kind::Bin), + 0xca | 0xcb => Ok(Kind::Float), + 0xd4..=0xd8 => extension(1), + 0xc7 => extension(2), + 0xc8 => extension(3), + 0xc9 => extension(5), + } + } + + fn expect(&self, kind: Kind) -> Read<()> { + if self.kind()? == kind { + Ok(()) + } else { + Err(Fault::Mismatch) + } + } + + /// Whether nil is next, which is then read + pub fn nil(&mut self) -> Read { + let nil = self.kind()? == Kind::Nil; + self.at += usize::from(nil); + Ok(nil) + } + + pub fn bool(&mut self) -> Read { + self.expect(Kind::Bool)?; + Ok(self.byte()? == 0xc3) + } + + pub fn integer(&mut self) -> Read { + self.expect(Kind::Int)?; + Ok(match self.byte()? { + byte @ 0x00..=0x7f => i128::from(byte), + byte @ 0xe0..=0xff => i128::from(byte as i8), + 0xcc => i128::from(self.unsigned(1)?), + 0xcd => i128::from(self.unsigned(2)?), + 0xce => i128::from(self.unsigned(4)?), + 0xcf => i128::from(self.unsigned(8)?), + 0xd0 => i128::from(self.unsigned(1)? as i8), + 0xd1 => i128::from(self.unsigned(2)? as i16), + 0xd2 => i128::from(self.unsigned(4)? as i32), + _ => i128::from(self.unsigned(8)? as i64), + }) + } + + /// Of either size + pub fn float(&mut self) -> Read { + self.expect(Kind::Float)?; + Ok(match self.byte()? { + 0xca => f64::from(f32::from_bits(self.unsigned(4)? as u32)), + _ => f64::from_bits(self.unsigned(8)?), + }) + } + + /// A length, of a form which is of one of three sizes + fn length(&mut self, short: u8, forms: [u8; 3]) -> Read { + let form = self.byte()?; + let bytes = match forms.iter().position(|sized| *sized == form) { + Some(index) => 1 << index, + None => return Ok(usize::from(form & short)), + }; + Ok(self.unsigned(bytes)? as usize) + } + + pub fn str(&mut self) -> Read<&'a str> { + self.expect(Kind::Str)?; + let length = self.length(0x1f, [0xd9, 0xda, 0xdb])?; + match std::str::from_utf8(self.take(length)?) { + Ok(text) => Ok(text), + Err(_) => error("msgpack data has a str which is not UTF-8"), + } + } + + pub fn bin(&mut self) -> Read<&'a [u8]> { + self.expect(Kind::Bin)?; + let length = self.length(0, [0xc4, 0xc5, 0xc6])?; + self.take(length) + } + + pub fn array(&mut self) -> Read { + self.expect(Kind::Array)?; + self.length(0x0f, [0, 0xdc, 0xdd]) + } + + pub fn map(&mut self) -> Read { + self.expect(Kind::Map)?; + self.length(0x0f, [0, 0xde, 0xdf]) + } + + fn extension(&mut self) -> Read<(i8, &'a [u8])> { + let length = match self.byte()? { + form @ 0xd4..=0xd8 => 1 << (form - 0xd4), + form @ 0xc7..=0xc9 => self.unsigned(1 << (form - 0xc7))? as usize, + _ => return Err(Fault::Mismatch), + }; + let code = self.byte()? as i8; + Ok((code, self.take(length)?)) + } + + /// Reads past a value, of whatever kind + pub fn skip(&mut self) -> Read<()> { + match self.kind()? { + Kind::Nil | Kind::Bool => self.at += 1, + Kind::Int => drop(self.integer()?), + Kind::Float => drop(self.float()?), + Kind::Str => drop(self.str()?), + Kind::Bin => drop(self.bin()?), + kind @ (Kind::Array | Kind::Map) => { + let values = if kind == Kind::Map { 2 * self.map()? } else { self.array()? }; + self.nested(|reader| (0..values).try_for_each(|_| reader.skip()))?; + } + Kind::Timestamp | Kind::Reference | Kind::Extension => drop(self.extension()?), + } + Ok(()) + } + + /// Reads what is within another value: which may be within more than is read + pub fn nested(&mut self, read: impl FnOnce(&mut Self) -> Read) -> Read { + if self.depth == MAX_DEPTH { + return error("msgpack data is too deeply nested"); + } + self.depth += 1; + let value = read(self); + self.depth -= 1; + value + } + + /// The key of an entry of a struct's map: or None, of one which is not a str, so not a field's + pub fn key(&mut self) -> Read> { + if self.kind()? == Kind::Str { + self.str().map(Some) + } else { + self.skip().map(|()| None) + } + } + + /// Reads a field of a struct, which says what is wrong with it if it is not of its type + pub fn field(&mut self, of: &str, name: &str, held: &mut Option) -> Read<()> { + if held.is_some() { + return Err(Fault::Error(format!("{of}.{name} is written twice"))); + } + match T::read(self) { + Ok(value) => { + *held = Some(value); + Ok(()) + } + Err(Fault::Mismatch) => { + Err(Fault::Error(format!("{of}.{name} cannot be read: it is not of its type, as written"))) + } + Err(fault) => Err(fault), + } + } + + /// A field which was read: or if not, which has no default, so must be + pub fn required(of: &str, name: &str, held: Option) -> Read { + held.ok_or_else(|| Fault::Error(format!("{of} cannot be read: no {name}"))) + } + + /// Reads a discriminated union: by what reads the member of a tag + pub fn tagged(&mut self, read: impl FnOnce(&mut Self, &str) -> Read) -> Read { + if self.map()? != 2 { + return Err(Fault::Mismatch); + } + // In either order + let (mut tag, mut value) = (None, None); + for _ in 0..2 { + match self.str()? { + "t" if tag.is_none() => tag = Some(self.str()?), + "v" if value.is_none() => { + value = Some(self.at); + self.skip()?; + } + _ => return Err(Fault::Mismatch), + } + } + match (tag, value) { + (Some(tag), Some(value)) => self.at(value, |reader| read(reader, tag)), + _ => Err(Fault::Mismatch), + } + } + + /// Reads the bundle which what shares objects is written as, giving where its root is + fn bundle(&mut self) -> Read { + let (mut root, mut shared) = (None, false); + for _ in 0..self.map()? { + match self.key()? { + Some("root") => { + root = Some(self.at); + self.skip()?; + } + Some("shared") => { + shared = true; + for _ in 0..self.array()? { + if self.array()? != 2 { + return Err(Fault::Mismatch); + } + let tag = self.str()?; + let mut rows = Vec::new(); + for _ in 0..self.array()? { + rows.push((self.at, Slot::Unread)); + self.skip()?; + } + self.tables.push(Table { tag, rows }); + } + } + _ => self.skip()?, + } + } + root.filter(|_| shared).ok_or(Fault::Mismatch) + } + + /// The table and row which a reference is to, if there is such a row: and the tag of its table + fn reference(&self) -> Read<(usize, usize, &'a str)> { + let (code, data) = Reader { data: self.data, at: self.at, depth: 0, tables: Vec::new() }.extension()?; + if code != REFERENCE || data.len() != 8 { + return Err(Fault::Mismatch); + } + let index = |bytes: &[u8]| bytes.iter().fold(0, |value, byte| value << 8 | usize::from(*byte)); + let (table, row) = (index(&data[..4]), index(&data[4..])); + match self.tables.get(table) { + Some(found) if row < found.rows.len() => Ok((table, row, found.tag)), + _ => Err(Fault::Mismatch), + } + } + + /// The tag of the shared object which a reference is to: by which the member of a union is told + pub fn referred(&self) -> Read<&'a str> { + self.reference().map(|(_, _, tag)| tag) + } + + /// The shared object which a reference is to, which is read if it has not been + pub fn shared(&mut self) -> Read> { + let (table, row, tag) = self.reference()?; + if tag != T::TAG { + return Err(Fault::Mismatch); + } + self.extension()?; + let position = match &self.tables[table].rows[row] { + (_, Slot::Read(object)) => return Arc::clone(object).downcast().map_err(|_| Fault::Mismatch), + // It shares itself, which no object written could + (_, Slot::Reading) => return Err(Fault::Mismatch), + (position, Slot::Unread) => *position, + }; + self.tables[table].rows[row].1 = Slot::Reading; + let object = Arc::new(self.at(position, T::read)?); + self.tables[table].rows[row].1 = Slot::Read(object.clone()); + Ok(object) + } +} + +impl Wire for bool { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.bool(*self); + Ok(()) + } + + fn read(reader: &mut Reader<'_>) -> Read { + reader.bool() + } +} + +macro_rules! integer { + ($($int:ty),*) => {$( + impl Wire for $int { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.integer(i128::from(*self)); + Ok(()) + } + + fn read(reader: &mut Reader<'_>) -> Read { + Self::try_from(reader.integer()?).map_err(|_| Fault::Mismatch) + } + } + )*}; +} + +integer!(i8, i16, i32, i64, u8, u16, u32, u64); + +impl Wire for f64 { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + Writer::sized(&mut writer.out, 0xcb, &self.to_be_bytes()); + Ok(()) + } + + fn read(reader: &mut Reader<'_>) -> Read { + reader.float() + } +} + +impl Wire for f32 { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + Writer::sized(&mut writer.out, 0xca, &self.to_be_bytes()); + Ok(()) + } + + fn read(reader: &mut Reader<'_>) -> Read { + Ok(reader.float()? as f32) + } +} + +impl Wire for String { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.str(self); + Ok(()) + } + + fn read(reader: &mut Reader<'_>) -> Read { + reader.str().map(str::to_string) + } +} + +impl Wire for Bytes { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.bin(&self.0); + Ok(()) + } + + fn read(reader: &mut Reader<'_>) -> Read { + Ok(Bytes(reader.bin()?.to_vec())) + } +} + +/// As days since 1970-01-01 +impl Wire for Date { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + self.0.write(writer) + } + + fn read(reader: &mut Reader<'_>) -> Read { + Wire::read(reader).map(Date) + } +} + +const DAY: i64 = 86_400_000_000; + +/// As microseconds since midnight +impl Wire for TimeOfDay { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + if !(0..DAY).contains(&self.0) { + return Err(Error("A time which is not within a day cannot be written".to_string())); + } + self.0.write(writer) + } + + fn read(reader: &mut Reader<'_>) -> Read { + Some(i64::read(reader)?).filter(|micros| (0..DAY).contains(micros)).map(TimeOfDay).ok_or(Fault::Mismatch) + } +} + +macro_rules! microseconds { + ($($of:ident),*) => {$( + impl Wire for $of { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + self.0.write(writer) + } + + fn read(reader: &mut Reader<'_>) -> Read { + Wire::read(reader).map($of) + } + } + )*}; +} + +microseconds!(TimeDelta, NaiveDateTime); + +/// As msgpack's timestamp: in the shortest of its three forms which holds the instant +impl Wire for DateTime { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + let (seconds, nanoseconds) = (self.0.div_euclid(1_000_000), self.0.rem_euclid(1_000_000) as u64 * 1000); + if !(0..1 << 34).contains(&seconds) { + let mut data = [0; 12]; + data[..4].copy_from_slice(&(nanoseconds as u32).to_be_bytes()); + data[4..].copy_from_slice(&seconds.to_be_bytes()); + writer.extension(TIMESTAMP, &data); + } else if nanoseconds != 0 || seconds >= 1 << 32 { + writer.extension(TIMESTAMP, &(nanoseconds << 34 | seconds as u64).to_be_bytes()); + } else { + writer.extension(TIMESTAMP, &(seconds as u32).to_be_bytes()); + } + Ok(()) + } + + fn read(reader: &mut Reader<'_>) -> Read { + reader.expect(Kind::Timestamp)?; + let (_, data) = reader.extension()?; + let number = |bytes: &[u8]| bytes.iter().fold(0u64, |value, byte| value << 8 | u64::from(*byte)); + let (nanoseconds, seconds) = match data.len() { + 4 => (0, number(data) as i64), + 8 => (number(data) >> 34, (number(data) & ((1 << 34) - 1)) as i64), + 12 => (number(&data[..4]), number(&data[4..]) as i64), + _ => return Err(Fault::Mismatch), + }; + // A whole number of microseconds, as that is what a datetime holds + if nanoseconds >= 1_000_000_000 || nanoseconds % 1000 != 0 { + return Err(Fault::Mismatch); + } + seconds + .checked_mul(1_000_000) + .and_then(|micros| micros.checked_add(nanoseconds as i64 / 1000)) + .map(DateTime) + .ok_or(Fault::Mismatch) + } +} + +/// As its 16 bytes +impl Wire for Uuid { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.bin(&self.0); + Ok(()) + } + + fn read(reader: &mut Reader<'_>) -> Read { + <[u8; 16]>::try_from(reader.bin()?).map(Uuid).map_err(|_| Fault::Mismatch) + } +} + +/// As a string, of its digits +impl Wire for Decimal { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + if !self.fits() { + return Err(Error("A Decimal of more than 18 digits cannot be written".to_string())); + } + writer.str(&self.to_string()); + Ok(()) + } + + fn read(reader: &mut Reader<'_>) -> Read { + Self::parse(reader.str()?).ok_or(Fault::Mismatch) + } +} + +impl Wire for Option { + const BUNDLED: bool = T::BUNDLED; + + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + match self { + Some(value) => value.write(writer), + None => { + writer.nil(); + Ok(()) + } + } + } + + fn read(reader: &mut Reader<'_>) -> Read { + if reader.nil()? { + Ok(None) + } else { + T::read(reader).map(Some) + } + } +} + +impl Wire for Vec { + const BUNDLED: bool = T::BUNDLED; + + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.array(self.len()); + self.iter().try_for_each(|item| item.write(writer)) + } + + fn read(reader: &mut Reader<'_>) -> Read { + (0..reader.array()?).map(|_| T::read(reader)).collect() + } +} + +/// In ascending order: and read whatever their order +impl Wire for BTreeSet { + const BUNDLED: bool = T::BUNDLED; + + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.array(self.len()); + self.iter().try_for_each(|item| item.write(writer)) + } + + fn read(reader: &mut Reader<'_>) -> Read { + (0..reader.array()?).map(|_| T::read(reader)).collect() + } +} + +/// In ascending order of key: and read whatever their order +impl Wire for BTreeMap { + const BUNDLED: bool = K::BUNDLED || V::BUNDLED; + + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.map(self.len()); + self.iter().try_for_each(|(key, value)| key.write(writer).and_then(|()| value.write(writer))) + } + + fn read(reader: &mut Reader<'_>) -> Read { + let mut read = BTreeMap::new(); + for _ in 0..reader.map()? { + if read.insert(K::read(reader)?, V::read(reader)?).is_some() { + return error("msgpack data has a map with a key twice"); + } + } + Ok(read) + } +} + +macro_rules! ordered { + ($($float:ty),*) => {$( + impl Wire for Ordered<$float> { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + self.0.write(writer) + } + + fn read(reader: &mut Reader<'_>) -> Read { + Wire::read(reader).map(Ordered) + } + } + )*}; +} + +ordered!(f64, f32); + +macro_rules! tuple { + ($count:literal: $($name:ident $index:tt),+) => { + impl<$($name: Wire),+> Wire for ($($name,)+) { + const BUNDLED: bool = $($name::BUNDLED)||+; + + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.array($count); + $(self.$index.write(writer)?;)+ + Ok(()) + } + + fn read(reader: &mut Reader<'_>) -> Read { + if reader.array()? != $count { + return Err(Fault::Mismatch); + } + Ok(($($name::read(reader)?,)+)) + } + } + }; +} + +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); + +/// What an array may be of: its numbers are written as a tuple of them is, which is binary if they are bytes +pub trait Element: Wire + Copy { + fn write_all(numbers: &[Self], writer: &mut Writer) -> Result<(), Error> { + writer.array(numbers.len()); + numbers.iter().try_for_each(|number| number.write(writer)) + } + + fn read_all(reader: &mut Reader<'_>) -> Read> { + Wire::read(reader) + } +} + +impl Element for u8 { + fn write_all(numbers: &[Self], writer: &mut Writer) -> Result<(), Error> { + writer.bin(numbers); + Ok(()) + } + + fn read_all(reader: &mut Reader<'_>) -> Read> { + reader.bin().map(<[u8]>::to_vec) + } +} + +macro_rules! element { + ($($number:ty),*) => {$(impl Element for $number {})*}; +} + +element!(i8, i16, i32, i64, u16, u32, u64, f32, f64); + +/// The numbers of an array, after its shape if it is of more than one dimension +fn write_array( + shape: &[usize; N], + numbers: &[T], + writer: &mut Writer, +) -> Result<(), Error> { + if N > 1 { + writer.array(2); + writer.array(N); + shape.iter().for_each(|size| writer.integer(*size as i128)); + } + T::write_all(numbers, writer) +} + +fn read_array(reader: &mut Reader<'_>) -> Read<([usize; N], Vec)> { + if N == 1 { + let numbers = T::read_all(reader)?; + return Ok(([numbers.len(); N], numbers)); + } + if reader.array()? != 2 { + return Err(Fault::Mismatch); + } + let shape: Vec = Vec::::read(reader)?.into_iter().map(|size| size as usize).collect(); + Ok((<[usize; N]>::try_from(shape).map_err(|_| Fault::Mismatch)?, T::read_all(reader)?)) +} + +impl Wire for Array { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + write_array(self.shape(), self.as_slice(), writer) + } + + fn read(reader: &mut Reader<'_>) -> Read { + let (shape, numbers) = read_array(reader)?; + Array::new(numbers, shape).ok_or(Fault::Mismatch) + } +} + +impl Wire for MutableArray { + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + write_array(self.shape(), &self.read(), writer) + } + + fn read(reader: &mut Reader<'_>) -> Read { + let (shape, numbers) = read_array(reader)?; + MutableArray::new(numbers, shape).ok_or(Fault::Mismatch) + } +} + +/// As its T +impl Wire for Indirect { + const BUNDLED: bool = T::BUNDLED; + + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + match self.get() { + Some(value) => value.write(writer), + None => Err(Error("An empty Indirect cannot be written".to_string())), + } + } + + fn read(reader: &mut Reader<'_>) -> Read { + T::read(reader).map(Indirect::new) + } +} + +/// A reference to it, which is written once however many share it +impl Wire for Arc { + const BUNDLED: bool = true; + + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.share(self) + } + + fn read(reader: &mut Reader<'_>) -> Read { + reader.shared() + } +} + +/// As its T: which may hold itself, so is not written if it is within too much +impl Wire for Mutable { + const BUNDLED: bool = T::BUNDLED; + + fn write(&self, writer: &mut Writer) -> Result<(), Error> { + writer.nested(|writer| self.read().write(writer)) + } + + fn read(reader: &mut Reader<'_>) -> Read { + T::read(reader).map(Mutable::new) + } +} diff --git a/src/dataclass_native/rust/src/python.rs b/src/dataclass_native/rust/src/python.rs index ec2665d..3b48247 100644 --- a/src/dataclass_native/rust/src/python.rs +++ b/src/dataclass_native/rust/src/python.rs @@ -1,13 +1,16 @@ //! 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::{ Array, Bytes, Date, DateTime, Decimal, Indirect, Mutable, MutableArray, NaiveDateTime, Ordered, TimeDelta, TimeOfDay, Uuid, }; +pub use crate::fields::{maker, Field, Fields, Told}; use pyo3::buffer::{Element, PyBuffer}; use pyo3::exceptions::{PyTypeError, PyValueError}; use pyo3::prelude::*; +use pyo3::sync::PyOnceLock; use pyo3::types::{ PyBool, PyBytes, PyCFunction, PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PyModule, PySet, PyString, PyTime, PyTimeAccess, PyTuple, PyTzInfo, PyTzInfoAccess, @@ -29,6 +32,17 @@ pub trait Native: Sized { self.to_native(py) } + /// As Python itself is to have it, not as to_native gives it for Python to convert: where it differs, and + /// can be made with what a field is told. Else None, and Python converts + fn to_python<'py>(&self, _py: Python<'py>, _told: &Told<'_, 'py>) -> PyResult>> { + Ok(None) + } + + /// From what Python itself has, likewise: or None, of what Python is to convert, or to say is wrong + fn from_python<'py>(_value: &Bound<'py, PyAny>, _told: &Told<'_, 'py>) -> PyResult> { + Ok(None) + } + /// Whether a value is of its kind, where that is quicker to tell than to read it: by which a union tells which /// of its members not to try fn is_native(_value: &Bound<'_, PyAny>) -> bool { @@ -41,6 +55,36 @@ pub trait Frozen: Clone + Send + Sync + 'static { fn wrap(py: Python<'_>, held: Held) -> PyResult>; fn unwrap(value: &Bound<'_, PyAny>) -> PyResult>; + + /// Writes to the struct which an object of the class holds: its own, which is first copied if it is held + /// elsewhere + fn write(value: &Bound<'_, PyAny>, write: impl FnOnce(&mut Self) -> R) -> PyResult; +} + +/// Held by value: so a copy of it +impl Native for T { + fn to_native<'py>(&self, py: Python<'py>) -> PyResult> { + T::wrap(py, Held::new(self.clone())) + } + + fn from_native(value: &Bound<'_, PyAny>) -> PyResult { + Ok((*T::unwrap(value)?).clone()) + } + + fn into_native<'py>(self, py: Python<'py>) -> PyResult> { + T::wrap(py, Held::new(self)) + } + + fn to_python<'py>(&self, py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> { + if told.wraps.is_none() { + return Ok(None); + } + told.wrapped(self.to_native(py)?) + } + + fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + told.unwrapped(value).map(|handle| Self::from_native(&handle)).transpose() + } } /// What the class of a frozen struct holds: a struct of its own, shared so that nothing is copied to share it, or @@ -454,6 +498,21 @@ impl Native for Option { None => Ok(py.None().into_bound(py)), } } + + fn to_python<'py>(&self, py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> { + match self { + Some(value) => value.to_python(py, told), + None => Ok(Some(py.None().into_bound(py))), + } + } + + fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + if value.is_none() { + Ok(Some(None)) + } else { + Ok(T::from_python(value, told)?.map(Some)) + } + } } /// A list, which Python makes a tuple of: from a list or a tuple @@ -478,11 +537,38 @@ impl Native for Vec { Ok(PyList::new(py, items)?.into_any()) } + /// A tuple, of what each is: if that is as to_native gives it, or can be made with what was told + fn to_python<'py>(&self, py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> { + let items = self.iter().map(|item| each_to(item, py, told)).collect::>>>()?; + items.map(|items| Ok(PyTuple::new(py, items)?.into_any())).transpose() + } + + /// From a tuple alone + fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + let Ok(tuple) = value.cast_exact::() else { return Ok(None) }; + tuple.iter().map(|item| each_from(&item, told)).collect() + } + fn is_native(value: &Bound<'_, PyAny>) -> bool { value.is_exact_instance_of::() || value.is_exact_instance_of::() } } +/// What a container holds, as Python is to have it +fn each_to<'py, T: Native>(item: &T, py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> { + match item.to_python(py, told)? { + None if told.direct => item.to_native(py).map(Some), + made => Ok(made), + } +} + +fn each_from<'py, T: Native>(item: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + match T::from_python(item, told)? { + None if told.direct => T::from_native(item).map(Some), + taken => Ok(taken), + } +} + /// A set, which Python makes a frozenset of: from either impl Native for BTreeSet { fn to_native<'py>(&self, py: Python<'py>) -> PyResult> { @@ -503,6 +589,19 @@ impl Native for BTreeSet { fn is_native(value: &Bound<'_, PyAny>) -> bool { value.is_exact_instance_of::() || value.is_exact_instance_of::() } + + fn to_python<'py>(&self, py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> { + let items = self.iter().map(|item| each_to(item, py, told)).collect::>>>()?; + items.map(|items| Ok(PyFrozenSet::new(py, items)?.into_any())).transpose() + } + + /// From a frozenset alone + fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + if !value.is_exact_instance_of::() { + return Ok(None); + } + value.try_iter()?.map(|item| each_from(&item?, told)).collect() + } } impl Native for BTreeMap { @@ -522,6 +621,15 @@ impl Native for BTreeMap { fn is_native(value: &Bound<'_, PyAny>) -> bool { value.is_exact_instance_of::() } + + /// From a dict alone, of what is as Python has it: read, it is as to_native gives it + fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + if told.direct && value.is_exact_instance_of::() { + Self::from_native(value).map(Some) + } else { + Ok(None) + } + } } macro_rules! ordered { @@ -668,7 +776,10 @@ fn shared<'py, T: Number, const N: usize>( ) -> PyResult> { let bytes = count * std::mem::size_of::(); let numbers = Bound::new(py, Numbers { _held: Box::new(held), at: at as usize, bytes, readonly })?; - let flat = py.import("numpy")?.call_method1("frombuffer", (numbers, T::DTYPE))?; + // Found once, as it is called for each array which is read + static FROM: PyOnceLock> = PyOnceLock::new(); + let from = FROM.get_or_try_init(py, || py.import("numpy")?.getattr("frombuffer").map(Bound::unbind))?; + let flat = from.bind(py).call1((numbers, T::DTYPE))?; if N == 1 { return Ok(flat); } @@ -818,3 +929,16 @@ function!(5: A 0, B 1, C 2, D 3, E 4); function!(6: A 0, B 1, C 2, D 3, E 4, F 5); function!(7: A 0, B 1, C 2, D 3, E 4, F 5, G 6); function!(8: A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7); + +/// A struct as msgpack, and one read from it: what the class of each has as `__msgpack__` and `__from_msgpack__`, +/// which dataclass_native's to_msgpack and from_msgpack call +pub fn to_msgpack<'py, T: msgpack::Wire>(py: Python<'py>, value: &T) -> PyResult> { + match msgpack::to_msgpack(value) { + Ok(data) => Ok(PyBytes::new(py, &data)), + Err(error) => Err(PyValueError::new_err(error.0)), + } +} + +pub fn from_msgpack(data: &[u8]) -> PyResult { + msgpack::from_msgpack(data).map_err(|error| PyValueError::new_err(error.0)) +} diff --git a/tests/performance.py b/tests/performance.py index 8041e82..1f07908 100644 --- a/tests/performance.py +++ b/tests/performance.py @@ -75,7 +75,11 @@ def _measure(root: str, python_descriptors: bool) -> dict[str, float]: if python_descriptors: # As an extension built before it had its own: so before any class is bound to it for module in ("common", "trades", "mutable", "arrays"): - extension = import_module(f"schemas._{module}_native") + try: + extension = import_module(f"schemas._{module}_native") + except ImportError: + # Of Rust, which has one extension for them all + extension = getattr(import_module("schemas._native"), module) delattr(extension, "__fields__") delattr(extension, "__maker__") names: dict = {"ORDERS": ORDERS} @@ -124,11 +128,13 @@ def main(): from dataclass_native import ENV_VAR, Mode # Each in a process of its own, as a process has one mode + rust = _rust() configurations = { "`pure`": (Mode.PURE, TESTS, ""), "C++": (Mode.STRICT, BUILD / "src", ""), + "Rust": (Mode.STRICT, rust, ""), "C++, Python's descriptors": (Mode.STRICT, BUILD / "src", "python"), - "Rust": (Mode.STRICT, _rust(), ""), + "Rust, Python's descriptors": (Mode.STRICT, rust, "python"), } times = {} for name, (mode, root, descriptors) in configurations.items(): diff --git a/tests/test_pyo3.py b/tests/test_pyo3.py index acfded4..28b456e 100644 --- a/tests/test_pyo3.py +++ b/tests/test_pyo3.py @@ -9,6 +9,7 @@ from pathlib import Path import pytest +from test_bindings import _AS_DESCRIBED, _DESCRIPTORS, _run from dataclass_native import ENV_VAR, Mode, rust_dir from dataclass_native.backends import pyo3 @@ -122,6 +123,19 @@ def test_classes(sources): """\ module.add_class::()?; """, + # What reads and sets each field without Python: where it is, if it is a struct which is not set + """\ + fields.frozen::("amount", |held| &held.amount, |held| &mut held.amount)?; + """, + """\ + fields.within::("money", |held| &held.money, |held| &mut held.money)?; + """, + """\ + fields.changing::("name", |held| &held.name, |held| &mut held.name)?; + """, + """\ + module.add("__maker__", maker(py)?)?; + """, # A struct which is a field is read where it is, if neither may be set """\ fn get_money<'py>(&self, py: Python<'py>) -> PyResult> { @@ -234,15 +248,7 @@ def test_the_extension_holds_them(built): for cls in Money, Order, Customer, Path: print(type(vars(cls.__new__(cls)).get("__native__")).__module__) """ - result = subprocess.run( - [sys.executable, "-c", textwrap.dedent(script)], - env=os.environ | {ENV_VAR: Mode.MIXED, "PYTHONPATH": str(built)}, - capture_output=True, - text=True, - check=False, - ) - assert result.returncode == 0, result.stderr - assert result.stdout.split() == [ + assert _run(built, Mode.MIXED, script).split() == [ "schemas._native.common", "schemas._native.sub.inner", "schemas._native.mutable", @@ -272,15 +278,25 @@ def halved(whole: int) -> int: ... except (ValueError, TypeError) as e: print(type(e).__name__, e) """ - result = subprocess.run( - [sys.executable, "-c", textwrap.dedent(script)], - env=os.environ | {ENV_VAR: Mode.STRICT, "PYTHONPATH": str(built)}, - capture_output=True, - text=True, - check=False, - ) - assert result.returncode == 0, result.stderr - done, odd, great = result.stdout.splitlines() + done, odd, great = _run(built, Mode.STRICT, script).splitlines() assert (done, odd) == ("3.5 1.5 2", "ValueError 3 is odd") # Then what Python says of it, which is not the same everywhere assert great.startswith("TypeError incompatible function arguments: argument 1: ") + + +@pytest.mark.parametrize( + ("before", "types"), + [ + ("", "Field builtin_function_or_method"), + # As one built before it had them, which is used as it was + ("del extension.__fields__, extension.__maker__", "_Field function"), + ], +) +def test_fields(built, before, types): + """Each field of a bound class is a descriptor of the extension, and its objects are made by it: as of C++""" + script = _DESCRIPTORS.replace( + "import schemas._common_native as extension", + "from schemas._native import common as extension", + ) + lines = _run(built, Mode.STRICT, script.format(before=before)).splitlines() + assert lines == [types, *_AS_DESCRIBED] diff --git a/tests/test_rust.py b/tests/test_rust.py index 660d4b2..00f82bd 100644 --- a/tests/test_rust.py +++ b/tests/test_rust.py @@ -80,6 +80,31 @@ def test_common(sources): GBP = 3, } + /// By the name of its member + impl dataclass_native::msgpack::Wire for Currency { + fn described() -> String { + "Currency".to_string() + } + + fn write(&self, writer: &mut dataclass_native::msgpack::Writer) -> Result<(), dataclass_native::msgpack::Error> { + writer.str(match self { + Self::USD => "USD", + Self::EUR => "EUR", + Self::GBP => "GBP", + }); + Ok(()) + } + + fn read(reader: &mut dataclass_native::msgpack::Reader<'_>) -> dataclass_native::msgpack::Read { + match reader.str()? { + "USD" => Ok(Self::USD), + "EUR" => Ok(Self::EUR), + "GBP" => Ok(Self::GBP), + _ => Err(dataclass_native::msgpack::Fault::Mismatch), + } + } + } + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(i8)] @@ -89,6 +114,29 @@ def test_common(sources): SELL = 1, } + /// By the name of its member + impl dataclass_native::msgpack::Wire for Side { + fn described() -> String { + "Side".to_string() + } + + fn write(&self, writer: &mut dataclass_native::msgpack::Writer) -> Result<(), dataclass_native::msgpack::Error> { + writer.str(match self { + Self::BUY => "BUY", + Self::SELL => "SELL", + }); + Ok(()) + } + + fn read(reader: &mut dataclass_native::msgpack::Reader<'_>) -> dataclass_native::msgpack::Read { + match reader.str()? { + "BUY" => Ok(Self::BUY), + "SELL" => Ok(Self::SELL), + _ => Err(dataclass_native::msgpack::Fault::Mismatch), + } + } + } + #[derive(Debug, Clone, PartialEq)] pub struct Money { pub amount: f64, @@ -104,6 +152,49 @@ def test_common(sources): } } } + + /// A map of its fields, by name: read in any order, one which is not written taking its default + impl dataclass_native::msgpack::Wire for Money { + const BUNDLED: bool = false; + + fn described() -> String { + "Money".to_string() + } + + fn write(&self, writer: &mut dataclass_native::msgpack::Writer) -> Result<(), dataclass_native::msgpack::Error> { + writer.map(2); + writer.str("amount"); + dataclass_native::msgpack::Wire::write(&self.amount, writer)?; + writer.str("currency"); + dataclass_native::msgpack::Wire::write(&self.currency, writer)?; + Ok(()) + } + + fn read(reader: &mut dataclass_native::msgpack::Reader<'_>) -> dataclass_native::msgpack::Read { + reader.nested(|reader| { + let mut field0 = None; + let mut field1 = None; + for _ in 0..reader.map()? { + match reader.key()? { + Some("amount") => reader.field("Money", "amount", &mut field0)?, + Some("currency") => reader.field("Money", "currency", &mut field1)?, + _ => reader.skip()?, + } + } + Ok(Self { + amount: dataclass_native::msgpack::Reader::required("Money", "amount", field0)?, + currency: match field1 { + Some(read) => read, + None => Self::default().currency, + }, + }) + }) + } + } + + impl dataclass_native::msgpack::Record for Money { + const TAG: &'static str = "schemas.common.Money"; + } """ ) ) @@ -225,6 +316,7 @@ def test_cli(tmp_path, capsys): #[allow(dead_code)] mod schemas; +use dataclass_native::msgpack::{from_msgpack, to_msgpack}; use dataclass_native::{Array, Date, Decimal, Mutable, MutableArray, Ordered, Shared, Uuid}; use schemas::arrays::{Curve, Surface}; use schemas::common::{Currency, Money, Party, Side}; @@ -291,6 +383,28 @@ def test_cli(tmp_path, capsys): path.points.write()[0] = 5.0; assert!(same.points.read()[0] == 5.0 && same == path); + // As msgpack, with no Python: as WIRE_FORMAT.md has it, and read back as what was written + let money = Money { amount: 1.5, currency: Currency::EUR }; + let data = to_msgpack(&money).unwrap(); + assert_eq!(data[..9], [0x82, 0xa6, b'a', b'm', b'o', b'u', b'n', b't', 0xcb]); + assert_eq!((data.len(), from_msgpack::(&data).unwrap()), (30, money)); + assert_eq!(from_msgpack::(&data[..12]).unwrap_err().0, "msgpack data is truncated"); + assert_eq!(from_msgpack::(&[0x80]).unwrap_err().0, "Money cannot be read: no amount"); + assert_eq!(from_msgpack::(&[0x90]).unwrap_err().0, "The data is not a Money, as written"); + for kinds in [Kinds::default(), Kinds { number: KindsNumber::Str("x".to_string()), ..Kinds::default() }] { + assert_eq!(from_msgpack::(&to_msgpack(&kinds).unwrap()).unwrap(), kinds); + } + assert_eq!(from_msgpack::(&to_msgpack(&keyed).unwrap()).unwrap(), keyed); + assert_eq!(from_msgpack::(&to_msgpack(&curve).unwrap()).unwrap(), curve); + assert_eq!(from_msgpack::(&to_msgpack(&surface).unwrap()).unwrap(), surface); + assert_eq!(from_msgpack::(&to_msgpack(&path).unwrap()).unwrap(), path); + // What is shared is written once, and is still shared when it is read + let last = Shared::new(Link { name: "b".to_string(), next: None }); + let first = Link { name: "a".to_string(), next: Some(last.clone()) }; + let both = (Shared::new(first.clone()), last.clone()); + 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)); + println!("ok"); } """