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