1use crate::error::{Error, Result};
8use crate::traits::Descriptor;
9use dvb_common::{Parse, Serialize};
10
11pub const TAG: u8 = 0x62;
13pub const HEADER_LEN: usize = 2;
15pub const CODING_BYTE_LEN: usize = 1;
17pub const ENTRY_LEN: usize = 4;
19pub const CODING_TYPE_MASK: u8 = 0x03;
21pub const RESERVED_BITS_MASK: u8 = 0xFC;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub enum CodingType {
28 Undefined,
30 Satellite,
32 Cable,
34 Terrestrial,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
40#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
41pub struct FrequencyListDescriptor {
42 pub coding_type: CodingType,
44 pub centre_frequencies_bcd: Vec<[u8; 4]>,
46}
47
48impl FrequencyListDescriptor {
49 #[must_use]
52 pub fn centre_frequencies_be(&self) -> Vec<u32> {
53 self.centre_frequencies_bcd
54 .iter()
55 .map(|b| u32::from_be_bytes(*b))
56 .collect()
57 }
58}
59
60impl<'a> Parse<'a> for FrequencyListDescriptor {
61 type Error = crate::error::Error;
62 fn parse(bytes: &'a [u8]) -> Result<Self> {
63 if bytes.len() < HEADER_LEN {
64 return Err(Error::BufferTooShort {
65 need: HEADER_LEN,
66 have: bytes.len(),
67 what: "FrequencyListDescriptor header",
68 });
69 }
70
71 let tag = bytes[0];
72 if tag != TAG {
73 return Err(Error::InvalidDescriptor {
74 tag,
75 reason: "expected tag 0x62",
76 });
77 }
78
79 let body_length = bytes[1] as usize;
80
81 if body_length < CODING_BYTE_LEN {
82 return Err(Error::InvalidDescriptor {
83 tag: TAG,
84 reason: "body too short (need at least coding_type byte)",
85 });
86 }
87
88 if (body_length - CODING_BYTE_LEN) % ENTRY_LEN != 0 {
89 return Err(Error::InvalidDescriptor {
90 tag: TAG,
91 reason: "body length minus coding byte must be multiple of 4",
92 });
93 }
94
95 let body_start = HEADER_LEN;
96 let total_needed = body_start + body_length;
97 if bytes.len() < total_needed {
98 return Err(Error::BufferTooShort {
99 need: total_needed,
100 have: bytes.len(),
101 what: "FrequencyListDescriptor body",
102 });
103 }
104
105 let coding_byte = bytes[body_start];
106 let coding_type_value = coding_byte & CODING_TYPE_MASK;
109 let coding_type = match coding_type_value {
110 0b00 => CodingType::Undefined,
111 0b01 => CodingType::Satellite,
112 0b10 => CodingType::Cable,
113 _ => CodingType::Terrestrial,
114 };
115
116 let entry_count = (body_length - CODING_BYTE_LEN) / ENTRY_LEN;
117 let mut centre_frequencies_bcd = Vec::with_capacity(entry_count);
118
119 let mut offset = body_start + CODING_BYTE_LEN;
120 for _ in 0..entry_count {
121 let mut entry = [0u8; ENTRY_LEN];
122 entry.copy_from_slice(&bytes[offset..offset + ENTRY_LEN]);
123 centre_frequencies_bcd.push(entry);
124 offset += ENTRY_LEN;
125 }
126
127 Ok(FrequencyListDescriptor {
128 coding_type,
129 centre_frequencies_bcd,
130 })
131 }
132}
133
134impl Serialize for FrequencyListDescriptor {
135 type Error = crate::error::Error;
136 fn serialized_len(&self) -> usize {
137 HEADER_LEN + CODING_BYTE_LEN + self.centre_frequencies_bcd.len() * ENTRY_LEN
138 }
139
140 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
141 let need = self.serialized_len();
142 if buf.len() < need {
143 return Err(Error::OutputBufferTooSmall {
144 need,
145 have: buf.len(),
146 });
147 }
148
149 let coding_type_bits = match self.coding_type {
150 CodingType::Undefined => 0b00,
151 CodingType::Satellite => 0b01,
152 CodingType::Cable => 0b10,
153 CodingType::Terrestrial => 0b11,
154 };
155
156 let body_length = CODING_BYTE_LEN + self.centre_frequencies_bcd.len() * ENTRY_LEN;
157
158 buf[0] = TAG;
159 buf[1] = body_length as u8;
160 buf[HEADER_LEN] = RESERVED_BITS_MASK | coding_type_bits;
161
162 let mut offset = HEADER_LEN + CODING_BYTE_LEN;
163 for entry in &self.centre_frequencies_bcd {
164 buf[offset..offset + ENTRY_LEN].copy_from_slice(entry);
165 offset += ENTRY_LEN;
166 }
167
168 Ok(need)
169 }
170}
171
172impl<'a> Descriptor<'a> for FrequencyListDescriptor {
173 const TAG: u8 = TAG;
174
175 fn descriptor_length(&self) -> u8 {
176 (self.serialized_len() - HEADER_LEN) as u8
177 }
178}
179
180impl<'a> crate::traits::DescriptorDef<'a> for FrequencyListDescriptor {
181 const TAG: u8 = TAG;
182 const NAME: &'static str = "FREQUENCY_LIST";
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
191 fn parse_empty_entries_is_valid() {
192 let raw: Vec<u8> = vec![TAG, 0x01, 0xFC];
193 let desc = FrequencyListDescriptor::parse(&raw).unwrap();
194 assert!(desc.centre_frequencies_bcd.is_empty());
195 assert!(matches!(desc.coding_type, CodingType::Undefined));
196 }
197
198 #[test]
200 fn parse_extracts_coding_type_satellite() {
201 let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
202 let desc = FrequencyListDescriptor::parse(&raw).unwrap();
203 assert!(matches!(desc.coding_type, CodingType::Satellite));
204 }
205
206 #[test]
208 fn parse_extracts_coding_type_cable() {
209 let raw: Vec<u8> = vec![TAG, 0x01, 0xFE];
210 let desc = FrequencyListDescriptor::parse(&raw).unwrap();
211 assert!(matches!(desc.coding_type, CodingType::Cable));
212 }
213
214 #[test]
216 fn parse_extracts_coding_type_terrestrial() {
217 let raw: Vec<u8> = vec![TAG, 0x01, 0xFF];
218 let desc = FrequencyListDescriptor::parse(&raw).unwrap();
219 assert!(matches!(desc.coding_type, CodingType::Terrestrial));
220 }
221
222 #[test]
224 fn parse_extracts_multiple_frequency_entries() {
225 let raw: Vec<u8> = vec![
226 TAG, 0x09, 0xFD, 0x02, 0x75, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, ];
231 let desc = FrequencyListDescriptor::parse(&raw).unwrap();
232 assert_eq!(desc.centre_frequencies_bcd.len(), 2);
233 assert_eq!(desc.centre_frequencies_bcd[0], [0x02, 0x75, 0x00, 0x00]);
234 assert_eq!(desc.centre_frequencies_bcd[1], [0x03, 0x00, 0x00, 0x00]);
235 }
236
237 #[test]
239 fn parse_rejects_wrong_tag() {
240 let raw: Vec<u8> = vec![0x63, 0x01, 0xFC];
241 let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
242 assert!(
243 matches!(err, Error::InvalidDescriptor { tag: 0x63, .. }),
244 "expected InvalidDescriptor(tag=0x63), got {err:?}"
245 );
246 }
247
248 #[test]
250 fn parse_ignores_reserved_bits() {
251 let raw: Vec<u8> = vec![TAG, 0x01, 0x03];
253 let d = FrequencyListDescriptor::parse(&raw).unwrap();
254 assert_eq!(d.coding_type, CodingType::Terrestrial);
255 assert!(d.centre_frequencies_bcd.is_empty());
256 }
257
258 #[test]
260 fn parse_rejects_length_not_1_plus_multiple_of_4() {
261 let raw: Vec<u8> = vec![TAG, 0x03, 0xFC, 0x01, 0x02]; let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
263 assert!(matches!(err, Error::InvalidDescriptor { .. }));
264 }
265
266 #[test]
268 fn parse_rejects_truncated_buffer() {
269 let raw: &[u8] = &[TAG];
270 let err = FrequencyListDescriptor::parse(raw).unwrap_err();
271 assert!(matches!(err, Error::BufferTooShort { need: 2, .. }));
272 }
273
274 #[test]
276 fn serialize_round_trip_empty() {
277 let desc = FrequencyListDescriptor {
278 coding_type: CodingType::Satellite,
279 centre_frequencies_bcd: vec![],
280 };
281 let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
282 let mut buf = vec![0u8; desc.serialized_len()];
283 let written = desc.serialize_into(&mut buf).unwrap();
284 assert_eq!(written, raw.len());
285 assert_eq!(buf, raw);
286
287 let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
288 assert_eq!(desc.coding_type, reparsed.coding_type);
289 assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
290 }
291
292 #[test]
294 fn serialize_round_trip_many_entries() {
295 let desc = FrequencyListDescriptor {
296 coding_type: CodingType::Cable,
297 centre_frequencies_bcd: vec![
298 [0x02, 0x75, 0x00, 0x00],
299 [0x03, 0x00, 0x00, 0x00],
300 [0x01, 0x15, 0x50, 0x00],
301 [0x04, 0x90, 0x25, 0x00],
302 ],
303 };
304 let mut buf = vec![0u8; desc.serialized_len()];
305 desc.serialize_into(&mut buf).unwrap();
306 let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
307 assert_eq!(desc.coding_type, reparsed.coding_type);
308 assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
309 }
310}