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 @ 0x02..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 (b2, _) = bytes[pos..]
220                .split_first_chunk::<2>()
221                .ok_or(Error::BufferTooShort {
222                    need: pos + crate::compatibility::COMPAT_DESC_LEN_FIELD,
223                    have: payload_end,
224                    what: "UntSection compatibilityDescriptorLength",
225                })?;
226            let compat_desc_len = u16::from_be_bytes(*b2) as usize;
227            let compat_total = crate::compatibility::COMPAT_DESC_LEN_FIELD + compat_desc_len;
228            if pos + compat_total > payload_end {
229                return Err(Error::SectionLengthOverflow {
230                    declared: compat_desc_len,
231                    available: payload_end
232                        .saturating_sub(pos + crate::compatibility::COMPAT_DESC_LEN_FIELD),
233                });
234            }
235            let compatibility_descriptor =
236                CompatibilityDescriptor::parse(&bytes[pos..pos + compat_total])?;
237            pos += compat_total;
238
239            if pos + PLATFORM_LOOP_LEN_FIELD > payload_end {
240                return Err(Error::BufferTooShort {
241                    need: pos + PLATFORM_LOOP_LEN_FIELD,
242                    have: payload_end,
243                    what: "UntSection platform_loop_length",
244                });
245            }
246            let (b2, _) = bytes[pos..]
247                .split_first_chunk::<2>()
248                .ok_or(Error::BufferTooShort {
249                    need: pos + PLATFORM_LOOP_LEN_FIELD,
250                    have: payload_end,
251                    what: "UntSection platform_loop_length",
252                })?;
253            let platform_loop_length = u16::from_be_bytes(*b2) as usize;
254            pos += PLATFORM_LOOP_LEN_FIELD;
255            let platform_end = pos + platform_loop_length;
256            if platform_end > payload_end {
257                return Err(Error::SectionLengthOverflow {
258                    declared: platform_loop_length,
259                    available: payload_end.saturating_sub(pos),
260                });
261            }
262
263            let mut target_operational_pairs = Vec::new();
264            while pos < platform_end {
265                if pos + DESC_LOOP_LEN_FIELD > platform_end {
266                    return Err(Error::BufferTooShort {
267                        need: pos + DESC_LOOP_LEN_FIELD,
268                        have: platform_end,
269                        what: "UntSection target_descriptor_loop length",
270                    });
271                }
272                let target_len = (((bytes[pos] & 0x0F) as usize) << 8) | bytes[pos + 1] as usize;
273                let target_start = pos + DESC_LOOP_LEN_FIELD;
274                let target_end = target_start + target_len;
275                if target_end > platform_end {
276                    return Err(Error::SectionLengthOverflow {
277                        declared: target_len,
278                        available: platform_end.saturating_sub(target_start),
279                    });
280                }
281                let target_descriptors = DescriptorLoop::new(&bytes[target_start..target_end]);
282                pos = target_end;
283
284                if pos + DESC_LOOP_LEN_FIELD > platform_end {
285                    return Err(Error::BufferTooShort {
286                        need: pos + DESC_LOOP_LEN_FIELD,
287                        have: platform_end,
288                        what: "UntSection operational_descriptor_loop length",
289                    });
290                }
291                let op_len = (((bytes[pos] & 0x0F) as usize) << 8) | bytes[pos + 1] as usize;
292                let op_start = pos + DESC_LOOP_LEN_FIELD;
293                let op_end = op_start + op_len;
294                if op_end > platform_end {
295                    return Err(Error::SectionLengthOverflow {
296                        declared: op_len,
297                        available: platform_end.saturating_sub(op_start),
298                    });
299                }
300                let operational_descriptors = DescriptorLoop::new(&bytes[op_start..op_end]);
301                pos = op_end;
302
303                target_operational_pairs.push((target_descriptors, operational_descriptors));
304            }
305            if pos != platform_end {
306                return Err(Error::SectionLengthOverflow {
307                    declared: platform_loop_length,
308                    available: pos.saturating_sub(platform_end - platform_loop_length),
309                });
310            }
311
312            platforms.push(UntPlatform {
313                compatibility_descriptor,
314                target_operational_pairs,
315            });
316        }
317
318        Ok(UntSection {
319            action_type,
320            oui_hash,
321            version_number,
322            current_next_indicator,
323            section_number,
324            last_section_number,
325            oui,
326            processing_order,
327            common_descriptors,
328            platforms,
329        })
330    }
331}
332
333impl Serialize for UntSection<'_> {
334    type Error = crate::error::Error;
335
336    fn serialized_len(&self) -> usize {
337        HEADER_LEN
338            + FIXED_BODY_LEN
339            + COMMON_DESC_LEN_FIELD
340            + self.common_descriptors.len()
341            + self
342                .platforms
343                .iter()
344                .map(unt_platform_serialized_len)
345                .sum::<usize>()
346            + CRC_LEN
347    }
348
349    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
350        let len = self.serialized_len();
351        if buf.len() < len {
352            return Err(Error::OutputBufferTooSmall {
353                need: len,
354                have: buf.len(),
355            });
356        }
357
358        let section_length = (len - HEADER_LEN) as u16;
359        if section_length > 0x0FFF {
360            return Err(Error::SectionLengthOverflow {
361                declared: section_length as usize,
362                available: 0x0FFF,
363            });
364        }
365        buf[0] = TABLE_ID;
366        buf[1] =
367            super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & LENGTH_HIGH_NIBBLE_MASK);
368        buf[2] = (section_length & 0xFF) as u8;
369
370        buf[OFFSET_ACTION_TYPE] = self.action_type.to_u8();
371        buf[OFFSET_OUI_HASH] = self.oui_hash;
372        buf[OFFSET_FLAGS] = FLAGS_RESERVED_BITS
373            | ((self.version_number & 0x1F) << VERSION_NUMBER_SHIFT)
374            | u8::from(self.current_next_indicator);
375        buf[OFFSET_SECTION_NUMBER] = self.section_number;
376        buf[OFFSET_LAST_SECTION_NUMBER] = self.last_section_number;
377        buf[OFFSET_OUI] = ((self.oui >> 16) & 0xFF) as u8;
378        buf[OFFSET_OUI + 1] = ((self.oui >> 8) & 0xFF) as u8;
379        buf[OFFSET_OUI + 2] = (self.oui & 0xFF) as u8;
380        buf[OFFSET_PROCESSING_ORDER] = self.processing_order;
381
382        let cdl = self.common_descriptors.len() as u16;
383        buf[OFFSET_COMMON_DESC_LEN] =
384            RESERVED_NIBBLE | ((cdl >> 8) as u8 & LENGTH_HIGH_NIBBLE_MASK);
385        buf[OFFSET_COMMON_DESC_LEN + 1] = (cdl & 0xFF) as u8;
386
387        let common_start = OFFSET_COMMON_DESC_LEN + COMMON_DESC_LEN_FIELD;
388        let common_end = common_start + self.common_descriptors.len();
389        buf[common_start..common_end].copy_from_slice(self.common_descriptors.raw());
390
391        let mut pos = common_end;
392        for platform in &self.platforms {
393            let written = platform
394                .compatibility_descriptor
395                .serialize_into(&mut buf[pos..])?;
396            pos += written;
397
398            let inner_len: usize = platform
399                .target_operational_pairs
400                .iter()
401                .map(|(t, o)| DESC_LOOP_LEN_FIELD + t.len() + DESC_LOOP_LEN_FIELD + o.len())
402                .sum();
403            buf[pos..pos + PLATFORM_LOOP_LEN_FIELD]
404                .copy_from_slice(&(inner_len as u16).to_be_bytes());
405            pos += PLATFORM_LOOP_LEN_FIELD;
406
407            for (target_descriptors, operational_descriptors) in &platform.target_operational_pairs
408            {
409                let tl = target_descriptors.len() as u16;
410                buf[pos] = RESERVED_NIBBLE | ((tl >> 8) as u8 & 0x0F);
411                buf[pos + 1] = (tl & 0xFF) as u8;
412                pos += DESC_LOOP_LEN_FIELD;
413                buf[pos..pos + target_descriptors.len()].copy_from_slice(target_descriptors.raw());
414                pos += target_descriptors.len();
415
416                let ol = operational_descriptors.len() as u16;
417                buf[pos] = RESERVED_NIBBLE | ((ol >> 8) as u8 & 0x0F);
418                buf[pos + 1] = (ol & 0xFF) as u8;
419                pos += DESC_LOOP_LEN_FIELD;
420                buf[pos..pos + operational_descriptors.len()]
421                    .copy_from_slice(operational_descriptors.raw());
422                pos += operational_descriptors.len();
423            }
424        }
425
426        let crc_pos = len - CRC_LEN;
427        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
428        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
429        Ok(len)
430    }
431}
432impl<'a> crate::traits::TableDef<'a> for UntSection<'a> {
433    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
434    const NAME: &'static str = "UPDATE_NOTIFICATION";
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440
441    #[test]
442    fn parse_happy_path() {
443        let oui: u32 = 0x00_01_5A;
444        let oui_hash: u8 = 0x01 ^ 0x5A;
445        let common_descs: &[u8] = &[0x66, 0x04, 0x00, 0x0A, 0x00, 0x00];
446        let unt = UntSection {
447            action_type: UntActionType::SystemSoftwareUpdate,
448            oui_hash,
449            version_number: 7,
450            current_next_indicator: true,
451            section_number: 0,
452            last_section_number: 0,
453            oui,
454            processing_order: 0x00,
455            common_descriptors: DescriptorLoop::new(common_descs),
456            platforms: vec![UntPlatform {
457                compatibility_descriptor: CompatibilityDescriptor {
458                    descriptors: vec![],
459                },
460                target_operational_pairs: vec![(
461                    DescriptorLoop::new(&[]),
462                    DescriptorLoop::new(&[]),
463                )],
464            }],
465        };
466        let sl = unt.serialized_len();
467        let mut buf = vec![0u8; sl];
468        unt.serialize_into(&mut buf).unwrap();
469        let parsed = UntSection::parse(&buf).unwrap();
470        assert_eq!(parsed.action_type, UntActionType::SystemSoftwareUpdate);
471        assert_eq!(parsed.oui_hash, oui_hash);
472        assert_eq!(parsed.version_number, 7);
473        assert!(parsed.current_next_indicator);
474        assert_eq!(parsed.oui, oui);
475        assert_eq!(parsed.common_descriptors.raw(), common_descs);
476        assert_eq!(parsed.platforms.len(), 1);
477        assert!(parsed.platforms[0]
478            .compatibility_descriptor
479            .descriptors
480            .is_empty());
481    }
482
483    #[test]
484    fn parse_empty_platforms() {
485        let unt = UntSection {
486            action_type: UntActionType::SystemSoftwareUpdate,
487            oui_hash: 0x5B,
488            version_number: 1,
489            current_next_indicator: false,
490            section_number: 1,
491            last_section_number: 2,
492            oui: 0x00015A,
493            processing_order: 0x01,
494            common_descriptors: DescriptorLoop::new(&[]),
495            platforms: Vec::new(),
496        };
497        let mut buf = vec![0u8; unt.serialized_len()];
498        unt.serialize_into(&mut buf).unwrap();
499        let parsed = UntSection::parse(&buf).unwrap();
500        assert!(!parsed.current_next_indicator);
501        assert!(parsed.platforms.is_empty());
502    }
503
504    #[test]
505    fn byte_exact_round_trip() {
506        let target_desc: &[u8] = &[0x09, 0x01, 0xAA];
507        let op_desc: &[u8] = &[0x0A, 0x01, 0xBB];
508        let unt = UntSection {
509            action_type: UntActionType::SystemSoftwareUpdate,
510            oui_hash: 0x5B,
511            version_number: 15,
512            current_next_indicator: true,
513            section_number: 2,
514            last_section_number: 5,
515            oui: 0x00015A,
516            processing_order: 0x02,
517            common_descriptors: DescriptorLoop::new(&[0x66, 0x04, 0x00, 0x0A, 0x00, 0x00]),
518            platforms: vec![UntPlatform {
519                compatibility_descriptor: CompatibilityDescriptor {
520                    descriptors: vec![],
521                },
522                target_operational_pairs: vec![(
523                    DescriptorLoop::new(target_desc),
524                    DescriptorLoop::new(op_desc),
525                )],
526            }],
527        };
528        let mut buf = vec![0u8; unt.serialized_len()];
529        unt.serialize_into(&mut buf).unwrap();
530        let re = UntSection::parse(&buf).unwrap();
531        let mut buf2 = vec![0u8; re.serialized_len()];
532        re.serialize_into(&mut buf2).unwrap();
533        assert_eq!(buf, buf2, "byte-exact re-serialize");
534        let re = UntSection::parse(&buf).unwrap();
535        assert_eq!(re.platforms.len(), 1);
536        assert!(re.platforms[0]
537            .compatibility_descriptor
538            .descriptors
539            .is_empty());
540        assert_eq!(re.platforms[0].target_operational_pairs.len(), 1);
541        assert_eq!(
542            re.platforms[0].target_operational_pairs[0].0.raw(),
543            target_desc
544        );
545        assert_eq!(re.platforms[0].target_operational_pairs[0].1.raw(), op_desc);
546    }
547
548    #[test]
549    fn round_trip_platform_with_multiple_pairs() {
550        let t0: &[u8] = &[0x09, 0x01, 0xAA];
551        let o0: &[u8] = &[0x0A, 0x01, 0xBB];
552        let t1: &[u8] = &[0x01, 0x02, 0xCC, 0xDD];
553        let o1: &[u8] = &[];
554        let unt = UntSection {
555            action_type: UntActionType::SystemSoftwareUpdate,
556            oui_hash: 0x5B,
557            version_number: 15,
558            current_next_indicator: true,
559            section_number: 0,
560            last_section_number: 0,
561            oui: 0x00015A,
562            processing_order: 0x02,
563            common_descriptors: DescriptorLoop::new(&[]),
564            platforms: vec![UntPlatform {
565                compatibility_descriptor: CompatibilityDescriptor {
566                    descriptors: vec![],
567                },
568                target_operational_pairs: vec![
569                    (DescriptorLoop::new(t0), DescriptorLoop::new(o0)),
570                    (DescriptorLoop::new(t1), DescriptorLoop::new(o1)),
571                ],
572            }],
573        };
574        let mut buf = vec![0u8; unt.serialized_len()];
575        unt.serialize_into(&mut buf).unwrap();
576        let re = UntSection::parse(&buf).unwrap();
577        assert_eq!(re.platforms.len(), 1);
578        let pairs = &re.platforms[0].target_operational_pairs;
579        assert_eq!(pairs.len(), 2, "both pairs must survive the round-trip");
580        assert_eq!(pairs[0].0.raw(), t0);
581        assert_eq!(pairs[0].1.raw(), o0);
582        assert_eq!(pairs[1].0.raw(), t1);
583        assert_eq!(pairs[1].1.raw(), o1);
584        // serialize is deterministic.
585        let mut buf2 = vec![0u8; unt.serialized_len()];
586        unt.serialize_into(&mut buf2).unwrap();
587        assert_eq!(buf, buf2, "byte-exact re-serialize");
588    }
589
590    #[test]
591    fn round_trip_platform_with_nonempty_compat() {
592        // A platform carrying a non-empty compatibilityDescriptor() (one entry
593        // with a sub-descriptor) — the other UNT tests only exercise the empty
594        // form, so this pins the full compat block through UntSection framing.
595        use crate::compatibility::{
596            CompatibilityDescriptorEntry, DescriptorType, SpecifierType, SubDescriptor,
597            SubDescriptorType,
598        };
599        let unt = UntSection {
600            action_type: UntActionType::SystemSoftwareUpdate,
601            oui_hash: 0x5B,
602            version_number: 3,
603            current_next_indicator: true,
604            section_number: 0,
605            last_section_number: 0,
606            oui: 0x00015A,
607            processing_order: 0x00,
608            common_descriptors: DescriptorLoop::new(&[]),
609            platforms: vec![UntPlatform {
610                compatibility_descriptor: CompatibilityDescriptor {
611                    descriptors: vec![CompatibilityDescriptorEntry {
612                        descriptor_type: DescriptorType::SystemHardware,
613                        specifier_type: SpecifierType::IeeeOui,
614                        specifier_data: [0x00, 0x15, 0x0A],
615                        model: 0x1234,
616                        version: 0x0001,
617                        sub_descriptors: vec![SubDescriptor {
618                            sub_descriptor_type: SubDescriptorType::Unallocated(0x05),
619                            data: &[0xAA, 0xBB],
620                        }],
621                    }],
622                },
623                target_operational_pairs: vec![(
624                    DescriptorLoop::new(&[]),
625                    DescriptorLoop::new(&[]),
626                )],
627            }],
628        };
629        let mut buf = vec![0u8; unt.serialized_len()];
630        unt.serialize_into(&mut buf).unwrap();
631        let re = UntSection::parse(&buf).unwrap();
632        assert_eq!(re, unt);
633        let entry = &re.platforms[0].compatibility_descriptor.descriptors[0];
634        assert_eq!(entry.descriptor_type, DescriptorType::SystemHardware);
635        assert_eq!(entry.model, 0x1234);
636        assert_eq!(entry.sub_descriptors[0].data, &[0xAA, 0xBB]);
637        let mut buf2 = vec![0u8; unt.serialized_len()];
638        unt.serialize_into(&mut buf2).unwrap();
639        assert_eq!(buf, buf2, "byte-exact re-serialize");
640    }
641
642    #[test]
643    fn parse_rejects_wrong_table_id() {
644        let unt = UntSection {
645            action_type: UntActionType::SystemSoftwareUpdate,
646            oui_hash: 0x5B,
647            version_number: 0,
648            current_next_indicator: true,
649            section_number: 0,
650            last_section_number: 0,
651            oui: 0x00015A,
652            processing_order: 0x00,
653            common_descriptors: DescriptorLoop::new(&[]),
654            platforms: Vec::new(),
655        };
656        let mut buf = vec![0u8; unt.serialized_len()];
657        unt.serialize_into(&mut buf).unwrap();
658        buf[0] = 0x4A;
659        assert!(matches!(
660            UntSection::parse(&buf).unwrap_err(),
661            Error::UnexpectedTableId { table_id: 0x4A, .. }
662        ));
663    }
664
665    #[test]
666    fn parse_rejects_short_buffer() {
667        assert!(matches!(
668            UntSection::parse(&[TABLE_ID, 0x00]).unwrap_err(),
669            Error::BufferTooShort { .. }
670        ));
671    }
672
673    #[test]
674    fn serialize_rejects_small_output_buffer() {
675        let unt = UntSection {
676            action_type: UntActionType::SystemSoftwareUpdate,
677            oui_hash: 0x5B,
678            version_number: 0,
679            current_next_indicator: true,
680            section_number: 0,
681            last_section_number: 0,
682            oui: 0x00015A,
683            processing_order: 0x00,
684            common_descriptors: DescriptorLoop::new(&[]),
685            platforms: Vec::new(),
686        };
687        let mut buf = vec![0u8; unt.serialized_len() - 1];
688        assert!(matches!(
689            unt.serialize_into(&mut buf).unwrap_err(),
690            Error::OutputBufferTooSmall { .. }
691        ));
692    }
693
694    #[test]
695    fn parse_rejects_zero_section_length() {
696        let mut buf = vec![0u8; 64];
697        buf[0] = TABLE_ID;
698        buf[1] = 0xF0;
699        buf[2] = 0x00;
700        for b in &mut buf[3..] {
701            *b = 0xFF;
702        }
703        assert!(matches!(
704            UntSection::parse(&buf).unwrap_err(),
705            Error::SectionLengthOverflow { .. }
706        ));
707    }
708
709    #[test]
710    fn parse_handwritten_unt_no_platforms() {
711        let mut bytes: Vec<u8> = vec![
712            0x4B, 0xF0, 0x0F, 0x01, 0x5B, 0xC1, 0x00, 0x00, 0x00, 0x01, 0x5A, 0x00, 0xF0, 0x00,
713        ];
714        let crc = dvb_common::crc32_mpeg2::compute(&bytes);
715        bytes.extend_from_slice(&crc.to_be_bytes());
716        let unt = UntSection::parse(&bytes).unwrap();
717        assert_eq!(unt.action_type, UntActionType::SystemSoftwareUpdate);
718        assert_eq!(unt.oui, 0x00015A);
719        assert!(unt.current_next_indicator);
720        assert!(unt.platforms.is_empty());
721    }
722
723    #[test]
724    fn action_type_full_range_round_trip() {
725        for byte in 0u8..=0xFF {
726            let at = UntActionType::from_u8(byte);
727            assert_eq!(
728                at.to_u8(),
729                byte,
730                "UntActionType round-trip failed for {byte:#04x}"
731            );
732        }
733    }
734}