Skip to main content

dvb_si/descriptors/
service_identifier.rs

1//! Service Identifier Descriptor — ETSI TS 102 809 §7.2, Table 39 (tag 0x71).
2//!
3//! Carried in the SDT/service loop to give a service a stable textual
4//! identifier. The body is a run of `textual_service_identifier_bytes`
5//! (ASCII), per ts_102_809_apps.md "Table 39 — Service identifier descriptor"
6//! (PDF p. 62).
7
8use crate::error::{Error, Result};
9use crate::traits::Descriptor;
10use dvb_common::{Parse, Serialize};
11
12/// Descriptor tag for service_identifier_descriptor.
13pub const TAG: u8 = 0x71;
14const HEADER_LEN: usize = 2;
15
16/// Service Identifier Descriptor.
17#[derive(Debug, Clone, PartialEq, Eq)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize))]
19#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
20pub struct ServiceIdentifierDescriptor<'a> {
21    /// Raw textual_service_identifier bytes (ASCII).
22    pub textual_service_identifier: &'a [u8],
23}
24
25impl<'a> Parse<'a> for ServiceIdentifierDescriptor<'a> {
26    type Error = crate::error::Error;
27    fn parse(bytes: &'a [u8]) -> Result<Self> {
28        if bytes.len() < HEADER_LEN {
29            return Err(Error::BufferTooShort {
30                need: HEADER_LEN,
31                have: bytes.len(),
32                what: "ServiceIdentifierDescriptor header",
33            });
34        }
35        if bytes[0] != TAG {
36            return Err(Error::InvalidDescriptor {
37                tag: bytes[0],
38                reason: "unexpected tag for service_identifier_descriptor",
39            });
40        }
41        let length = bytes[1] as usize;
42        let end = HEADER_LEN + length;
43        if bytes.len() < end {
44            return Err(Error::BufferTooShort {
45                need: end,
46                have: bytes.len(),
47                what: "ServiceIdentifierDescriptor body",
48            });
49        }
50        Ok(Self {
51            textual_service_identifier: &bytes[HEADER_LEN..end],
52        })
53    }
54}
55
56impl Serialize for ServiceIdentifierDescriptor<'_> {
57    type Error = crate::error::Error;
58    fn serialized_len(&self) -> usize {
59        HEADER_LEN + self.textual_service_identifier.len()
60    }
61
62    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
63        if self.textual_service_identifier.len() > u8::MAX as usize {
64            return Err(Error::InvalidDescriptor {
65                tag: TAG,
66                reason: "textual_service_identifier exceeds 255 bytes",
67            });
68        }
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        buf[0] = TAG;
77        buf[1] = self.descriptor_length();
78        buf[HEADER_LEN..len].copy_from_slice(self.textual_service_identifier);
79        Ok(len)
80    }
81}
82
83impl<'a> Descriptor<'a> for ServiceIdentifierDescriptor<'a> {
84    const TAG: u8 = TAG;
85    fn descriptor_length(&self) -> u8 {
86        self.textual_service_identifier.len() as u8
87    }
88}
89
90impl<'a> crate::traits::DescriptorDef<'a> for ServiceIdentifierDescriptor<'a> {
91    const TAG: u8 = TAG;
92    const NAME: &'static str = "SERVICE_IDENTIFIER";
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn parse_extracts_identifier_bytes() {
101        let bytes = [TAG, 6, b'B', b'B', b'C', b'O', b'N', b'E'];
102        let d = ServiceIdentifierDescriptor::parse(&bytes).unwrap();
103        assert_eq!(d.textual_service_identifier, b"BBCONE");
104    }
105
106    #[test]
107    fn parse_rejects_wrong_tag() {
108        assert!(matches!(
109            ServiceIdentifierDescriptor::parse(&[0x70, 1, 0]).unwrap_err(),
110            Error::InvalidDescriptor { tag: 0x70, .. }
111        ));
112    }
113
114    #[test]
115    fn parse_rejects_short_header() {
116        assert!(matches!(
117            ServiceIdentifierDescriptor::parse(&[TAG]).unwrap_err(),
118            Error::BufferTooShort { .. }
119        ));
120    }
121
122    #[test]
123    fn parse_rejects_length_overrunning_buffer() {
124        let bytes = [TAG, 5, 1, 2, 3];
125        assert!(matches!(
126            ServiceIdentifierDescriptor::parse(&bytes).unwrap_err(),
127            Error::BufferTooShort { .. }
128        ));
129    }
130
131    #[test]
132    fn empty_identifier_is_valid() {
133        let bytes = [TAG, 0];
134        let d = ServiceIdentifierDescriptor::parse(&bytes).unwrap();
135        assert!(d.textual_service_identifier.is_empty());
136    }
137
138    #[test]
139    fn serialize_round_trip() {
140        let d = ServiceIdentifierDescriptor {
141            textual_service_identifier: b"CH4-HD",
142        };
143        let mut buf = vec![0u8; d.serialized_len()];
144        d.serialize_into(&mut buf).unwrap();
145        assert_eq!(ServiceIdentifierDescriptor::parse(&buf).unwrap(), d);
146    }
147
148    #[test]
149    fn serialize_rejects_too_small_buffer() {
150        let d = ServiceIdentifierDescriptor {
151            textual_service_identifier: b"test",
152        };
153        let mut buf = vec![0u8; 1];
154        assert!(matches!(
155            d.serialize_into(&mut buf).unwrap_err(),
156            Error::OutputBufferTooSmall { .. }
157        ));
158    }
159
160    #[cfg(feature = "serde")]
161    #[test]
162    fn serde_serializes_to_stable_json() {
163        // Borrowed `&[u8]` cannot deserialize from a JSON number array (serde
164        // has no JSON byte type), so we assert the Serialize impl is wired and
165        // emits stable, re-parseable JSON rather than attempting a borrow
166        // round-trip through JSON.
167        let d = ServiceIdentifierDescriptor {
168            textual_service_identifier: b"ITV1",
169        };
170        let j = serde_json::to_string(&d).unwrap();
171        // Valid, re-parseable JSON (key order is map-defined, so we do not
172        // assert byte-for-byte string stability).
173        let _v: serde_json::Value = serde_json::from_str(&j).unwrap();
174        assert!(j.contains("textual_service_identifier"));
175    }
176}