spacepackets 0.17.0

Generic implementations for various CCSDS and ECSS packet standards
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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
//! # Support of the CCSDS Unified Space Data Link Protocol (USLP)
#![warn(missing_docs)]
use crate::{crc::CRC_CCITT_FALSE, ByteConversionError};

/// Only this version is supported by the library
pub const USLP_VERSION_NUMBER: u8 = 0b1100;

/// Identifies the association of the data contained in the transfer frame.
#[derive(Debug, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[bitbybit::bitenum(u1, exhaustive = true)]
#[repr(u8)]
pub enum SourceOrDestField {
    /// SCID refers to the source of the transfer frame.
    Source = 0,
    /// SCID refers to the destination of the transfer frame.
    Dest = 1,
}

/// Bypass sequence control flag.
#[derive(Debug, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[bitbybit::bitenum(u1, exhaustive = true)]
#[repr(u8)]
pub enum BypassSequenceControlFlag {
    /// Acceptance of this frame on the receiving end is subject to normal frame acceptance
    /// checks of FARM.
    SequenceControlledQoS = 0,
    /// Frame Acceptance Checks of FARM by the receiving end shall be bypassed.
    ExpeditedQoS = 1,
}

/// Protcol Control Command Flag.
#[derive(
    Debug, Copy, Clone, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum ProtocolControlCommandFlag {
    /// Transfer frame data field contains user data.
    TfdfContainsUserData = 0,
    /// Transfer frame data field contains protocol information.
    TfdfContainsProtocolInfo = 1,
}

/// USLP error enumeration.
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
pub enum UslpError {
    /// Byte conversion error.
    #[error("byte conversion error: {0}")]
    ByteConversion(#[from] ByteConversionError),
    /// Header is truncated, which is not supported.
    #[error("header is truncated, which is not supported")]
    HeaderIsTruncated,
    /// Invalid protocol ID.
    #[error("invalid protocol id: {0}")]
    InvalidProtocolId(u8),
    /// Invalid construction rule.
    #[error("invalid construction rule: {0}")]
    InvalidConstructionRule(u8),
    /// Invalid version number.
    #[error("invalid version number: {0}")]
    InvalidVersionNumber(u8),
    /// Invalid virtual channel ID.
    #[error("invalid virtual channel ID: {0}")]
    InvalidVcId(u8),
    /// Invalid MAP ID.
    #[error("invalid MAP ID: {0}")]
    InvalidMapId(u8),
    /// Checksum failure.
    #[error("checksum failure")]
    ChecksumFailure(u16),
}

/// Invalid value for length.
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[error("invalid value for length of the field")]
pub struct InvalidValueForLenError {
    value: u64,
    len: u8,
}

/// Primary header of a USLP transfer frame.
#[derive(Debug, Copy, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct PrimaryHeader {
    /// Spacecraft ID.
    pub spacecraft_id: u16,
    /// Source or destination identifier.
    pub source_or_dest_field: SourceOrDestField,
    /// Virtual channel ID.
    pub vc_id: u8,
    /// MAP ID.
    pub map_id: u8,
    frame_len_field: u16,
    /// Bypass sequence control flag.
    pub sequence_control_flag: BypassSequenceControlFlag,
    /// Procol control command flag.
    pub protocol_control_command_flag: ProtocolControlCommandFlag,
    /// Operational control field flag.
    pub ocf_flag: bool,
    vc_frame_count_len: u8,
    vc_frame_count: u64,
}

impl PrimaryHeader {
    /// Generic constructor.
    pub fn new(
        spacecraft_id: u16,
        source_or_dest_field: SourceOrDestField,
        vc_id: u8,
        map_id: u8,
        frame_len: u16,
    ) -> Result<Self, UslpError> {
        if vc_id > 0b111111 {
            return Err(UslpError::InvalidVcId(vc_id));
        }
        if map_id > 0b1111 {
            return Err(UslpError::InvalidMapId(map_id));
        }
        Ok(Self {
            spacecraft_id,
            source_or_dest_field,
            vc_id,
            map_id,
            frame_len_field: frame_len.saturating_sub(1),
            sequence_control_flag: BypassSequenceControlFlag::SequenceControlledQoS,
            protocol_control_command_flag: ProtocolControlCommandFlag::TfdfContainsUserData,
            ocf_flag: false,
            vc_frame_count_len: 0,
            vc_frame_count: 0,
        })
    }

    /// Set the virtual channel frame count.
    pub fn set_vc_frame_count(
        &mut self,
        count_len: u8,
        count: u64,
    ) -> Result<(), InvalidValueForLenError> {
        if count > 2_u64.pow(count_len as u32 * 8) - 1 {
            return Err(InvalidValueForLenError {
                value: count,
                len: count_len,
            });
        }
        self.vc_frame_count_len = count_len;
        self.vc_frame_count = count;
        Ok(())
    }

    /// Virtual channel frame count.
    #[inline]
    pub fn vc_frame_count(&self) -> u64 {
        self.vc_frame_count
    }

    /// Length of the virtual channel frame count field.
    #[inline]
    pub fn vc_frame_count_len(&self) -> u8 {
        self.vc_frame_count_len
    }

    /// Parse [Self] from raw bytes.
    pub fn from_bytes(buf: &[u8]) -> Result<Self, UslpError> {
        if buf.len() < 4 {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: buf.len(),
                expected: 4,
            }
            .into());
        }
        // Can only deal with regular frames for now.
        if (buf[3] & 0b1) == 1 {
            return Err(UslpError::HeaderIsTruncated);
        }
        // We could check this above, but this is a better error for the case where the user
        // tries to read a truncated frame.
        if buf.len() < 7 {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: buf.len(),
                expected: 7,
            }
            .into());
        }
        let version_number = (buf[0] >> 4) & 0b1111;
        if version_number != USLP_VERSION_NUMBER {
            return Err(UslpError::InvalidVersionNumber(version_number));
        }
        let source_or_dest_field = match (buf[2] >> 3) & 1 {
            0 => SourceOrDestField::Source,
            1 => SourceOrDestField::Dest,
            _ => unreachable!(),
        };
        let vc_frame_count_len = buf[6] & 0b111;
        if buf.len() < 7 + vc_frame_count_len as usize {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: buf.len(),
                expected: 7 + vc_frame_count_len as usize,
            }
            .into());
        }
        let vc_frame_count = match vc_frame_count_len {
            1 => buf[7] as u64,
            2 => u16::from_be_bytes(buf[7..9].try_into().unwrap()) as u64,
            4 => u32::from_be_bytes(buf[7..11].try_into().unwrap()) as u64,
            len => {
                let mut vcf_count = 0u64;
                let mut end = len;
                for byte in buf[7..7 + len as usize].iter() {
                    vcf_count |= (*byte as u64) << ((end - 1) * 8);
                    end -= 1;
                }
                vcf_count
            }
        };
        Ok(Self {
            spacecraft_id: (((buf[0] as u16) & 0b1111) << 12)
                | ((buf[1] as u16) << 4)
                | ((buf[2] as u16) >> 4) & 0b1111,
            source_or_dest_field,
            vc_id: ((buf[2] & 0b111) << 3) | (buf[3] >> 5) & 0b111,
            map_id: (buf[3] >> 1) & 0b1111,
            frame_len_field: ((buf[4] as u16) << 8) | buf[5] as u16,
            sequence_control_flag: ((buf[6] >> 7) & 0b1).try_into().unwrap(),
            protocol_control_command_flag: ((buf[6] >> 6) & 0b1).try_into().unwrap(),
            ocf_flag: ((buf[6] >> 3) & 0b1) != 0,
            vc_frame_count_len,
            vc_frame_count,
        })
    }

    /// Write primary header to bytes.
    pub fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        if buf.len() < self.len_header() {
            return Err(ByteConversionError::ToSliceTooSmall {
                found: buf.len(),
                expected: self.len_header(),
            });
        }
        buf[0] = (USLP_VERSION_NUMBER << 4) | ((self.spacecraft_id >> 12) as u8) & 0b1111;
        buf[1] = (self.spacecraft_id >> 4) as u8;
        buf[2] = (((self.spacecraft_id & 0b1111) as u8) << 4)
            | ((self.source_or_dest_field as u8) << 3)
            | (self.vc_id >> 3) & 0b111;
        buf[3] = ((self.vc_id & 0b111) << 5) | (self.map_id << 1);
        buf[4..6].copy_from_slice(&self.frame_len_field.to_be_bytes());
        buf[6] = ((self.sequence_control_flag as u8) << 7)
            | ((self.protocol_control_command_flag as u8) << 6)
            | ((self.ocf_flag as u8) << 3)
            | self.vc_frame_count_len;
        let mut packet_idx = 7;
        for idx in (0..self.vc_frame_count_len).rev() {
            buf[packet_idx] = ((self.vc_frame_count >> (idx * 8)) & 0xff) as u8;
            packet_idx += 1;
        }
        Ok(self.len_header())
    }

    /// Set frame length field.
    #[inline(always)]
    pub fn set_frame_len(&mut self, frame_len: usize) {
        // 4.1.2.7.2
        // The field contains a length count C that equals one fewer than the total octets
        // in the transfer frame.
        self.frame_len_field = frame_len.saturating_sub(1) as u16;
    }

    /// Length of primary header when written to bytes.
    #[inline(always)]
    pub fn len_header(&self) -> usize {
        7 + self.vc_frame_count_len as usize
    }

    /// Length of the entire frame.
    #[inline(always)]
    pub fn len_frame(&self) -> usize {
        // 4.1.2.7.2
        // The field contains a length count C that equals one fewer than the total octets
        // in the transfer frame.
        self.frame_len_field as usize + 1
    }
}

/// Custom implementation which skips the check whether the VC frame count length field is equal.
/// Only the actual VC count value is compared.
impl PartialEq for PrimaryHeader {
    fn eq(&self, other: &Self) -> bool {
        self.spacecraft_id == other.spacecraft_id
            && self.source_or_dest_field == other.source_or_dest_field
            && self.vc_id == other.vc_id
            && self.map_id == other.map_id
            && self.frame_len_field == other.frame_len_field
            && self.sequence_control_flag == other.sequence_control_flag
            && self.protocol_control_command_flag == other.protocol_control_command_flag
            && self.ocf_flag == other.ocf_flag
            && self.vc_frame_count == other.vc_frame_count
    }
}

/// USLP protocol ID enumeration.
#[derive(Debug, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[bitbybit::bitenum(u5, exhaustive = false)]
#[repr(u8)]
#[non_exhaustive]
pub enum UslpProtocolId {
    /// Space packets or encapsulation packets.
    SpacePacketsOrEncapsulation = 0b00000,
    /// COP-1 control commands within the TFDZ.
    Cop1ControlCommands = 0b00001,
    /// COP-P control commands within the TFDZ.
    CopPControlCommands = 0b00010,
    /// SDLS control commands within the TFDZ.
    Sdls = 0b00011,
    /// User defined octet stream.
    UserDefinedOctetStream = 0b00100,
    /// Proximity-1 Supervisory Protocol Data Units (SPDUs) within the TFDZ.
    Spdu = 0b00111,
    /// Entire fixed-length TFDZ contains idle data.
    Idle = 0b11111,
}

/// USLP construction rule enumeration.
#[derive(Debug, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[bitbybit::bitenum(u3, exhaustive = true)]
#[repr(u8)]
pub enum ConstructionRule {
    /// Indicated fixed-length TFDZ whose contents are CCSDS packets concatenated together, which
    /// span transfer frame boundaries. The First Header Pointer (FHP) is required for packet
    /// extraction.
    PacketSpanningMultipleFrames = 0b000,
    /// Start of a MAPA SDU or VCA SDU.
    StartOfMapaSduOrVcaSdu = 0b001,
    /// Continuing portion of a MAPA SDU.
    ContinuingPortionOfMapaSdu = 0b010,
    /// Octet stream.
    OctetStream = 0b011,
    /// Starting segment.
    StartingSegment = 0b100,
    /// Continuing segment.
    ContinuingSegment = 0b101,
    /// Last segment.
    LastSegment = 0b110,
    /// No segmentation.
    NoSegmentation = 0b111,
}

impl ConstructionRule {
    /// Is the construction rule applicable to fixed-length TFDZs?
    #[inline]
    pub const fn applicable_to_fixed_len_tfdz(&self) -> bool {
        match self {
            ConstructionRule::PacketSpanningMultipleFrames => true,
            ConstructionRule::StartOfMapaSduOrVcaSdu => true,
            ConstructionRule::ContinuingPortionOfMapaSdu => true,
            ConstructionRule::OctetStream => false,
            ConstructionRule::StartingSegment => false,
            ConstructionRule::ContinuingSegment => false,
            ConstructionRule::LastSegment => false,
            ConstructionRule::NoSegmentation => false,
        }
    }
}

/// Transfer frame data field header.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct TransferFrameDataFieldHeader {
    /// Construction rule for the TFDZ.
    construction_rule: ConstructionRule,
    uslp_protocol_id: UslpProtocolId,
    /// First header or last valid octet pointer. Only present if the constuction rule indicated
    /// a fixed-length TFDZ.
    fhp_or_lvo: Option<u16>,
}

impl TransferFrameDataFieldHeader {
    /// Length of the header when written to bytes.
    #[inline]
    pub const fn len_header(&self) -> usize {
        if self.construction_rule.applicable_to_fixed_len_tfdz() {
            3
        } else {
            1
        }
    }

    /// Construction rule.
    #[inline]
    pub const fn construction_rule(&self) -> ConstructionRule {
        self.construction_rule
    }

    /// USLP protocol ID.
    #[inline]
    pub const fn uslp_protocol_id(&self) -> UslpProtocolId {
        self.uslp_protocol_id
    }

    /// FHP or LVO field when present.
    #[inline]
    pub const fn fhp_or_lvo(&self) -> Option<u16> {
        self.fhp_or_lvo
    }

    /// Parse [Self] from raw bytes.
    pub fn from_bytes(buf: &[u8]) -> Result<Self, UslpError> {
        if buf.is_empty() {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: 0,
                expected: 1,
            }
            .into());
        }
        let construction_rule = ConstructionRule::try_from((buf[0] >> 5) & 0b111)
            .map_err(|e| UslpError::InvalidConstructionRule(e.number))?;
        let mut fhp_or_lvo = None;
        if construction_rule.applicable_to_fixed_len_tfdz() {
            if buf.len() < 3 {
                return Err(ByteConversionError::FromSliceTooSmall {
                    found: buf.len(),
                    expected: 3,
                }
                .into());
            }
            fhp_or_lvo = Some(u16::from_be_bytes(buf[1..3].try_into().unwrap()));
        }
        Ok(Self {
            construction_rule,
            uslp_protocol_id: UslpProtocolId::try_from(buf[0] & 0b11111)
                .map_err(|e| UslpError::InvalidProtocolId(e.number))?,
            fhp_or_lvo,
        })
    }
}

/// Simple USLP transfer frame reader.
///
/// Currently, only insert zone lengths of 0 are supported.
#[derive(Debug)]
pub struct TransferFrameReader<'buf> {
    primary_header: PrimaryHeader,
    data_field_header: TransferFrameDataFieldHeader,
    data: &'buf [u8],
    operational_control_field: Option<u32>,
}

impl<'buf> TransferFrameReader<'buf> {
    /// This function assumes an insert zone length of 0.
    pub fn from_bytes(
        buf: &'buf [u8],
        has_fecf: bool,
    ) -> Result<TransferFrameReader<'buf>, UslpError> {
        let primary_header = PrimaryHeader::from_bytes(buf)?;
        if primary_header.len_frame() > buf.len() {
            return Err(ByteConversionError::FromSliceTooSmall {
                expected: primary_header.len_frame(),
                found: buf.len(),
            }
            .into());
        }
        let data_field_header =
            TransferFrameDataFieldHeader::from_bytes(&buf[primary_header.len_header()..])?;
        let data_idx = primary_header.len_header() + data_field_header.len_header();
        let frame_len = primary_header.len_frame();
        let mut operational_control_field = None;
        let mut data_len = frame_len - data_idx;
        if has_fecf {
            data_len -= 2;
        }
        if primary_header.ocf_flag {
            data_len -= 4;
            operational_control_field = Some(u32::from_be_bytes(
                buf[data_idx + data_len..data_idx + data_len + 4]
                    .try_into()
                    .unwrap(),
            ));
        }
        let data_end = data_idx + data_len;
        if has_fecf {
            let mut digest = CRC_CCITT_FALSE.digest();
            digest.update(&buf[0..frame_len]);
            if digest.finalize() != 0 {
                return Err(UslpError::ChecksumFailure(u16::from_be_bytes(
                    buf[frame_len - 2..frame_len].try_into().unwrap(),
                )));
            }
        }
        Ok(Self {
            primary_header,
            data_field_header,
            data: buf[data_idx..data_end].try_into().unwrap(),
            operational_control_field,
        })
    }

    /// Length of the entire frame.
    #[inline]
    pub fn len_frame(&self) -> usize {
        self.primary_header.len_frame()
    }

    /// Primary header.
    #[inline]
    pub fn primary_header(&self) -> &PrimaryHeader {
        &self.primary_header
    }

    /// Transfer frame data field header.
    #[inline]
    pub fn data_field_header(&self) -> &TransferFrameDataFieldHeader {
        &self.data_field_header
    }

    /// Data contained in the transfer frame data field.
    #[inline]
    pub fn data(&self) -> &'buf [u8] {
        self.data
    }

    /// Operational control field when present.
    #[inline]
    pub fn operational_control_field(&self) -> Option<u32> {
        self.operational_control_field
    }
}

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

    fn common_basic_check(buf: &[u8]) {
        assert_eq!(buf[0] >> 4, USLP_VERSION_NUMBER);
        // First four bits SCID.
        assert_eq!(buf[0] & 0b1111, 0b1010);
        // Next eight bits SCID.
        assert_eq!(buf[1], 0b01011100);
        // Last four bits SCID.
        assert_eq!(buf[2] >> 4, 0b0011);
        assert_eq!((buf[2] >> 3) & 0b1, SourceOrDestField::Dest as u8);
        // First three bits VCID.
        assert_eq!(buf[2] & 0b111, 0b110);
        // Last three bits VCID.
        assert_eq!(buf[3] >> 5, 0b101);
        // MAP ID
        assert_eq!((buf[3] >> 1) & 0b1111, 0b1010);
        // End of primary header flag
        assert_eq!(buf[3] & 0b1, 0);
        assert_eq!(u16::from_be_bytes(buf[4..6].try_into().unwrap()), 0x2344);
    }

    #[test]
    fn test_basic_0() {
        let mut buf: [u8; 8] = [0; 8];
        // Should be all zeros after writing.
        buf[6] = 0xff;
        let primary_header = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b110101,
            0b1010,
            0x2345,
        )
        .unwrap();
        // Virtual channel count 0.
        assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 7);
        common_basic_check(&buf);
        assert_eq!(primary_header.vc_frame_count_len(), 0);
        assert_eq!(primary_header.vc_frame_count(), 0);
        // Bypass / Sequence Control Flag.
        assert_eq!(
            (buf[6] >> 7) & 0b1,
            BypassSequenceControlFlag::SequenceControlledQoS as u8
        );
        // Protocol Control Command Flag.
        assert_eq!(
            (buf[6] >> 6) & 0b1,
            ProtocolControlCommandFlag::TfdfContainsUserData as u8
        );
        // OCF flag.
        assert_eq!((buf[6] >> 3) & 0b1, false as u8);
        // VCF count length.
        assert_eq!(buf[6] & 0b111, 0);
    }

    #[test]
    fn test_basic_1() {
        let mut buf: [u8; 16] = [0; 16];
        // Should be all zeros after writing.
        buf[6] = 0xff;
        let mut primary_header = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b110101,
            0b1010,
            0x2345,
        )
        .unwrap();
        primary_header.sequence_control_flag = BypassSequenceControlFlag::ExpeditedQoS;
        primary_header.protocol_control_command_flag =
            ProtocolControlCommandFlag::TfdfContainsProtocolInfo;
        primary_header.ocf_flag = true;
        primary_header.set_vc_frame_count(4, 0x12345678).unwrap();
        // Virtual channel count 4.
        assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 11);
        assert_eq!(primary_header.vc_frame_count_len(), 4);
        assert_eq!(primary_header.vc_frame_count(), 0x12345678);
        common_basic_check(&buf);
        // Bypass / Sequence Control Flag.
        assert_eq!(
            (buf[6] >> 7) & 0b1,
            BypassSequenceControlFlag::ExpeditedQoS as u8
        );
        // Protocol Control Command Flag.
        assert_eq!(
            (buf[6] >> 6) & 0b1,
            ProtocolControlCommandFlag::TfdfContainsProtocolInfo as u8
        );
        // OCF flag.
        assert_eq!((buf[6] >> 3) & 0b1, true as u8);
        // VCF count length.
        assert_eq!(buf[6] & 0b111, 4);
        assert_eq!(
            u32::from_be_bytes(buf[7..11].try_into().unwrap()),
            0x12345678
        );
    }

    #[test]
    fn test_vcf_count_len_two() {
        let mut buf: [u8; 16] = [0; 16];
        // Should be all zeros after writing.
        buf[6] = 0xff;
        let mut primary_header = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b110101,
            0b1010,
            0x2345,
        )
        .unwrap();
        primary_header.set_vc_frame_count(2, 5).unwrap();
        assert_eq!(primary_header.vc_frame_count_len(), 2);
        assert_eq!(primary_header.vc_frame_count(), 5);
        assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 9);
        assert_eq!(buf[6] & 0b111, 2);
        assert_eq!(u16::from_be_bytes(buf[7..9].try_into().unwrap()), 5);

        let primary_header = PrimaryHeader::from_bytes(&buf).unwrap();
        assert_eq!(primary_header.vc_frame_count_len(), 2);
        assert_eq!(primary_header.vc_frame_count(), 5);
    }

    #[test]
    fn test_vcf_count_len_one() {
        let mut buf: [u8; 16] = [0; 16];
        // Should be all zeros after writing.
        buf[6] = 0xff;
        let mut primary_header = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b110101,
            0b1010,
            0x2345,
        )
        .unwrap();
        primary_header.set_vc_frame_count(1, 255).unwrap();
        assert_eq!(primary_header.vc_frame_count_len(), 1);
        assert_eq!(primary_header.vc_frame_count(), 255);
        assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 8);
        assert_eq!(buf[6] & 0b111, 1);
        assert_eq!(buf[7], 255);

        let primary_header = PrimaryHeader::from_bytes(&buf).unwrap();
        assert_eq!(primary_header.vc_frame_count_len(), 1);
        assert_eq!(primary_header.vc_frame_count(), 255);
    }

    #[test]
    fn test_reading_0() {
        let mut buf: [u8; 8] = [0; 8];
        let primary_header = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b110101,
            0b1010,
            0x2345,
        )
        .unwrap();
        assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 7);
        let parsed_header = PrimaryHeader::from_bytes(&buf).unwrap();
        assert_eq!(parsed_header, primary_header);
    }

    #[test]
    fn test_reading_1() {
        let mut buf: [u8; 16] = [0; 16];
        let mut primary_header = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b110101,
            0b1010,
            0x2345,
        )
        .unwrap();
        primary_header.sequence_control_flag = BypassSequenceControlFlag::ExpeditedQoS;
        primary_header.protocol_control_command_flag =
            ProtocolControlCommandFlag::TfdfContainsProtocolInfo;
        primary_header.ocf_flag = true;
        primary_header.set_vc_frame_count(4, 0x12345678).unwrap();
        assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 11);
        let parsed_header = PrimaryHeader::from_bytes(&buf).unwrap();
        assert_eq!(parsed_header, primary_header);
    }

    #[test]
    fn test_invalid_vcid() {
        let error = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b1101011,
            0b1010,
            0x2345,
        );
        assert!(error.is_err());
        let error = error.unwrap_err();
        matches!(error, UslpError::InvalidVcId(0b1101011));
    }

    #[test]
    fn test_invalid_mapid() {
        let error = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b110101,
            0b10101,
            0x2345,
        );
        assert!(error.is_err());
        let error = error.unwrap_err();
        matches!(error, UslpError::InvalidMapId(0b10101));
    }

    #[test]
    fn test_invalid_vc_count() {
        let mut primary_header = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b110101,
            0b1010,
            0x2345,
        )
        .unwrap();
        matches!(
            primary_header.set_vc_frame_count(0, 1).unwrap_err(),
            InvalidValueForLenError { value: 1, len: 0 }
        );
        matches!(
            primary_header.set_vc_frame_count(1, 256).unwrap_err(),
            InvalidValueForLenError { value: 256, len: 1 }
        );
    }

    #[test]
    fn test_frame_parser() {
        let mut buf: [u8; 32] = [0; 32];
        // Build a variable frame manually.
        let mut primary_header =
            PrimaryHeader::new(0x01, SourceOrDestField::Dest, 0b110101, 0b1010, 0).unwrap();
        let header_len = primary_header.len_header();
        buf[header_len] = ((ConstructionRule::NoSegmentation as u8) << 5)
            | (UslpProtocolId::UserDefinedOctetStream as u8) & 0b11111;
        buf[header_len + 1] = 0x42;
        // 1 byte TFDH, 1 byte data, 2 bytes CRC.
        primary_header.set_frame_len(header_len + 4);
        primary_header.write_to_be_bytes(&mut buf).unwrap();
        // Calculate and write CRC16.
        let mut digest = CRC_CCITT_FALSE.digest();
        digest.update(&buf[0..header_len + 2]);
        buf[header_len + 2..header_len + 4].copy_from_slice(&digest.finalize().to_be_bytes());
        // Now parse the frame.
        let frame = TransferFrameReader::from_bytes(&buf, true).unwrap();
        assert_eq!(*frame.primary_header(), primary_header);
        assert_eq!(frame.data().len(), 1);
        assert_eq!(frame.data()[0], 0x42);
        assert_eq!(
            frame.data_field_header().uslp_protocol_id(),
            UslpProtocolId::UserDefinedOctetStream
        );
        assert_eq!(
            frame.data_field_header().construction_rule(),
            ConstructionRule::NoSegmentation
        );
        assert!(frame.data_field_header().fhp_or_lvo().is_none());
        assert_eq!(frame.len_frame(), 11);
        assert!(frame.operational_control_field().is_none());
    }

    #[test]
    fn test_frame_parser_invalid_checksum() {
        let mut buf: [u8; 32] = [0; 32];
        // Build a variable frame manually.
        let mut primary_header =
            PrimaryHeader::new(0x01, SourceOrDestField::Dest, 0b110101, 0b1010, 0).unwrap();
        let header_len = primary_header.len_header();
        buf[header_len] = ((ConstructionRule::NoSegmentation as u8) << 5)
            | (UslpProtocolId::UserDefinedOctetStream as u8) & 0b11111;
        buf[header_len + 1] = 0x42;
        // 1 byte TFDH, 1 byte data, 2 bytes CRC.
        primary_header.set_frame_len(header_len + 4);
        primary_header.write_to_be_bytes(&mut buf).unwrap();
        // Now parse the frame without having calculated the checksum.
        match TransferFrameReader::from_bytes(&buf, true) {
            Ok(_) => panic!("transfer frame read call did not fail"),
            Err(e) => {
                assert_eq!(e, UslpError::ChecksumFailure(0));
            }
        }
    }

    #[test]
    fn test_frame_parser_buf_too_small() {
        let mut buf: [u8; 32] = [0; 32];
        // Build a variable frame manually.
        let mut primary_header =
            PrimaryHeader::new(0x01, SourceOrDestField::Dest, 0b110101, 0b1010, 0).unwrap();
        let header_len = primary_header.len_header();
        buf[header_len] = ((ConstructionRule::NoSegmentation as u8) << 5)
            | (UslpProtocolId::UserDefinedOctetStream as u8) & 0b11111;
        buf[header_len + 1] = 0x42;
        // 1 byte TFDH, 1 byte data, 2 bytes CRC.
        primary_header.set_frame_len(header_len + 4);
        primary_header.write_to_be_bytes(&mut buf).unwrap();
        // Now parse the frame.
        let error = TransferFrameReader::from_bytes(&buf[0..7], true).unwrap_err();
        assert_eq!(
            error,
            ByteConversionError::FromSliceTooSmall {
                expected: primary_header.len_frame(),
                found: 7
            }
            .into()
        );
    }

    #[test]
    fn test_from_bytes_too_small_0() {
        let buf: [u8; 3] = [0; 3];
        assert_eq!(
            PrimaryHeader::from_bytes(&buf).unwrap_err(),
            ByteConversionError::FromSliceTooSmall {
                found: 3,
                expected: 4
            }
            .into()
        );
    }

    #[test]
    fn test_from_bytes_too_small_1() {
        let buf: [u8; 6] = [0; 6];
        assert_eq!(
            PrimaryHeader::from_bytes(&buf).unwrap_err(),
            ByteConversionError::FromSliceTooSmall {
                found: 6,
                expected: 7
            }
            .into()
        );
    }

    #[test]
    fn test_from_bytes_truncated_not_supported() {
        let mut buf: [u8; 7] = [0; 7];
        let primary_header =
            PrimaryHeader::new(0x01, SourceOrDestField::Dest, 0b110101, 0b1010, 0).unwrap();
        primary_header.write_to_be_bytes(&mut buf).unwrap();
        // Set truncated header flag manually.
        buf[3] |= 0b1;
        assert_eq!(
            PrimaryHeader::from_bytes(&buf).unwrap_err(),
            UslpError::HeaderIsTruncated
        );
    }

    #[test]
    fn test_from_bytes_too_small_2() {
        let mut buf: [u8; 16] = [0; 16];
        // Should be all zeros after writing.
        buf[6] = 0xff;
        let mut primary_header = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b110101,
            0b1010,
            0x2345,
        )
        .unwrap();
        primary_header.set_vc_frame_count(4, 0x12345678).unwrap();
        primary_header.write_to_be_bytes(&mut buf).unwrap();

        assert_eq!(
            PrimaryHeader::from_bytes(&buf[0..8]).unwrap_err(),
            UslpError::ByteConversion(ByteConversionError::FromSliceTooSmall {
                found: 8,
                expected: 11
            })
        );
    }

    #[test]
    fn test_invalid_version_number() {
        let mut buf: [u8; 7] = [0; 7];
        let primary_header =
            PrimaryHeader::new(0x01, SourceOrDestField::Dest, 0b110101, 0b1010, 0).unwrap();
        primary_header.write_to_be_bytes(&mut buf).unwrap();
        buf[0] &= 0b00001111;
        assert_eq!(
            PrimaryHeader::from_bytes(&buf).unwrap_err(),
            UslpError::InvalidVersionNumber(0)
        );
    }

    #[test]
    fn test_primary_header_buf_too_small() {
        let primary_header = PrimaryHeader::new(
            0b10100101_11000011,
            SourceOrDestField::Dest,
            0b110101,
            0b1010,
            0x2345,
        )
        .unwrap();
        if let Err(ByteConversionError::ToSliceTooSmall { found, expected }) =
            primary_header.write_to_be_bytes(&mut [0; 4])
        {
            assert_eq!(found, 4);
            assert_eq!(expected, 7);
        } else {
            panic!("writing primary header did not fail or failed with wrong error");
        }
    }

    #[test]
    fn test_applicability_contr_rules() {
        assert!(ConstructionRule::PacketSpanningMultipleFrames.applicable_to_fixed_len_tfdz());
        assert!(ConstructionRule::StartOfMapaSduOrVcaSdu.applicable_to_fixed_len_tfdz());
        assert!(ConstructionRule::ContinuingPortionOfMapaSdu.applicable_to_fixed_len_tfdz());
        assert!(!ConstructionRule::OctetStream.applicable_to_fixed_len_tfdz());
        assert!(!ConstructionRule::StartingSegment.applicable_to_fixed_len_tfdz());
        assert!(!ConstructionRule::ContinuingSegment.applicable_to_fixed_len_tfdz());
        assert!(!ConstructionRule::LastSegment.applicable_to_fixed_len_tfdz());
        assert!(!ConstructionRule::NoSegmentation.applicable_to_fixed_len_tfdz());
    }

    #[test]
    fn test_header_len_correctness() {
        let mut tfdh = TransferFrameDataFieldHeader {
            construction_rule: ConstructionRule::PacketSpanningMultipleFrames,
            uslp_protocol_id: UslpProtocolId::UserDefinedOctetStream,
            fhp_or_lvo: Some(0),
        };
        assert_eq!(tfdh.len_header(), 3);
        tfdh = TransferFrameDataFieldHeader {
            construction_rule: ConstructionRule::StartOfMapaSduOrVcaSdu,
            uslp_protocol_id: UslpProtocolId::UserDefinedOctetStream,
            fhp_or_lvo: Some(0),
        };
        assert_eq!(tfdh.len_header(), 3);
        tfdh = TransferFrameDataFieldHeader {
            construction_rule: ConstructionRule::ContinuingPortionOfMapaSdu,
            uslp_protocol_id: UslpProtocolId::UserDefinedOctetStream,
            fhp_or_lvo: Some(0),
        };
        assert_eq!(tfdh.len_header(), 3);
        tfdh = TransferFrameDataFieldHeader {
            construction_rule: ConstructionRule::OctetStream,
            uslp_protocol_id: UslpProtocolId::UserDefinedOctetStream,
            fhp_or_lvo: None,
        };
        assert_eq!(tfdh.len_header(), 1);
    }

    #[test]
    fn test_frame_data_field_header_from_bytes_too_small() {
        let buf: [u8; 0] = [];
        assert_eq!(
            TransferFrameDataFieldHeader::from_bytes(&buf).unwrap_err(),
            ByteConversionError::FromSliceTooSmall {
                found: 0,
                expected: 1
            }
            .into()
        );
    }
}