Metadata-Version: 2.4
Name: rustdantist
Version: 0.3.0
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
License-File: LICENSE
Summary: Optional Rust core for pydantist
Author-email: firezdev <nta16022013@gmail.com>
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/firezdev/rustdantist

# rustdantist

Optional Rust core for [pydantist](https://github.com/firezdev/pydantist).

pydantist reads type annotations and builds a schema once per model;
rustdantist turns that schema into a native validator and runs
`from_dict` without executing Python code for built-in types.
It can also parse JSON straight into models, without building Python dicts first.
If rustdantist is not installed, pydantist falls back to pure Python.

```bash
pip install "pydantist[rust]"
```

## Speed

Per call, Python 3.13, compared with pydantic 2.14.

Python dict input (`validate` vs `model_validate`):

| Case | rustdantist | pydantic |
|---|---|---|
| 7 fields incl. `list[int]` ×100 and `dict[str, float]` ×20, valid types | 0.9 µs | 2.4 µs |
| Same, every value as a string (`"30"`, `"yes"`) | 2.2 µs | 3.9 µs |
| 3 fields | 0.13 µs | 0.52 µs |
| 50 nested models | 5.3 µs | 13 µs |
| `int \| None`, `int \| str` fields | 0.2 µs | 0.75 µs |
| `int \| float` with `"2.5"` (first option fails) | 0.34 µs | 1.0 µs |
| `list[int]` ×1000 | 2.1 µs | 8.8 µs |

JSON input (`validate_json` vs `model_validate_json`):

| Case | `json.loads` + `validate` | `validate_json` | pydantic |
|---|---|---|---|
| 7 fields, as above | 8.6 µs | 4.2 µs | 4.4 µs |
| 50 nested models | 20 µs | 13.7 µs | 20.7 µs |
| 3 fields | 1.2 µs | 0.26 µs | 0.63 µs |

## How it works

rustdantist does not read annotations itself. The caller (pydantist) builds a
**spec** — nested tuples describing every field — and passes it to `build()`.

```python
import rustdantist as rs

rs.setup(UnparseableError, invalid_value, MissingFieldError, json.loads, resolver)  # once per process

validator = rs.build((
    rs.K_MODEL, "User", User,
    ("name", "age"),                                 # field names
    ((rs.K_STR, "str"), (rs.K_INT, "int")),          # field specs
    (False, False),                                  # has a class-level default
    False,                                           # use setattr instead of __dict__
))
user = validator.validate({"name": "Bob", "age": "42"})
user = validator.validate_json(b'{"name": "Bob", "age": "42"}')  # str or bytes
```

`validate_json` follows the same rules as `validate(json.loads(data))` and raises the
same errors; invalid JSON raises `ValueError`.

### Spec format (`SCHEMA_VERSION = 3`)

Every node is a tuple `(kind, type_name, *args)`; `type_name` is used in error messages.

| Kind | Args | Meaning |
|---|---|---|
| `K_ANY` | — | Value returned as is |
| `K_STR`, `K_INT`, `K_FLOAT`, `K_BOOL`, `K_NONE` | `[fallback]` | Built-in scalar with lax coercion (see below) |
| `K_LIST` | `item_spec, [fallback]` | `list[T]`; also accepts a JSON array string |
| `K_DICT` | `key_spec, value_spec, [fallback]` | `dict[K, V]`; also accepts a JSON object string |
| `K_UNION` | `(option_specs...), (exact_types...)` | Values whose type is in `exact_types` are returned as is, otherwise options are tried in order |
| `K_MODEL` | `cls, names, specs, has_default, use_setattr` | Creates `cls` without calling `__init__` and fills its fields |
| `K_MODELREF` | `cls` | Nested model; resolved lazily through `resolver(cls)`, so models may reference themselves |
| `K_PYFUNC` | `cls_or_None, func` | Fallback to Python: returns the value if `type(value) is cls`, otherwise calls `func(value)` |

`fallback` is an optional Python callable for values whose type the core has no rule for
(e.g. an `Enum` member for a `str` field). It is never called when the core has a rule,
so `"x"` for an `int` field still raises the `invalid` error.

### `setup(unparseable, invalid, missing, loads, resolver)`

The first three arguments are factories returning the exception to raise:

| Factory | Called when | Example |
|---|---|---|
| `unparseable(value, type_name)` | There is no conversion rule for the value's type | `[1]` → `int` |
| `invalid(value, type_name)` | A rule exists, but the value is wrong | `"x"` → `int`, `1.5` → `int`, `"maybe"` → `bool` |
| `missing(field_name)` | A required field is absent from the input | `{}` for a model with `zip: int` |

A union fails with `unparseable` when none of its options accepts the value.
Exceptions raised by `K_PYFUNC` callbacks propagate unchanged.
If an exception has a `path` tuple attribute, rustdantist prepends field names
and list indices to it; otherwise it is left as is.

- `loads` — JSON parser used for JSON strings in `list` / `dict` fields.
- `resolver(cls)` — returns the `Validator` of a nested model class.

### Coercion rules

| To \ From | `str` | `int` | `float` | `bool` |
|---|---|---|---|---|
| `int` | ASCII digits with optional sign and surrounding whitespace | — | whole numbers only | `0` / `1` |
| `float` | Rust float syntax (`"1.5"`, `"1e3"`, `"inf"`), no `_` | ✅ | — | `0.0` / `1.0` |
| `bool` | `true t yes y on + 1` / `false f no n off - 0`, case-insensitive | `0` / `1` only | `0.0` / `1.0` only | — |
| `str` | — | ✅ | ✅ | `"true"` / `"false"` |

## Development

```bash
uv sync
uv run maturin develop --release
uv run pytest tests
```

## Release

Wheels are built by GitHub Actions (`.github/workflows/ci.yml`) for Linux (glibc and musl),
macOS and Windows on x86_64 and ARM, Python 3.11–3.14. Publish them from the run artifacts:

```bash
gh run download <run-id> --repo firezdev/rustdantist --dir dist
uv publish dist/*/*
```

