Skip to main content

dvb_si/descriptors/
country_availability.rs

1//! Country Availability Descriptor — ETSI EN 300 468 §6.2.10 (tag 0x49).
2//!
3//! Table 30 (PDF p. 70). Carried in SDT/BAT descriptor loops. A flag byte
4//! (`country_availability_flag` MSB + 7 reserved bits) followed by a loop of
5//! 3-byte ISO 3166 country codes. When the flag is set, the service is
6//! intended for reception in the listed countries; when clear, in all
7//! countries EXCEPT those listed.
8
9use super::descriptor_body;
10use crate::error::{Error, Result};
11use crate::text::LangCode;
12use alloc::vec::Vec;
13use dvb_common::{Parse, Serialize};
14
15/// Descriptor tag for country_availability_descriptor.
16pub const TAG: u8 = 0x49;
17const HEADER_LEN: usize = 2;
18const FLAG_LEN: usize = 1;
19const COUNTRY_CODE_LEN: usize = 3;
20const MIN_BODY_LEN: usize = FLAG_LEN;
21/// Maximum body length expressible in the 8-bit `descriptor_length` field.
22const MAX_BODY_LEN: usize = u8::MAX as usize;
23/// country_availability_flag occupies bit 7 (MSB) of the flag byte.
24const AVAILABILITY_FLAG_MASK: u8 = 0x80;
25/// Lower 7 bits are reserved_future_use — emitted as 1s on serialize.
26const RESERVED_MASK: u8 = 0x7F;
27
28/// Country Availability Descriptor.
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize))]
31pub struct CountryAvailabilityDescriptor {
32    /// true = available in the listed countries; false = available everywhere
33    /// EXCEPT the listed countries.
34    pub country_availability_flag: bool,
35    /// ISO 3166 alpha-3 country codes in wire order.
36    pub country_codes: Vec<LangCode>,
37}
38
39impl<'a> Parse<'a> for CountryAvailabilityDescriptor {
40    type Error = crate::error::Error;
41    fn parse(bytes: &'a [u8]) -> Result<Self> {
42        let body = descriptor_body(
43            bytes,
44            TAG,
45            "CountryAvailabilityDescriptor",
46            "unexpected tag for country_availability_descriptor",
47        )?;
48        if body.len() < MIN_BODY_LEN {
49            return Err(Error::InvalidDescriptor {
50                tag: TAG,
51                reason: "country_availability_descriptor missing flag byte",
52            });
53        }
54        if (body.len() - FLAG_LEN) % COUNTRY_CODE_LEN != 0 {
55            return Err(Error::InvalidDescriptor {
56                tag: TAG,
57                reason: "country_code loop length must be a multiple of 3",
58            });
59        }
60        let flags = body[0];
61        let country_availability_flag = flags & AVAILABILITY_FLAG_MASK != 0;
62        let loop_body = &body[FLAG_LEN..];
63        let mut country_codes = Vec::with_capacity(loop_body.len() / COUNTRY_CODE_LEN);
64        for chunk in loop_body.chunks_exact(COUNTRY_CODE_LEN) {
65            country_codes.push(LangCode([chunk[0], chunk[1], chunk[2]]));
66        }
67        Ok(Self {
68            country_availability_flag,
69            country_codes,
70        })
71    }
72}
73
74impl Serialize for CountryAvailabilityDescriptor {
75    type Error = crate::error::Error;
76    fn serialized_len(&self) -> usize {
77        HEADER_LEN + FLAG_LEN + COUNTRY_CODE_LEN * self.country_codes.len()
78    }
79
80    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
81        let len = self.serialized_len();
82        if buf.len() < len {
83            return Err(Error::OutputBufferTooSmall {
84                need: len,
85                have: buf.len(),
86            });
87        }
88        let body_len = FLAG_LEN + COUNTRY_CODE_LEN * self.country_codes.len();
89        // 8-bit descriptor_length field: error rather than silently truncate.
90        if body_len > MAX_BODY_LEN {
91            return Err(Error::InvalidDescriptor {
92                tag: TAG,
93                reason: "country_availability_descriptor body exceeds 255 bytes",
94            });
95        }
96        buf[0] = TAG;
97        buf[1] = body_len as u8;
98        // reserved_future_use bits emitted as 1s (EN 300 468 §5.1).
99        let flag_bit = if self.country_availability_flag {
100            AVAILABILITY_FLAG_MASK
101        } else {
102            0
103        };
104        buf[HEADER_LEN] = flag_bit | RESERVED_MASK;
105        let mut pos = HEADER_LEN + FLAG_LEN;
106        for code in &self.country_codes {
107            buf[pos..pos + COUNTRY_CODE_LEN].copy_from_slice(&code.0);
108            pos += COUNTRY_CODE_LEN;
109        }
110        Ok(len)
111    }
112}
113impl<'a> crate::traits::DescriptorDef<'a> for CountryAvailabilityDescriptor {
114    const TAG: u8 = TAG;
115    const NAME: &'static str = "COUNTRY_AVAILABILITY";
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn parse_available_with_countries() {
124        // flag=1 (0x80) + reserved 1s ignored, two country codes
125        let bytes = [TAG, 7, 0xFF, b'G', b'B', b'R', b'F', b'R', b'A'];
126        let d = CountryAvailabilityDescriptor::parse(&bytes).unwrap();
127        assert!(d.country_availability_flag);
128        assert_eq!(d.country_codes, vec![LangCode(*b"GBR"), LangCode(*b"FRA")]);
129    }
130
131    #[test]
132    fn parse_flag_clear() {
133        let bytes = [TAG, 4, 0x7F, b'D', b'E', b'U'];
134        let d = CountryAvailabilityDescriptor::parse(&bytes).unwrap();
135        assert!(!d.country_availability_flag);
136        assert_eq!(d.country_codes, vec![LangCode(*b"DEU")]);
137    }
138
139    #[test]
140    fn parse_flag_only_no_countries() {
141        let bytes = [TAG, 1, 0x80];
142        let d = CountryAvailabilityDescriptor::parse(&bytes).unwrap();
143        assert!(d.country_availability_flag);
144        assert!(d.country_codes.is_empty());
145    }
146
147    #[test]
148    fn parse_rejects_wrong_tag() {
149        assert!(matches!(
150            CountryAvailabilityDescriptor::parse(&[0x4A, 1, 0x80]).unwrap_err(),
151            Error::InvalidDescriptor { tag: 0x4A, .. }
152        ));
153    }
154
155    #[test]
156    fn parse_rejects_short_buffer() {
157        // declares 7 body bytes, only 4 present
158        let bytes = [TAG, 7, 0x80, b'G', b'B'];
159        assert!(matches!(
160            CountryAvailabilityDescriptor::parse(&bytes).unwrap_err(),
161            Error::BufferTooShort { .. }
162        ));
163    }
164
165    #[test]
166    fn parse_rejects_loop_not_multiple_of_3() {
167        // 1 flag byte + 2 loop bytes — loop not a multiple of 3
168        let bytes = [TAG, 3, 0x80, b'G', b'B'];
169        assert!(matches!(
170            CountryAvailabilityDescriptor::parse(&bytes).unwrap_err(),
171            Error::InvalidDescriptor { tag: TAG, .. }
172        ));
173    }
174
175    #[test]
176    fn parse_rejects_zero_length() {
177        let bytes = [TAG, 0];
178        assert!(matches!(
179            CountryAvailabilityDescriptor::parse(&bytes).unwrap_err(),
180            Error::InvalidDescriptor { tag: TAG, .. }
181        ));
182    }
183
184    #[test]
185    fn serialize_round_trip() {
186        let d = CountryAvailabilityDescriptor {
187            country_availability_flag: true,
188            country_codes: vec![LangCode(*b"GBR"), LangCode(*b"IRL")],
189        };
190        let mut buf = vec![0u8; d.serialized_len()];
191        d.serialize_into(&mut buf).unwrap();
192        assert_eq!(CountryAvailabilityDescriptor::parse(&buf).unwrap(), d);
193    }
194
195    #[test]
196    fn serialize_emits_reserved_ones() {
197        let d = CountryAvailabilityDescriptor {
198            country_availability_flag: false,
199            country_codes: vec![],
200        };
201        let mut buf = vec![0u8; d.serialized_len()];
202        d.serialize_into(&mut buf).unwrap();
203        // flag clear, reserved bits all 1 -> 0x7F
204        assert_eq!(buf[HEADER_LEN], 0x7F);
205    }
206
207    #[cfg(feature = "serde")]
208    #[test]
209    fn serde_round_trip() {
210        let d = CountryAvailabilityDescriptor {
211            country_availability_flag: true,
212            country_codes: vec![LangCode(*b"FRA")],
213        };
214        let json = serde_json::to_string(&d).unwrap();
215        // Serialize-only: assert the emitted JSON re-parses (serialize-stable).
216        let _v: serde_json::Value = serde_json::from_str(&json).unwrap();
217    }
218}