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 super::descriptor_body;
8use crate::error::{Error, Result};
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))]
24#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
25pub struct StuffingDescriptor<'a> {
26    /// Arbitrary stuffing bytes (any value), in wire order.
27    pub stuffing_bytes: &'a [u8],
28}
29
30impl<'a> Parse<'a> for StuffingDescriptor<'a> {
31    type Error = crate::error::Error;
32    fn parse(bytes: &'a [u8]) -> Result<Self> {
33        let body = descriptor_body(
34            bytes,
35            TAG,
36            "StuffingDescriptor",
37            "unexpected tag for stuffing_descriptor",
38        )?;
39        Ok(Self {
40            stuffing_bytes: body,
41        })
42    }
43}
44
45impl Serialize for StuffingDescriptor<'_> {
46    type Error = crate::error::Error;
47    fn serialized_len(&self) -> usize {
48        HEADER_LEN + self.stuffing_bytes.len()
49    }
50
51    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
52        let len = self.serialized_len();
53        if buf.len() < len {
54            return Err(Error::OutputBufferTooSmall {
55                need: len,
56                have: buf.len(),
57            });
58        }
59        // 8-bit descriptor_length field: error rather than silently truncate.
60        if self.stuffing_bytes.len() > MAX_BODY_LEN {
61            return Err(Error::InvalidDescriptor {
62                tag: TAG,
63                reason: "stuffing_descriptor body exceeds 255 bytes",
64            });
65        }
66        buf[0] = TAG;
67        buf[1] = self.stuffing_bytes.len() as u8;
68        buf[HEADER_LEN..len].copy_from_slice(self.stuffing_bytes);
69        Ok(len)
70    }
71}
72impl<'a> crate::traits::DescriptorDef<'a> for StuffingDescriptor<'a> {
73    const TAG: u8 = TAG;
74    const NAME: &'static str = "STUFFING";
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn parse_arbitrary_bytes() {
83        let bytes = [TAG, 4, 0x00, 0xFF, 0xAB, 0x7E];
84        let d = StuffingDescriptor::parse(&bytes).unwrap();
85        assert_eq!(d.stuffing_bytes, &[0x00, 0xFF, 0xAB, 0x7E]);
86    }
87
88    #[test]
89    fn parse_empty_body_valid() {
90        let bytes = [TAG, 0];
91        let d = StuffingDescriptor::parse(&bytes).unwrap();
92        assert!(d.stuffing_bytes.is_empty());
93    }
94
95    #[test]
96    fn parse_rejects_wrong_tag() {
97        assert!(matches!(
98            StuffingDescriptor::parse(&[0x43, 0]).unwrap_err(),
99            Error::InvalidDescriptor { tag: 0x43, .. }
100        ));
101    }
102
103    #[test]
104    fn parse_rejects_short_buffer() {
105        // declared length 4 but only 2 body bytes present
106        let bytes = [TAG, 4, 0x00, 0xFF];
107        assert!(matches!(
108            StuffingDescriptor::parse(&bytes).unwrap_err(),
109            Error::BufferTooShort { .. }
110        ));
111    }
112
113    #[test]
114    fn serialize_round_trip() {
115        let d = StuffingDescriptor {
116            stuffing_bytes: &[0xDE, 0xAD, 0xBE, 0xEF],
117        };
118        let mut buf = vec![0u8; d.serialized_len()];
119        d.serialize_into(&mut buf).unwrap();
120        assert_eq!(StuffingDescriptor::parse(&buf).unwrap(), d);
121    }
122
123    #[test]
124    fn serialize_rejects_small_buffer() {
125        let d = StuffingDescriptor {
126            stuffing_bytes: &[0x01, 0x02],
127        };
128        let mut tiny = [0u8; 3];
129        assert!(matches!(
130            d.serialize_into(&mut tiny).unwrap_err(),
131            Error::OutputBufferTooSmall { .. }
132        ));
133    }
134
135    #[test]
136    fn serialize_rejects_over_range_body() {
137        let big = vec![0u8; 256];
138        let d = StuffingDescriptor {
139            stuffing_bytes: &big,
140        };
141        let mut buf = vec![0u8; d.serialized_len()];
142        assert!(matches!(
143            d.serialize_into(&mut buf).unwrap_err(),
144            Error::InvalidDescriptor { tag: TAG, .. }
145        ));
146    }
147
148    #[cfg(feature = "serde")]
149    #[test]
150    fn serde_serialize_stable() {
151        // Borrowed-byte fields cannot deserialize from a JSON array (serde_json
152        // requires a borrowed-str for &[u8]); assert the Serialize half is
153        // stable and captures the payload, matching how the other borrowed
154        // descriptors (e.g. content_identifier) handle serde.
155        let d = StuffingDescriptor {
156            stuffing_bytes: &[0x11, 0x22, 0x33],
157        };
158        let json = serde_json::to_string(&d).unwrap();
159        assert!(json.contains("17") && json.contains("34") && json.contains("51"));
160        // Re-serializing an equal value yields identical JSON (no nondeterminism).
161        let d2 = StuffingDescriptor {
162            stuffing_bytes: &[0x11, 0x22, 0x33],
163        };
164        assert_eq!(json, serde_json::to_string(&d2).unwrap());
165    }
166}