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