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
//! Common definitions and helpers required to create PUS TMTC packets according to
//! [ECSS-E-ST-70-41C](https://ecss.nl/standard/ecss-e-st-70-41c-space-engineering-telemetry-and-telecommand-packet-utilization-15-april-2016/)
//!
//! You can find the PUS telecommand types in the [tc] module and the the PUS telemetry
//! types inside the [tm] module.
use crate::{
    crc::{CRC_CCITT_FALSE, CRC_CCITT_FALSE_NO_TABLE},
    ByteConversionError, CcsdsPacket,
};
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use arbitrary_int::u4;
use core::fmt::Debug;
use core::mem::size_of;
use num_enum::{IntoPrimitive, TryFromPrimitive};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

pub mod event;
pub mod hk;
pub mod scheduling;
pub mod tc;
pub mod tc_pus_a;
pub mod tm;
pub mod tm_pus_a;
pub mod verification;

/// Type alias for the CRC16 type.
pub type CrcType = u16;

/// Standard PUS service IDs.
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
#[non_exhaustive]
pub enum PusServiceId {
    /// Service 1 Verification
    Verification = 1,
    /// Service 2 Device Access
    DeviceAccess = 2,
    /// Service 3 Housekeeping
    Housekeeping = 3,
    /// Service 4 Parameter Statistics
    ParameterStatistics = 4,
    /// Service 5 Event
    Event = 5,
    /// Service 6 Memory Management
    MemoryManagement = 6,
    /// Service 8 Action
    Action = 8,
    /// Service 9 Time Management
    TimeManagement = 9,
    /// Service 11 Scheduling
    Scheduling = 11,
    /// Service 12 On-Board Monitoring
    OnBoardMonitoring = 12,
    /// Service 13 Large Packet Transfer
    LargePacketTransfer = 13,
    /// Service 14 Real-Time Forwarding Control
    RealTimeForwardingControl = 14,
    /// Service 15 Storage And Retrival
    StorageAndRetrival = 15,
    /// Service 17 Test
    Test = 17,
    /// Service 18 Operations And Procedures
    OpsAndProcedures = 18,
    /// Service 19 Event Action
    EventAction = 19,
    /// Service 20 Parameter
    Parameter = 20,
    /// Service 21 Request Sequencing
    RequestSequencing = 21,
    /// Service 22 Position Based Scheduling
    PositionBasedScheduling = 22,
    /// Service 23 File Management
    FileManagement = 23,
}

/// All PUS versions. Only PUS C is supported by this library.
#[derive(PartialEq, Eq, Debug, num_enum::TryFromPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[bitbybit::bitenum(u4, exhaustive = false)]
#[repr(u8)]
#[non_exhaustive]
pub enum PusVersion {
    /// ESA PUS
    EsaPus = 0,
    /// PUS A
    PusA = 1,
    /// PUS C
    PusC = 2,
}

impl TryFrom<u4> for PusVersion {
    type Error = u4;

    fn try_from(value: u4) -> Result<Self, Self::Error> {
        match value {
            x if x == PusVersion::EsaPus.raw_value() => Ok(PusVersion::EsaPus),
            x if x == PusVersion::PusA.raw_value() => Ok(PusVersion::PusA),
            x if x == PusVersion::PusC.raw_value() => Ok(PusVersion::PusC),
            _ => Err(value),
        }
    }
}

/// ECSS Packet Type Codes (PTC)s.
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum PacketTypeCodes {
    /// Boolean.
    Boolean = 1,
    /// Enumerated.
    Enumerated = 2,
    /// Unsigned Integer.
    UnsignedInt = 3,
    /// Signed Integer.
    SignedInt = 4,
    /// Real (floating point).
    Real = 5,
    /// Bit string.
    BitString = 6,
    /// Octet (byte) string.
    OctetString = 7,
    /// Character string.
    CharString = 8,
    /// Absolute time.
    AbsoluteTime = 9,
    /// Relative time.
    RelativeTime = 10,
    /// Deduced.
    Deduced = 11,
    /// Packet.
    Packet = 12,
}

/// Type alias for the ECSS Packet Type Codes (PTC)s.
pub type Ptc = PacketTypeCodes;

/// ECSS Packet Field Codes (PFC)s for the unsigned [Ptc].
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum PfcUnsigned {
    /// 1 byte.
    OneByte = 4,
    /// 12 bits.
    TwelveBits = 8,
    /// 2 bytes.
    TwoBytes = 12,
    /// 3 bytes.
    ThreeBytes = 13,
    /// 4 bytes.
    FourBytes = 14,
    /// 6 bytes.
    SixBytes = 15,
    /// 8 bytes.
    EightBytes = 16,
    /// 1 bit.
    OneBit = 17,
    /// 2 bits.
    TwoBits = 18,
    /// 3 bits.
    ThreeBits = 19,
}

/// ECSS Packet Field Codes (PFC)s for the real (floating point) [Ptc].
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum PfcReal {
    /// 4 octets simple precision format (IEEE)
    Float = 1,
    /// 8 octets simple precision format (IEEE)
    Double = 2,
    /// 4 octets simple precision format (MIL-STD)
    FloatMilStd = 3,
    /// 8 octets simple precision format (MIL-STD)
    DoubleMilStd = 4,
}

/// Generic PUS 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 PusError {
    /// PUS version is not supported.
    #[error("PUS version {0:?} not supported")]
    VersionNotSupported(u4),
    /// Checksum failure.
    #[error("checksum verification for crc16 {0:#06x} failed")]
    ChecksumFailure(u16),
    /// CRC16 needs to be calculated first
    //#[error("crc16 was not calculated")]
    //CrcCalculationMissing,
    #[error("pus error: {0}")]
    ByteConversion(#[from] ByteConversionError),
}

/// Message type ID field.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct MessageTypeId {
    /// Service type ID.
    pub type_id: u8,
    /// Subtype ID.
    pub subtype_id: u8,
}

impl MessageTypeId {
    /// Generic constructor.
    pub const fn new(type_id: u8, subtype_id: u8) -> Self {
        Self {
            type_id,
            subtype_id,
        }
    }
}

/// Generic trait to describe common attributes for both PUS Telecommands (TC) and PUS Telemetry
/// (TM) packets. All PUS packets are also a special type of [CcsdsPacket]s.
pub trait PusPacket: CcsdsPacket {
    /// PUS version.
    fn pus_version(&self) -> Result<PusVersion, u4>;

    /// Message type ID.
    fn message_type_id(&self) -> MessageTypeId;

    /// Service type ID.
    #[inline]
    fn service_type_id(&self) -> u8 {
        self.message_type_id().type_id
    }

    /// Message subtype ID.
    #[inline]
    fn message_subtype_id(&self) -> u8 {
        self.message_type_id().subtype_id
    }

    /// User data field.
    fn user_data(&self) -> &[u8];

    /// CRC-16-CCITT checksum.
    fn checksum(&self) -> Option<u16>;

    /// The presence of the CRC-16-CCITT checksum is optional.
    fn has_checksum(&self) -> bool {
        self.checksum().is_some()
    }
}

pub(crate) fn crc_from_raw_data(raw_data: &[u8]) -> Result<u16, ByteConversionError> {
    if raw_data.len() < 2 {
        return Err(ByteConversionError::FromSliceTooSmall {
            found: raw_data.len(),
            expected: 2,
        });
    }
    Ok(u16::from_be_bytes(
        raw_data[raw_data.len() - 2..raw_data.len()]
            .try_into()
            .unwrap(),
    ))
}

pub(crate) fn calc_pus_crc16(bytes: &[u8]) -> u16 {
    let mut digest = CRC_CCITT_FALSE.digest();
    digest.update(bytes);
    digest.finalize()
}

pub(crate) fn user_data_from_raw(
    current_idx: usize,
    total_len: usize,
    slice: &[u8],
    has_checksum: bool,
) -> Result<&[u8], ByteConversionError> {
    if has_checksum {
        if current_idx > total_len - 2 {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: total_len - 2,
                expected: current_idx,
            });
        }
        Ok(&slice[current_idx..total_len - 2])
    } else {
        Ok(&slice[current_idx..total_len])
    }
}

/// Verify the CRC16 of a raw packet and return a [PusError] on failure.
pub fn verify_crc16_ccitt_false_from_raw_to_pus_error(
    raw_data: &[u8],
    crc16: u16,
) -> Result<(), PusError> {
    verify_crc16_ccitt_false_from_raw(raw_data)
        .then_some(())
        .ok_or(PusError::ChecksumFailure(crc16))
}

/// Verify the CRC16 of a raw packet using a table-less implementation and return a [PusError] on
/// failure.
pub fn verify_crc16_ccitt_false_from_raw_to_pus_error_no_table(
    raw_data: &[u8],
    crc16: u16,
) -> Result<(), PusError> {
    verify_crc16_ccitt_false_from_raw_no_table(raw_data)
        .then_some(())
        .ok_or(PusError::ChecksumFailure(crc16))
}

/// Verify the CRC16 of a raw packet.
pub fn verify_crc16_ccitt_false_from_raw(raw_data: &[u8]) -> bool {
    let mut digest = CRC_CCITT_FALSE.digest();
    digest.update(raw_data);
    if digest.finalize() == 0 {
        return true;
    }
    false
}

/// Verify the CRC16 of a raw packet, using the table-less implementation.
pub fn verify_crc16_ccitt_false_from_raw_no_table(raw_data: &[u8]) -> bool {
    let mut digest = CRC_CCITT_FALSE_NO_TABLE.digest();
    digest.update(raw_data);
    if digest.finalize() == 0 {
        return true;
    }
    false
}

macro_rules! sp_header_impls {
    () => {
        delegate!(to self.sp_header {
            /// Set the CCSDS APID.
            #[inline]
            pub fn set_apid(&mut self, apid: u11);

            /// Set the CCSDS sequence count.
            #[inline]
            pub fn set_seq_count(&mut self, seq_count: u14);

            /// Set the CCSDS sequence flags.
            #[inline]
            pub fn set_seq_flags(&mut self, seq_flag: SequenceFlags);
        });
    }
}

use crate::util::{GenericUnsignedByteField, ToBeBytes, UnsignedEnum};
pub(crate) use sp_header_impls;

/// Generic trait for ECSS enumeration which consist of a PFC field denoting their bit length
/// and an unsigned value. The trait makes no assumptions about the actual type of the unsigned
/// value and only requires implementors to implement a function which writes the enumeration into
/// a raw byte format.
pub trait EcssEnumeration: UnsignedEnum {
    /// Packet Format Code, which denotes the number of bits of the enumeration
    fn pfc(&self) -> u8;
}

/// Extension trait for [EcssEnumeration] which adds common trait bounds.
pub trait EcssEnumerationExt: EcssEnumeration + Debug + Copy + Clone + PartialEq + Eq {}

/// ECSS enumerated type wrapper.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GenericEcssEnumWrapper<TYPE: Copy + Into<u64>>(GenericUnsignedByteField<TYPE>);

impl<TYPE: Copy + Into<u64>> GenericEcssEnumWrapper<TYPE> {
    /// Returns [PacketTypeCodes::Enumerated].
    pub const fn ptc() -> PacketTypeCodes {
        PacketTypeCodes::Enumerated
    }

    /// Value.
    pub const fn value(&self) -> TYPE {
        self.0.value()
    }

    /// Generic constructor.
    pub const fn new(val: TYPE) -> Self {
        Self(GenericUnsignedByteField::new(val))
    }
}

impl<TYPE: Copy + ToBeBytes + Into<u64>> UnsignedEnum for GenericEcssEnumWrapper<TYPE> {
    fn size(&self) -> usize {
        (self.pfc() / 8) as usize
    }

    fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        self.0.write_to_be_bytes(buf)
    }

    fn value_raw(&self) -> u64 {
        self.0.value().into()
    }
}

impl<TYPE: Copy + ToBeBytes + Into<u64>> EcssEnumeration for GenericEcssEnumWrapper<TYPE> {
    fn pfc(&self) -> u8 {
        size_of::<TYPE>() as u8 * 8_u8
    }
}

impl<TYPE: Debug + Copy + Clone + PartialEq + Eq + ToBeBytes + Into<u64>> EcssEnumerationExt
    for GenericEcssEnumWrapper<TYPE>
{
}

impl<T: Copy + Into<u64>> From<T> for GenericEcssEnumWrapper<T> {
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

macro_rules! generic_ecss_enum_typedefs_and_from_impls {
    ($($ty:ty => $Enum:ident),*) => {
        $(
            /// Type alias for ECSS enumeration wrapper around `$ty`
            pub type $Enum = GenericEcssEnumWrapper<$ty>;

            impl From<$Enum> for $ty {
                fn from(value: $Enum) -> Self {
                    value.value()
                }
            }
        )*
    };
}

// Generates EcssEnum<$TY> type definitions as well as a From<$TY> for EcssEnum<$TY>
// implementation.
generic_ecss_enum_typedefs_and_from_impls! {
    u8 => EcssEnumU8,
    u16 => EcssEnumU16,
    u32 => EcssEnumU32,
    u64 => EcssEnumU64
}

/// Generic trait for PUS packet abstractions which can written to a raw slice as their raw
/// byte representation. This is especially useful for generic abstractions which depend only
/// on the serialization of those packets.
pub trait WritablePusPacket {
    /// The length here also includes the CRC length.
    fn len_written(&self) -> usize;

    /// Checksum generation is enabled for the packet.
    fn has_checksum(&self) -> bool;

    /// Writes the packet to the given slice without writing the CRC checksum.
    ///
    /// The returned size is the written size WITHOUT the CRC checksum.
    /// If the checksum generation is disabled, this function is identical to the APIs which
    /// generate a checksum.
    fn write_to_bytes_no_checksum(&self, slice: &mut [u8]) -> Result<usize, PusError>;

    /// First uses [Self::write_to_bytes_no_checksum] to write the packet to the given slice and
    /// then uses the [CRC_CCITT_FALSE] to calculate the CRC and write it to the slice if the
    /// packet is configured to include a checksum.
    fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
        let mut curr_idx = self.write_to_bytes_no_checksum(slice)?;
        if self.has_checksum() {
            let mut digest = CRC_CCITT_FALSE.digest();
            digest.update(&slice[0..curr_idx]);
            slice[curr_idx..curr_idx + 2].copy_from_slice(&digest.finalize().to_be_bytes());
            curr_idx += 2;
        }
        Ok(curr_idx)
    }

    /// First uses [Self::write_to_bytes_no_checksum] to write the packet to the given slice and then
    /// uses the [CRC_CCITT_FALSE_NO_TABLE] to calculate the CRC and write it to the slice if
    /// the paket is configured to include a checksum.
    fn write_to_bytes_checksum_no_table(&self, slice: &mut [u8]) -> Result<usize, PusError> {
        let mut curr_idx = self.write_to_bytes_no_checksum(slice)?;
        if self.has_checksum() {
            let mut digest = CRC_CCITT_FALSE_NO_TABLE.digest();
            digest.update(&slice[0..curr_idx]);
            slice[curr_idx..curr_idx + 2].copy_from_slice(&digest.finalize().to_be_bytes());
            curr_idx += 2;
        }
        Ok(curr_idx)
    }

    /// Converts the packet into an owned [alloc::vec::Vec].
    #[cfg(feature = "alloc")]
    fn to_vec(&self) -> Result<Vec<u8>, PusError> {
        // 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)
    }
}

/// PUS packet creator configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct CreatorConfig {
    /// Set the CCSDS data length field on construction.
    pub set_ccsds_len: bool,
    /// CRC-16-CCITT Checksum is present.
    pub has_checksum: bool,
}

impl Default for CreatorConfig {
    fn default() -> Self {
        Self {
            set_ccsds_len: true,
            has_checksum: true,
        }
    }
}

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

    use crate::ecss::{EcssEnumU16, EcssEnumU32, EcssEnumU8, UnsignedEnum};
    use crate::ByteConversionError;

    use super::*;
    #[cfg(feature = "serde")]
    use crate::tests::generic_serde_test;

    #[test]
    fn test_enum_u8() {
        let mut buf = [0, 0, 0];
        let my_enum = EcssEnumU8::new(1);
        assert_eq!(EcssEnumU8::ptc(), Ptc::Enumerated);
        assert_eq!(my_enum.size(), 1);
        assert_eq!(my_enum.pfc(), 8);
        my_enum
            .write_to_be_bytes(&mut buf[1..2])
            .expect("To byte conversion of u8 failed");
        assert_eq!(buf[1], 1);
        assert_eq!(my_enum.value(), 1);
        assert_eq!(my_enum.value(), 1);
        let enum_as_u8: u8 = my_enum.into();
        assert_eq!(enum_as_u8, 1);
        let vec = my_enum.to_vec();
        assert_eq!(vec, buf[1..2]);
    }

    #[test]
    fn test_enum_u16() {
        let mut buf = [0, 0, 0];
        let my_enum = EcssEnumU16::new(0x1f2f);
        my_enum
            .write_to_be_bytes(&mut buf[1..3])
            .expect("To byte conversion of u8 failed");
        assert_eq!(my_enum.size(), 2);
        assert_eq!(my_enum.pfc(), 16);
        assert_eq!(buf[1], 0x1f);
        assert_eq!(buf[2], 0x2f);
        assert_eq!(my_enum.value(), 0x1f2f);
        assert_eq!(my_enum.value(), 0x1f2f);
        let enum_as_raw: u16 = my_enum.into();
        assert_eq!(enum_as_raw, 0x1f2f);
        let vec = my_enum.to_vec();
        assert_eq!(vec, buf[1..3]);
    }

    #[test]
    fn test_slice_u16_too_small() {
        let mut buf = [0];
        let my_enum = EcssEnumU16::new(0x1f2f);
        let res = my_enum.write_to_be_bytes(&mut buf[0..1]);
        assert!(res.is_err());
        let error = res.unwrap_err();
        match error {
            ByteConversionError::ToSliceTooSmall { found, expected } => {
                assert_eq!(expected, 2);
                assert_eq!(found, 1);
            }
            _ => {
                panic!("Unexpected error {:?}", error);
            }
        }
    }

    #[test]
    fn test_enum_u32() {
        let mut buf = [0, 0, 0, 0, 0];
        let my_enum = EcssEnumU32::new(0x1f2f3f4f);
        my_enum
            .write_to_be_bytes(&mut buf[1..5])
            .expect("To byte conversion of u8 failed");
        assert_eq!(buf[1], 0x1f);
        assert_eq!(buf[2], 0x2f);
        assert_eq!(buf[3], 0x3f);
        assert_eq!(buf[4], 0x4f);
        assert_eq!(my_enum.value(), 0x1f2f3f4f);
        assert_eq!(my_enum.value(), 0x1f2f3f4f);
        let enum_as_raw: u32 = my_enum.into();
        assert_eq!(enum_as_raw, 0x1f2f3f4f);
        let vec = my_enum.to_vec();
        assert_eq!(vec, buf[1..5]);
    }

    #[test]
    fn test_slice_u32_too_small() {
        let mut buf = [0, 0, 0, 0, 0];
        let my_enum = EcssEnumU32::new(0x1f2f3f4f);
        let res = my_enum.write_to_be_bytes(&mut buf[0..3]);
        assert!(res.is_err());
        let error = res.unwrap_err();
        match error {
            ByteConversionError::ToSliceTooSmall { found, expected } => {
                assert_eq!(expected, 4);
                assert_eq!(found, 3);
            }
            _ => {
                panic!("Unexpected error {:?}", error);
            }
        }
    }

    #[test]
    fn test_enum_u64() {
        let mut buf = [0; 8];
        let my_enum = EcssEnumU64::new(0x1f2f3f4f5f);
        my_enum
            .write_to_be_bytes(&mut buf)
            .expect("To byte conversion of u64 failed");
        assert_eq!(buf[3], 0x1f);
        assert_eq!(buf[4], 0x2f);
        assert_eq!(buf[5], 0x3f);
        assert_eq!(buf[6], 0x4f);
        assert_eq!(buf[7], 0x5f);
        assert_eq!(my_enum.value(), 0x1f2f3f4f5f);
        assert_eq!(my_enum.value(), 0x1f2f3f4f5f);
        let enum_as_raw: u64 = my_enum.into();
        assert_eq!(enum_as_raw, 0x1f2f3f4f5f);
        assert_eq!(u64::from_be_bytes(buf), 0x1f2f3f4f5f);
        let vec = my_enum.to_vec();
        assert_eq!(vec, buf);
    }

    #[test]
    fn test_pus_error_display() {
        let unsupport_version =
            PusError::VersionNotSupported(super::PusVersion::EsaPus.raw_value());
        let write_str = unsupport_version.to_string();
        assert_eq!(write_str, "PUS version 0 not supported")
    }

    #[test]
    fn test_service_id_from_u8() {
        let verification_id_raw = 1;
        let verification_id = PusServiceId::try_from(verification_id_raw).unwrap();
        assert_eq!(verification_id, PusServiceId::Verification);
    }

    #[test]
    fn test_ptc_from_u8() {
        let ptc_raw = Ptc::AbsoluteTime as u8;
        let ptc = Ptc::try_from(ptc_raw).unwrap();
        assert_eq!(ptc, Ptc::AbsoluteTime);
    }

    #[test]
    fn test_unsigned_pfc_from_u8() {
        let pfc_raw = PfcUnsigned::OneByte as u8;
        let pfc = PfcUnsigned::try_from(pfc_raw).unwrap();
        assert_eq!(pfc, PfcUnsigned::OneByte);
    }

    #[test]
    fn test_real_pfc_from_u8() {
        let pfc_raw = PfcReal::Double as u8;
        let pfc = PfcReal::try_from(pfc_raw).unwrap();
        assert_eq!(pfc, PfcReal::Double);
    }

    #[test]
    fn test_pus_error_eq_impl() {
        assert_eq!(
            PusError::VersionNotSupported(PusVersion::EsaPus.raw_value()),
            PusError::VersionNotSupported(PusVersion::EsaPus.raw_value())
        );
    }

    #[test]
    fn test_pus_error_clonable() {
        let pus_error = PusError::ChecksumFailure(0x0101);
        let cloned = pus_error;
        assert_eq!(pus_error, cloned);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_pus_service_id() {
        generic_serde_test(PusServiceId::Verification);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_ptc() {
        generic_serde_test(Ptc::AbsoluteTime);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_pfc_unsigned() {
        generic_serde_test(PfcUnsigned::EightBytes);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_pfc_real() {
        generic_serde_test(PfcReal::Double);
    }
}