Skip to main content

dvb_si/descriptors/
stuffing.rs

1//! Stuffing Descriptor — ETSI EN 300 468 §6.2.41 (tag 0x42).
2//!
3//! Table 98 (PDF p. 105). A descriptor whose body is `N` arbitrary
4//! `stuffing_byte`s of any value. Used to pad descriptor loops; carries no
5//! semantic information. The bytes are kept verbatim as a borrowed slice.
6
7use crate::error::{Error, Result};
8use crate::traits::Descriptor;
9use dvb_common::{Parse, Serialize};
10
11/// Descriptor tag for stuffing_descriptor.
12pub const TAG: u8 = 0x42;
13const HEADER_LEN: usize = 2;
14/// Maximum body length expressible in the 8-bit `descriptor_length` field.
15const MAX_BODY_LEN: usize = u8::MAX as usize;
16
17/// Stuffing Descriptor.
18///
19/// EN 300 468 §6.2.41: `stuffing_byte` values are unconstrained ("This is an
20/// 8-bit field whose value is not specified"), so the payload is stored as an
21/// opaque borrowed slice and round-trips byte-for-byte.
22#[derive(Debug, Clone, PartialEq, Eq)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24#[cfg_attr(feature = "serde", serde(bound(deserialize = "'de: 'a")))]
25pub struct StuffingDescriptor<'a> {
26    /// Arbitrary stuffing bytes (any value), in wire order.
27    #[cfg_attr(feature = "serde", serde(borrow))]
28    pub stuffing_bytes: &'a [u8],
29}
30
31impl<'a> Parse<'a> for StuffingDescriptor<'a> {
32    type Error = crate::error::Error;
33    fn parse(bytes: &'a [u8]) -> Result<Self> {
34        if bytes.len() < HEADER_LEN {
35            return Err(Error::BufferTooShort {
36                need: HEADER_LEN,
37                have: bytes.len(),
38                what: "StuffingDescriptor header",
39            });
40        }
41        if bytes[0] != TAG {
42            return Err(Error::InvalidDescriptor {
43                tag: bytes[0],
44                reason: "unexpected tag for stuffing_descriptor",
45            });
46        }
47        let length = bytes[1] as usize;
48        let end = HEADER_LEN + length;
49        if bytes.len() < end {
50            return Err(Error::BufferTooShort {
51                need: end,
52                have: bytes.len(),
53                what: "StuffingDescriptor body",
54            });
55        }
56        Ok(Self {
57            stuffing_bytes: &bytes[HEADER_LEN..end],
58        })
59    }
60}
61
62impl Serialize for StuffingDescriptor<'_> {
63    type Error = crate::error::Error;
64    fn serialized_len(&self) -> usize {
65        HEADER_LEN + self.stuffing_bytes.len()
66    }
67
68    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
69        let len = self.serialized_len();
70        if buf.len() < len {
71            return Err(Error::OutputBufferTooSmall {
72                need: len,
73                have: buf.len(),
74            });
75        }
76        // 8-bit descriptor_length field: error rather than silently truncate.
77        if self.stuffing_bytes.len() > MAX_BODY_LEN {
78            return Err(Error::SectionLengthOverflow {
79                declared: self.stuffing_bytes.len(),
80                available: MAX_BODY_LEN,
81            });
82        }
83        buf[0] = TAG;
84        buf[1] = self.stuffing_bytes.len() as u8;
85        buf[HEADER_LEN..len].copy_from_slice(self.stuffing_bytes);
86        Ok(len)
87    }
88}
89
90impl<'a> Descriptor<'a> for StuffingDescriptor<'a> {
91    const TAG: u8 = TAG;
92    fn descriptor_length(&self) -> u8 {
93        self.stuffing_bytes.len() as u8
94    }
95}
96
97impl<'a> crate::traits::DescriptorDef<'a> for StuffingDescriptor<'a> {
98    const TAG: u8 = TAG;
99    const NAME: &'static str = "STUFFING";
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[test]
107    fn parse_arbitrary_bytes() {
108        let bytes = [TAG, 4, 0x00, 0xFF, 0xAB, 0x7E];
109        let d = StuffingDescriptor::parse(&bytes).unwrap();
110        assert_eq!(d.stuffing_bytes, &[0x00, 0xFF, 0xAB, 0x7E]);
111    }
112
113    #[test]
114    fn parse_empty_body_valid() {
115        let bytes = [TAG, 0];
116        let d = StuffingDescriptor::parse(&bytes).unwrap();
117        assert!(d.stuffing_bytes.is_empty());
118    }
119
120    #[test]
121    fn parse_rejects_wrong_tag() {
122        assert!(matches!(
123            StuffingDescriptor::parse(&[0x43, 0]).unwrap_err(),
124            Error::InvalidDescriptor { tag: 0x43, .. }
125        ));
126    }
127
128    #[test]
129    fn parse_rejects_short_buffer() {
130        // declared length 4 but only 2 body bytes present
131        let bytes = [TAG, 4, 0x00, 0xFF];
132        assert!(matches!(
133            StuffingDescriptor::parse(&bytes).unwrap_err(),
134            Error::BufferTooShort { .. }
135        ));
136    }
137
138    #[test]
139    fn serialize_round_trip() {
140        let d = StuffingDescriptor {
141            stuffing_bytes: &[0xDE, 0xAD, 0xBE, 0xEF],
142        };
143        let mut buf = vec![0u8; d.serialized_len()];
144        d.serialize_into(&mut buf).unwrap();
145        assert_eq!(StuffingDescriptor::parse(&buf).unwrap(), d);
146    }
147
148    #[test]
149    fn serialize_rejects_small_buffer() {
150        let d = StuffingDescriptor {
151            stuffing_bytes: &[0x01, 0x02],
152        };
153        let mut tiny = [0u8; 3];
154        assert!(matches!(
155            d.serialize_into(&mut tiny).unwrap_err(),
156            Error::OutputBufferTooSmall { .. }
157        ));
158    }
159
160    #[test]
161    fn serialize_rejects_over_range_body() {
162        let big = vec![0u8; 256];
163        let d = StuffingDescriptor {
164            stuffing_bytes: &big,
165        };
166        let mut buf = vec![0u8; d.serialized_len()];
167        assert!(matches!(
168            d.serialize_into(&mut buf).unwrap_err(),
169            Error::SectionLengthOverflow { .. }
170        ));
171    }
172
173    #[cfg(feature = "serde")]
174    #[test]
175    fn serde_serialize_stable() {
176        // Borrowed-byte fields cannot deserialize from a JSON array (serde_json
177        // requires a borrowed-str for &[u8]); assert the Serialize half is
178        // stable and captures the payload, matching how the other borrowed
179        // descriptors (e.g. content_identifier) handle serde.
180        let d = StuffingDescriptor {
181            stuffing_bytes: &[0x11, 0x22, 0x33],
182        };
183        let json = serde_json::to_string(&d).unwrap();
184        assert!(json.contains("17") && json.contains("34") && json.contains("51"));
185        // Re-serializing an equal value yields identical JSON (no nondeterminism).
186        let d2 = StuffingDescriptor {
187            stuffing_bytes: &[0x11, 0x22, 0x33],
188        };
189        assert_eq!(json, serde_json::to_string(&d2).unwrap());
190    }
191}