Skip to main content

nros_serdes/
traits.rs

1//! Serialization traits
2
3use crate::{
4    cdr::{CdrReader, CdrWriter},
5    error::{DeserError, SerError},
6};
7
8/// Trait for types that can be serialized to CDR format
9pub trait Serialize {
10    /// Serialize this value to the CDR writer
11    fn serialize(&self, writer: &mut CdrWriter) -> Result<(), SerError>;
12}
13
14/// Trait for types that can be deserialized from CDR format
15pub trait Deserialize: Sized {
16    /// Deserialize a value from the CDR reader
17    fn deserialize(reader: &mut CdrReader) -> Result<Self, DeserError>;
18}
19
20/// Trait for borrowed (zero-copy) deserialization from CDR format (RFC-0033
21/// `borrowed` storage mode, issue 0007).
22///
23/// Unlike [`Deserialize`], which copies variable-length fields into owned
24/// (`heapless`/heap) storage, an implementor borrows `&'a [u8]` / `&'a str`
25/// slices directly out of the `CdrReader`'s source buffer. The resulting value
26/// is therefore tied to that buffer's lifetime `'a` — it is valid only while
27/// the receive buffer it points into is held (i.e. inside a subscription
28/// callback). Fixed-size header fields are still read onto the stack; only the
29/// unbounded sequence/string fields borrow.
30///
31/// The reader's zero-copy primitives (`read_slice_u8`, `read_string`,
32/// `read_slice_f32_raw`, …) supply the borrowed slices.
33pub trait DeserializeBorrowed<'a>: Sized {
34    /// Deserialize a value, borrowing variable-length fields from the reader's
35    /// source buffer (no copy).
36    fn deserialize_borrowed(reader: &mut CdrReader<'a>) -> Result<Self, DeserError>;
37}