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