dvb-ci 0.10.0

DVB Common Interface (EN 50221) — APDU/resource objects, session/transport PDUs, and a CA_PMT builder from a dvb-si PMT.
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
//! Transport Protocol Data Unit (TPDU) framing — ETSI EN 50221 Annex A §A.4.1,
//! Tables A.1-A.16 (PDF pp. 63-70).
//!
//! The transport layer is a command-response protocol: the host sends a Command
//! TPDU (C_TPDU), the module replies with a Response TPDU (R_TPDU) that always
//! ends in a Status Byte. The `length_field` uses the Table 1 coding (see
//! [`crate::length`]). This module covers the wire framing only — the PC-Card
//! hardware transport itself is out of scope.

use crate::error::{Error, Result};
use crate::length::{self, LengthForm};
use alloc::vec::Vec;
use broadcast_common::{Parse, Serialize};

/// `tpdu_tag` values — Table A.16 (p. 70). One byte each.
pub mod tags {
    /// `TSB` (status byte) = `80`.
    pub const SB: u8 = 0x80;
    /// `TRCV` (receive data) = `81`.
    pub const RCV: u8 = 0x81;
    /// `Tcreate_t_c` = `82`.
    pub const CREATE_T_C: u8 = 0x82;
    /// `Tc_t_c_reply` = `83`.
    pub const C_T_C_REPLY: u8 = 0x83;
    /// `Tdelete_t_c` = `84`.
    pub const DELETE_T_C: u8 = 0x84;
    /// `Td_t_c_reply` = `85`.
    pub const D_T_C_REPLY: u8 = 0x85;
    /// `Trequest_t_c` = `86`.
    pub const REQUEST_T_C: u8 = 0x86;
    /// `Tnew_t_c` = `87`.
    pub const NEW_T_C: u8 = 0x87;
    /// `Tt_c_error` = `88`.
    pub const T_C_ERROR: u8 = 0x88;
    /// `Tdata_last` (last data block) = `A0`.
    pub const DATA_LAST: u8 = 0xA0;
    /// `Tdata_more` (more data follows) = `A1`.
    pub const DATA_MORE: u8 = 0xA1;
}

/// Status Byte value (`SB_value`, Figure A.6 + Table A.3, p. 64). The single
/// 1-bit DA (Data Available) flag is bit 8; the remaining bits are reserved
/// (shall be zero) and preserved here for fidelity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct SbValue(pub u8);

impl SbValue {
    /// DA (Data Available): true when the module has a message for the host.
    #[must_use]
    pub const fn data_available(self) -> bool {
        self.0 & 0x80 != 0
    }
    /// Build an `SB_value` with the DA bit set/clear and reserved bits zero.
    #[must_use]
    pub const fn new(data_available: bool) -> Self {
        Self(if data_available { 0x80 } else { 0x00 })
    }
}

/// `c_TPDU_tag` for the data-carrying C_TPDU (chaining): last vs. more (§A.4.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum DataBlock {
    /// `Tdata_last` (`A0`): the final (or only) data block.
    Last,
    /// `Tdata_more` (`A1`): more blocks follow.
    More,
}

impl DataBlock {
    fn from_tag(tag: u8) -> Option<Self> {
        match tag {
            tags::DATA_LAST => Some(Self::Last),
            tags::DATA_MORE => Some(Self::More),
            _ => None,
        }
    }
    /// The `tpdu_tag` byte for this data block (`A0` last / `A1` more).
    #[must_use]
    pub fn to_tag(self) -> u8 {
        match self {
            Self::Last => tags::DATA_LAST,
            Self::More => tags::DATA_MORE,
        }
    }
    /// Spec token.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Last => "data_last",
            Self::More => "data_more",
        }
    }
}
broadcast_common::impl_spec_display!(DataBlock);

// --- single-field connection-management objects (tag + length + t_c_id) ---

/// A connection-management object carrying just `t_c_id`: `Create_T_C`
/// (Table A.4), `C_T_C_Reply`, `Delete_T_C` (A.6), `D_T_C_Reply`, `Request_T_C`
/// (A.8). The `tag` distinguishes which (`length_field = 1`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct TcObject {
    /// The `tpdu_tag` (one of `CREATE_T_C`/`C_T_C_REPLY`/`DELETE_T_C`/
    /// `D_T_C_REPLY`/`REQUEST_T_C`).
    pub tag: u8,
    /// `t_c_id` — the transport connection identifier.
    pub t_c_id: u8,
    /// How the `length_field` was coded on the wire (non-minimal long forms
    /// such as `82 00 09` are preserved so the object re-serializes
    /// byte-for-byte; [`LengthForm::Minimal`] for a hand-built value).
    #[cfg_attr(feature = "serde", serde(skip))]
    pub length_form: LengthForm,
}

impl TcObject {
    /// `true` when `tag` is one of the five single-`t_c_id` connection
    /// objects this type models (Table A.16): `Tcreate_t_c`, `Tc_t_c_reply`,
    /// `Tdelete_t_c`, `Td_t_c_reply`, `Trequest_t_c`. Any other tag belongs to
    /// a different object (`SB`, `RCV`, `New_T_C`, `T_C_Error`, data) with a
    /// different body layout (audit r10-O-3).
    #[must_use]
    pub const fn is_tc_tag(tag: u8) -> bool {
        matches!(
            tag,
            tags::CREATE_T_C
                | tags::C_T_C_REPLY
                | tags::DELETE_T_C
                | tags::D_T_C_REPLY
                | tags::REQUEST_T_C
        )
    }
}

impl<'a> Parse<'a> for TcObject {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        if bytes.is_empty() {
            return Err(Error::BufferTooShort {
                need: 1,
                have: 0,
                what: "TcObject",
            });
        }
        let tag = bytes[0];
        if !Self::is_tc_tag(tag) {
            return Err(Error::InvalidObject {
                what: "TcObject",
                reason: "tpdu_tag is not a single-t_c_id connection object",
            });
        }
        let (len, hdr, length_form) = length::decode_form(&bytes[1..])?;
        if len != 1 {
            return Err(Error::InvalidObject {
                what: "TcObject",
                reason: "length_field must be 1",
            });
        }
        let t_c_id = *bytes.get(1 + hdr).ok_or(Error::BufferTooShort {
            need: 1 + hdr + 1,
            have: bytes.len(),
            what: "TcObject t_c_id",
        })?;
        Ok(Self {
            tag,
            t_c_id,
            length_form,
        })
    }
}
impl Serialize for TcObject {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        // tag + length_field(value 1) + t_c_id
        1 + length::encoded_len_with(1, self.length_form) + 1
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let total = self.serialized_len();
        if buf.len() < total {
            return Err(Error::OutputBufferTooSmall {
                need: total,
                have: buf.len(),
            });
        }
        if !Self::is_tc_tag(self.tag) {
            return Err(Error::InvalidObject {
                what: "TcObject",
                reason: "tpdu_tag is not a single-t_c_id connection object",
            });
        }
        buf[0] = self.tag;
        let pos = 1 + length::encode_with(1, self.length_form, &mut buf[1..])?;
        buf[pos] = self.t_c_id;
        Ok(pos + 1)
    }
}

/// `New_T_C` (Table A.9, `length=2`): a new connection identifier to establish.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct NewTc {
    /// `t_c_id` of the connection issuing this.
    pub t_c_id: u8,
    /// `new_t_c_id` — the identifier for the new connection.
    pub new_t_c_id: u8,
    /// How the `length_field` was coded on the wire (non-minimal long forms
    /// such as `82 00 09` are preserved so the object re-serializes
    /// byte-for-byte; [`LengthForm::Minimal`] for a hand-built value).
    #[cfg_attr(feature = "serde", serde(skip))]
    pub length_form: LengthForm,
}

impl<'a> Parse<'a> for NewTc {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let (length_form, body) = parse_fixed(bytes, tags::NEW_T_C, 2, "New_T_C")?;
        Ok(Self {
            t_c_id: body[0],
            new_t_c_id: body[1],
            length_form,
        })
    }
}
impl Serialize for NewTc {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        1 + length::encoded_len_with(2, self.length_form) + 2
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        write_fixed(
            tags::NEW_T_C,
            self.length_form,
            &[self.t_c_id, self.new_t_c_id],
            buf,
        )
    }
}

/// `T_C_Error` (Table A.10, `length=2`): an error on a transport connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct TcError {
    /// `t_c_id`.
    pub t_c_id: u8,
    /// `error_code` (Table A.11: `1` = no transport connections available).
    pub error_code: u8,
    /// How the `length_field` was coded on the wire (non-minimal long forms
    /// such as `82 00 09` are preserved so the object re-serializes
    /// byte-for-byte; [`LengthForm::Minimal`] for a hand-built value).
    #[cfg_attr(feature = "serde", serde(skip))]
    pub length_form: LengthForm,
}

impl<'a> Parse<'a> for TcError {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let (length_form, body) = parse_fixed(bytes, tags::T_C_ERROR, 2, "T_C_Error")?;
        Ok(Self {
            t_c_id: body[0],
            error_code: body[1],
            length_form,
        })
    }
}
impl Serialize for TcError {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        1 + length::encoded_len_with(2, self.length_form) + 2
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        write_fixed(
            tags::T_C_ERROR,
            self.length_form,
            &[self.t_c_id, self.error_code],
            buf,
        )
    }
}

/// `C_TPDU` (Table A.1): a Command TPDU, host → module. `length_field` covers
/// `t_c_id` + data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CommandTpdu<'a> {
    /// The `c_tpdu_tag` (e.g. `RCV`, or `DATA_LAST`/`DATA_MORE` for Send Data).
    pub tag: u8,
    /// `t_c_id`.
    pub t_c_id: u8,
    /// Data field (`length_value - 1` bytes).
    #[cfg_attr(feature = "serde", serde(borrow, with = "crate::objects::bytes_serde"))]
    pub data: &'a [u8],
    /// How the `length_field` was coded on the wire (non-minimal long forms
    /// such as `82 00 09` are preserved so the object re-serializes
    /// byte-for-byte; [`LengthForm::Minimal`] for a hand-built value).
    #[cfg_attr(feature = "serde", serde(skip))]
    pub length_form: LengthForm,
}

impl<'a> Parse<'a> for CommandTpdu<'a> {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        if bytes.is_empty() {
            return Err(Error::BufferTooShort {
                need: 1,
                have: 0,
                what: "C_TPDU",
            });
        }
        let tag = bytes[0];
        let (len, hdr, length_form) = length::decode_form(&bytes[1..])?;
        if len == 0 {
            return Err(Error::InvalidObject {
                what: "C_TPDU",
                reason: "length_field must include t_c_id (>=1)",
            });
        }
        let start = 1 + hdr;
        let end = start + len;
        if bytes.len() < end {
            return Err(Error::LengthMismatch {
                what: "C_TPDU",
                declared: len,
                actual: bytes.len().saturating_sub(start),
            });
        }
        Ok(Self {
            tag,
            t_c_id: bytes[start],
            data: &bytes[start + 1..end],
            length_form,
        })
    }
}
impl Serialize for CommandTpdu<'_> {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        let len_value = 1 + self.data.len();
        1 + length::encoded_len_with(len_value, self.length_form) + len_value
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len_value = 1 + self.data.len();
        let total = self.serialized_len();
        if buf.len() < total {
            return Err(Error::OutputBufferTooSmall {
                need: total,
                have: buf.len(),
            });
        }
        buf[0] = self.tag;
        let mut pos = 1 + length::encode_with(len_value, self.length_form, &mut buf[1..])?;
        buf[pos] = self.t_c_id;
        pos += 1;
        buf[pos..pos + self.data.len()].copy_from_slice(self.data);
        Ok(pos + self.data.len())
    }
}

/// `R_TPDU` (Table A.2): a Response TPDU, module → host. The mandatory trailing
/// Status (SB) is NOT included in the `length_field` and is modelled separately.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ResponseTpdu<'a> {
    /// The `r_tpdu_tag` (e.g. `DATA_LAST`/`DATA_MORE`).
    pub tag: u8,
    /// `t_c_id`.
    pub t_c_id: u8,
    /// Data field (`length_value - 1` bytes).
    #[cfg_attr(feature = "serde", serde(borrow, with = "crate::objects::bytes_serde"))]
    pub data: &'a [u8],
    /// `SB_value` from the mandatory trailing Status.
    pub sb_value: SbValue,
    /// Whether the data block was the last (`Tdata_last`) — convenience view of
    /// `tag` for chaining, `None` if `tag` is not a data block tag.
    pub block: Option<DataBlock>,
    /// How the `length_field` was coded on the wire (non-minimal long forms
    /// such as `82 00 09` are preserved so the object re-serializes
    /// byte-for-byte; [`LengthForm::Minimal`] for a hand-built value).
    #[cfg_attr(feature = "serde", serde(skip))]
    pub length_form: LengthForm,
    /// How the trailing Status (SB) object's own `length_field` (value 2) was
    /// coded; see [`length_form`](Self::length_form).
    #[cfg_attr(feature = "serde", serde(skip))]
    pub status_length_form: LengthForm,
}

impl<'a> Parse<'a> for ResponseTpdu<'a> {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        if bytes.is_empty() {
            return Err(Error::BufferTooShort {
                need: 1,
                have: 0,
                what: "R_TPDU",
            });
        }
        let tag = bytes[0];
        let (len, hdr, length_form) = length::decode_form(&bytes[1..])?;
        if len == 0 {
            return Err(Error::InvalidObject {
                what: "R_TPDU",
                reason: "length_field must include t_c_id (>=1)",
            });
        }
        let start = 1 + hdr;
        let data_end = start + len;
        // Status trailer: SB_tag + length_field(value 2) + t_c_id + SB_value.
        // Need at least the tag and one length byte to learn the field's width.
        if bytes.len() < data_end + 2 {
            return Err(Error::BufferTooShort {
                need: data_end + 2,
                have: bytes.len(),
                what: "R_TPDU status",
            });
        }
        if bytes[data_end] != tags::SB {
            return Err(Error::UnexpectedTpduTag {
                got: bytes[data_end],
                expected: tags::SB,
                what: "R_TPDU SB_tag",
            });
        }
        let (sb_len, sb_hdr, status_length_form) = length::decode_form(&bytes[data_end + 1..])?;
        if sb_len != 2 {
            return Err(Error::InvalidObject {
                what: "R_TPDU status",
                reason: "SB length_field must be 2",
            });
        }
        let sb_body = data_end + 1 + sb_hdr;
        let status_end = sb_body + 2;
        if bytes.len() < status_end {
            return Err(Error::BufferTooShort {
                need: status_end,
                have: bytes.len(),
                what: "R_TPDU status",
            });
        }
        // bytes[sb_body] = t_c_id (status), bytes[sb_body+1] = SB_value.
        // The status trailer names the same transport connection as the
        // TPDU body's own leading t_c_id (bytes[start]) — a mismatch means
        // this status is not actually reporting on this TPDU.
        if bytes[sb_body] != bytes[start] {
            return Err(Error::InvalidObject {
                what: "R_TPDU status",
                reason: "status t_c_id does not match the TPDU's t_c_id",
            });
        }
        Ok(Self {
            tag,
            t_c_id: bytes[start],
            data: &bytes[start + 1..data_end],
            sb_value: SbValue(bytes[sb_body + 1]),
            block: DataBlock::from_tag(tag),
            length_form,
            status_length_form,
        })
    }
}
impl Serialize for ResponseTpdu<'_> {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        let len_value = 1 + self.data.len();
        1 + length::encoded_len_with(len_value, self.length_form)
            + len_value
            + 1
            + length::encoded_len_with(2, self.status_length_form)
            + 2
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let total = self.serialized_len();
        if buf.len() < total {
            return Err(Error::OutputBufferTooSmall {
                need: total,
                have: buf.len(),
            });
        }
        let len_value = 1 + self.data.len();
        buf[0] = self.tag;
        let mut pos = 1 + length::encode_with(len_value, self.length_form, &mut buf[1..])?;
        buf[pos] = self.t_c_id;
        pos += 1;
        buf[pos..pos + self.data.len()].copy_from_slice(self.data);
        pos += self.data.len();
        // Status trailer.
        buf[pos] = tags::SB;
        pos += 1;
        pos += length::encode_with(2, self.status_length_form, &mut buf[pos..])?;
        buf[pos] = self.t_c_id;
        buf[pos + 1] = self.sb_value.0;
        Ok(pos + 2)
    }
}

// --- helpers for the fixed-length tag+length+body objects ---

fn parse_fixed<'a>(
    bytes: &'a [u8],
    expected: u8,
    body_len: usize,
    what: &'static str,
) -> Result<(LengthForm, &'a [u8])> {
    if bytes.is_empty() {
        return Err(Error::BufferTooShort {
            need: 1,
            have: 0,
            what,
        });
    }
    if bytes[0] != expected {
        return Err(Error::UnexpectedTpduTag {
            got: bytes[0],
            expected,
            what,
        });
    }
    let (len, hdr, form) = length::decode_form(&bytes[1..])?;
    if len != body_len {
        return Err(Error::InvalidObject {
            what,
            reason: "unexpected length_field",
        });
    }
    let start = 1 + hdr;
    let end = start + body_len;
    if bytes.len() < end {
        return Err(Error::BufferTooShort {
            need: end,
            have: bytes.len(),
            what,
        });
    }
    Ok((form, &bytes[start..end]))
}

fn write_fixed(tag: u8, form: LengthForm, body: &[u8], buf: &mut [u8]) -> Result<usize> {
    let total = 1 + length::encoded_len_with(body.len(), form) + body.len();
    if buf.len() < total {
        return Err(Error::OutputBufferTooSmall {
            need: total,
            have: buf.len(),
        });
    }
    buf[0] = tag;
    let pos = 1 + length::encode_with(body.len(), form, &mut buf[1..])?;
    buf[pos..pos + body.len()].copy_from_slice(body);
    Ok(total)
}

/// Build a `Create_T_C` object (`tag = CREATE_T_C`, `t_c_id`).
#[must_use]
pub fn create_t_c(t_c_id: u8) -> TcObject {
    TcObject {
        tag: tags::CREATE_T_C,
        t_c_id,
        length_form: LengthForm::Minimal,
    }
}

/// Collect a `Vec` of the wire bytes for a [`TcObject`] (convenience).
///
/// Fails with [`Error::InvalidObject`] when `o.tag` is not a connection
/// object tag (audit r10-O-3 / T15: this used to panic through `to_bytes`).
pub fn tc_object_bytes(o: &TcObject) -> Result<Vec<u8>> {
    o.try_to_bytes()
}

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

    #[test]
    fn tc_object_rejects_foreign_tags_both_ways() {
        // 0x80 is TSB (status byte), 0x87 New_T_C: valid TPDU tags, wrong
        // object. Previously any tag byte was accepted and re-emitted.
        for tag in [
            tags::SB,
            tags::RCV,
            tags::NEW_T_C,
            tags::T_C_ERROR,
            0x00,
            0xFF,
        ] {
            let wire = [tag, 0x01, 0x05];
            assert!(
                matches!(TcObject::parse(&wire), Err(Error::InvalidObject { .. })),
                "tag {tag:#04X} must be rejected on parse"
            );
            let o = TcObject {
                length_form: crate::length::LengthForm::Minimal,
                tag,
                t_c_id: 5,
            };
            assert!(matches!(
                tc_object_bytes(&o),
                Err(Error::InvalidObject { .. })
            ));
        }
        for tag in [
            tags::CREATE_T_C,
            tags::C_T_C_REPLY,
            tags::DELETE_T_C,
            tags::D_T_C_REPLY,
            tags::REQUEST_T_C,
        ] {
            let o = TcObject::parse(&[tag, 0x01, 0x05]).unwrap();
            assert_eq!(
                o,
                TcObject {
                    length_form: crate::length::LengthForm::Minimal,
                    tag,
                    t_c_id: 5
                }
            );
            assert_eq!(tc_object_bytes(&o).unwrap(), [tag, 0x01, 0x05]);
        }
    }

    #[test]
    fn tc_object_round_trip() {
        let o = create_t_c(0x01);
        let bytes = o.try_to_bytes().unwrap();
        assert_eq!(bytes, [0x82, 0x01, 0x01]);
        assert_eq!(TcObject::parse(&bytes).unwrap(), o);
    }

    #[test]
    fn new_tc_round_trip() {
        let n = NewTc {
            length_form: crate::length::LengthForm::Minimal,
            t_c_id: 1,
            new_t_c_id: 2,
        };
        let bytes = n.try_to_bytes().unwrap();
        assert_eq!(bytes, [0x87, 0x02, 0x01, 0x02]);
        assert_eq!(NewTc::parse(&bytes).unwrap(), n);
    }

    #[test]
    fn tc_error_round_trip() {
        let e = TcError {
            length_form: crate::length::LengthForm::Minimal,
            t_c_id: 3,
            error_code: 1,
        };
        let bytes = e.try_to_bytes().unwrap();
        assert_eq!(bytes, [0x88, 0x02, 0x03, 0x01]);
        assert_eq!(TcError::parse(&bytes).unwrap(), e);
    }

    #[test]
    fn command_tpdu_round_trip() {
        let c = CommandTpdu {
            length_form: crate::length::LengthForm::Minimal,
            tag: tags::DATA_LAST,
            t_c_id: 1,
            data: &[0xAA, 0xBB, 0xCC],
        };
        let bytes = c.try_to_bytes().unwrap();
        // tag A0, length 4 (t_c_id + 3 data), t_c_id, data.
        assert_eq!(bytes, [0xA0, 0x04, 0x01, 0xAA, 0xBB, 0xCC]);
        assert_eq!(CommandTpdu::parse(&bytes).unwrap(), c);
    }

    #[test]
    fn receive_data_command_no_payload() {
        let c = CommandTpdu {
            length_form: crate::length::LengthForm::Minimal,
            tag: tags::RCV,
            t_c_id: 1,
            data: &[],
        };
        let bytes = c.try_to_bytes().unwrap();
        assert_eq!(bytes, [0x81, 0x01, 0x01]);
        assert_eq!(CommandTpdu::parse(&bytes).unwrap(), c);
    }

    #[test]
    fn response_tpdu_round_trip_with_status() {
        let r = ResponseTpdu {
            length_form: crate::length::LengthForm::Minimal,
            status_length_form: crate::length::LengthForm::Minimal,
            tag: tags::DATA_LAST,
            t_c_id: 1,
            data: &[0x9F, 0x80, 0x30, 0x00],
            sb_value: SbValue::new(true),
            block: Some(DataBlock::Last),
        };
        let bytes = r.try_to_bytes().unwrap();
        // header: A0 05 01 + 4 data ; status: 80 02 01 80.
        assert_eq!(
            bytes,
            [
                0xA0, 0x05, 0x01, 0x9F, 0x80, 0x30, 0x00, 0x80, 0x02, 0x01, 0x80
            ]
        );
        let parsed = ResponseTpdu::parse(&bytes).unwrap();
        assert_eq!(parsed, r);
        assert!(parsed.sb_value.data_available());
        assert_eq!(parsed.block, Some(DataBlock::Last));
    }

    /// r10-W-8: the status trailer's own `t_c_id` (`bytes[data_end+2]`) must
    /// match the TPDU body's `t_c_id`, not merely be read past and dropped.
    /// A status reporting on a different transport connection than the one
    /// this TPDU's body names is not a well-formed R_TPDU.
    #[test]
    fn response_tpdu_rejects_mismatched_status_t_c_id() {
        let r = ResponseTpdu {
            length_form: crate::length::LengthForm::Minimal,
            status_length_form: crate::length::LengthForm::Minimal,
            tag: tags::DATA_LAST,
            t_c_id: 1,
            data: &[0x9F, 0x80, 0x30, 0x00],
            sb_value: SbValue::new(true),
            block: Some(DataBlock::Last),
        };
        let mut bytes = r.try_to_bytes().unwrap();
        let status_t_c_id_idx = bytes.len() - 2;
        assert_eq!(bytes[status_t_c_id_idx], 1);
        bytes[status_t_c_id_idx] = 2; // status now claims a different t_c_id
        assert!(matches!(
            ResponseTpdu::parse(&bytes),
            Err(Error::InvalidObject { .. })
        ));
    }

    #[test]
    fn mutating_data_changes_bytes() {
        let c = CommandTpdu {
            length_form: crate::length::LengthForm::Minimal,
            tag: tags::DATA_LAST,
            t_c_id: 1,
            data: &[0xAA],
        };
        let a = c.try_to_bytes().unwrap();
        let b = CommandTpdu {
            length_form: crate::length::LengthForm::Minimal,
            tag: tags::DATA_LAST,
            t_c_id: 1,
            data: &[0xBB],
        }
        .try_to_bytes()
        .unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn sb_value_da() {
        assert!(SbValue::new(true).data_available());
        assert!(!SbValue::new(false).data_available());
    }

    /// Rewrite the `length_field` of a TPDU wire (1-byte tag + minimal
    /// length) into the long form with `octets` length octets.
    fn widen(wire: &[u8], octets: usize) -> alloc::vec::Vec<u8> {
        let (value, hdr) = length::decode(&wire[1..]).unwrap();
        let mut out = alloc::vec![wire[0], 0x80 | octets as u8];
        for i in (0..octets).rev() {
            out.push((value >> (8 * i)) as u8);
        }
        out.extend_from_slice(&wire[1 + hdr..]);
        out
    }

    /// The module's `profile_reply` frame, captured raw on hardware
    /// (dvb-ci-runtime #337): the R_TPDU `length_field` is the long form
    /// `82 00 09` for the value 9. It must parse and re-serialize to exactly
    /// these 17 bytes, not the minimal `A0 09 ..`.
    #[test]
    fn captured_long_form_r_tpdu_round_trips_byte_exactly() {
        let frame: [u8; 17] = [
            0xA0, 0x82, 0x00, 0x09, 0x01, 0x90, 0x02, 0x00, 0x01, 0x9F, 0x80, 0x11, 0x00, 0x80,
            0x02, 0x01, 0x00,
        ];
        let r = ResponseTpdu::parse(&frame).unwrap();
        assert_eq!(r.length_form, LengthForm::Long { octets: 2 });
        assert_eq!(r.status_length_form, LengthForm::Minimal);
        assert_eq!(r.t_c_id, 1);
        assert_eq!(r.data, &frame[5..13]);
        assert_eq!(r.try_to_bytes().unwrap(), frame);
    }

    /// r10-W-4: each TPDU object round-trips every length form byte-for-byte,
    /// including the R_TPDU's own trailing Status `length_field`.
    #[test]
    fn every_tpdu_round_trips_each_length_form_byte_exactly() {
        macro_rules! forms {
            ($ty:ty, $wire:expr) => {{
                let wire: &[u8] = &$wire;
                assert_eq!(<$ty>::parse(wire).unwrap().try_to_bytes().unwrap(), wire);
                for octets in 1..=4 {
                    let wide = widen(wire, octets);
                    let parsed = <$ty>::parse(&wide).unwrap();
                    assert_eq!(
                        parsed.try_to_bytes().unwrap(),
                        wide,
                        "{} {octets}",
                        stringify!($ty)
                    );
                    assert_ne!(parsed, <$ty>::parse(wire).unwrap());
                }
            }};
        }
        forms!(TcObject, [tags::CREATE_T_C, 0x01, 0x05]);
        forms!(NewTc, [tags::NEW_T_C, 0x02, 0x01, 0x02]);
        forms!(TcError, [tags::T_C_ERROR, 0x02, 0x01, 0x01]);
        forms!(CommandTpdu, [tags::DATA_LAST, 0x03, 0x01, 0xAA, 0xBB]);
        forms!(
            ResponseTpdu,
            [
                tags::DATA_LAST,
                0x03,
                0x01,
                0xAA,
                0xBB,
                0x80,
                0x02,
                0x01,
                0x80
            ]
        );
        // The Status trailer's own length_field, widened independently.
        let wire = [
            tags::DATA_LAST,
            0x03,
            0x01,
            0xAA,
            0xBB,
            0x80,
            0x82,
            0x00,
            0x02,
            0x01,
            0x80,
        ];
        let r = ResponseTpdu::parse(&wire).unwrap();
        assert_eq!(r.status_length_form, LengthForm::Long { octets: 2 });
        assert_eq!(r.try_to_bytes().unwrap(), wire);
    }
}