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
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
//! CFDP Packet Data Unit (PDU) support.
use crate::cfdp::pdu::ack::InvalidAckedDirectiveCodeError;
use crate::cfdp::pdu::nak::InvalidStartOrEndOfScopeError;
use crate::cfdp::*;
use crate::crc::CRC_CCITT_FALSE;
use crate::util::{UnsignedByteField, UnsignedByteFieldU8, UnsignedEnum};
use crate::ByteConversionError;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;

pub mod ack;
pub mod eof;
pub mod file_data;
pub mod finished;
pub mod metadata;
pub mod nak;

/// File directive type.
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum FileDirectiveType {
    /// EOF.
    Eof = 0x04,
    /// Finished.
    Finished = 0x05,
    /// ACK.
    Ack = 0x06,
    /// Metadata.
    Metadata = 0x07,
    /// NAK.
    Nak = 0x08,
    /// Prompt.
    Prompt = 0x09,
    /// Keep Alive.
    KeepAlive = 0x0c,
}

/// PDU error.
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum PduError {
    /// Byte conversion error.
    #[error("byte conversion error: {0}")]
    ByteConversion(#[from] ByteConversionError),
    /// Found version ID invalid, not equal to [super::CFDP_VERSION_2].
    #[error("CFDP version missmatch, found {0}, expected {ver}", ver = super::CFDP_VERSION_2)]
    CfdpVersionMissmatch(u8),
    /// Invalid length for the entity ID detected. Only the values 1, 2, 4 and 8 are supported.
    #[error("invalid PDU entity ID length {0}, only [1, 2, 4, 8] are allowed")]
    InvalidEntityLen(u8),
    /// Invalid length for the entity ID detected. Only the values 1, 2, 4 and 8 are supported.
    #[error("invalid transaction ID length {0}")]
    InvalidTransactionSeqNumLen(u8),
    /// Source and destination entity ID lengths do not match.
    #[error(
        "missmatch of PDU source ID length {src_id_len} and destination ID length {dest_id_len}"
    )]
    SourceDestIdLenMissmatch {
        /// Source ID length.
        src_id_len: usize,
        /// Destination ID length.
        dest_id_len: usize,
    },
    /// Wrong directive type, for example when parsing the directive field for a file directive
    /// PDU.
    #[error("wrong directive type, found {found:?}, expected {expected:?}")]
    WrongDirectiveType {
        /// Found directive type.
        found: FileDirectiveType,
        /// Expected directive type.
        expected: FileDirectiveType,
    },
    /// The directive type field contained a value not in the range of permitted values. This can
    /// also happen if an invalid value is passed to the ACK PDU reader.
    #[error("invalid directive type, found {found:?}, expected {expected:?}")]
    InvalidDirectiveType {
        /// Found raw directive type.
        found: u8,
        /// Expected raw directive type if applicable.
        expected: Option<FileDirectiveType>,
    },
    /// Invalid start or end of scope for a NAK PDU.
    #[error("nak pdu: {0}")]
    InvalidStartOrEndOfScope(#[from] InvalidStartOrEndOfScopeError),
    /// Invalid condition code. Contains the raw detected value.
    #[error("invalid condition code {0}")]
    InvalidConditionCode(u8),
    /// Invalid checksum type which is not part of the checksums listed in the
    /// [SANA Checksum Types registry](https://sanaregistry.org/r/checksum_identifiers/).
    #[error("invalid checksum type {0}")]
    InvalidChecksumType(u8),
    /// File size is too large.
    #[error("file size {0} too large")]
    FileSizeTooLarge(u64),
    /// If the CRC flag for a PDU is enabled and the checksum check fails. Contains raw 16-bit CRC.
    #[error("checksum error for checksum {0}")]
    Checksum(u16),
    /// Generic error for invalid PDU formats.
    #[error("generic PDU format error")]
    Format,
    /// Error handling a TLV field.
    #[error("PDU error: {0}")]
    TlvLv(#[from] TlvLvError),
}

impl From<InvalidAckedDirectiveCodeError> for PduError {
    fn from(value: InvalidAckedDirectiveCodeError) -> Self {
        Self::InvalidDirectiveType {
            found: value.0 as u8,
            expected: None,
        }
    }
}

/// Generic trait for a PDU which can be written to bytes.
pub trait WritablePduPacket {
    /// Length when written to bytes.
    fn len_written(&self) -> usize;

    /// Write the PDU to a raw buffer, returning the written length.
    fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError>;

    /// Convert the PDU to an owned vector of bytes.
    #[cfg(feature = "alloc")]
    fn to_vec(&self) -> Result<Vec<u8>, PduError> {
        // This is the correct way to do this. See
        // [this issue](https://github.com/rust-lang/rust-clippy/issues/4483) for caveats of more
        // "efficient" implementations.
        let mut vec = alloc::vec![0; self.len_written()];
        self.write_to_bytes(&mut vec)?;
        Ok(vec)
    }
}

/// Abstraction trait for fields and properties common for all PDUs.
pub trait CfdpPdu {
    /// PDU header.
    fn pdu_header(&self) -> &PduHeader;

    /// Source ID (file sender).
    #[inline]
    fn source_id(&self) -> UnsignedByteField {
        self.pdu_header().common_pdu_conf().source_entity_id
    }

    /// Destination ID (file sender).
    #[inline]
    fn dest_id(&self) -> UnsignedByteField {
        self.pdu_header().common_pdu_conf().dest_entity_id
    }

    /// Transaction sequence number.
    #[inline]
    fn transaction_seq_num(&self) -> UnsignedByteField {
        self.pdu_header().common_pdu_conf().transaction_seq_num
    }

    /// Transmission mode.
    #[inline]
    fn transmission_mode(&self) -> TransmissionMode {
        self.pdu_header().common_pdu_conf().trans_mode
    }

    /// Direction.
    #[inline]
    fn direction(&self) -> Direction {
        self.pdu_header().common_pdu_conf().direction
    }

    /// CRC flag.
    #[inline]
    fn crc_flag(&self) -> CrcFlag {
        self.pdu_header().common_pdu_conf().crc_flag
    }

    /// File flag.
    #[inline]
    fn file_flag(&self) -> LargeFileFlag {
        self.pdu_header().common_pdu_conf().file_flag
    }

    /// PDU type.
    #[inline]
    fn pdu_type(&self) -> PduType {
        self.pdu_header().pdu_type()
    }

    /// File directive type when applicable.
    fn file_directive_type(&self) -> Option<FileDirectiveType>;
}

/// Common configuration fields for a PDU.
///
/// Please note that this structure has a custom implementation of [PartialEq] which only
/// compares the values for source entity ID, destination entity ID and transaction sequence
/// number. This permits that those fields can have different widths, as long as the value is the
/// same.
#[derive(Debug, Copy, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct CommonPduConfig {
    source_entity_id: UnsignedByteField,
    dest_entity_id: UnsignedByteField,
    /// Transaction sequence number.
    pub transaction_seq_num: UnsignedByteField,
    /// Transmission mode.
    pub trans_mode: TransmissionMode,
    /// File flag.
    pub file_flag: LargeFileFlag,
    /// CRC flag.
    pub crc_flag: CrcFlag,
    /// Direction.
    pub direction: Direction,
}

// TODO: Builder pattern might be applicable here..
impl CommonPduConfig {
    /// Generic constructor.
    #[inline]
    pub fn new(
        source_id: impl Into<UnsignedByteField>,
        dest_id: impl Into<UnsignedByteField>,
        transaction_seq_num: impl Into<UnsignedByteField>,
        trans_mode: TransmissionMode,
        file_flag: LargeFileFlag,
        crc_flag: CrcFlag,
        direction: Direction,
    ) -> Result<Self, PduError> {
        let (source_id, dest_id) = Self::source_dest_id_check(source_id, dest_id)?;
        let transaction_seq_num = transaction_seq_num.into();
        if transaction_seq_num.size() != 1
            && transaction_seq_num.size() != 2
            && transaction_seq_num.size() != 4
            && transaction_seq_num.size() != 8
        {
            return Err(PduError::InvalidTransactionSeqNumLen(
                transaction_seq_num.size() as u8,
            ));
        }
        Ok(Self {
            source_entity_id: source_id,
            dest_entity_id: dest_id,
            transaction_seq_num,
            trans_mode,
            file_flag,
            crc_flag,
            direction,
        })
    }

    /// Constructor for custom byte field with default field values for the other fields.
    #[inline]
    pub fn new_with_byte_fields(
        source_id: impl Into<UnsignedByteField>,
        dest_id: impl Into<UnsignedByteField>,
        transaction_seq_num: impl Into<UnsignedByteField>,
    ) -> Result<Self, PduError> {
        Self::new(
            source_id,
            dest_id,
            transaction_seq_num,
            TransmissionMode::Acknowledged,
            LargeFileFlag::Normal,
            CrcFlag::NoCrc,
            Direction::TowardsReceiver,
        )
    }

    /// Source ID (file sender).
    #[inline]
    pub fn source_id(&self) -> UnsignedByteField {
        self.source_entity_id
    }

    #[inline]
    fn source_dest_id_check(
        source_id: impl Into<UnsignedByteField>,
        dest_id: impl Into<UnsignedByteField>,
    ) -> Result<(UnsignedByteField, UnsignedByteField), PduError> {
        let source_id = source_id.into();
        let dest_id = dest_id.into();
        if source_id.size() != dest_id.size() {
            return Err(PduError::SourceDestIdLenMissmatch {
                src_id_len: source_id.size(),
                dest_id_len: dest_id.size(),
            });
        }
        if source_id.size() != 1
            && source_id.size() != 2
            && source_id.size() != 4
            && source_id.size() != 8
        {
            return Err(PduError::InvalidEntityLen(source_id.size() as u8));
        }
        Ok((source_id, dest_id))
    }

    /// Set the source and destination ID field.
    #[inline]
    pub fn set_source_and_dest_id(
        &mut self,
        source_id: impl Into<UnsignedByteField>,
        dest_id: impl Into<UnsignedByteField>,
    ) -> Result<(), PduError> {
        let (source_id, dest_id) = Self::source_dest_id_check(source_id, dest_id)?;
        self.source_entity_id = source_id;
        self.dest_entity_id = dest_id;
        Ok(())
    }

    /// Destination ID (file receiver).
    #[inline]
    pub fn dest_id(&self) -> UnsignedByteField {
        self.dest_entity_id
    }
}

impl Default for CommonPduConfig {
    /// The defaults for the source ID, destination ID and the transaction sequence number is the
    /// [UnsignedByteFieldU8] with an intitial value of 0
    #[inline]
    fn default() -> Self {
        // The new function can not fail for these input parameters.
        Self::new(
            UnsignedByteFieldU8::new(0),
            UnsignedByteFieldU8::new(0),
            UnsignedByteFieldU8::new(0),
            TransmissionMode::Acknowledged,
            LargeFileFlag::Normal,
            CrcFlag::NoCrc,
            Direction::TowardsReceiver,
        )
        .unwrap()
    }
}

impl PartialEq for CommonPduConfig {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.source_entity_id.value() == other.source_entity_id.value()
            && self.dest_entity_id.value() == other.dest_entity_id.value()
            && self.transaction_seq_num.value() == other.transaction_seq_num.value()
            && self.trans_mode == other.trans_mode
            && self.file_flag == other.file_flag
            && self.crc_flag == other.crc_flag
            && self.direction == other.direction
    }
}

/// Fixed header length of the PDU header.
pub const FIXED_HEADER_LEN: usize = 4;

/// Abstraction for the PDU header common to all CFDP PDUs.
///
/// For detailed information, refer to chapter 5.1 of the CFDP standard.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct PduHeader {
    pdu_type: PduType,
    pdu_conf: CommonPduConfig,
    seg_metadata_flag: SegmentMetadataFlag,
    seg_ctrl: SegmentationControl,
    pdu_datafield_len: u16,
}

impl PduHeader {
    /// Fixed length of the PDU header when written to a raw buffer.
    pub const FIXED_LEN: usize = FIXED_HEADER_LEN;

    /// Constructor for a File Data PDU header.
    #[inline]
    pub fn new_for_file_data(
        pdu_conf: CommonPduConfig,
        pdu_datafield_len: u16,
        seg_metadata_flag: SegmentMetadataFlag,
        seg_ctrl: SegmentationControl,
    ) -> Self {
        Self::new_generic(
            PduType::FileData,
            pdu_conf,
            pdu_datafield_len,
            seg_metadata_flag,
            seg_ctrl,
        )
    }

    /// Constructor for a file data PDU.
    #[inline]
    pub fn new_for_file_data_default(pdu_conf: CommonPduConfig, pdu_datafield_len: u16) -> Self {
        Self::new_generic(
            PduType::FileData,
            pdu_conf,
            pdu_datafield_len,
            SegmentMetadataFlag::NotPresent,
            SegmentationControl::NoRecordBoundaryPreservation,
        )
    }

    /// Constructor for a file directive PDU.
    #[inline]
    pub fn new_for_file_directive(pdu_conf: CommonPduConfig, pdu_datafield_len: u16) -> Self {
        Self::new_generic(
            PduType::FileDirective,
            pdu_conf,
            pdu_datafield_len,
            SegmentMetadataFlag::NotPresent,
            SegmentationControl::NoRecordBoundaryPreservation,
        )
    }

    /// Constructor from a given [CommonPduConfig] and for a file directive PDU.
    #[inline]
    pub fn from_pdu_conf_for_file_directive(pdu_conf: CommonPduConfig) -> Self {
        Self::new_generic(
            PduType::FileDirective,
            pdu_conf,
            0,
            SegmentMetadataFlag::NotPresent,
            SegmentationControl::NoRecordBoundaryPreservation,
        )
    }

    /// Generic constructor.
    #[inline]
    pub fn new_generic(
        pdu_type: PduType,
        pdu_conf: CommonPduConfig,
        pdu_datafield_len: u16,
        seg_metadata_flag: SegmentMetadataFlag,
        seg_ctrl: SegmentationControl,
    ) -> Self {
        Self {
            pdu_type,
            pdu_conf,
            seg_metadata_flag,
            seg_ctrl,
            pdu_datafield_len,
        }
    }

    /// Returns only the length of the PDU header when written to a raw buffer.
    #[inline]
    pub fn header_len(&self) -> usize {
        FIXED_HEADER_LEN
            + self.pdu_conf.source_entity_id.size()
            + self.pdu_conf.transaction_seq_num.size()
            + self.pdu_conf.dest_entity_id.size()
    }

    /// PDU data field length.
    #[inline]
    pub fn pdu_datafield_len(&self) -> usize {
        self.pdu_datafield_len.into()
    }

    /// Returns the full length of the PDU when written to a raw buffer, which is the header length
    /// plus the PDU datafield length.
    #[inline]
    pub fn pdu_len(&self) -> usize {
        self.header_len() + self.pdu_datafield_len as usize
    }

    /// Write the header to a raw buffer, returning the written length on success.
    pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        // The API does not allow passing entity IDs with different sizes, so this should
        // never happen.
        assert_eq!(
            self.pdu_conf.source_entity_id.size(),
            self.pdu_conf.dest_entity_id.size(),
            "unexpected missmatch of source and destination entity ID length"
        );
        if buf.len()
            < FIXED_HEADER_LEN
                + self.pdu_conf.source_entity_id.size()
                + self.pdu_conf.transaction_seq_num.size()
        {
            return Err(ByteConversionError::ToSliceTooSmall {
                found: buf.len(),
                expected: FIXED_HEADER_LEN,
            });
        }
        let mut current_idx = 0;
        buf[current_idx] = (CFDP_VERSION_2 << 5)
            | ((self.pdu_type as u8) << 4)
            | ((self.pdu_conf.direction as u8) << 3)
            | ((self.pdu_conf.trans_mode as u8) << 2)
            | ((self.pdu_conf.crc_flag as u8) << 1)
            | (self.pdu_conf.file_flag as u8);
        current_idx += 1;
        buf[current_idx..current_idx + 2].copy_from_slice(&self.pdu_datafield_len.to_be_bytes());
        current_idx += 2;
        buf[current_idx] = ((self.seg_ctrl as u8) << 7)
            | (((self.pdu_conf.source_entity_id.size() - 1) as u8) << 4)
            | ((self.seg_metadata_flag as u8) << 3)
            | ((self.pdu_conf.transaction_seq_num.size() - 1) as u8);
        current_idx += 1;
        self.pdu_conf.source_entity_id.write_to_be_bytes(
            &mut buf[current_idx..current_idx + self.pdu_conf.source_entity_id.size()],
        )?;
        current_idx += self.pdu_conf.source_entity_id.size();
        self.pdu_conf.transaction_seq_num.write_to_be_bytes(
            &mut buf[current_idx..current_idx + self.pdu_conf.transaction_seq_num.size()],
        )?;
        current_idx += self.pdu_conf.transaction_seq_num.size();
        self.pdu_conf.dest_entity_id.write_to_be_bytes(
            &mut buf[current_idx..current_idx + self.pdu_conf.dest_entity_id.size()],
        )?;
        current_idx += self.pdu_conf.dest_entity_id.size();
        Ok(current_idx)
    }

    /// This function first verifies that the buffer can hold the full length of the PDU parsed from
    /// the header. Then, it verifies the checksum as specified in the standard if the CRC flag
    /// of the PDU header is set.
    ///
    /// This function will return the PDU length excluding the 2 CRC bytes on success. If the CRC
    /// flag is not set, it will simply return the PDU length.
    pub fn verify_length_and_checksum(&self, buf: &[u8]) -> Result<usize, PduError> {
        if buf.len() < self.pdu_len() {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: buf.len(),
                expected: self.pdu_len(),
            }
            .into());
        }
        if self.pdu_conf.crc_flag == CrcFlag::WithCrc {
            let mut digest = CRC_CCITT_FALSE.digest();
            digest.update(&buf[..self.pdu_len()]);
            if digest.finalize() != 0 {
                return Err(PduError::Checksum(u16::from_be_bytes(
                    buf[self.pdu_len() - 2..self.pdu_len()].try_into().unwrap(),
                )));
            }
            return Ok(self.pdu_len() - 2);
        }
        Ok(self.pdu_len())
    }

    /// Please note that this function will not verify that the passed buffer can hold the full
    /// PDU length. This allows recovering the header portion even if the data field length is
    /// invalid. This function will also not do the CRC procedure specified in chapter 4.1.1
    /// and 4.1.2 because performing the CRC procedure requires the buffer to be large enough
    /// to hold the full PDU.
    ///
    /// Both functions can however be performed with the [Self::verify_length_and_checksum]
    /// function.
    pub fn from_bytes(buf: &[u8]) -> Result<(Self, usize), PduError> {
        if buf.len() < FIXED_HEADER_LEN {
            return Err(PduError::ByteConversion(
                ByteConversionError::FromSliceTooSmall {
                    found: buf.len(),
                    expected: FIXED_HEADER_LEN,
                },
            ));
        }
        let cfdp_version_raw = (buf[0] >> 5) & 0b111;
        if cfdp_version_raw != CFDP_VERSION_2 {
            return Err(PduError::CfdpVersionMissmatch(cfdp_version_raw));
        }
        // unwrap for single bit fields: This operation will always succeed.
        let pdu_type = PduType::try_from((buf[0] >> 4) & 0b1).unwrap();
        let direction = Direction::try_from((buf[0] >> 3) & 0b1).unwrap();
        let trans_mode = TransmissionMode::try_from((buf[0] >> 2) & 0b1).unwrap();
        let crc_flag = CrcFlag::try_from((buf[0] >> 1) & 0b1).unwrap();
        let file_flag = LargeFileFlag::try_from(buf[0] & 0b1).unwrap();
        let pdu_datafield_len = u16::from_be_bytes(buf[1..3].try_into().unwrap());
        let seg_ctrl = SegmentationControl::try_from((buf[3] >> 7) & 0b1).unwrap();
        let expected_len_entity_ids = (((buf[3] >> 4) & 0b111) + 1) as usize;
        if (expected_len_entity_ids != 1)
            && (expected_len_entity_ids != 2)
            && (expected_len_entity_ids != 4)
            && (expected_len_entity_ids != 8)
        {
            return Err(PduError::InvalidEntityLen(expected_len_entity_ids as u8));
        }
        let seg_metadata_flag = SegmentMetadataFlag::try_from((buf[3] >> 3) & 0b1).unwrap();
        let expected_len_seq_num = ((buf[3] & 0b111) + 1) as usize;
        if (expected_len_seq_num != 1)
            && (expected_len_seq_num != 2)
            && (expected_len_seq_num != 4)
            && (expected_len_seq_num != 8)
        {
            return Err(PduError::InvalidTransactionSeqNumLen(
                expected_len_seq_num as u8,
            ));
        }
        if buf.len() < (4 + 2 * expected_len_entity_ids + expected_len_seq_num) {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: buf.len(),
                expected: 4 + 2 * expected_len_entity_ids + expected_len_seq_num,
            }
            .into());
        }
        let mut current_idx = 4;
        // It is okay to unwrap here because we checked the validity of the expected length and of
        // the remaining buffer length.
        let source_id =
            UnsignedByteField::new_from_be_bytes(expected_len_entity_ids, &buf[current_idx..])
                .unwrap();
        current_idx += expected_len_entity_ids;
        let transaction_seq_num =
            UnsignedByteField::new_from_be_bytes(expected_len_seq_num, &buf[current_idx..])
                .unwrap();
        current_idx += expected_len_seq_num;
        let dest_id =
            UnsignedByteField::new_from_be_bytes(expected_len_entity_ids, &buf[current_idx..])
                .unwrap();
        current_idx += expected_len_entity_ids;
        let common_pdu_conf = CommonPduConfig::new(
            source_id,
            dest_id,
            transaction_seq_num,
            trans_mode,
            file_flag,
            crc_flag,
            direction,
        )
        .unwrap();
        Ok((
            PduHeader {
                pdu_type,
                pdu_conf: common_pdu_conf,
                seg_metadata_flag,
                seg_ctrl,
                pdu_datafield_len,
            },
            current_idx,
        ))
    }

    /// PDU type.
    #[inline]
    pub fn pdu_type(&self) -> PduType {
        self.pdu_type
    }

    /// Common PDU configuration fields.
    #[inline]
    pub fn common_pdu_conf(&self) -> &CommonPduConfig {
        &self.pdu_conf
    }

    /// Segment metadata flag.
    #[inline]
    pub fn seg_metadata_flag(&self) -> SegmentMetadataFlag {
        self.seg_metadata_flag
    }

    /// Segmentation Control.
    #[inline]
    pub fn seg_ctrl(&self) -> SegmentationControl {
        self.seg_ctrl
    }
}

pub(crate) fn write_fss_field(
    file_flag: LargeFileFlag,
    file_size: u64,
    buf: &mut [u8],
) -> Result<usize, PduError> {
    Ok(if file_flag == LargeFileFlag::Large {
        buf[..core::mem::size_of::<u64>()].copy_from_slice(&file_size.to_be_bytes());
        core::mem::size_of::<u64>()
    } else {
        if file_size > u32::MAX as u64 {
            return Err(PduError::FileSizeTooLarge(file_size));
        }
        buf[..core::mem::size_of::<u32>()].copy_from_slice(&(file_size as u32).to_be_bytes());
        core::mem::size_of::<u32>()
    })
}

pub(crate) fn read_fss_field(file_flag: LargeFileFlag, buf: &[u8]) -> (usize, u64) {
    if file_flag == LargeFileFlag::Large {
        (
            core::mem::size_of::<u64>(),
            u64::from_be_bytes(buf[..core::mem::size_of::<u64>()].try_into().unwrap()),
        )
    } else {
        (
            core::mem::size_of::<u32>(),
            u32::from_be_bytes(buf[..core::mem::size_of::<u32>()].try_into().unwrap()).into(),
        )
    }
}

// This is a generic length check applicable to most PDU deserializations. It first checks whether
// a given buffer can hold an expected minimum size, and then it checks whether the PDU datafield
// length is larger than that expected minimum size.
pub(crate) fn generic_length_checks_pdu_deserialization(
    buf: &[u8],
    min_expected_len: usize,
    full_len_without_crc: usize,
) -> Result<(), ByteConversionError> {
    // Buffer too short to hold additional expected minimum datasize.
    if buf.len() < min_expected_len {
        return Err(ByteConversionError::FromSliceTooSmall {
            found: buf.len(),
            expected: min_expected_len,
        });
    }
    // This can happen if the PDU datafield length value is invalid.
    if full_len_without_crc < min_expected_len {
        return Err(ByteConversionError::FromSliceTooSmall {
            found: full_len_without_crc,
            expected: min_expected_len,
        });
    }
    Ok(())
}

pub(crate) fn add_pdu_crc(buf: &mut [u8], mut current_idx: usize) -> usize {
    let mut digest = CRC_CCITT_FALSE.digest();
    digest.update(&buf[..current_idx]);
    buf[current_idx..current_idx + 2].copy_from_slice(&digest.finalize().to_be_bytes());
    current_idx += 2;
    current_idx
}

#[cfg(test)]
mod tests {
    use alloc::string::ToString;

    use crate::cfdp::pdu::{CommonPduConfig, PduError, PduHeader, FIXED_HEADER_LEN};
    use crate::cfdp::{
        CrcFlag, Direction, LargeFileFlag, PduType, SegmentMetadataFlag, SegmentationControl,
        TransmissionMode, CFDP_VERSION_2,
    };
    use crate::util::{
        UbfU16, UbfU8, UnsignedByteField, UnsignedByteFieldU16, UnsignedByteFieldU8, UnsignedEnum,
    };
    use crate::ByteConversionError;
    use std::format;

    pub(crate) const TEST_SRC_ID: UbfU8 = UbfU8::new(5);
    pub(crate) const TEST_DEST_ID: UbfU8 = UbfU8::new(10);
    pub(crate) const TEST_SEQ_NUM: UbfU8 = UbfU8::new(20);

    pub(crate) fn common_pdu_conf(crc_flag: CrcFlag, fss: LargeFileFlag) -> CommonPduConfig {
        let mut pdu_conf =
            CommonPduConfig::new_with_byte_fields(TEST_SRC_ID, TEST_DEST_ID, TEST_SEQ_NUM)
                .expect("Generating common PDU config");
        pdu_conf.crc_flag = crc_flag;
        pdu_conf.file_flag = fss;
        pdu_conf
    }

    pub(crate) fn verify_raw_header(pdu_conf: &PduHeader, buf: &[u8]) {
        assert_eq!((buf[0] >> 5) & 0b111, CFDP_VERSION_2);
        // File directive
        assert_eq!((buf[0] >> 4) & 1, pdu_conf.pdu_type as u8);
        assert_eq!((buf[0] >> 3) & 1, pdu_conf.pdu_conf.direction as u8);
        // Acknowledged
        assert_eq!((buf[0] >> 2) & 1, pdu_conf.pdu_conf.trans_mode as u8);
        // No CRC
        assert_eq!((buf[0] >> 1) & 1, pdu_conf.pdu_conf.crc_flag as u8);
        // Regular file size
        assert_eq!(buf[0] & 1, pdu_conf.pdu_conf.file_flag as u8);
        let pdu_datafield_len = u16::from_be_bytes(buf[1..3].try_into().unwrap());
        assert_eq!(pdu_datafield_len, pdu_conf.pdu_datafield_len);
        // No record boundary preservation
        assert_eq!((buf[3] >> 7) & 1, pdu_conf.seg_ctrl as u8);
        // Entity ID length raw value is actual number of octets - 1 => 0
        let entity_id_len = pdu_conf.pdu_conf.source_entity_id.size();
        assert_eq!((buf[3] >> 4) & 0b111, entity_id_len as u8 - 1);
        // No segment metadata
        assert_eq!((buf[3] >> 3) & 0b1, pdu_conf.seg_metadata_flag as u8);
        // Transaction Sequence ID length raw value is actual number of octets - 1 => 0
        let seq_num_len = pdu_conf.pdu_conf.transaction_seq_num.size();
        assert_eq!(buf[3] & 0b111, seq_num_len as u8 - 1);
        let mut current_idx = 4;
        let mut byte_field_check = |field_len: usize, ubf: &UnsignedByteField| {
            match field_len {
                1 => assert_eq!(buf[current_idx], ubf.value() as u8),
                2 => assert_eq!(
                    u16::from_be_bytes(
                        buf[current_idx..current_idx + field_len]
                            .try_into()
                            .unwrap()
                    ),
                    ubf.value() as u16
                ),
                4 => assert_eq!(
                    u32::from_be_bytes(
                        buf[current_idx..current_idx + field_len]
                            .try_into()
                            .unwrap()
                    ),
                    ubf.value() as u32
                ),
                8 => assert_eq!(
                    u64::from_be_bytes(
                        buf[current_idx..current_idx + field_len]
                            .try_into()
                            .unwrap()
                    ),
                    ubf.value()
                ),
                _ => panic!("invalid entity ID length"),
            }
            current_idx += field_len
        };
        byte_field_check(entity_id_len, &pdu_conf.pdu_conf.source_entity_id);
        byte_field_check(seq_num_len, &pdu_conf.pdu_conf.transaction_seq_num);
        byte_field_check(entity_id_len, &pdu_conf.pdu_conf.dest_entity_id);
    }

    #[test]
    fn test_basic_state() {
        let src_id = UnsignedByteFieldU8::new(1);
        let dest_id = UnsignedByteFieldU8::new(2);
        let transaction_id = UnsignedByteFieldU8::new(3);
        let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
            .expect("common config creation failed");
        let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
        assert_eq!(pdu_header.pdu_type(), PduType::FileDirective);
        let common_conf_ref = pdu_header.common_pdu_conf();
        assert_eq!(*common_conf_ref, common_pdu_cfg);
        // These should be 0 and ignored for non-filedata PDUs
        assert_eq!(
            pdu_header.seg_metadata_flag(),
            SegmentMetadataFlag::NotPresent
        );
        assert_eq!(
            pdu_header.seg_ctrl(),
            SegmentationControl::NoRecordBoundaryPreservation
        );
        assert_eq!(pdu_header.pdu_datafield_len, 5);
        assert_eq!(pdu_header.header_len(), 7);
    }

    #[test]
    fn test_common_pdu_conf_partial_eq() {
        let common_pdu_cfg_0 =
            CommonPduConfig::new_with_byte_fields(UbfU8::new(1), UbfU8::new(2), UbfU8::new(3))
                .expect("common config creation failed");
        let common_pdu_cfg_1 =
            CommonPduConfig::new_with_byte_fields(UbfU16::new(1), UbfU16::new(2), UbfU16::new(3))
                .expect("common config creation failed");
        assert_eq!(common_pdu_cfg_0, common_pdu_cfg_1);
    }

    #[test]
    fn test_basic_state_default() {
        let default_conf = CommonPduConfig::default();
        assert_eq!(default_conf.source_id(), UnsignedByteFieldU8::new(0).into());
        assert_eq!(default_conf.dest_id(), UnsignedByteFieldU8::new(0).into());
        assert_eq!(
            default_conf.transaction_seq_num,
            UnsignedByteFieldU8::new(0).into()
        );
        assert_eq!(default_conf.trans_mode, TransmissionMode::Acknowledged);
        assert_eq!(default_conf.direction, Direction::TowardsReceiver);
        assert_eq!(default_conf.crc_flag, CrcFlag::NoCrc);
        assert_eq!(default_conf.file_flag, LargeFileFlag::Normal);
    }

    #[test]
    fn test_pdu_header_setter() {
        let src_id = UnsignedByteFieldU8::new(1);
        let dest_id = UnsignedByteFieldU8::new(2);
        let transaction_id = UnsignedByteFieldU8::new(3);
        let mut common_pdu_cfg =
            CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
                .expect("common config creation failed");
        let other_src_id = UnsignedByteFieldU16::new(5);
        let other_dest_id = UnsignedByteFieldU16::new(6);
        let set_result = common_pdu_cfg.set_source_and_dest_id(other_src_id, other_dest_id);
        assert!(set_result.is_ok());
        assert_eq!(common_pdu_cfg.source_id(), other_src_id.into());
        assert_eq!(common_pdu_cfg.dest_id(), other_dest_id.into());
    }

    #[test]
    fn test_serialization_1() {
        let src_id = UnsignedByteFieldU8::new(1);
        let dest_id = UnsignedByteFieldU8::new(2);
        let transaction_id = UnsignedByteFieldU8::new(3);
        let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
            .expect("common config creation failed");
        let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
        let mut buf: [u8; 7] = [0; 7];
        let res = pdu_header.write_to_bytes(&mut buf);
        assert!(res.is_ok());
        // 4 byte fixed header plus three bytes src, dest ID and transaction ID
        assert_eq!(res.unwrap(), 7);
        verify_raw_header(&pdu_header, &buf);
        assert_eq!(pdu_header.pdu_datafield_len(), 5);
    }

    #[test]
    fn test_deserialization_1() {
        let src_id = UnsignedByteFieldU8::new(1);
        let dest_id = UnsignedByteFieldU8::new(2);
        let transaction_id = UnsignedByteFieldU8::new(3);
        let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
            .expect("common config creation failed");
        let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
        let mut buf: [u8; 7] = [0; 7];
        let res = pdu_header.write_to_bytes(&mut buf);
        assert!(res.is_ok());
        let deser_res = PduHeader::from_bytes(&buf);
        assert!(deser_res.is_ok());
        let (header_read_back, read_size) = deser_res.unwrap();
        assert_eq!(read_size, 7);
        assert_eq!(header_read_back, pdu_header);
    }

    #[test]
    fn test_serialization_2() {
        let src_id = UnsignedByteFieldU16::new(0x0001);
        let dest_id = UnsignedByteFieldU16::new(0x0203);
        let transaction_id = UnsignedByteFieldU16::new(0x0405);
        let mut common_pdu_cfg =
            CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
                .expect("common config creation failed");
        common_pdu_cfg.crc_flag = CrcFlag::WithCrc;
        common_pdu_cfg.direction = Direction::TowardsSender;
        common_pdu_cfg.trans_mode = TransmissionMode::Unacknowledged;
        common_pdu_cfg.file_flag = LargeFileFlag::Large;
        let pdu_header = PduHeader::new_for_file_data(
            common_pdu_cfg,
            5,
            SegmentMetadataFlag::Present,
            SegmentationControl::WithRecordBoundaryPreservation,
        );
        assert_eq!(pdu_header.header_len(), 10);
        let mut buf: [u8; 16] = [0; 16];
        let res = pdu_header.write_to_bytes(&mut buf);
        assert!(res.is_ok(), "{}", format!("Result {res:?} not okay"));
        // 4 byte fixed header, 6 bytes additional fields
        assert_eq!(res.unwrap(), 10);
        verify_raw_header(&pdu_header, &buf);
    }

    #[test]
    fn test_deserialization_2() {
        let src_id = UnsignedByteFieldU16::new(0x0001);
        let dest_id = UnsignedByteFieldU16::new(0x0203);
        let transaction_id = UnsignedByteFieldU16::new(0x0405);
        let mut common_pdu_cfg =
            CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
                .expect("common config creation failed");
        common_pdu_cfg.crc_flag = CrcFlag::WithCrc;
        common_pdu_cfg.direction = Direction::TowardsSender;
        common_pdu_cfg.trans_mode = TransmissionMode::Unacknowledged;
        common_pdu_cfg.file_flag = LargeFileFlag::Large;
        let pdu_header = PduHeader::new_for_file_data(
            common_pdu_cfg,
            5,
            SegmentMetadataFlag::Present,
            SegmentationControl::WithRecordBoundaryPreservation,
        );
        let mut buf: [u8; 16] = [0; 16];
        let res = pdu_header.write_to_bytes(&mut buf);
        assert!(res.is_ok());
        let deser_res = PduHeader::from_bytes(&buf);
        assert!(deser_res.is_ok());
        let (header_read_back, read_size) = deser_res.unwrap();
        assert_eq!(read_size, 10);
        assert_eq!(header_read_back, pdu_header);
    }

    #[test]
    fn test_invalid_raw_version() {
        let src_id = UnsignedByteFieldU8::new(1);
        let dest_id = UnsignedByteFieldU8::new(2);
        let transaction_id = UnsignedByteFieldU8::new(3);
        let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
            .expect("common config creation failed");
        let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
        let mut buf: [u8; 7] = [0; 7];
        let res = pdu_header.write_to_bytes(&mut buf);
        assert!(res.is_ok());
        buf[0] &= !0b1110_0000;
        buf[0] |= (CFDP_VERSION_2 + 1) << 5;
        let res = PduHeader::from_bytes(&buf);
        assert!(res.is_err());
        let error = res.unwrap_err();
        if let PduError::CfdpVersionMissmatch(raw_version) = error {
            assert_eq!(raw_version, CFDP_VERSION_2 + 1);
            assert_eq!(
                error.to_string(),
                "CFDP version missmatch, found 2, expected 1"
            );
        } else {
            panic!("invalid exception: {}", error);
        }
    }

    #[test]
    fn test_buf_too_small_1() {
        let buf: [u8; 3] = [0; 3];
        let res = PduHeader::from_bytes(&buf);
        assert!(res.is_err());
        let error = res.unwrap_err();
        if let PduError::ByteConversion(ByteConversionError::FromSliceTooSmall {
            found,
            expected,
        }) = error
        {
            assert_eq!(found, 3);
            assert_eq!(expected, FIXED_HEADER_LEN);
        } else {
            panic!("invalid exception: {}", error);
        }
    }

    #[test]
    fn test_buf_too_small_2() {
        let src_id = UnsignedByteFieldU8::new(1);
        let dest_id = UnsignedByteFieldU8::new(2);
        let transaction_id = UnsignedByteFieldU8::new(3);
        let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
            .expect("common config creation failed");
        let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
        let mut buf: [u8; 7] = [0; 7];
        let res = pdu_header.write_to_bytes(&mut buf);
        assert!(res.is_ok());
        let header = PduHeader::from_bytes(&buf[0..6]);
        assert!(header.is_err());
        let error = header.unwrap_err();
        if let PduError::ByteConversion(ByteConversionError::FromSliceTooSmall {
            found,
            expected,
        }) = error
        {
            assert_eq!(found, 6);
            assert_eq!(expected, 7);
            assert_eq!(
                error.to_string(),
                "byte conversion error: source slice with size 6 too small, expected at least 7 bytes"
            );
        }
    }

    #[test]
    fn test_invalid_seq_len() {
        let src_id = UbfU8::new(1);
        let dest_id = UbfU8::new(2);
        let transaction_seq_id = UbfU8::new(3);
        let invalid_byte_field = UnsignedByteField::new(3, 5);
        let pdu_conf_res =
            CommonPduConfig::new_with_byte_fields(src_id, dest_id, invalid_byte_field);
        assert!(pdu_conf_res.is_err());
        let error = pdu_conf_res.unwrap_err();
        if let PduError::InvalidTransactionSeqNumLen(len) = error {
            assert_eq!(len, 3);
        } else {
            panic!("Invalid exception: {}", error)
        }
        let pdu_conf_res = CommonPduConfig::new_with_byte_fields(
            invalid_byte_field,
            invalid_byte_field,
            transaction_seq_id,
        );
        assert!(pdu_conf_res.is_err());
        let error = pdu_conf_res.unwrap_err();
        if let PduError::InvalidEntityLen(len) = error {
            assert_eq!(len, 3);
            assert_eq!(
                error.to_string(),
                "invalid PDU entity ID length 3, only [1, 2, 4, 8] are allowed"
            );
        } else {
            panic!("Invalid exception: {}", error)
        }
    }
    #[test]
    fn test_missmatch_src_dest_id() {
        let src_id = UnsignedByteField::new(1, 5);
        let dest_id = UnsignedByteField::new(2, 5);
        let transaction_seq_id = UbfU8::new(3);
        let pdu_conf_res =
            CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_seq_id);
        assert!(pdu_conf_res.is_err());
        let error = pdu_conf_res.unwrap_err();
        if let PduError::SourceDestIdLenMissmatch {
            src_id_len,
            dest_id_len,
        } = error
        {
            assert_eq!(src_id_len, 1);
            assert_eq!(dest_id_len, 2);
            assert_eq!(
                error.to_string(),
                "missmatch of PDU source ID length 1 and destination ID length 2"
            );
        }
    }

    #[test]
    fn test_invalid_raw_src_id_len() {
        let src_id = UnsignedByteFieldU8::new(1);
        let dest_id = UnsignedByteFieldU8::new(2);
        let transaction_id = UnsignedByteFieldU8::new(3);
        let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
            .expect("common config creation failed");
        let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
        let mut buf: [u8; 7] = [0; 7];
        let res = pdu_header.write_to_bytes(&mut buf);
        assert!(res.is_ok());
        buf[3] &= !0b0111_0000;
        // Equivalent to the length of three
        buf[3] |= 0b10 << 4;
        let header_res = PduHeader::from_bytes(&buf);
        assert!(header_res.is_err());
        let error = header_res.unwrap_err();
        if let PduError::InvalidEntityLen(len) = error {
            assert_eq!(len, 3);
        } else {
            panic!("invalid exception {:?}", error)
        }
    }

    #[test]
    fn test_invalid_transaction_seq_id_len() {
        let src_id = UnsignedByteFieldU8::new(1);
        let dest_id = UnsignedByteFieldU8::new(2);
        let transaction_id = UnsignedByteFieldU8::new(3);
        let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
            .expect("common config creation failed");
        let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
        let mut buf: [u8; 7] = [0; 7];
        let res = pdu_header.write_to_bytes(&mut buf);
        assert!(res.is_ok());
        buf[3] &= !0b0000_0111;
        // Equivalent to the length of three
        buf[3] |= 0b10;
        let header_res = PduHeader::from_bytes(&buf);
        assert!(header_res.is_err());
        let error = header_res.unwrap_err();
        if let PduError::InvalidTransactionSeqNumLen(len) = error {
            assert_eq!(len, 3);
        } else {
            panic!("invalid exception {:?}", error)
        }
    }

    #[test]
    fn test_pdu_error_clonable_and_comparable() {
        let pdu_error = PduError::InvalidEntityLen(0);
        let pdu_error_2 = pdu_error;
        assert_eq!(pdu_error, pdu_error_2);
    }

    #[test]
    fn test_pdu_config_clonable_and_comparable() {
        let common_pdu_cfg_0 =
            CommonPduConfig::new_with_byte_fields(UbfU8::new(1), UbfU8::new(2), UbfU8::new(3))
                .expect("common config creation failed");
        let common_pdu_cfg_1 = common_pdu_cfg_0;
        assert_eq!(common_pdu_cfg_0, common_pdu_cfg_1);
    }

    #[test]
    fn test_ctor_from_pdu_conf() {
        assert_eq!(
            PduHeader::from_pdu_conf_for_file_directive(CommonPduConfig::default()),
            PduHeader::new_for_file_directive(CommonPduConfig::default(), 0)
        );
    }
}