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.
34 ///
35 /// # Panics
36 /// Panics if `serialize_into` returns an error on a buffer of exactly
37 /// `serialized_len()` bytes. For values obtained by parsing real wire data
38 /// this never happens; it can only occur for a **hand-constructed** value
39 /// that violates a wire constraint (e.g. a section whose body exceeds the
40 /// 12-bit `section_length`). When building values by hand and that's a
41 /// possibility, call [`serialize_into`](Self::serialize_into) and handle the
42 /// error instead.
43 fn to_bytes(&self) -> Vec<u8>
44 where
45 Self::Error: core::fmt::Debug,
46 {
47 let mut v = vec![0u8; self.serialized_len()];
48 self.serialize_into(&mut v)
49 .expect("serialize_into must succeed when buffer is exactly serialized_len()");
50 v
51 }
52}