Skip to main content

broadcast_core/
traits.rs

1//! Canonical `Parse`, `ParsePrefix`, `ParseWith` 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    ///
18    /// The structure starts at `bytes[0]`. Bytes after a structure's own
19    /// declared end are not part of it (the crate's trailing-byte policy says
20    /// whether they are ignored or refused); a structure with no declared end
21    /// consumes all of `bytes`. A caller that needs the length consumed uses
22    /// [`ParsePrefix`].
23    fn parse(bytes: &'a [u8]) -> Result<Self, Self::Error>;
24}
25
26/// Parse one length-delimited structure from the front of `bytes` and say
27/// how many bytes it took, so a loop can walk a run of them (TLV items,
28/// descriptors, boxes, data units).
29///
30/// This is a separate trait, not a blanket over [`Parse`]: a type with its
31/// own end implements it explicitly.
32pub trait ParsePrefix<'a>: Sized {
33    /// The error type this implementer returns. Typically the enclosing
34    /// crate's `Error` enum.
35    type Error;
36
37    /// Parse one `Self` starting at `bytes[0]`, returning it and the number
38    /// of bytes it occupies (never more than `bytes.len()`).
39    fn parse_prefix(bytes: &'a [u8]) -> Result<(Self, usize), Self::Error>;
40}
41
42/// Parse a structure whose work or nesting the caller must bound.
43///
44/// A type implements [`Parse`] when its work and allocation are bounded by
45/// `bytes.len()` and its recursion depth is fixed by the format; otherwise it
46/// implements `ParseWith` and not `Parse`, so a limit is never invented by the
47/// library. The limits are a plain `*Limits` literal struct the caller builds
48/// and passes by reference; there is no default and no unlimited value.
49pub trait ParseWith<'a>: Sized {
50    /// The caller's bounds.
51    type Limits: ?Sized;
52
53    /// The error type this implementer returns.
54    type Error;
55
56    /// Parse `bytes` as `Self`, refusing or reporting what exceeds `limits`.
57    fn parse_with(bytes: &'a [u8], limits: &Self::Limits) -> Result<Self, Self::Error>;
58}
59
60/// Serialize a DVB structure back to bytes. Split from [`Parse`] so owned
61/// and borrowed variants of the same type can implement `Serialize`
62/// without carrying a lifetime.
63pub trait Serialize {
64    /// The error type this implementer returns (usually the same as the
65    /// corresponding [`Parse`] impl, but need not be).
66    type Error;
67
68    /// Number of bytes `serialize_into` will write.
69    fn serialized_len(&self) -> usize;
70
71    /// Write the serialised form into `buf`. Returns the number of bytes
72    /// written (always equal to `serialized_len()`).
73    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize, Self::Error>;
74
75    /// Allocate a `Vec` and serialize into it, returning the serializer's error instead of
76    /// panicking. This is the only
77    /// allocate-and-serialize entry point: there is deliberately no panicking
78    /// `to_bytes` (hand-built values, or values assembled from damaged wire data,
79    /// can violate a wire constraint, so the error must reach the caller).
80    fn try_to_bytes(&self) -> Result<Vec<u8>, Self::Error> {
81        let mut v = alloc::vec![0u8; self.serialized_len()];
82        let written = self.serialize_into(&mut v)?;
83        // A serializer that writes fewer bytes than it promised must not
84        // leave trailing zeros in the result.
85        if written != v.len() {
86            v.truncate(written);
87        }
88        Ok(v)
89    }
90
91    /// Append the serialised form to `out`, returning the number of bytes
92    /// appended. `out` is left unchanged when the serializer fails.
93    fn serialize_append(&self, out: &mut Vec<u8>) -> Result<usize, Self::Error> {
94        let start = out.len();
95        out.resize(start + self.serialized_len(), 0);
96        match self.serialize_into(&mut out[start..]) {
97            Ok(written) => {
98                out.truncate(start + written);
99                Ok(written)
100            }
101            Err(e) => {
102                out.truncate(start);
103                Err(e)
104            }
105        }
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use alloc::vec;
113    use core::fmt;
114
115    #[derive(Debug, PartialEq)]
116    struct TestError;
117
118    #[derive(Debug, PartialEq)]
119    struct LengthPrefixed<'a>(&'a [u8]);
120
121    impl<'a> ParsePrefix<'a> for LengthPrefixed<'a> {
122        type Error = TestError;
123        fn parse_prefix(bytes: &'a [u8]) -> Result<(Self, usize), TestError> {
124            let (&len, rest) = bytes.split_first().ok_or(TestError)?;
125            let body = rest.get(..usize::from(len)).ok_or(TestError)?;
126            Ok((LengthPrefixed(body), 1 + body.len()))
127        }
128    }
129
130    #[derive(Debug, PartialEq)]
131    struct Bounded<'a>(&'a [u8]);
132
133    struct MaxLen {
134        max: usize,
135    }
136
137    impl<'a> ParseWith<'a> for Bounded<'a> {
138        type Limits = MaxLen;
139        type Error = TestError;
140        fn parse_with(bytes: &'a [u8], limits: &MaxLen) -> Result<Self, TestError> {
141            if bytes.len() > limits.max {
142                return Err(TestError);
143            }
144            Ok(Bounded(bytes))
145        }
146    }
147
148    #[test]
149    fn parse_with_takes_the_callers_limits() {
150        let limits = MaxLen { max: 2 };
151        assert_eq!(Bounded::parse_with(&[1, 2], &limits), Ok(Bounded(&[1, 2])));
152        assert_eq!(Bounded::parse_with(&[1, 2, 3], &limits), Err(TestError));
153    }
154
155    #[test]
156    fn parse_prefix_walks_a_run_and_reports_what_it_consumed() {
157        let run = [2, 0xA, 0xB, 0, 1, 0xC];
158        let mut rest = &run[..];
159        let mut items = vec![];
160        while !rest.is_empty() {
161            let (item, used) = LengthPrefixed::parse_prefix(rest).unwrap();
162            items.push(item);
163            rest = &rest[used..];
164        }
165        assert_eq!(
166            items,
167            [
168                LengthPrefixed(&[0xA, 0xB]),
169                LengthPrefixed(&[]),
170                LengthPrefixed(&[0xC])
171            ]
172        );
173        assert_eq!(LengthPrefixed::parse_prefix(&[]), Err(TestError));
174        assert_eq!(LengthPrefixed::parse_prefix(&[2, 0xA]), Err(TestError));
175    }
176
177    impl fmt::Display for TestError {
178        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179            f.write_str("test serializer error")
180        }
181    }
182
183    /// Minimal `Serialize` impl whose `serialize_into` fails when `fail` is set.
184    struct Flagged {
185        fail: bool,
186        written: usize,
187    }
188
189    impl Serialize for Flagged {
190        type Error = TestError;
191
192        fn serialized_len(&self) -> usize {
193            4
194        }
195
196        fn serialize_into(&self, buf: &mut [u8]) -> Result<usize, Self::Error> {
197            if self.fail {
198                return Err(TestError);
199            }
200            let n = self.written.min(buf.len());
201            buf[..n].copy_from_slice(&[1, 2, 3, 4][..n]);
202            Ok(n)
203        }
204    }
205
206    #[test]
207    fn serialize_append_extends_and_leaves_out_untouched_on_error() {
208        let mut out = vec![9u8];
209        let ok = Flagged {
210            fail: false,
211            written: 4,
212        };
213        assert_eq!(ok.serialize_append(&mut out), Ok(4));
214        assert_eq!(out, [9, 1, 2, 3, 4]);
215        let bad = Flagged {
216            fail: true,
217            written: 4,
218        };
219        assert_eq!(bad.serialize_append(&mut out), Err(TestError));
220        assert_eq!(out, [9, 1, 2, 3, 4]);
221    }
222
223    #[test]
224    fn try_to_bytes_returns_serializer_error() {
225        assert_eq!(
226            Flagged {
227                fail: true,
228                written: 0
229            }
230            .try_to_bytes(),
231            Err(TestError)
232        );
233    }
234
235    #[test]
236    fn try_to_bytes_truncates_when_serializer_writes_less_than_promised() {
237        // serialized_len is 4 but only 3 bytes are written: no trailing zero.
238        let v = Flagged {
239            fail: false,
240            written: 3,
241        }
242        .try_to_bytes()
243        .unwrap();
244        assert_eq!(v, vec![1, 2, 3]);
245    }
246
247    #[test]
248    fn try_to_bytes_happy_path_fills_buffer() {
249        let ok = Flagged {
250            fail: false,
251            written: 4,
252        };
253        assert_eq!(ok.try_to_bytes().unwrap(), vec![1, 2, 3, 4]);
254    }
255}