Skip to main content

dvb_si/tables/
unt.rs

1//! Update Notification Table — ETSI TS 102 006 v1.4.1 §9.4.
2//!
3//! The UNT delivers software-update instructions for DVB receivers. It is
4//! carried on a PID that is **signalled** — there is no fixed PID. The PMT
5//! ES_info loop for the update data carousel contains a
6//! `data_broadcast_id_descriptor` (tag 0x66) with `data_broadcast_id = 0x000A`;
7//! the associated elementary PID is the one carrying UNT sections.
8//!
9//! The platform loop is unfolded into [`UntPlatform`] entries (Tables 11/15/17/18,
10//! §9.4.2.2–9.4.2.4). The `compatibilityDescriptor()` block is typed as
11//! [`CompatibilityDescriptor`] (ISO/IEC 13818-6 groupInfo form — NOT a standard
12//! SI tag/length descriptor).
13
14use crate::compatibility::CompatibilityDescriptor;
15use crate::descriptors::DescriptorLoop;
16use crate::error::{Error, Result};
17use alloc::vec::Vec;
18use dvb_common::{Parse, Serialize};
19
20/// `table_id` for the Update Notification Table.
21pub const TABLE_ID: u8 = 0x4B;
22
23/// Well-known PID for UNT: **none** — the UNT has no fixed PID.
24pub const PID: u16 = 0x0000;
25
26/// Action type coding — ETSI TS 102 006 §9.4.2 Table 12.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize))]
29#[non_exhaustive]
30pub enum UntActionType {
31    /// 0x00 — reserved.
32    Reserved,
33    /// 0x01 — System Software Update.
34    SystemSoftwareUpdate,
35    /// 0x02..=0x7F — DVB reserved for future use.
36    DvbReserved(u8),
37    /// 0x80..=0xFF — user defined.
38    UserDefined(u8),
39}
40
41impl UntActionType {
42    #[must_use]
43    /// Decode from the wire value.  Every value maps (lossless).
44    pub fn from_u8(v: u8) -> Self {
45        match v {
46            0x00 => Self::Reserved,
47            0x01 => Self::SystemSoftwareUpdate,
48            v if v < 0x80 => Self::DvbReserved(v),
49            _ => Self::UserDefined(v),
50        }
51    }
52
53    #[must_use]
54    /// Encode to the wire value.  Inverse of `from_u8` / `from_u16`.
55    pub fn to_u8(self) -> u8 {
56        match self {
57            Self::Reserved => 0x00,
58            Self::SystemSoftwareUpdate => 0x01,
59            Self::DvbReserved(v) | Self::UserDefined(v) => v,
60        }
61    }
62
63    #[must_use]
64    /// Human-readable spec display name.
65    pub fn name(self) -> &'static str {
66        match self {
67            Self::Reserved => "Reserved",
68            Self::SystemSoftwareUpdate => "System Software Update",
69            Self::DvbReserved(_) => "DVB Reserved",
70            Self::UserDefined(_) => "User Defined",
71        }
72    }
73}
74dvb_common::impl_spec_display!(UntActionType, DvbReserved, UserDefined);
75
76const HEADER_LEN: usize = 3;
77const FIXED_BODY_LEN: usize = 9;
78const COMMON_DESC_LEN_FIELD: usize = 2;
79const CRC_LEN: usize = 4;
80const MIN_SECTION_LEN: usize = HEADER_LEN + FIXED_BODY_LEN + COMMON_DESC_LEN_FIELD + CRC_LEN;
81
82const OFFSET_ACTION_TYPE: usize = HEADER_LEN;
83const OFFSET_OUI_HASH: usize = HEADER_LEN + 1;
84const OFFSET_FLAGS: usize = HEADER_LEN + 2;
85const OFFSET_SECTION_NUMBER: usize = HEADER_LEN + 3;
86const OFFSET_LAST_SECTION_NUMBER: usize = HEADER_LEN + 4;
87const OFFSET_OUI: usize = HEADER_LEN + 5;
88const OFFSET_PROCESSING_ORDER: usize = HEADER_LEN + 8;
89const OFFSET_COMMON_DESC_LEN: usize = HEADER_LEN + FIXED_BODY_LEN;
90
91const VERSION_NUMBER_MASK: u8 = 0x3E;
92const VERSION_NUMBER_SHIFT: u8 = 1;
93const CURRENT_NEXT_MASK: u8 = 0x01;
94const LENGTH_HIGH_NIBBLE_MASK: u8 = 0x0F;
95const FLAGS_RESERVED_BITS: u8 = 0xC0;
96const RESERVED_NIBBLE: u8 = 0xF0;
97
98const PLATFORM_LOOP_LEN_FIELD: usize = 2;
99const DESC_LOOP_LEN_FIELD: usize = 2;
100
101/// A single platform entry in the UNT platform loop
102/// (Tables 11/15/17/18, §9.4.2.2–9.4.2.4).
103///
104/// Each entry consists of a `compatibilityDescriptor()` block (typed as
105/// [`CompatibilityDescriptor`] — ISO/IEC 13818-6 groupInfo structure, not a
106/// standard SI descriptor), followed by a `platform_loop_length` field and
107/// target/operational descriptor-loop pairs.
108#[derive(Debug, Clone, PartialEq, Eq)]
109#[cfg_attr(feature = "serde", derive(serde::Serialize))]
110pub struct UntPlatform<'a> {
111    /// `compatibilityDescriptor()` — TS 102 006 Table 15 / ISO/IEC 13818-6.
112    pub compatibility_descriptor: CompatibilityDescriptor<'a>,
113    /// N pairs of (target_descriptor_loop, operational_descriptor_loop) per
114    /// TS 102 006 Table 11.
115    pub target_operational_pairs: Vec<(DescriptorLoop<'a>, DescriptorLoop<'a>)>,
116}
117
118fn unt_platform_serialized_len(p: &UntPlatform) -> usize {
119    p.compatibility_descriptor.serialized_len()
120        + PLATFORM_LOOP_LEN_FIELD
121        + p.target_operational_pairs
122            .iter()
123            .map(|(t, o)| DESC_LOOP_LEN_FIELD + t.len() + DESC_LOOP_LEN_FIELD + o.len())
124            .sum::<usize>()
125}
126
127/// Update Notification Table (UNT), ETSI TS 102 006 v1.4.1 §9.4, Table 11.
128///
129/// The platform loop is unfolded into typed [`UntPlatform`] entries.
130/// The `compatibilityDescriptor()` within each entry is typed as
131/// [`CompatibilityDescriptor`] (ISO/IEC 13818-6 groupInfo form — not a
132/// standard SI tag/length descriptor).
133#[derive(Debug, Clone, PartialEq, Eq)]
134#[cfg_attr(feature = "serde", derive(serde::Serialize))]
135#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
136pub struct UntSection<'a> {
137    /// Action type (Table 12): 0x01 = System Software Update, 0x80–0xFF user defined.
138    pub action_type: UntActionType,
139    /// OUI hash: XOR of the three OUI bytes.
140    pub oui_hash: u8,
141    /// 5-bit version_number of this sub-table.
142    pub version_number: u8,
143    /// `current_next_indicator`: `true` means currently applicable.
144    pub current_next_indicator: bool,
145    /// Index of this section within the sub-table.
146    pub section_number: u8,
147    /// Index of the last section in the sub-table.
148    pub last_section_number: u8,
149    /// 24-bit IEEE OUI (low 24 bits of u32).
150    pub oui: u32,
151    /// Processing order (Table 13).
152    pub processing_order: u8,
153    /// Body of `common_descriptor_loop()` — the bytes AFTER the 12-bit length
154    /// field.
155    pub common_descriptors: DescriptorLoop<'a>,
156    /// Platform entries — unfolded per §9.4.2.2–9.4.2.4.
157    pub platforms: Vec<UntPlatform<'a>>,
158}
159
160impl<'a> Parse<'a> for UntSection<'a> {
161    type Error = crate::error::Error;
162
163    fn parse(bytes: &'a [u8]) -> Result<Self> {
164        if bytes.len() < MIN_SECTION_LEN {
165            return Err(Error::BufferTooShort {
166                need: MIN_SECTION_LEN,
167                have: bytes.len(),
168                what: "UntSection",
169            });
170        }
171        if bytes[0] != TABLE_ID {
172            return Err(Error::UnexpectedTableId {
173                table_id: bytes[0],
174                what: "UntSection",
175                expected: &[TABLE_ID],
176            });
177        }
178
179        let section_length =
180            (((bytes[1] & LENGTH_HIGH_NIBBLE_MASK) as usize) << 8) | bytes[2] as usize;
181        let total =
182            super::check_section_length(bytes.len(), HEADER_LEN, section_length, MIN_SECTION_LEN)?;
183
184        let action_type = UntActionType::from_u8(bytes[OFFSET_ACTION_TYPE]);
185        let oui_hash = bytes[OFFSET_OUI_HASH];
186        let flags_byte = bytes[OFFSET_FLAGS];
187        let version_number = (flags_byte & VERSION_NUMBER_MASK) >> VERSION_NUMBER_SHIFT;
188        let current_next_indicator = (flags_byte & CURRENT_NEXT_MASK) != 0;
189        let section_number = bytes[OFFSET_SECTION_NUMBER];
190        let last_section_number = bytes[OFFSET_LAST_SECTION_NUMBER];
191        let oui = ((bytes[OFFSET_OUI] as u32) << 16)
192            | ((bytes[OFFSET_OUI + 1] as u32) << 8)
193            | (bytes[OFFSET_OUI + 2] as u32);
194        let processing_order = bytes[OFFSET_PROCESSING_ORDER];
195
196        let cdl = (((bytes[OFFSET_COMMON_DESC_LEN] & LENGTH_HIGH_NIBBLE_MASK) as usize) << 8)
197            | bytes[OFFSET_COMMON_DESC_LEN + 1] as usize;
198        let common_desc_start = OFFSET_COMMON_DESC_LEN + COMMON_DESC_LEN_FIELD;
199        let common_desc_end = common_desc_start + cdl;
200        if common_desc_end > total - CRC_LEN {
201            return Err(Error::SectionLengthOverflow {
202                declared: cdl,
203                available: (total - CRC_LEN).saturating_sub(common_desc_start),
204            });
205        }
206        let common_descriptors = DescriptorLoop::new(&bytes[common_desc_start..common_desc_end]);
207
208        let payload_end = total - CRC_LEN;
209        let mut pos = common_desc_end;
210        let mut platforms = Vec::new();
211        while pos < payload_end {
212            if pos + crate::compatibility::COMPAT_DESC_LEN_FIELD > payload_end {
213                return Err(Error::BufferTooShort {
214                    need: pos + crate::compatibility::COMPAT_DESC_LEN_FIELD,
215                    have: payload_end,
216                    what: "UntSection compatibilityDescriptorLength",
217                });
218            }
219            let compat_desc_len = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]) as usize;
220            let compat_total = crate::compatibility::COMPAT_DESC_LEN_FIELD + compat_desc_len;
221            if pos + compat_total > payload_end {
222                return Err(Error::SectionLengthOverflow {
223                    declared: compat_desc_len,
224                    available: payload_end
225                        .saturating_sub(pos + crate::compatibility::COMPAT_DESC_LEN_FIELD),
226                });
227            }
228            let compatibility_descriptor =
229                CompatibilityDescriptor::parse(&bytes[pos..pos + compat_total])?;
230            pos += compat_total;
231
232            if pos + PLATFORM_LOOP_LEN_FIELD > payload_end {
233                return Err(Error::BufferTooShort {
234                    need: pos + PLATFORM_LOOP_LEN_FIELD,
235                    have: payload_end,
236                    what: "UntSection platform_loop_length",
237                });
238            }
239            let platform_loop_length = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]) as usize;
240            pos += PLATFORM_LOOP_LEN_FIELD;
241            let platform_end = pos + platform_loop_length;
242            if platform_end > payload_end {
243                return Err(Error::SectionLengthOverflow {
244                    declared: platform_loop_length,
245                    available: payload_end.saturating_sub(pos),
246                });
247            }
248
249            let mut target_operational_pairs = Vec::new();
250            while pos < platform_end {
251                if pos + DESC_LOOP_LEN_FIELD > platform_end {
252                    return Err(Error::BufferTooShort {
253                        need: pos + DESC_LOOP_LEN_FIELD,
254                        have: platform_end,
255                        what: "UntSection target_descriptor_loop length",
256                    });
257                }
258                let target_len = (((bytes[pos] & 0x0F) as usize) << 8) | bytes[pos + 1] as usize;
259                let target_start = pos + DESC_LOOP_LEN_FIELD;
260                let target_end = target_start + target_len;
261                if target_end > platform_end {
262                    return Err(Error::SectionLengthOverflow {
263                        declared: target_len,
264                        available: platform_end.saturating_sub(target_start),
265                    });
266                }
267                let target_descriptors = DescriptorLoop::new(&bytes[target_start..target_end]);
268                pos = target_end;
269
270                if pos + DESC_LOOP_LEN_FIELD > platform_end {
271                    return Err(Error::BufferTooShort {
272                        need: pos + DESC_LOOP_LEN_FIELD,
273                        have: platform_end,
274                        what: "UntSection operational_descriptor_loop length",
275                    });
276                }
277                let op_len = (((bytes[pos] & 0x0F) as usize) << 8) | bytes[pos + 1] as usize;
278                let op_start = pos + DESC_LOOP_LEN_FIELD;
279                let op_end = op_start + op_len;
280                if op_end > platform_end {
281                    return Err(Error::SectionLengthOverflow {
282                        declared: op_len,
283                        available: platform_end.saturating_sub(op_start),
284                    });
285                }
286                let operational_descriptors = DescriptorLoop::new(&bytes[op_start..op_end]);
287                pos = op_end;
288
289                target_operational_pairs.push((target_descriptors, operational_descriptors));
290            }
291            if pos != platform_end {
292                return Err(Error::SectionLengthOverflow {
293                    declared: platform_loop_length,
294                    available: pos.saturating_sub(platform_end - platform_loop_length),
295                });
296            }
297
298            platforms.push(UntPlatform {
299                compatibility_descriptor,
300                target_operational_pairs,
301            });
302        }
303
304        Ok(UntSection {
305            action_type,
306            oui_hash,
307            version_number,
308            current_next_indicator,
309            section_number,
310            last_section_number,
311            oui,
312            processing_order,
313            common_descriptors,
314            platforms,
315        })
316    }
317}
318
319impl Serialize for UntSection<'_> {
320    type Error = crate::error::Error;
321
322    fn serialized_len(&self) -> usize {
323        HEADER_LEN
324            + FIXED_BODY_LEN
325            + COMMON_DESC_LEN_FIELD
326            + self.common_descriptors.len()
327            + self
328                .platforms
329                .iter()
330                .map(unt_platform_serialized_len)
331                .sum::<usize>()
332            + CRC_LEN
333    }
334
335    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
336        let len = self.serialized_len();
337        if buf.len() < len {
338            return Err(Error::OutputBufferTooSmall {
339                need: len,
340                have: buf.len(),
341            });
342        }
343
344        let section_length = (len - HEADER_LEN) as u16;
345        if section_length > 0x0FFF {
346            return Err(Error::SectionLengthOverflow {
347                declared: section_length as usize,
348                available: 0x0FFF,
349            });
350        }
351        buf[0] = TABLE_ID;
352        buf[1] =
353            super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & LENGTH_HIGH_NIBBLE_MASK);
354        buf[2] = (section_length & 0xFF) as u8;
355
356        buf[OFFSET_ACTION_TYPE] = self.action_type.to_u8();
357        buf[OFFSET_OUI_HASH] = self.oui_hash;
358        buf[OFFSET_FLAGS] = FLAGS_RESERVED_BITS
359            | ((self.version_number & 0x1F) << VERSION_NUMBER_SHIFT)
360            | u8::from(self.current_next_indicator);
361        buf[OFFSET_SECTION_NUMBER] = self.section_number;
362        buf[OFFSET_LAST_SECTION_NUMBER] = self.last_section_number;
363        buf[OFFSET_OUI] = ((self.oui >> 16) & 0xFF) as u8;
364        buf[OFFSET_OUI + 1] = ((self.oui >> 8) & 0xFF) as u8;
365        buf[OFFSET_OUI + 2] = (self.oui & 0xFF) as u8;
366        buf[OFFSET_PROCESSING_ORDER] = self.processing_order;
367
368        let cdl = self.common_descriptors.len() as u16;
369        buf[OFFSET_COMMON_DESC_LEN] =
370            RESERVED_NIBBLE | ((cdl >> 8) as u8 & LENGTH_HIGH_NIBBLE_MASK);
371        buf[OFFSET_COMMON_DESC_LEN + 1] = (cdl & 0xFF) as u8;
372
373        let common_start = OFFSET_COMMON_DESC_LEN + COMMON_DESC_LEN_FIELD;
374        let common_end = common_start + self.common_descriptors.len();
375        buf[common_start..common_end].copy_from_slice(self.common_descriptors.raw());
376
377        let mut pos = common_end;
378        for platform in &self.platforms {
379            let written = platform
380                .compatibility_descriptor
381                .serialize_into(&mut buf[pos..])?;
382            pos += written;
383
384            let inner_len: usize = platform
385                .target_operational_pairs
386                .iter()
387                .map(|(t, o)| DESC_LOOP_LEN_FIELD + t.len() + DESC_LOOP_LEN_FIELD + o.len())
388                .sum();
389            buf[pos..pos + PLATFORM_LOOP_LEN_FIELD]
390                .copy_from_slice(&(inner_len as u16).to_be_bytes());
391            pos += PLATFORM_LOOP_LEN_FIELD;
392
393            for (target_descriptors, operational_descriptors) in &platform.target_operational_pairs
394            {
395                let tl = target_descriptors.len() as u16;
396                buf[pos] = RESERVED_NIBBLE | ((tl >> 8) as u8 & 0x0F);
397                buf[pos + 1] = (tl & 0xFF) as u8;
398                pos += DESC_LOOP_LEN_FIELD;
399                buf[pos..pos + target_descriptors.len()].copy_from_slice(target_descriptors.raw());
400                pos += target_descriptors.len();
401
402                let ol = operational_descriptors.len() as u16;
403                buf[pos] = RESERVED_NIBBLE | ((ol >> 8) as u8 & 0x0F);
404                buf[pos + 1] = (ol & 0xFF) as u8;
405                pos += DESC_LOOP_LEN_FIELD;
406                buf[pos..pos + operational_descriptors.len()]
407                    .copy_from_slice(operational_descriptors.raw());
408                pos += operational_descriptors.len();
409            }
410        }
411
412        let crc_pos = len - CRC_LEN;
413        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
414        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
415        Ok(len)
416    }
417}
418impl<'a> crate::traits::TableDef<'a> for UntSection<'a> {
419    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
420    const NAME: &'static str = "UPDATE_NOTIFICATION";
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    #[test]
428    fn parse_happy_path() {
429        let oui: u32 = 0x00_01_5A;
430        let oui_hash: u8 = 0x01 ^ 0x5A;
431        let common_descs: &[u8] = &[0x66, 0x04, 0x00, 0x0A, 0x00, 0x00];
432        let unt = UntSection {
433            action_type: UntActionType::SystemSoftwareUpdate,
434            oui_hash,
435            version_number: 7,
436            current_next_indicator: true,
437            section_number: 0,
438            last_section_number: 0,
439            oui,
440            processing_order: 0x00,
441            common_descriptors: DescriptorLoop::new(common_descs),
442            platforms: vec![UntPlatform {
443                compatibility_descriptor: CompatibilityDescriptor {
444                    descriptors: vec![],
445                },
446                target_operational_pairs: vec![(
447                    DescriptorLoop::new(&[]),
448                    DescriptorLoop::new(&[]),
449                )],
450            }],
451        };
452        let sl = unt.serialized_len();
453        let mut buf = vec![0u8; sl];
454        unt.serialize_into(&mut buf).unwrap();
455        let parsed = UntSection::parse(&buf).unwrap();
456        assert_eq!(parsed.action_type, UntActionType::SystemSoftwareUpdate);
457        assert_eq!(parsed.oui_hash, oui_hash);
458        assert_eq!(parsed.version_number, 7);
459        assert!(parsed.current_next_indicator);
460        assert_eq!(parsed.oui, oui);
461        assert_eq!(parsed.common_descriptors.raw(), common_descs);
462        assert_eq!(parsed.platforms.len(), 1);
463        assert!(parsed.platforms[0]
464            .compatibility_descriptor
465            .descriptors
466            .is_empty());
467    }
468
469    #[test]
470    fn parse_empty_platforms() {
471        let unt = UntSection {
472            action_type: UntActionType::SystemSoftwareUpdate,
473            oui_hash: 0x5B,
474            version_number: 1,
475            current_next_indicator: false,
476            section_number: 1,
477            last_section_number: 2,
478            oui: 0x00015A,
479            processing_order: 0x01,
480            common_descriptors: DescriptorLoop::new(&[]),
481            platforms: Vec::new(),
482        };
483        let mut buf = vec![0u8; unt.serialized_len()];
484        unt.serialize_into(&mut buf).unwrap();
485        let parsed = UntSection::parse(&buf).unwrap();
486        assert!(!parsed.current_next_indicator);
487        assert!(parsed.platforms.is_empty());
488    }
489
490    #[test]
491    fn byte_exact_round_trip() {
492        let target_desc: &[u8] = &[0x09, 0x01, 0xAA];
493        let op_desc: &[u8] = &[0x0A, 0x01, 0xBB];
494        let unt = UntSection {
495            action_type: UntActionType::SystemSoftwareUpdate,
496            oui_hash: 0x5B,
497            version_number: 15,
498            current_next_indicator: true,
499            section_number: 2,
500            last_section_number: 5,
501            oui: 0x00015A,
502            processing_order: 0x02,
503            common_descriptors: DescriptorLoop::new(&[0x66, 0x04, 0x00, 0x0A, 0x00, 0x00]),
504            platforms: vec![UntPlatform {
505                compatibility_descriptor: CompatibilityDescriptor {
506                    descriptors: vec![],
507                },
508                target_operational_pairs: vec![(
509                    DescriptorLoop::new(target_desc),
510                    DescriptorLoop::new(op_desc),
511                )],
512            }],
513        };
514        let mut buf = vec![0u8; unt.serialized_len()];
515        unt.serialize_into(&mut buf).unwrap();
516        let re = UntSection::parse(&buf).unwrap();
517        let mut buf2 = vec![0u8; re.serialized_len()];
518        re.serialize_into(&mut buf2).unwrap();
519        assert_eq!(buf, buf2, "byte-exact re-serialize");
520        let re = UntSection::parse(&buf).unwrap();
521        assert_eq!(re.platforms.len(), 1);
522        assert!(re.platforms[0]
523            .compatibility_descriptor
524            .descriptors
525            .is_empty());
526        assert_eq!(re.platforms[0].target_operational_pairs.len(), 1);
527        assert_eq!(
528            re.platforms[0].target_operational_pairs[0].0.raw(),
529            target_desc
530        );
531        assert_eq!(re.platforms[0].target_operational_pairs[0].1.raw(), op_desc);
532    }
533
534    #[test]
535    fn round_trip_platform_with_multiple_pairs() {
536        let t0: &[u8] = &[0x09, 0x01, 0xAA];
537        let o0: &[u8] = &[0x0A, 0x01, 0xBB];
538        let t1: &[u8] = &[0x01, 0x02, 0xCC, 0xDD];
539        let o1: &[u8] = &[];
540        let unt = UntSection {
541            action_type: UntActionType::SystemSoftwareUpdate,
542            oui_hash: 0x5B,
543            version_number: 15,
544            current_next_indicator: true,
545            section_number: 0,
546            last_section_number: 0,
547            oui: 0x00015A,
548            processing_order: 0x02,
549            common_descriptors: DescriptorLoop::new(&[]),
550            platforms: vec![UntPlatform {
551                compatibility_descriptor: CompatibilityDescriptor {
552                    descriptors: vec![],
553                },
554                target_operational_pairs: vec![
555                    (DescriptorLoop::new(t0), DescriptorLoop::new(o0)),
556                    (DescriptorLoop::new(t1), DescriptorLoop::new(o1)),
557                ],
558            }],
559        };
560        let mut buf = vec![0u8; unt.serialized_len()];
561        unt.serialize_into(&mut buf).unwrap();
562        let re = UntSection::parse(&buf).unwrap();
563        assert_eq!(re.platforms.len(), 1);
564        let pairs = &re.platforms[0].target_operational_pairs;
565        assert_eq!(pairs.len(), 2, "both pairs must survive the round-trip");
566        assert_eq!(pairs[0].0.raw(), t0);
567        assert_eq!(pairs[0].1.raw(), o0);
568        assert_eq!(pairs[1].0.raw(), t1);
569        assert_eq!(pairs[1].1.raw(), o1);
570        // serialize is deterministic.
571        let mut buf2 = vec![0u8; unt.serialized_len()];
572        unt.serialize_into(&mut buf2).unwrap();
573        assert_eq!(buf, buf2, "byte-exact re-serialize");
574    }
575
576    #[test]
577    fn round_trip_platform_with_nonempty_compat() {
578        // A platform carrying a non-empty compatibilityDescriptor() (one entry
579        // with a sub-descriptor) — the other UNT tests only exercise the empty
580        // form, so this pins the full compat block through UntSection framing.
581        use crate::compatibility::{
582            CompatibilityDescriptorEntry, DescriptorType, SpecifierType, SubDescriptor,
583            SubDescriptorType,
584        };
585        let unt = UntSection {
586            action_type: UntActionType::SystemSoftwareUpdate,
587            oui_hash: 0x5B,
588            version_number: 3,
589            current_next_indicator: true,
590            section_number: 0,
591            last_section_number: 0,
592            oui: 0x00015A,
593            processing_order: 0x00,
594            common_descriptors: DescriptorLoop::new(&[]),
595            platforms: vec![UntPlatform {
596                compatibility_descriptor: CompatibilityDescriptor {
597                    descriptors: vec![CompatibilityDescriptorEntry {
598                        descriptor_type: DescriptorType::SystemHardware,
599                        specifier_type: SpecifierType::IeeeOui,
600                        specifier_data: [0x00, 0x15, 0x0A],
601                        model: 0x1234,
602                        version: 0x0001,
603                        sub_descriptors: vec![SubDescriptor {
604                            sub_descriptor_type: SubDescriptorType::Unallocated(0x05),
605                            data: &[0xAA, 0xBB],
606                        }],
607                    }],
608                },
609                target_operational_pairs: vec![(
610                    DescriptorLoop::new(&[]),
611                    DescriptorLoop::new(&[]),
612                )],
613            }],
614        };
615        let mut buf = vec![0u8; unt.serialized_len()];
616        unt.serialize_into(&mut buf).unwrap();
617        let re = UntSection::parse(&buf).unwrap();
618        assert_eq!(re, unt);
619        let entry = &re.platforms[0].compatibility_descriptor.descriptors[0];
620        assert_eq!(entry.descriptor_type, DescriptorType::SystemHardware);
621        assert_eq!(entry.model, 0x1234);
622        assert_eq!(entry.sub_descriptors[0].data, &[0xAA, 0xBB]);
623        let mut buf2 = vec![0u8; unt.serialized_len()];
624        unt.serialize_into(&mut buf2).unwrap();
625        assert_eq!(buf, buf2, "byte-exact re-serialize");
626    }
627
628    #[test]
629    fn parse_rejects_wrong_table_id() {
630        let unt = UntSection {
631            action_type: UntActionType::SystemSoftwareUpdate,
632            oui_hash: 0x5B,
633            version_number: 0,
634            current_next_indicator: true,
635            section_number: 0,
636            last_section_number: 0,
637            oui: 0x00015A,
638            processing_order: 0x00,
639            common_descriptors: DescriptorLoop::new(&[]),
640            platforms: Vec::new(),
641        };
642        let mut buf = vec![0u8; unt.serialized_len()];
643        unt.serialize_into(&mut buf).unwrap();
644        buf[0] = 0x4A;
645        assert!(matches!(
646            UntSection::parse(&buf).unwrap_err(),
647            Error::UnexpectedTableId { table_id: 0x4A, .. }
648        ));
649    }
650
651    #[test]
652    fn parse_rejects_short_buffer() {
653        assert!(matches!(
654            UntSection::parse(&[TABLE_ID, 0x00]).unwrap_err(),
655            Error::BufferTooShort { .. }
656        ));
657    }
658
659    #[test]
660    fn serialize_rejects_small_output_buffer() {
661        let unt = UntSection {
662            action_type: UntActionType::SystemSoftwareUpdate,
663            oui_hash: 0x5B,
664            version_number: 0,
665            current_next_indicator: true,
666            section_number: 0,
667            last_section_number: 0,
668            oui: 0x00015A,
669            processing_order: 0x00,
670            common_descriptors: DescriptorLoop::new(&[]),
671            platforms: Vec::new(),
672        };
673        let mut buf = vec![0u8; unt.serialized_len() - 1];
674        assert!(matches!(
675            unt.serialize_into(&mut buf).unwrap_err(),
676            Error::OutputBufferTooSmall { .. }
677        ));
678    }
679
680    #[test]
681    fn parse_rejects_zero_section_length() {
682        let mut buf = vec![0u8; 64];
683        buf[0] = TABLE_ID;
684        buf[1] = 0xF0;
685        buf[2] = 0x00;
686        for b in &mut buf[3..] {
687            *b = 0xFF;
688        }
689        assert!(matches!(
690            UntSection::parse(&buf).unwrap_err(),
691            Error::SectionLengthOverflow { .. }
692        ));
693    }
694
695    #[test]
696    fn parse_handwritten_unt_no_platforms() {
697        let mut bytes: Vec<u8> = vec![
698            0x4B, 0xF0, 0x0F, 0x01, 0x5B, 0xC1, 0x00, 0x00, 0x00, 0x01, 0x5A, 0x00, 0xF0, 0x00,
699        ];
700        let crc = dvb_common::crc32_mpeg2::compute(&bytes);
701        bytes.extend_from_slice(&crc.to_be_bytes());
702        let unt = UntSection::parse(&bytes).unwrap();
703        assert_eq!(unt.action_type, UntActionType::SystemSoftwareUpdate);
704        assert_eq!(unt.oui, 0x00015A);
705        assert!(unt.current_next_indicator);
706        assert!(unt.platforms.is_empty());
707    }
708
709    #[test]
710    fn action_type_full_range_round_trip() {
711        for byte in 0u8..=0xFF {
712            let at = UntActionType::from_u8(byte);
713            assert_eq!(
714                at.to_u8(),
715                byte,
716                "UntActionType round-trip failed for {byte:#04x}"
717            );
718        }
719    }
720}