dvb-si 12.0.1

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! Mosaic Descriptor — ETSI EN 300 468 §6.2.21 (tag 0x51).
//!
//! Table 71 (PDF p. 91, verified against the vendored PDF). Describes a mosaic
//! service: a grid of elementary cells, each logical cell grouping one or more
//! elementary cells and optionally linking to a bouquet / service / event.
//!
//! Wire layout:
//!   header byte: mosaic_entry_point(1) | num_horizontal_cells(3)
//!                | reserved(1) | num_vertical_cells(3)
//!   for each logical cell:
//!     2 bytes: logical_cell_id(6) | reserved(7) | logical_cell_presentation_info(3)
//!     elementary_cell_field_length(8)
//!     elementary_cell_field_length × { reserved(2) | elementary_cell_id(6) }
//!     cell_linkage_info(8)
//!     conditional linkage payload (see CellLinkage)
//!
//! The first loop level (logical cells) is typed. Within each cell, the
//! elementary_cell_id list is exposed as `Vec<u8>` of 6-bit ids and the
//! linkage payload as the typed `CellLinkage` enum.

use super::descriptor_body;
use crate::error::{Error, Result};
use alloc::vec::Vec;
use broadcast_common::{Parse, Serialize};

/// Descriptor tag for mosaic_descriptor.
pub const TAG: u8 = 0x51;
const HEADER_LEN: usize = 2;
const GRID_HEADER_LEN: usize = 1;
const CELL_FIXED_LEN: usize = 3; // 2 id/presentation bytes + elementary_cell_field_length
/// Maximum body length expressible in the 8-bit `descriptor_length` field.
const MAX_BODY_LEN: usize = u8::MAX as usize;
const ENTRY_POINT_MASK: u8 = 0x80; // header bit 7
const ELEM_CELL_ID_MASK: u8 = 0x3F; // low 6 bits
const ELEM_RESERVED_SHIFT: u8 = 6; // top 2 bits of an elementary-cell byte
const GRID_RESERVED_MASK: u8 = 0x08; // header bit 3
const GRID_RESERVED_SHIFT: u8 = 3;
/// 7-bit `reserved_future_use` spans the low 2 bits of cell byte 0 and the
/// high 5 bits of cell byte 1.
const CELL_RESERVED_HI_MASK: u8 = 0x03;
const CELL_RESERVED_LO_SHIFT: u8 = 3;
const CELL_RESERVED_HI_SHIFT: u8 = 5;
const CELL_PRESENTATION_MASK: u8 = 0x07;
/// Spec default of the grid header `reserved_future_use`(1): `1` (EN 300 468
/// V1.3.1-V1.20.1 Table 71; audit `dvb-si/docs/reserved-bits-edition-audit.md`
/// §6.1, class A: stable in every edition).
pub const GRID_RESERVED_FUTURE_USE_DEFAULT: u8 = 1;
/// Spec default of the per-logical-cell `reserved_future_use`(7): all ones.
pub const CELL_RESERVED_FUTURE_USE_DEFAULT: u8 = 0x7F;
/// Spec default of the per-elementary-cell `reserved_future_use`(2): all ones.
pub const ELEMENTARY_CELL_RESERVED_FUTURE_USE_DEFAULT: u8 = 0b11;

/// Conditional linkage payload selected by `cell_linkage_info` (Table 75).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum CellLinkage {
    /// 0x00 — undefined (no payload).
    Undefined,
    /// 0x01 — bouquet related.
    Bouquet {
        /// Linked bouquet_id.
        bouquet_id: u16,
    },
    /// 0x02 — service related.
    Service {
        /// Linked original_network_id.
        original_network_id: u16,
        /// Linked transport_stream_id.
        transport_stream_id: u16,
        /// Linked service_id.
        service_id: u16,
    },
    /// 0x03 — other mosaic related.
    OtherMosaic {
        /// Linked original_network_id.
        original_network_id: u16,
        /// Linked transport_stream_id.
        transport_stream_id: u16,
        /// Linked service_id.
        service_id: u16,
    },
    /// 0x04 — event related.
    Event {
        /// Linked original_network_id.
        original_network_id: u16,
        /// Linked transport_stream_id.
        transport_stream_id: u16,
        /// Linked service_id.
        service_id: u16,
        /// Linked event_id.
        event_id: u16,
    },
    /// 0x05..=0xFF — reserved; the raw byte is preserved so unknown linkage
    /// values round-trip (they carry no further payload per Table 75).
    Reserved {
        /// The raw cell_linkage_info byte.
        value: u8,
    },
}

impl CellLinkage {
    /// The cell_linkage_info byte this variant serializes to.
    fn info_byte(&self) -> u8 {
        match self {
            CellLinkage::Undefined => 0x00,
            CellLinkage::Bouquet { .. } => 0x01,
            CellLinkage::Service { .. } => 0x02,
            CellLinkage::OtherMosaic { .. } => 0x03,
            CellLinkage::Event { .. } => 0x04,
            CellLinkage::Reserved { value } => *value,
        }
    }

    /// Length of the conditional payload (excluding the info byte).
    fn payload_len(&self) -> usize {
        match self {
            CellLinkage::Undefined | CellLinkage::Reserved { .. } => 0,
            CellLinkage::Bouquet { .. } => 2,
            CellLinkage::Service { .. } | CellLinkage::OtherMosaic { .. } => 6,
            CellLinkage::Event { .. } => 8,
        }
    }
}

/// One elementary cell entry: `reserved_future_use`(2) + `elementary_cell_id`(6).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ElementaryCell {
    /// `reserved_future_use`(2) ahead of the id (2 bits, right-aligned).
    /// Captured on parse, re-emitted verbatim; [`ElementaryCell::new`] defaults
    /// to [`ELEMENTARY_CELL_RESERVED_FUTURE_USE_DEFAULT`].
    pub reserved_future_use: u8,
    /// 6-bit elementary_cell_id.
    pub elementary_cell_id: u8,
}

impl ElementaryCell {
    /// Build an entry with the spec-default reserved bits (all ones).
    #[must_use]
    pub const fn new(elementary_cell_id: u8) -> Self {
        Self {
            reserved_future_use: ELEMENTARY_CELL_RESERVED_FUTURE_USE_DEFAULT,
            elementary_cell_id,
        }
    }
}

/// One logical cell within the mosaic.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct MosaicLogicalCell {
    /// `reserved_future_use`(7) between `logical_cell_id` and
    /// `logical_cell_presentation_info` (7 bits, right-aligned). Captured on
    /// parse, re-emitted verbatim; [`MosaicLogicalCell::new`] defaults to
    /// [`CELL_RESERVED_FUTURE_USE_DEFAULT`].
    pub reserved_future_use: u8,
    /// 6-bit logical_cell_id.
    pub logical_cell_id: u8,
    /// 3-bit logical_cell_presentation_info (Table 74): 1 = video,
    /// 2 = still picture, 3 = graphics/text.
    pub presentation_info: u8,
    /// Elementary cells (each `reserved_future_use`(2) + 6-bit id) composing
    /// this logical cell.
    pub elementary_cells: Vec<ElementaryCell>,
    /// Linkage of this logical cell to a bouquet / service / event.
    pub linkage: CellLinkage,
}

impl MosaicLogicalCell {
    /// Build a logical cell with the spec-default reserved bits (all ones).
    #[must_use]
    pub const fn new(
        logical_cell_id: u8,
        presentation_info: u8,
        elementary_cells: Vec<ElementaryCell>,
        linkage: CellLinkage,
    ) -> Self {
        Self {
            reserved_future_use: CELL_RESERVED_FUTURE_USE_DEFAULT,
            logical_cell_id,
            presentation_info,
            elementary_cells,
            linkage,
        }
    }
}

/// Mosaic Descriptor.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct MosaicDescriptor {
    /// `reserved_future_use`(1) between the horizontal and vertical cell
    /// counts (1 bit). Captured on parse, re-emitted verbatim;
    /// [`MosaicDescriptor::new`] defaults to
    /// [`GRID_RESERVED_FUTURE_USE_DEFAULT`].
    pub reserved_future_use: u8,
    /// mosaic_entry_point: set when this mosaic is the top of a hierarchy.
    pub mosaic_entry_point: bool,
    /// 3-bit number_of_horizontal_elementary_cells (Table 72; 0 = one cell).
    pub num_horizontal_cells: u8,
    /// 3-bit number_of_vertical_elementary_cells (Table 73; 0 = one cell).
    pub num_vertical_cells: u8,
    /// Logical cells in wire order.
    pub logical_cells: Vec<MosaicLogicalCell>,
}

impl MosaicDescriptor {
    /// Build a descriptor with the spec-default reserved bit.
    #[must_use]
    pub const fn new(
        mosaic_entry_point: bool,
        num_horizontal_cells: u8,
        num_vertical_cells: u8,
        logical_cells: Vec<MosaicLogicalCell>,
    ) -> Self {
        Self {
            reserved_future_use: GRID_RESERVED_FUTURE_USE_DEFAULT,
            mosaic_entry_point,
            num_horizontal_cells,
            num_vertical_cells,
            logical_cells,
        }
    }
}

fn read_u16(b: &[u8], at: usize) -> Result<u16> {
    crate::wire::be_u16(b, at, "mosaic")
}

impl<'a> Parse<'a> for MosaicDescriptor {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "MosaicDescriptor",
            "unexpected tag for mosaic_descriptor",
        )?;
        if body.len() < GRID_HEADER_LEN {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "mosaic_descriptor missing grid header byte",
            });
        }
        let mosaic_entry_point = body[0] & ENTRY_POINT_MASK != 0;
        let num_horizontal_cells = (body[0] >> 4) & 0x07;
        let num_vertical_cells = body[0] & 0x07;

        let mut logical_cells = Vec::new();
        let mut pos = GRID_HEADER_LEN;
        while pos < body.len() {
            if pos + CELL_FIXED_LEN > body.len() {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "truncated mosaic logical cell header",
                });
            }
            // logical_cell_id(6) | reserved(7) | presentation_info(3)
            let logical_cell_id = (body[pos] >> 2) & 0x3F;
            let presentation_info = body[pos + 1] & CELL_PRESENTATION_MASK;
            let cell_reserved = ((body[pos] & CELL_RESERVED_HI_MASK) << CELL_RESERVED_HI_SHIFT)
                | (body[pos + 1] >> CELL_RESERVED_LO_SHIFT);
            let elem_field_len = body[pos + 2] as usize;
            pos += CELL_FIXED_LEN;
            if pos + elem_field_len > body.len() {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "elementary_cell_field_length exceeds descriptor body",
                });
            }
            let mut elementary_cells = Vec::with_capacity(elem_field_len);
            for &b in &body[pos..pos + elem_field_len] {
                elementary_cells.push(ElementaryCell {
                    reserved_future_use: b >> ELEM_RESERVED_SHIFT,
                    elementary_cell_id: b & ELEM_CELL_ID_MASK,
                });
            }
            pos += elem_field_len;
            if pos >= body.len() {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "missing cell_linkage_info byte",
                });
            }
            let info = body[pos];
            pos += 1;
            let linkage = match info {
                0x00 => CellLinkage::Undefined,
                0x01 => {
                    if pos + 2 > body.len() {
                        return Err(Error::InvalidDescriptor {
                            tag: TAG,
                            reason: "truncated bouquet linkage payload",
                        });
                    }
                    let l = CellLinkage::Bouquet {
                        bouquet_id: read_u16(body, pos)?,
                    };
                    pos += 2;
                    l
                }
                0x02 | 0x03 => {
                    if pos + 6 > body.len() {
                        return Err(Error::InvalidDescriptor {
                            tag: TAG,
                            reason: "truncated service/mosaic linkage payload",
                        });
                    }
                    let original_network_id = read_u16(body, pos)?;
                    let transport_stream_id = read_u16(body, pos + 2)?;
                    let service_id = read_u16(body, pos + 4)?;
                    pos += 6;
                    if info == 0x02 {
                        CellLinkage::Service {
                            original_network_id,
                            transport_stream_id,
                            service_id,
                        }
                    } else {
                        CellLinkage::OtherMosaic {
                            original_network_id,
                            transport_stream_id,
                            service_id,
                        }
                    }
                }
                0x04 => {
                    if pos + 8 > body.len() {
                        return Err(Error::InvalidDescriptor {
                            tag: TAG,
                            reason: "truncated event linkage payload",
                        });
                    }
                    let l = CellLinkage::Event {
                        original_network_id: read_u16(body, pos)?,
                        transport_stream_id: read_u16(body, pos + 2)?,
                        service_id: read_u16(body, pos + 4)?,
                        event_id: read_u16(body, pos + 6)?,
                    };
                    pos += 8;
                    l
                }
                // 0x05..=0xFF reserved: no defined payload (Table 75).
                other => CellLinkage::Reserved { value: other },
            };
            logical_cells.push(MosaicLogicalCell {
                reserved_future_use: cell_reserved,
                logical_cell_id,
                presentation_info,
                elementary_cells,
                linkage,
            });
        }
        Ok(Self {
            reserved_future_use: (body[0] & GRID_RESERVED_MASK) >> GRID_RESERVED_SHIFT,
            mosaic_entry_point,
            num_horizontal_cells,
            num_vertical_cells,
            logical_cells,
        })
    }
}

impl Serialize for MosaicDescriptor {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        let cells: usize = self
            .logical_cells
            .iter()
            .map(|c| CELL_FIXED_LEN + c.elementary_cells.len() + 1 + c.linkage.payload_len())
            .sum();
        HEADER_LEN + GRID_HEADER_LEN + cells
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(Error::OutputBufferTooSmall {
                need: len,
                have: buf.len(),
            });
        }
        let body_len = len - HEADER_LEN;
        // 8-bit descriptor_length field: error rather than silently truncate.
        if body_len > MAX_BODY_LEN {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "mosaic_descriptor body exceeds 255 bytes",
            });
        }
        crate::descriptors::write_descriptor_header(buf, TAG, body_len)?;
        // grid header: reserved_future_use (bit 3) preserved from parse.
        buf[2] = if self.mosaic_entry_point {
            ENTRY_POINT_MASK
        } else {
            0
        } | (broadcast_common::len::fit_mask(
            self.num_horizontal_cells,
            0x07,
            "num_horizontal_cells",
        )? << 4)
            | (broadcast_common::len::fit_mask(
                self.reserved_future_use,
                GRID_RESERVED_MASK >> GRID_RESERVED_SHIFT,
                "reserved_future_use",
            )? << GRID_RESERVED_SHIFT)
            | broadcast_common::len::fit_mask(self.num_vertical_cells, 0x07, "num_vertical_cells")?;
        let mut pos = HEADER_LEN + GRID_HEADER_LEN;
        for cell in &self.logical_cells {
            broadcast_common::len::fit_mask(cell.reserved_future_use, 0x7F, "reserved_future_use")?;
            // byte0: logical_cell_id(6) | high 2 bits of reserved_future_use(7).
            buf[pos] =
                (broadcast_common::len::fit_mask(cell.logical_cell_id, 0x3F, "logical_cell_id")?
                    << 2)
                    | ((cell.reserved_future_use >> CELL_RESERVED_HI_SHIFT)
                        & CELL_RESERVED_HI_MASK);
            // byte1: low 5 bits of reserved_future_use(7) | presentation_info(3).
            buf[pos + 1] = (cell.reserved_future_use << CELL_RESERVED_LO_SHIFT)
                | broadcast_common::len::fit_mask(
                    cell.presentation_info,
                    CELL_PRESENTATION_MASK,
                    "presentation_info",
                )?;
            buf[pos + 2] = broadcast_common::len::fit_u8(
                cell.elementary_cells.len(),
                "elementary_cell_field_length",
            )?;
            pos += CELL_FIXED_LEN;
            for ec in &cell.elementary_cells {
                // reserved_future_use(2) preserved | elementary_cell_id(6).
                buf[pos] = (broadcast_common::len::fit_mask(
                    ec.reserved_future_use,
                    !ELEM_CELL_ID_MASK >> ELEM_RESERVED_SHIFT,
                    "reserved_future_use",
                )? << ELEM_RESERVED_SHIFT)
                    | broadcast_common::len::fit_mask(
                        ec.elementary_cell_id,
                        ELEM_CELL_ID_MASK,
                        "elementary_cell_id",
                    )?;
                pos += 1;
            }
            buf[pos] = cell.linkage.info_byte();
            pos += 1;
            match &cell.linkage {
                CellLinkage::Undefined | CellLinkage::Reserved { .. } => {}
                CellLinkage::Bouquet { bouquet_id } => {
                    buf[pos..pos + 2].copy_from_slice(&bouquet_id.to_be_bytes());
                    pos += 2;
                }
                CellLinkage::Service {
                    original_network_id,
                    transport_stream_id,
                    service_id,
                }
                | CellLinkage::OtherMosaic {
                    original_network_id,
                    transport_stream_id,
                    service_id,
                } => {
                    buf[pos..pos + 2].copy_from_slice(&original_network_id.to_be_bytes());
                    buf[pos + 2..pos + 4].copy_from_slice(&transport_stream_id.to_be_bytes());
                    buf[pos + 4..pos + 6].copy_from_slice(&service_id.to_be_bytes());
                    pos += 6;
                }
                CellLinkage::Event {
                    original_network_id,
                    transport_stream_id,
                    service_id,
                    event_id,
                } => {
                    buf[pos..pos + 2].copy_from_slice(&original_network_id.to_be_bytes());
                    buf[pos + 2..pos + 4].copy_from_slice(&transport_stream_id.to_be_bytes());
                    buf[pos + 4..pos + 6].copy_from_slice(&service_id.to_be_bytes());
                    buf[pos + 6..pos + 8].copy_from_slice(&event_id.to_be_bytes());
                    pos += 8;
                }
            }
        }
        Ok(len)
    }
}
impl crate::traits::DescriptorDef<'_> for MosaicDescriptor {
    const TAG: u8 = TAG;
    const NAME: &'static str = "MOSAIC";
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_single_cell_undefined_linkage() {
        // grid header 0x80|0x08 (entry point + reserved), 2x2 grid coded as 1,1
        // logical cell: id=5, presentation=1, 2 elem cells [3,7], linkage 0x00
        let bytes = [
            TAG,
            0x07,
            0x80 | (1 << 4) | 0x08 | 1, // header
            (5 << 2) | 0x03,            // logical_cell_id=5
            0xF8 | 1,                   // presentation_info=1
            0x02,                       // elementary_cell_field_length=2
            0xC0 | 3,
            0xC0 | 7,
            0x00, // cell_linkage_info = undefined
        ];
        let d = MosaicDescriptor::parse(&bytes).unwrap();
        assert!(d.mosaic_entry_point);
        assert_eq!(d.num_horizontal_cells, 1);
        assert_eq!(d.num_vertical_cells, 1);
        assert_eq!(d.logical_cells.len(), 1);
        let c = &d.logical_cells[0];
        assert_eq!(c.logical_cell_id, 5);
        assert_eq!(c.presentation_info, 1);
        assert_eq!(
            c.elementary_cells,
            vec![ElementaryCell::new(3), ElementaryCell::new(7)]
        );
        assert_eq!(c.linkage, CellLinkage::Undefined);
    }

    #[test]
    fn parse_service_linkage() {
        let d = MosaicDescriptor::new(
            false,
            0,
            0,
            vec![MosaicLogicalCell::new(
                1,
                2,
                vec![ElementaryCell::new(0)],
                CellLinkage::Service {
                    original_network_id: 0x1111,
                    transport_stream_id: 0x2222,
                    service_id: 0x3333,
                },
            )],
        );
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        let p = MosaicDescriptor::parse(&buf).unwrap();
        assert_eq!(p, d);
        assert!(matches!(
            p.logical_cells[0].linkage,
            CellLinkage::Service {
                original_network_id: 0x1111,
                transport_stream_id: 0x2222,
                service_id: 0x3333,
            }
        ));
    }

    #[test]
    fn parse_event_linkage_round_trip() {
        let d = MosaicDescriptor::new(
            true,
            3,
            2,
            vec![MosaicLogicalCell::new(
                10,
                3,
                vec![
                    ElementaryCell::new(1),
                    ElementaryCell::new(2),
                    ElementaryCell::new(3),
                ],
                CellLinkage::Event {
                    original_network_id: 0xAAAA,
                    transport_stream_id: 0xBBBB,
                    service_id: 0xCCCC,
                    event_id: 0xDDDD,
                },
            )],
        );
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(MosaicDescriptor::parse(&buf).unwrap(), d);
    }

    #[test]
    fn parse_reserved_linkage_round_trips() {
        let bytes = [
            TAG,
            0x05,
            0x08, // grid header, no entry point, grid 0,0
            (1 << 2) | 0x03,
            0xF8,
            0x00, // no elementary cells
            0x42, // reserved linkage value
        ];
        let d = MosaicDescriptor::parse(&bytes).unwrap();
        assert_eq!(
            d.logical_cells[0].linkage,
            CellLinkage::Reserved { value: 0x42 }
        );
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(MosaicDescriptor::parse(&buf).unwrap(), d);
    }

    #[test]
    fn parse_multiple_cells() {
        let d = MosaicDescriptor::new(
            false,
            1,
            1,
            vec![
                MosaicLogicalCell::new(
                    0,
                    1,
                    vec![ElementaryCell::new(0)],
                    CellLinkage::Bouquet { bouquet_id: 0x1234 },
                ),
                MosaicLogicalCell::new(1, 1, vec![ElementaryCell::new(1)], CellLinkage::Undefined),
            ],
        );
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        let p = MosaicDescriptor::parse(&buf).unwrap();
        assert_eq!(p.logical_cells.len(), 2);
        assert_eq!(p, d);
    }

    #[test]
    fn parse_rejects_wrong_tag() {
        assert!(matches!(
            MosaicDescriptor::parse(&[0x52, 1, 0x08]).unwrap_err(),
            Error::InvalidDescriptor { tag: 0x52, .. }
        ));
    }

    #[test]
    fn parse_rejects_short_buffer() {
        // declares 5 body bytes, only 2 present
        let bytes = [TAG, 5, 0x08, 0x00];
        assert!(matches!(
            MosaicDescriptor::parse(&bytes).unwrap_err(),
            Error::BufferTooShort { .. }
        ));
    }

    #[test]
    fn parse_rejects_elem_field_overrun() {
        // elementary_cell_field_length=10 but body has no room
        let bytes = [TAG, 4, 0x08, (1 << 2) | 0x03, 0xF8, 0x0A];
        assert!(matches!(
            MosaicDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn parse_rejects_missing_linkage_byte() {
        // cell header present, elem_field_len=0, but no cell_linkage_info byte
        let bytes = [TAG, 4, 0x08, (1 << 2) | 0x03, 0xF8, 0x00];
        // length=4 means body is [0x08, hdr0, hdr1, 0x00]; after the 3 fixed
        // cell bytes pos == body.len() so the linkage byte is missing.
        assert!(matches!(
            MosaicDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn parse_rejects_zero_length() {
        assert!(matches!(
            MosaicDescriptor::parse(&[TAG, 0]).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    /// Reserved regions of all three levels (grid 1 bit, logical cell 7 bits
    /// spanning two bytes, elementary cell 2 bits) re-serialize verbatim for
    /// non-default and default values.
    #[test]
    fn reserved_preserved() {
        for g in 0u8..=1 {
            for c in [0u8, 0x01, 0x2A, 0x55, 0x7F] {
                for e in 0u8..=3 {
                    let bytes = [
                        TAG,
                        0x08,
                        0x80 | (1 << 4) | (g << 3) | 1,
                        (5 << 2) | (c >> 5),
                        ((c & 0x1F) << 3) | 1,
                        0x02,
                        (e << 6) | 3,
                        ((3 - e) << 6) | 7,
                        0x01,
                        0x12,
                        0x34,
                    ];
                    // body length: 1 + 3 + 2 + 1 + 2 = 9
                    let mut b = bytes.to_vec();
                    b[1] = 9;
                    let d = MosaicDescriptor::parse(&b).unwrap();
                    assert_eq!(d.reserved_future_use, g);
                    assert_eq!(d.logical_cells[0].reserved_future_use, c);
                    assert_eq!(
                        d.logical_cells[0].elementary_cells[0].reserved_future_use,
                        e
                    );
                    let mut buf = vec![0u8; d.serialized_len()];
                    d.serialize_into(&mut buf).unwrap();
                    assert_eq!(buf, b);
                }
            }
        }
    }

    #[test]
    fn default_is_spec_value() {
        let d = MosaicDescriptor::new(
            false,
            0,
            0,
            vec![MosaicLogicalCell::new(
                1,
                1,
                vec![ElementaryCell::new(2)],
                CellLinkage::Undefined,
            )],
        );
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, [TAG, 6, 0x08, (1 << 2) | 0x03, 0xF9, 0x01, 0xC2, 0x00]);
    }

    #[test]
    fn serialize_emits_reserved_ones() {
        let d = MosaicDescriptor::new(false, 0, 0, vec![]);
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        // grid header reserved bit (bit 3) set
        assert_eq!(buf[2] & 0x08, 0x08);
    }

    #[test]
    fn serialize_round_trip_empty_grid() {
        let d = MosaicDescriptor::new(true, 7, 7, vec![]);
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(MosaicDescriptor::parse(&buf).unwrap(), d);
    }
}