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