Skip to main content

dvb_si/descriptors/
data_broadcast_id.rs

1//! Data Broadcast Id Descriptor — ETSI EN 300 468 §6.2.13 (tag 0x66).
2//!
3//! Table 32 (PDF p. 72). Identifies the data broadcast specification used by a
4//! data component, plus a raw `id_selector_byte` tail whose interpretation
5//! depends on the `data_broadcast_id` (see ETSI TS 101 162).
6
7use crate::error::{Error, Result};
8use crate::traits::Descriptor;
9use dvb_common::{Parse, Serialize};
10
11/// Descriptor tag for data_broadcast_id_descriptor.
12pub const TAG: u8 = 0x66;
13const HEADER_LEN: usize = 2;
14/// Fixed prefix length: the 16-bit data_broadcast_id (EN 300 468 Table 32).
15const ID_LEN: usize = 2;
16
17/// Data Broadcast Id Descriptor (tag 0x66).
18#[derive(Debug, Clone, PartialEq, Eq)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20pub struct DataBroadcastIdDescriptor<'a> {
21    /// 16-bit data_broadcast_id (ETSI TS 101 162 registration).
22    pub data_broadcast_id: u16,
23    /// Raw id_selector_byte tail — interpretation depends on data_broadcast_id.
24    #[cfg_attr(feature = "serde", serde(borrow))]
25    pub id_selector: &'a [u8],
26}
27
28impl<'a> Parse<'a> for DataBroadcastIdDescriptor<'a> {
29    type Error = crate::error::Error;
30    fn parse(bytes: &'a [u8]) -> Result<Self> {
31        if bytes.len() < HEADER_LEN {
32            return Err(Error::BufferTooShort {
33                need: HEADER_LEN,
34                have: bytes.len(),
35                what: "DataBroadcastIdDescriptor header",
36            });
37        }
38        if bytes[0] != TAG {
39            return Err(Error::InvalidDescriptor {
40                tag: bytes[0],
41                reason: "unexpected tag for data_broadcast_id_descriptor",
42            });
43        }
44        let length = bytes[1] as usize;
45        let end = HEADER_LEN + length;
46        if bytes.len() < end {
47            return Err(Error::BufferTooShort {
48                need: end,
49                have: bytes.len(),
50                what: "DataBroadcastIdDescriptor body",
51            });
52        }
53        if length < ID_LEN {
54            return Err(Error::InvalidDescriptor {
55                tag: TAG,
56                reason: "data_broadcast_id_descriptor body shorter than 2 bytes",
57            });
58        }
59        let data_broadcast_id = u16::from_be_bytes([bytes[HEADER_LEN], bytes[HEADER_LEN + 1]]);
60        let id_selector = &bytes[HEADER_LEN + ID_LEN..end];
61        Ok(Self {
62            data_broadcast_id,
63            id_selector,
64        })
65    }
66}
67
68impl Serialize for DataBroadcastIdDescriptor<'_> {
69    type Error = crate::error::Error;
70    fn serialized_len(&self) -> usize {
71        HEADER_LEN + ID_LEN + self.id_selector.len()
72    }
73
74    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
75        let len = self.serialized_len();
76        let body = ID_LEN + self.id_selector.len();
77        if body > u8::MAX as usize {
78            return Err(Error::InvalidDescriptor {
79                tag: TAG,
80                reason: "data_broadcast_id_descriptor body exceeds 255 bytes",
81            });
82        }
83        if buf.len() < len {
84            return Err(Error::OutputBufferTooSmall {
85                need: len,
86                have: buf.len(),
87            });
88        }
89        buf[0] = TAG;
90        buf[1] = body as u8;
91        buf[HEADER_LEN..HEADER_LEN + ID_LEN].copy_from_slice(&self.data_broadcast_id.to_be_bytes());
92        let sel_start = HEADER_LEN + ID_LEN;
93        buf[sel_start..sel_start + self.id_selector.len()].copy_from_slice(self.id_selector);
94        Ok(len)
95    }
96}
97
98impl<'a> Descriptor<'a> for DataBroadcastIdDescriptor<'a> {
99    const TAG: u8 = TAG;
100    fn descriptor_length(&self) -> u8 {
101        (ID_LEN + self.id_selector.len()) as u8
102    }
103}
104
105impl<'a> crate::traits::DescriptorDef<'a> for DataBroadcastIdDescriptor<'a> {
106    const TAG: u8 = TAG;
107    const NAME: &'static str = "DATA_BROADCAST_ID";
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn parse_extracts_id_and_selector() {
116        let bytes = [TAG, 0x05, 0x00, 0x0B, 0xAA, 0xBB, 0xCC];
117        let d = DataBroadcastIdDescriptor::parse(&bytes).unwrap();
118        assert_eq!(d.data_broadcast_id, 0x000B);
119        assert_eq!(d.id_selector, &[0xAA, 0xBB, 0xCC]);
120    }
121
122    #[test]
123    fn parse_accepts_empty_selector() {
124        let bytes = [TAG, 0x02, 0x00, 0x0A];
125        let d = DataBroadcastIdDescriptor::parse(&bytes).unwrap();
126        assert_eq!(d.data_broadcast_id, 0x000A);
127        assert!(d.id_selector.is_empty());
128    }
129
130    #[test]
131    fn parse_rejects_wrong_tag() {
132        let err = DataBroadcastIdDescriptor::parse(&[0x65, 0x02, 0x00, 0x0A]).unwrap_err();
133        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x65, .. }));
134    }
135
136    #[test]
137    fn parse_rejects_short_buffer() {
138        let err = DataBroadcastIdDescriptor::parse(&[TAG]).unwrap_err();
139        assert!(matches!(err, Error::BufferTooShort { .. }));
140    }
141
142    #[test]
143    fn parse_rejects_body_too_short() {
144        // length=1: not even the 16-bit id fits.
145        let err = DataBroadcastIdDescriptor::parse(&[TAG, 0x01, 0x00]).unwrap_err();
146        assert!(matches!(err, Error::InvalidDescriptor { .. }));
147    }
148
149    #[test]
150    fn parse_rejects_length_overrun() {
151        // length=5 but only 3 payload bytes available.
152        let err = DataBroadcastIdDescriptor::parse(&[TAG, 0x05, 0x00, 0x0B, 0xAA]).unwrap_err();
153        assert!(matches!(err, Error::BufferTooShort { .. }));
154    }
155
156    #[test]
157    fn serialize_round_trip() {
158        let d = DataBroadcastIdDescriptor {
159            data_broadcast_id: 0x0123,
160            id_selector: &[0xDE, 0xAD, 0xBE, 0xEF],
161        };
162        let mut buf = vec![0u8; d.serialized_len()];
163        d.serialize_into(&mut buf).unwrap();
164        let re = DataBroadcastIdDescriptor::parse(&buf).unwrap();
165        assert_eq!(d, re);
166    }
167
168    #[test]
169    fn serialize_rejects_too_small_buffer() {
170        let d = DataBroadcastIdDescriptor {
171            data_broadcast_id: 0x0001,
172            id_selector: &[0x01],
173        };
174        let mut tiny = [0u8; 2];
175        let err = d.serialize_into(&mut tiny).unwrap_err();
176        assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
177    }
178
179    #[test]
180    fn serialize_rejects_over_range_body() {
181        // 254 selector bytes + 2 id bytes = 256 > 255.
182        let sel = vec![0u8; 254];
183        let d = DataBroadcastIdDescriptor {
184            data_broadcast_id: 0x0001,
185            id_selector: &sel,
186        };
187        let mut buf = vec![0u8; d.serialized_len()];
188        let err = d.serialize_into(&mut buf).unwrap_err();
189        assert!(matches!(err, Error::InvalidDescriptor { tag: TAG, .. }));
190    }
191
192    #[cfg(feature = "serde")]
193    #[test]
194    fn serde_serialize_is_stable() {
195        // Borrowed `&[u8]` cannot be deserialized from a JSON array by
196        // serde_json; matching the borrowed-bytes descriptors in this crate we
197        // exercise the serialize path and assert it is deterministic.
198        let d = DataBroadcastIdDescriptor {
199            data_broadcast_id: 0x000B,
200            id_selector: &[0x01, 0x02],
201        };
202        let json = serde_json::to_string(&d).unwrap();
203        assert_eq!(json, serde_json::to_string(&d.clone()).unwrap());
204    }
205}