dvb_common/traits.rs
1//! Canonical `Parse` and `Serialize` traits for the DVB crate family.
2//!
3//! Each implementer picks its own error type via `type Error`, so
4//! domain-specific error variants stay visible to the caller.
5
6/// Parse a DVB structure from raw bytes. Borrowing allowed via `<'a>`; the
7/// concrete error type is chosen per implementer.
8pub trait Parse<'a>: Sized {
9 /// The error type this implementer returns. Typically the enclosing
10 /// crate's `Error` enum.
11 type Error;
12
13 /// Parse `bytes` as `Self`. Returns `Err(Self::Error)` on any protocol
14 /// violation or buffer underrun.
15 fn parse(bytes: &'a [u8]) -> Result<Self, Self::Error>;
16}
17
18/// Serialize a DVB structure back to bytes. Split from [`Parse`] so owned
19/// and borrowed variants of the same type can implement `Serialize`
20/// without carrying a lifetime.
21pub trait Serialize {
22 /// The error type this implementer returns (usually the same as the
23 /// corresponding [`Parse`] impl, but need not be).
24 type Error;
25
26 /// Number of bytes `serialize_into` will write.
27 fn serialized_len(&self) -> usize;
28
29 /// Write the serialised form into `buf`. Returns the number of bytes
30 /// written (always equal to `serialized_len()`).
31 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize, Self::Error>;
32
33 /// Convenience: allocate a `Vec` and serialise into it. Panics only if
34 /// `serialize_into` misreports `serialized_len()` — a contract every
35 /// implementer is responsible for upholding.
36 fn to_bytes(&self) -> Vec<u8>
37 where
38 Self::Error: core::fmt::Debug,
39 {
40 let mut v = vec![0u8; self.serialized_len()];
41 self.serialize_into(&mut v)
42 .expect("serialize_into must succeed when buffer is exactly serialized_len()");
43 v
44 }
45}