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