zerodds-wire

The runtime the generated encoders call: XCDR1 and XCDR2 writers and readers, alignment and framing exactly as the layout plan states it.

The runtime a generated encoder calls.

Writer and Reader put bytes on the wire and take them off, in XCDR1 and XCDR2, in either byte order. They hold the alignment rules and the framing forms — DHEADER, EMHEADER, PL_CDR1 parameter headers, the PID_LIST_END sentinel — and nothing else.

This crate makes no decisions about a type. Which members are written, in what order, with which header and which length code, is the layout plan's answer and reaches this crate as arguments. A runtime that decided any of it would be a second place where the wire format lives, and the two would drift.

Position

A Rust type for an IDL primitive or string

WireRepr lets a Rust type stand for an IDL primitive or string in the code zerodds-build generates (Config::rust_type): a checked date-time newtype for a string, NonZeroU32 for an unsigned long. The octets, the TypeObject, the TypeIdentifier and the key hash stay the IDL's.

impl WireRepr for CallSign {
    type Idl = str; // an IDL `string`
    fn to_wire(&self, out: IdlOut<'_, str>) -> Result<Written, WireError> {
        out.str(&self.0)
    }
    fn from_wire(wire: &str) -> Result<Self, WireError> {
        if (2..=8).contains(&wire.len()) {
            Ok(Self(wire.to_owned()))
        } else {
            Err(WireError::invalid_value("a call sign of 2 to 8 octets"))
        }
    }
}
  • Idl names the IDL type: str for a string, u32 for an unsigned long, and so on. to_wire gets an IdlOut for exactly that type and returns the Written only an IdlOut makes, so an impl writes one value of the member's IDL type.
  • IdlOut::str writes a borrowed &str; IdlOut::display formats a Display value straight into the sample's buffer and patches the length in afterwards. The bound of a string<N> and the NUL check run on the written text.
  • from_wire gets a &str lent out of the received sample (Reader::read_str), with no allocation. A refusal (WireError::invalid_value) rejects the sample with its reason.
  • Impls in this crate: core::num::NonZero* over the integers, String, Cow<'_, str> and each primitive's own Rust type. A type from another crate goes through an adapter, WireReprWith; DisplayFromStr is the one for any Display + FromStr type on a string.

A type defined in Rust: the codec API

A type defined in Rust (derive(DdsType)) implements three traits of zerodds_wire::codec: DdsTypeInfo, its IDL shape — the members' Rust types as a type list and the declaration as a constant —, and DdsSerialize and DdsDeserialize<'de>. A hand-written codec writes all three, or takes the description from the derive (#[dds(codec = "manual")]):

impl DdsTypeInfo for Pose {
    type Members = (u32, (String, ()));
    type Extensibility = Final;
    const LAYOUT: TypeDesc = TypeDesc::structure::<Self::Members, Final>(
        "app::Pose",
        &[MemberDesc::new("id").key(), MemberDesc::new("label").bound(16)],
    );
}

impl DdsSerialize for Pose {
    fn serialize(&self, out: DdsSerializer<'_>) -> Result<Serialized, WireError> {
        out.serialize_struct::<Self>()?
            .member(&self.id)?
            .member(&self.label)?
            .end()
    }
}
  • The serializer is typed by the member list: member takes a value of the next member's type, and end exists only when no member is left. A member left out, one too many or one of another type does not compile, and neither does a description with another number of members than the list.
  • Decoding mirrors it: deserialize_struct hands out the members of a @final or @appendable type in order, deserialize_mutable fills one typed slot per member id of a @mutable type. A string reaches a WireRepr member as a &str lent out of the sample.
  • The framing — alignment, DHEADER, EMHEADER with member id and must-understand flag, @optional presence, bounds, the key holder — is the layout plan's, one plan per encapsulation (XCDR1 or XCDR2, either byte order). What is checked at run time depends on the value: a bound, a NonZero that arrives as zero, a text its type does not parse.
  • A union (DdsUnionInfo, with its Discriminator type) is written through serialize_union: branch::<B1>(&discriminator, &value) takes the branch as a type-level index and a value of exactly that branch’s type, so another type does not compile; the discriminator is checked against the branch’s labels at run time. deserialize_union reads the discriminator and says which branch it selects.
  • A member read through DdsMemberRead<'de> may borrow from the received bytes: &'de str, &'de [u8], Cow<'de, str>, Cow<'de, [u8]>.
  • core::time::Duration is the DDS Duration_t { long sec; unsigned long nanosec; }, Duration::MAX its DURATION_INFINITE; with the std feature, std::time::SystemTime is Time_t. Both are @final, as DDS 1.4 §2.3.3 declares them.

Specification

docs/specs/zerodds-ast-1.0.md §7 — the layout plan this crate serves.

zerodds-wire

Die Laufzeit, die erzeugte Encoder aufrufen: Writer und Reader für XCDR1 und XCDR2, Ausrichtung und Rahmung genau so, wie der Layoutplan sie angibt.

Die Laufzeit, die ein erzeugter Encoder aufruft.

Writer und Reader legen Bytes auf die Leitung und nehmen sie herunter, in XCDR1 und XCDR2, in beiden Bytereihenfolgen. Sie halten die Ausrichtungsregeln und die Rahmenformen — DHEADER, EMHEADER, PL_CDR1-Parameterheader, den Abschluss PID_LIST_END — und sonst nichts.

Diese Crate trifft keine Entscheidung über einen Typ. Welche Member in welcher Reihenfolge mit welchem Header und welchem Längencode geschrieben werden, beantwortet der Layoutplan; die Antwort erreicht diese Crate als Argumente. Eine Laufzeit, die irgendetwas davon entschiede, wäre ein zweiter Ort, an dem das Format auf der Leitung festgelegt wird, und die beiden würden auseinanderlaufen.

Stellung

Ein Rust-Typ für einen primitiven IDL-Typ oder einen string

WireRepr lässt einen Rust-Typ im Code, den zerodds-build erzeugt (Config::rust_type), für einen primitiven IDL-Typ oder einen string stehen: einen geprüften Newtype für Datum und Zeit für einen string, NonZeroU32 für einen unsigned long. Die Oktette, das TypeObject, der TypeIdentifier und der Key-Hash bleiben die der IDL.

impl WireRepr for CallSign {
    type Idl = str; // ein IDL-`string`
    fn to_wire(&self, out: IdlOut<'_, str>) -> Result<Written, WireError> {
        out.str(&self.0)
    }
    fn from_wire(wire: &str) -> Result<Self, WireError> {
        if (2..=8).contains(&wire.len()) {
            Ok(Self(wire.to_owned()))
        } else {
            Err(WireError::invalid_value("a call sign of 2 to 8 octets"))
        }
    }
}
  • Idl nennt den IDL-Typ: str für einen string, u32 für einen unsigned long und so fort. to_wire bekommt ein IdlOut für genau diesen Typ und gibt das Written zurück, das nur ein IdlOut erzeugt; eine Implementierung schreibt also einen Wert vom IDL-Typ des Members.
  • IdlOut::str schreibt einen geliehenen &str; IdlOut::display formatiert einen Wert mit Display direkt in den Puffer des Samples und trägt die Länge danach ein. Die Grenze eines string<N> und die Prüfung auf NUL gelten für den geschriebenen Text.
  • from_wire bekommt einen &str, der aus dem empfangenen Sample geliehen ist (Reader::read_str), ohne Allokation. Eine Ablehnung (WireError::invalid_value) weist das Sample mit ihrem Grund zurück.
  • Implementierungen in dieser Crate: core::num::NonZero* über den Ganzzahlen, String, Cow<'_, str> und der Rust-Typ jedes primitiven Typs selbst. Ein Typ aus einer anderen Crate geht über einen Adapter, WireReprWith; DisplayFromStr ist der für jeden Typ mit Display + FromStr auf einem string.

Ein in Rust definierter Typ: die Codec-API

Ein in Rust definierter Typ (derive(DdsType)) implementiert drei Traits aus zerodds_wire::codec: DdsTypeInfo, seine IDL-Gestalt — die Rust-Typen der Member als Typliste und die Deklaration als Konstante —, und DdsSerialize und DdsDeserialize<'de>. Ein von Hand geschriebener Codec schreibt alle drei oder nimmt die Beschreibung aus dem Derive (#[dds(codec = "manual")]):

impl DdsTypeInfo for Pose {
    type Members = (u32, (String, ()));
    type Extensibility = Final;
    const LAYOUT: TypeDesc = TypeDesc::structure::<Self::Members, Final>(
        "app::Pose",
        &[MemberDesc::new("id").key(), MemberDesc::new("label").bound(16)],
    );
}

impl DdsSerialize for Pose {
    fn serialize(&self, out: DdsSerializer<'_>) -> Result<Serialized, WireError> {
        out.serialize_struct::<Self>()?
            .member(&self.id)?
            .member(&self.label)?
            .end()
    }
}
  • Der Serializer ist über die Memberliste typisiert: member nimmt einen Wert vom Typ des nächsten Members, und end gibt es erst, wenn kein Member mehr übrig ist. Ein ausgelassener Member, einer zu viel oder einer von anderem Typ übersetzt nicht, ebenso wenig eine Beschreibung mit einer anderen Memberzahl als die Liste.
  • Das Dekodieren spiegelt das: deserialize_struct gibt die Member eines @final- oder @appendable-Typs der Reihe nach heraus, deserialize_mutable füllt bei einem @mutable-Typ einen typisierten Platz je Member-ID. Ein string erreicht einen WireRepr-Member als &str, aus dem Sample geliehen.
  • Die Rahmung — Ausrichtung, DHEADER, EMHEADER mit Member-ID und Must-Understand-Flag, Vorhandensein bei @optional, Grenzen, der Key-Holder — gibt der Layoutplan vor, ein Plan je Kapselung (XCDR1 oder XCDR2, beide Bytereihenfolgen). Zur Laufzeit geprüft wird, was vom Wert abhängt: eine Grenze, ein NonZero, das als Null ankommt, ein Text, den sein Typ nicht einliest.
  • Eine Union (DdsUnionInfo, mit ihrem Discriminator-Typ) wird über serialize_union geschrieben: branch::<B1>(&discriminator, &value) nimmt den Zweig als Index auf Typebene und einen Wert genau vom Typ dieses Zweigs, ein anderer Typ übersetzt also nicht; der Diskriminator wird zur Laufzeit gegen die Labels des Zweigs geprüft. deserialize_union liest den Diskriminator und sagt, welchen Zweig er wählt.
  • Ein über DdsMemberRead<'de> gelesener Member darf aus den empfangenen Bytes leihen: &'de str, &'de [u8], Cow<'de, str>, Cow<'de, [u8]>.
  • core::time::Duration ist das DDS-Duration_t { long sec; unsigned long nanosec; }, Duration::MAX dessen DURATION_INFINITE; mit dem Feature std ist std::time::SystemTime das Time_t. Beide sind @final, wie DDS 1.4 §2.3.3 sie deklariert.

Spezifikation

docs/specs/zerodds-ast-1.0.md §7 — der Layoutplan, dem diese Crate dient.