Models
A model is a type that crosses as data. Derive Model on a Serde type, with both Serialize and Deserialize, so that values cross in both directions with one wire shape. Serde controls the wire names. apps/examples/showcase/src/lib.rs has every kind.
Model supports structs with named fields, enums with only unit variants, internally tagged enums with named fields, enums in Serde's default form, and #[serde(transparent)] tuple structs with one field.
Structs
/// Settings with defaults and a fixed value.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Model)]
#[serde(rename_all = "camelCase")]
pub struct Settings {
/// Always `"v1"`.
#[bimetal(literal = "v1")]
pub version: String,
#[serde(default)]
pub verbose: bool,
#[serde(default)]
pub prefix: String,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub retry: Retry,
}Python gets a frozen Pydantic model, and a dict passed where a model is expected is validated as that model. TypeScript gets a readonly interface, and values are plain frozen objects:
self.assertFalse(echo_settings(Settings(version="v1")).verbose)assert.equal(echoSettings({ version: "v1" }).verbose, false);#[serde(default)] makes a field optional when its type has a Rust Default: a bool, a number, a String, a list, a map, an enum or another model. An absent field holds that Default:
impl Default for Retry {
fn default() -> Self {
Self {
attempts: 3,
factor: 2.0,
}
}
}A Python model holds the default as soon as it is built, and no two models share a list or a nested model. A TypeScript object is plain, so it gains the default when it crosses into Rust:
self.assertEqual(Settings(version="v1").retry, Retry(attempts=3, factor=2.0))assert.deepEqual(echoSettings({ version: "v1" }).retry, { attempts: 3, factor: 2 });#[serde(default = "path")] gives an absent field what the function path returns, for a default that isn't the Default of its type:
#[serde(default = "default_icon")]
pub icon: String,fn default_icon() -> String {
"brackets-curly".to_owned()
}The hosts get the value that the function returns, so Python, TypeScript and Rust agree:
self.assertEqual(Settings(version="v1").icon, "brackets-curly")assert.equal(echoSettings({ version: "v1" }).icon, "brackets-curly");Bimetal reads each default from the compiled library, when it builds the packages and again when a package loads. A Default or a default function therefore runs each time a program imports the package, so it must be cheap, must not panic, and must give the same value on every call. The field's type must be Serialize. bimetal build fails, and names the field, when a default differs between two calls, breaks a field rule, holds a NaN or an infinity at any depth, or can't be written as JSON.
An Option field is None when absent under #[serde(default)], and holds what the function returns under default = "path". A required field takes neither. A field with a default function takes no skip_serializing_if, because Serde would leave out a None and read it back as what the function returns.
Field rules
#[bimetal(...)] on a field adds a rule that every host sees:
#[bimetal(min_length = 1, max_length = 40)]
pub label: String,
pub priority: Priority,
pub score: Score,
#[bimetal(ge = 1, le = 5)]
pub stars: u8,
/// A field that is always present, even though it may be empty.
#[bimetal(required)]
pub note: Option<String>,| Attribute | Rule |
|---|---|
required |
The Option<T> field must be present, even as None |
literal = <literal> |
The field must have this boolean, integer or string value. It doesn't apply to an Option field |
min_length, max_length |
Limits for the length of a string or a list |
ge, le |
Limits for an integer field. They don't apply through an alias |
Rust checks literal, min_length, max_length, ge and le on every argument and result of an export, and on what a callback returns, on every host, including models inside lists and maps. A string's length counts Unicode code points, as Python's len does, so an emoji counts once, though JavaScript's .length counts two.
Pydantic also checks the rules where a Python model is built. Rust catches what Pydantic doesn't validate, such as a model changed with model_copy(update=...). TypeScript's declarations carry the same names and types: a field with a default is optional, and a literal field has its value as its type.
Serde reads a missing Option field as None, so the hosts check required before the call: Pydantic in Python, and the generated wrapper in TypeScript. Only Python rejects unknown fields, which Serde ignores.
The check is one more pass over each decoded value. It skips values whose types have no rules, except inside maps and recursive models, which it still walks.
Failures says what each broken rule raises.
Enums
An enum with only unit variants becomes a Python StrEnum and a TypeScript string union, with a frozen object of the same name:
/// How urgent a record is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Model)]
#[serde(rename_all = "snake_case")]
pub enum Priority {self.assertEqual(Priority.High, "high")assert.equal(Priority.High, "high");An internally tagged enum becomes a discriminated union:
/// Something that happened to a record.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Model)]
#[serde(
tag = "kind",
rename_all = "snake_case",
rename_all_fields = "camelCase"
)]
pub enum Event {
/// The record was created.
Created { record_id: RecordId },An enum in Serde's default form, without a tag, becomes the union of its variants. A variant without data crosses as its name, and a variant with data as an object whose only key is that name. A variant can hold named fields or one value, and a Box crosses as the value inside it, so an enum can hold itself:
/// One step of a drawing, in Serde's default enum form.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Model)]
#[serde(rename_all = "snake_case")]
pub enum Stroke {
/// Lift the pen.
Lift,
/// Move the pen to a point.
MoveTo(Point),In Python each variant is a model, such as StrokeMoveTo, which holds a one-value variant's data as value, and the union picks the model by the variant's name. TypeScript keeps the wire form: a variant without data is its name's string type, and one with data an interface with that one key:
start = StrokeMoveTo(value=Point(x=1.0, y=2.0))
self.assertEqual(retrace([StrokeLift(), start]), [start, StrokeLift()])assert.deepEqual(retrace(["lift", { move_to: { x: 1, y: 2 } }]), [{ move_to: { x: 1, y: 2 } }, "lift"]);A tuple variant crosses only with one value, and a field of a struct variant can't have the variant's name. Untagged and adjacently tagged enums don't cross.
Aliases
A #[serde(transparent)] tuple struct with one field becomes an alias of its field's type on each host:
/// A stable identifier that hosts see as a plain string.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Model)]
#[serde(transparent)]
pub struct RecordId(pub String);What a model can't hold
A model can't hold buffers, Arrow values, resources or callbacks. A Vec<u8> field is a list of integers, so send large payloads as separate parameters. A Model must be a type of your crate, so a type from another crate needs a mirror, as each trial does.