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
6use alloc::vec::Vec;
7
8/// Parse a DVB structure from raw bytes. Borrowing allowed via `<'a>`; the
9/// concrete error type is chosen per implementer.
10pub trait Parse<'a>: Sized {
11 /// The error type this implementer returns. Typically the enclosing
12 /// crate's `Error` enum.
13 type Error;
14
15 /// Parse `bytes` as `Self`. Returns `Err(Self::Error)` on any protocol
16 /// violation or buffer underrun.
17 fn parse(bytes: &'a [u8]) -> Result<Self, Self::Error>;
18}
19
20/// Serialize a DVB structure back to bytes. Split from [`Parse`] so owned
21/// and borrowed variants of the same type can implement `Serialize`
22/// without carrying a lifetime.
23pub trait Serialize {
24 /// The error type this implementer returns (usually the same as the
25 /// corresponding [`Parse`] impl, but need not be).
26 type Error;
27
28 /// Number of bytes `serialize_into` will write.
29 fn serialized_len(&self) -> usize;
30
31 /// Write the serialised form into `buf`. Returns the number of bytes
32 /// written (always equal to `serialized_len()`).
33 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize, Self::Error>;
34
35 /// Convenience: allocate a `Vec` and serialise into it.
36 ///
37 /// # Panics
38 /// Panics if `serialize_into` returns an error on a buffer of exactly
39 /// `serialized_len()` bytes. For values obtained by parsing real wire data
40 /// this never happens; it can only occur for a **hand-constructed** value
41 /// that violates a wire constraint (e.g. a section whose body exceeds the
42 /// 12-bit `section_length`). When building values by hand and that's a
43 /// possibility, call [`serialize_into`](Self::serialize_into) and handle the
44 /// error instead.
45 fn to_bytes(&self) -> Vec<u8>
46 where
47 Self::Error: core::fmt::Debug,
48 {
49 let mut v = alloc::vec![0u8; self.serialized_len()];
50 self.serialize_into(&mut v)
51 .expect("serialize_into must succeed when buffer is exactly serialized_len()");
52 v
53 }
54}