Skip to main content

dvb_si/descriptors/
service_availability.rs

1//! Service Availability Descriptor — ETSI EN 300 468 §6.2.36 (tag 0x72, Table 90, PDF p. 101).
2//!
3//! Carried inside the SDT. Body layout (Table 90):
4//! `availability_flag` (1 bit) + `reserved_future_use` (7 bits), then a
5//! `for (i=0;i<N;i++) { cell_id (16) }` loop listing the cells in which the
6//! service is (un)available. `availability_flag`=1 → service available in the
7//! listed cells; =0 → unavailable in the listed cells.
8
9use crate::error::{Error, Result};
10use crate::traits::Descriptor;
11use dvb_common::{Parse, Serialize};
12
13/// Descriptor tag for service_availability_descriptor.
14pub const TAG: u8 = 0x72;
15/// Length of the header (tag byte + length byte).
16pub const HEADER_LEN: usize = 2;
17/// Length of the flags byte (availability_flag + reserved).
18pub const FLAGS_LEN: usize = 1;
19/// Length of one cell_id entry.
20pub const CELL_ID_LEN: usize = 2;
21
22const AVAILABILITY_FLAG_MASK: u8 = 0b1000_0000;
23const RESERVED_MASK: u8 = 0b0111_1111;
24
25/// Service Availability Descriptor.
26#[derive(Debug, Clone, PartialEq, Eq)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize))]
28pub struct ServiceAvailabilityDescriptor {
29    /// `availability_flag`: true = available in listed cells, false = unavailable.
30    pub availability_flag: bool,
31    /// cell_id entries in wire order.
32    pub cell_ids: Vec<u16>,
33}
34
35impl<'a> Parse<'a> for ServiceAvailabilityDescriptor {
36    type Error = crate::error::Error;
37    fn parse(bytes: &'a [u8]) -> Result<Self> {
38        if bytes.len() < HEADER_LEN {
39            return Err(Error::BufferTooShort {
40                need: HEADER_LEN,
41                have: bytes.len(),
42                what: "ServiceAvailabilityDescriptor header",
43            });
44        }
45        if bytes[0] != TAG {
46            return Err(Error::InvalidDescriptor {
47                tag: bytes[0],
48                reason: "unexpected tag for service_availability_descriptor",
49            });
50        }
51        let length = bytes[1] as usize;
52        if length < FLAGS_LEN {
53            return Err(Error::InvalidDescriptor {
54                tag: TAG,
55                reason: "service_availability_descriptor body too short (need flags byte)",
56            });
57        }
58        if (length - FLAGS_LEN) % CELL_ID_LEN != 0 {
59            return Err(Error::InvalidDescriptor {
60                tag: TAG,
61                reason: "service_availability cell_id loop must be a multiple of 2 bytes",
62            });
63        }
64        let end = HEADER_LEN + length;
65        if bytes.len() < end {
66            return Err(Error::BufferTooShort {
67                need: end,
68                have: bytes.len(),
69                what: "ServiceAvailabilityDescriptor body",
70            });
71        }
72        let flags = bytes[HEADER_LEN];
73        // reserved_future_use (7 bits) ignored on parse (§5.1).
74        let availability_flag = flags & AVAILABILITY_FLAG_MASK != 0;
75        let count = (length - FLAGS_LEN) / CELL_ID_LEN;
76        let mut cell_ids = Vec::with_capacity(count);
77        let mut pos = HEADER_LEN + FLAGS_LEN;
78        for _ in 0..count {
79            cell_ids.push(u16::from_be_bytes([bytes[pos], bytes[pos + 1]]));
80            pos += CELL_ID_LEN;
81        }
82        Ok(Self {
83            availability_flag,
84            cell_ids,
85        })
86    }
87}
88
89impl Serialize for ServiceAvailabilityDescriptor {
90    type Error = crate::error::Error;
91    fn serialized_len(&self) -> usize {
92        HEADER_LEN + FLAGS_LEN + self.cell_ids.len() * CELL_ID_LEN
93    }
94
95    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
96        let body_len = FLAGS_LEN + self.cell_ids.len() * CELL_ID_LEN;
97        if body_len > u8::MAX as usize {
98            return Err(Error::InvalidDescriptor {
99                tag: TAG,
100                reason: "service_availability_descriptor body exceeds 255 bytes",
101            });
102        }
103        let len = self.serialized_len();
104        if buf.len() < len {
105            return Err(Error::OutputBufferTooSmall {
106                need: len,
107                have: buf.len(),
108            });
109        }
110        buf[0] = TAG;
111        buf[1] = body_len as u8;
112        // reserved 7 bits emitted as 1s (§5.1).
113        let mut flags = RESERVED_MASK;
114        if self.availability_flag {
115            flags |= AVAILABILITY_FLAG_MASK;
116        }
117        buf[HEADER_LEN] = flags;
118        let mut pos = HEADER_LEN + FLAGS_LEN;
119        for cid in &self.cell_ids {
120            buf[pos..pos + CELL_ID_LEN].copy_from_slice(&cid.to_be_bytes());
121            pos += CELL_ID_LEN;
122        }
123        Ok(len)
124    }
125}
126
127impl<'a> Descriptor<'a> for ServiceAvailabilityDescriptor {
128    const TAG: u8 = TAG;
129    fn descriptor_length(&self) -> u8 {
130        (FLAGS_LEN + self.cell_ids.len() * CELL_ID_LEN) as u8
131    }
132}
133
134impl<'a> crate::traits::DescriptorDef<'a> for ServiceAvailabilityDescriptor {
135    const TAG: u8 = TAG;
136    const NAME: &'static str = "SERVICE_AVAILABILITY";
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn parse_extracts_flag_and_cells() {
145        // flags=0x80 (available), two cell_ids 0x0001 and 0x0002.
146        let bytes = [TAG, 5, 0x80, 0x00, 0x01, 0x00, 0x02];
147        let d = ServiceAvailabilityDescriptor::parse(&bytes).unwrap();
148        assert!(d.availability_flag);
149        assert_eq!(d.cell_ids, vec![0x0001, 0x0002]);
150    }
151
152    #[test]
153    fn parse_flag_false() {
154        let bytes = [TAG, 1, 0x00];
155        let d = ServiceAvailabilityDescriptor::parse(&bytes).unwrap();
156        assert!(!d.availability_flag);
157        assert!(d.cell_ids.is_empty());
158    }
159
160    #[test]
161    fn parse_ignores_reserved_bits() {
162        // reserved bits set, availability clear: 0x7F.
163        let bytes = [TAG, 1, 0x7F];
164        let d = ServiceAvailabilityDescriptor::parse(&bytes).unwrap();
165        assert!(!d.availability_flag);
166    }
167
168    #[test]
169    fn parse_rejects_wrong_tag() {
170        assert!(matches!(
171            ServiceAvailabilityDescriptor::parse(&[0x73, 1, 0]).unwrap_err(),
172            Error::InvalidDescriptor { tag: 0x73, .. }
173        ));
174    }
175
176    #[test]
177    fn parse_rejects_zero_length_body() {
178        assert!(matches!(
179            ServiceAvailabilityDescriptor::parse(&[TAG, 0]).unwrap_err(),
180            Error::InvalidDescriptor { tag: TAG, .. }
181        ));
182    }
183
184    #[test]
185    fn parse_rejects_odd_cell_loop() {
186        // body = flags + 1 odd byte.
187        let bytes = [TAG, 2, 0x80, 0x00];
188        assert!(matches!(
189            ServiceAvailabilityDescriptor::parse(&bytes).unwrap_err(),
190            Error::InvalidDescriptor { tag: TAG, .. }
191        ));
192    }
193
194    #[test]
195    fn parse_rejects_truncated_buffer() {
196        let bytes = [TAG, 5, 0x80, 0x00, 0x01];
197        assert!(matches!(
198            ServiceAvailabilityDescriptor::parse(&bytes).unwrap_err(),
199            Error::BufferTooShort { .. }
200        ));
201    }
202
203    #[test]
204    fn serialize_round_trip() {
205        let d = ServiceAvailabilityDescriptor {
206            availability_flag: true,
207            cell_ids: vec![0x00AB, 0x00CD, 0x00EF],
208        };
209        let mut buf = vec![0u8; d.serialized_len()];
210        d.serialize_into(&mut buf).unwrap();
211        assert_eq!(ServiceAvailabilityDescriptor::parse(&buf).unwrap(), d);
212    }
213
214    #[test]
215    fn serialize_rejects_too_small_buffer() {
216        let d = ServiceAvailabilityDescriptor {
217            availability_flag: false,
218            cell_ids: vec![0x0001],
219        };
220        let mut buf = vec![0u8; 2];
221        assert!(matches!(
222            d.serialize_into(&mut buf).unwrap_err(),
223            Error::OutputBufferTooSmall { .. }
224        ));
225    }
226
227    #[test]
228    fn serialize_rejects_over_range_count() {
229        // 128 cell_ids = 256 body bytes + flags = 257 > 255.
230        let d = ServiceAvailabilityDescriptor {
231            availability_flag: true,
232            cell_ids: vec![0u16; 128],
233        };
234        let mut buf = vec![0u8; d.serialized_len()];
235        assert!(matches!(
236            d.serialize_into(&mut buf).unwrap_err(),
237            Error::InvalidDescriptor { tag: TAG, .. }
238        ));
239    }
240
241    #[cfg(feature = "serde")]
242    #[test]
243    fn serde_round_trip() {
244        let d = ServiceAvailabilityDescriptor {
245            availability_flag: true,
246            cell_ids: vec![0x0001, 0x0002],
247        };
248        let json = serde_json::to_string(&d).unwrap();
249        // Serialize-only: assert the emitted JSON re-parses (serialize-stable).
250        let _v: serde_json::Value = serde_json::from_str(&json).unwrap();
251    }
252}