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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
//! # CCSDS and ECSS packet standards implementations
//!
//! This crate contains generic implementations for various
//! CCSDS (Consultative Committee for Space Data Systems) and
//! ECSS (European Cooperation for Space Standardization) packet standards.
//! Currently, this includes the following components:
//!
//!  - Space Packet implementation according to
//!    [CCSDS Blue Book 133.0-B-2](https://public.ccsds.org/Pubs/133x0b2e1.pdf)
//!  - CCSDS File Delivery Protocol (CFDP) packet implementations according to
//!    [CCSDS Blue Book 727.0-B-5](https://public.ccsds.org/Pubs/727x0b5.pdf)
//!  - PUS Telecommand and PUS Telemetry implementation according to the
//!    [ECSS-E-ST-70-41C standard](https://ecss.nl/standard/ecss-e-st-70-41c-space-engineering-telemetry-and-telecommand-packet-utilization-15-april-2016/).
//!  - CUC (CCSDS Unsegmented Time Code) implementation according to
//!    [CCSDS 301.0-B-4 3.2](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
//!  - CDS (CCSDS Day Segmented Time Code) implementation according to
//!    [CCSDS 301.0-B-4 3.3](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
//!  - Some helper types to support ASCII timecodes as specified in
//!    [CCSDS 301.0-B-4 3.5](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
//!
//! ## Features
//!
//! `spacepackets` supports various runtime environments and is also suitable for `no_std` environments.
//!
//! ### Default features
//!
//!  - [`std`](https://doc.rust-lang.org/std/): Enables functionality relying on the standard library.
//!  - [`alloc`](https://doc.rust-lang.org/alloc/): Enables features which operate on containers
//!    like [`alloc::vec::Vec`](https://doc.rust-lang.org/beta/alloc/vec/struct.Vec.html).
//!    Enabled by the `std` feature.
//!
//! ### Optional features
//!
//!  - [`serde`](https://serde.rs/): Adds `serde` support for most types by adding `Serialize` and
//!    `Deserialize` `derives.
//!  - [`chrono`](https://crates.io/crates/chrono): Add basic support for the `chrono` time library.
//!  - [`timelib`](https://crates.io/crates/time): Add basic support for the `time` time library.
//!  - [`defmt`](https://defmt.ferrous-systems.com/): Add support for the `defmt` by adding the
//!    [`defmt::Format`](https://defmt.ferrous-systems.com/format) derive on many types.
//!  - [`portable-atomic`](https://github.com/taiki-e/portable-atomic): Basic support for
//!    `portable-atomic` crate in addition to the support for core atomic types. This support
//!    requires atomic CAS support enabled in the portable atomic crate.
//!
//! ## Module
//!
//! This module contains helpers and data structures to generate Space Packets according to the
//! [CCSDS 133.0-B-2](https://public.ccsds.org/Pubs/133x0b2e1.pdf). This includes the
//! [SpHeader] class to generate the Space Packet Header component common to all space packets.
//!
//! ## Example
//!
//! ```rust
//! use spacepackets::SpHeader;
//! use arbitrary_int::{u11, u14};
//!
//! let sp_header = SpHeader::new_for_unseg_tc(u11::new(0x42), u14::new(12), 1);
//! println!("{:?}", sp_header);
//! let mut ccsds_buf: [u8; 32] = [0; 32];
//! sp_header.write_to_be_bytes(&mut ccsds_buf).expect("Writing CCSDS TC header failed");
//! println!("{:x?}", &ccsds_buf[0..6]);
//! ```
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_docs)]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(any(feature = "std", test))]
extern crate std;

use arbitrary_int::{prelude::*, u11, u14};
use core::{fmt::Debug, hash::Hash};
use delegate::delegate;
use zerocopy::{FromBytes, IntoBytes};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::crc::CRC_CCITT_FALSE;

pub mod cfdp;
pub mod crc;
pub mod ecss;
pub mod seq_count;
pub mod time;
pub mod uslp;
pub mod util;

mod private {
    pub trait Sealed {}
}

/// Length of the CCSDS header.
pub const CCSDS_HEADER_LEN: usize = core::mem::size_of::<crate::zc::SpHeader>();

/// Maximum allowed value for the 11-bit APID.
pub const MAX_APID: u11 = u11::MAX;
/// Maximum allowed value for the 14-bit APID.
pub const MAX_SEQ_COUNT: u14 = u14::MAX;

/// Checksum types currently provided by the CCSDS packet support.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ChecksumType {
    /// Check the default CRC16-CCITT checksum.
    WithCrc16,
    /// Packet has a CRC16 which should be ignored.
    ///
    /// It is either not generated for packet creation or ignored when reading a packet.
    WithCrc16ButIgnored,
}

/// Generic error type when converting to and from raw byte slices.
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ByteConversionError {
    /// The passed slice is too small. Returns the passed slice length and expected minimum size
    #[error("target slice with size {found} is too small, expected size of at least {expected}")]
    ToSliceTooSmall {
        /// Found slice size.
        found: usize,
        /// Expected slice size.
        expected: usize,
    },
    /// The provider buffer is too small. Returns the passed slice length and expected minimum size
    #[error("source slice with size {found} too small, expected at least {expected} bytes")]
    FromSliceTooSmall {
        /// Found slice size.
        found: usize,
        /// Expected slice size.
        expected: usize,
    },
}

/// [zerocopy] serialization and deserialization errors.
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ZeroCopyError {
    /// The [zerocopy] library failed to write to bytes
    #[error("zerocopy serialization error")]
    ZeroCopyToError,
    /// The [zerocopy] library failed to read from bytes
    #[error("zerocopy deserialization error")]
    ZeroCopyFromError,
}

/// Invalid payload length which is bounded by [u16::MAX]
#[derive(thiserror::Error, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[error("invalid payload length: {0}")]
pub struct InvalidPayloadLengthError(usize);

/// Errors during CCSDS packet creation.
#[derive(thiserror::Error, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CcsdsPacketCreationError {
    /// Byte conversion error.
    #[error("byte conversion: {0}")]
    ByteConversion(#[from] ByteConversionError),
    /// Invalid payload length which exceeded [u16::MAX].
    #[error("invalid payload length: {0}")]
    InvalidPayloadLength(#[from] InvalidPayloadLengthError),
}

/// CCSDS packet type enumeration.
#[derive(Debug, PartialEq, Eq, num_enum::TryFromPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[bitbybit::bitenum(u1, exhaustive = true)]
#[repr(u8)]
pub enum PacketType {
    /// Telemetry packet.
    Tm = 0,
    /// Telecommand packet.
    Tc = 1,
}

/// CCSDS packet sequence flags.
#[derive(Debug, PartialEq, Eq, num_enum::TryFromPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[bitbybit::bitenum(u2, exhaustive = true)]
#[repr(u8)]
pub enum SequenceFlags {
    /// Continuation segment of a segmented packet.
    ContinuationSegment = 0b00,
    /// First segment of a sequence.
    FirstSegment = 0b01,
    /// Last segment of a sequence.
    LastSegment = 0b10,
    /// Unsegmented packet.
    Unsegmented = 0b11,
}

/// Retrieve the [PacketType] from a raw packet ID.
#[inline]
pub fn packet_type_in_raw_packet_id(packet_id: u16) -> PacketType {
    PacketType::try_from((packet_id >> 12) as u8 & 0b1).unwrap()
}

/// Calculate the full CCSDS packet length for a given user data length and optional checksum type.
///
/// Returns [None] if the calculated length allowed by the CCSDS data length field.
#[inline]
pub const fn ccsds_packet_len_for_user_data_len(
    data_len: usize,
    checksum: Option<ChecksumType>,
) -> Option<usize> {
    // Special case: A value of zero is not allowed for the data length field.
    if data_len == 0 {
        return Some(7);
    }
    let checksum_len = match checksum {
        Some(ChecksumType::WithCrc16) => 2,
        Some(ChecksumType::WithCrc16ButIgnored) => 2,
        None => 0,
    };
    let len = data_len
        .saturating_add(CCSDS_HEADER_LEN)
        .saturating_add(checksum_len);
    if len - CCSDS_HEADER_LEN - 1 > u16::MAX as usize {
        return None;
    }
    Some(len)
}

/// Calculate the full CCSDS packet length for a given user data length.
///
/// Returns [None] if the packet length exceeds the maximum allowed size [u16::MAX].
#[inline]
pub fn ccsds_packet_len_for_user_data_len_with_checksum(data_len: usize) -> Option<usize> {
    ccsds_packet_len_for_user_data_len(data_len, Some(ChecksumType::WithCrc16))
}

/// Abstraction for the CCSDS Packet ID, which forms the last thirteen bits
/// of the first two bytes in the CCSDS primary header.
#[derive(Debug, Eq, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct PacketId {
    /// Packet type (telemetry or telecommand).
    pub packet_type: PacketType,
    /// Secondary header flag.
    pub sec_header_flag: bool,
    /// Application Process ID (APID).
    pub apid: u11,
}

impl PartialEq for PacketId {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.raw().eq(&other.raw())
    }
}

impl PartialOrd for PacketId {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for PacketId {
    #[inline]
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.raw().cmp(&other.raw())
    }
}

impl Hash for PacketId {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        let raw = self.raw();
        raw.hash(state);
    }
}

impl Default for PacketId {
    #[inline]
    fn default() -> Self {
        PacketId {
            packet_type: PacketType::Tm,
            sec_header_flag: false,
            apid: u11::new(0),
        }
    }
}

impl PacketId {
    /// Generic constructor for telecommands.
    #[inline]
    pub const fn new_for_tc(sec_header: bool, apid: u11) -> Self {
        Self::new(PacketType::Tc, sec_header, apid)
    }

    /// Generic constructor for telemetry.
    #[inline]
    pub const fn new_for_tm(sec_header: bool, apid: u11) -> Self {
        Self::new(PacketType::Tm, sec_header, apid)
    }

    /// Generic constructor.
    #[inline]
    pub const fn new(packet_type: PacketType, sec_header_flag: bool, apid: u11) -> Self {
        PacketId {
            packet_type,
            sec_header_flag,
            apid,
        }
    }

    /// Set a new Application Process ID (APID). If the passed number is invalid, the APID will
    /// not be set and false will be returned. The maximum allowed value for the 11-bit field is
    /// 2047
    #[inline]
    pub fn set_apid(&mut self, apid: u11) {
        self.apid = apid;
    }

    /// 11-bit CCSDS Application Process ID (APID) field.
    #[inline]
    pub const fn apid(&self) -> u11 {
        self.apid
    }

    /// Raw numeric value.
    #[inline]
    pub const fn raw(&self) -> u16 {
        ((self.packet_type as u16) << 12)
            | ((self.sec_header_flag as u16) << 11)
            | self.apid.value()
    }
}

impl From<u16> for PacketId {
    fn from(raw_id: u16) -> Self {
        PacketId {
            packet_type: PacketType::try_from(((raw_id >> 12) & 0b1) as u8).unwrap(),
            sec_header_flag: ((raw_id >> 11) & 0b1) != 0,
            apid: u11::new(raw_id & 0x7FF),
        }
    }
}

/// Deprecated type alias.
#[deprecated(since = "0.16.0", note = "use PacketSequenceControl instead")]
pub type PacketSequenceCtrl = PacketSequenceControl;

/// Abstraction for the CCSDS Packet Sequence Control (PSC) field which is the
/// third and the fourth byte in the CCSDS primary header.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct PacketSequenceControl {
    /// CCSDS sequence flags.
    pub seq_flags: SequenceFlags,
    /// CCSDS sequence count.
    pub seq_count: u14,
}

impl PacketSequenceControl {
    /// Generic constructor.
    #[inline]
    pub const fn new(seq_flags: SequenceFlags, seq_count: u14) -> PacketSequenceControl {
        PacketSequenceControl {
            seq_flags,
            seq_count,
        }
    }

    /// Raw value.
    #[inline]
    pub const fn raw(&self) -> u16 {
        ((self.seq_flags as u16) << 14) | self.seq_count.value()
    }
}

impl From<u16> for PacketSequenceControl {
    fn from(raw_id: u16) -> Self {
        PacketSequenceControl {
            seq_flags: SequenceFlags::try_from(((raw_id >> 14) & 0b11) as u8).unwrap(),
            seq_count: u14::new(raw_id & SSC_MASK),
        }
    }
}

macro_rules! sph_from_other {
    ($Self: path, $other: path) => {
        impl From<$other> for $Self {
            fn from(other: $other) -> Self {
                Self::new_from_composite_fields(
                    other.packet_id(),
                    other.psc(),
                    other.data_len(),
                    Some(other.ccsds_version()),
                )
            }
        }
    };
}

const SSC_MASK: u16 = 0x3FFF;
const VERSION_MASK: u16 = 0xE000;

/// Generic trait to access fields of a CCSDS space packet header according to CCSDS 133.0-B-2.
pub trait CcsdsPacket {
    /// CCSDS version field.
    fn ccsds_version(&self) -> u3;

    /// CCSDS packet ID.
    ///
    /// First two bytes of the CCSDS primary header without the first three bits.
    fn packet_id(&self) -> PacketId;

    /// CCSDS packet sequence control.
    ///
    /// Third and fourth byte of the CCSDS primary header.
    fn psc(&self) -> PacketSequenceControl;

    /// Data length field.
    ///
    /// Please note that this is NOT the full packet length.
    /// The full length can be calculated by adding the header length [CCSDS_HEADER_LEN] + 1 or
    /// using [Self::packet_len].
    fn data_len(&self) -> u16;

    /// Total packet size based on the data length field
    #[inline]
    fn packet_len(&self) -> usize {
        usize::from(self.data_len()) + CCSDS_HEADER_LEN + 1
    }

    /// Deprecated alias for [Self::packet_len].
    #[deprecated(since = "0.16.0", note = "use packet_len instead")]
    #[inline]
    fn total_len(&self) -> usize {
        self.packet_len()
    }

    /// Retrieve 13 bit Packet Identification field. Can usually be retrieved with a bitwise AND
    /// of the first 2 bytes with 0x1FFF.
    #[inline]
    fn packet_id_raw(&self) -> u16 {
        self.packet_id().raw()
    }
    /// Retrieve Packet Sequence Count
    #[inline]
    fn psc_raw(&self) -> u16 {
        self.psc().raw()
    }

    /// CCSDS packet type.
    #[inline]
    fn packet_type(&self) -> PacketType {
        // This call should never fail because only 0 and 1 can be passed to the try_from call
        self.packet_id().packet_type
    }

    /// Is this a telemetry packet?
    #[inline]
    fn is_tm(&self) -> bool {
        self.packet_type() == PacketType::Tm
    }

    /// Is this a telecommand packet?
    #[inline]
    fn is_tc(&self) -> bool {
        self.packet_type() == PacketType::Tc
    }

    /// CCSDS secondary header flag. Returns true if a secondary header is present
    /// and false if it is not.
    #[inline]
    fn sec_header_flag(&self) -> bool {
        self.packet_id().sec_header_flag
    }

    /// CCSDS Application Process ID (APID).
    #[inline]
    fn apid(&self) -> u11 {
        self.packet_id().apid
    }

    /// CCSDS sequence count.
    #[inline]
    fn seq_count(&self) -> u14 {
        self.psc().seq_count
    }

    /// CCSDS sequence flags.
    #[inline]
    fn sequence_flags(&self) -> SequenceFlags {
        // This call should never fail because the mask ensures that only valid values are passed
        // into the try_from function
        self.psc().seq_flags
    }
}

/// Helper trait to generate the primary header from the composite fields.
pub trait CcsdsPrimaryHeader {
    /// Constructor.
    fn new_from_composite_fields(
        packet_id: PacketId,
        psc: PacketSequenceControl,
        data_len: u16,
        version: Option<u3>,
    ) -> Self;
}

/// Space Packet Primary Header according to CCSDS 133.0-B-2.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct SpacePacketHeader {
    /// CCSDS version field, occupies the first 3 bits of the raw header. Will generally
    /// be set to 0b000 in all constructors provided by this crate.
    pub version: u3,
    /// CCSDS Packet Identifier, which can also be used as a start marker. Occupies the last
    /// 13 bits of the first two bytes of the raw header
    pub packet_id: PacketId,
    /// CCSDS Packet Sequence Control, occupies the third and fourth byte of the raw header
    pub psc: PacketSequenceControl,
    /// Data length field occupies the fifth and the sixth byte of the raw header
    pub data_len: u16,
}

/// Alias for [SpacePacketHeader].
pub type SpHeader = SpacePacketHeader;

impl Default for SpacePacketHeader {
    /// The default function sets the sequence flag field to [SequenceFlags::Unsegmented] and the
    /// data length to 0.
    #[inline]
    fn default() -> Self {
        SpHeader {
            version: u3::new(0),
            packet_id: PacketId::default(),
            psc: PacketSequenceControl {
                seq_flags: SequenceFlags::Unsegmented,
                seq_count: u14::new(0),
            },
            data_len: 0,
        }
    }
}

impl SpacePacketHeader {
    /// Length of the CCSDS primary header.
    pub const LENGTH: usize = CCSDS_HEADER_LEN;

    /// Generic constructor.
    #[inline]
    pub const fn new(packet_id: PacketId, psc: PacketSequenceControl, data_len: u16) -> Self {
        Self {
            version: u3::new(0),
            packet_id,
            psc,
            data_len,
        }
    }

    /// This constructor sets the sequence flag field to [SequenceFlags::Unsegmented] and the data
    /// length to 0.
    #[inline]
    pub const fn new_from_apid(apid: u11) -> Self {
        Self {
            version: u3::new(0b000),
            packet_id: PacketId::new(PacketType::Tm, false, apid),
            psc: PacketSequenceControl {
                seq_flags: SequenceFlags::Unsegmented,
                seq_count: u14::new(0),
            },
            data_len: 0,
        }
    }

    /// Constructor from individual fields.
    #[inline]
    pub const fn new_from_fields(
        ptype: PacketType,
        sec_header: bool,
        apid: u11,
        seq_flags: SequenceFlags,
        seq_count: u14,
        data_len: u16,
    ) -> Self {
        Self {
            psc: PacketSequenceControl::new(seq_flags, seq_count),
            packet_id: PacketId::new(ptype, sec_header, apid),
            data_len,
            version: u3::new(0b000),
        }
    }

    /// Constructor for telemetry packets.
    #[inline]
    pub const fn new_for_tm(
        apid: u11,
        seq_flags: SequenceFlags,
        seq_count: u14,
        data_len: u16,
    ) -> Self {
        Self::new_from_fields(PacketType::Tm, false, apid, seq_flags, seq_count, data_len)
    }

    /// Constructor for telecommand packets.
    #[inline]
    pub const fn new_for_tc(
        apid: u11,
        seq_flags: SequenceFlags,
        seq_count: u14,
        data_len: u16,
    ) -> Self {
        Self::new_from_fields(PacketType::Tc, false, apid, seq_flags, seq_count, data_len)
    }

    /// Variant of [SpHeader::new_for_tc] which sets the sequence flag field to [SequenceFlags::Unsegmented].
    #[inline]
    pub const fn new_for_unseg_tc(apid: u11, seq_count: u14, data_len: u16) -> Self {
        Self::new_for_tc(apid, SequenceFlags::Unsegmented, seq_count, data_len)
    }

    /// Variant of [SpHeader::new_for_tm] which sets the sequence flag field to [SequenceFlags::Unsegmented].
    #[inline]
    pub const fn new_for_unseg_tm(apid: u11, seq_count: u14, data_len: u16) -> Self {
        Self::new_for_tm(apid, SequenceFlags::Unsegmented, seq_count, data_len)
    }

    delegate! {
        to self.packet_id {
            /// Set the application process ID (APID).
            #[inline]
            pub fn set_apid(&mut self, apid: u11);
        }
    }

    /// Retrieve the total packet size based on the data length field
    #[inline]
    pub fn packet_len(&self) -> usize {
        usize::from(self.data_len()) + Self::LENGTH + 1
    }

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

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

    /// Set the CCSDS secondary header flag.
    #[inline]
    pub fn set_sec_header_flag(&mut self) {
        self.packet_id.sec_header_flag = true;
    }

    /// Clear the CCSDS secondary header flag.
    #[inline]
    pub fn clear_sec_header_flag(&mut self) {
        self.packet_id.sec_header_flag = false;
    }

    /// Set the CCSDS packet type.
    #[inline]
    pub fn set_packet_type(&mut self, packet_type: PacketType) {
        self.packet_id.packet_type = packet_type;
    }

    /// Application Process ID (APID) field.
    #[inline]
    pub fn apid(&self) -> u11 {
        self.packet_id.apid
    }

    /// Create a struct from a raw slice where the fields have network endianness (big).
    /// This function also returns the remaining part of the passed slice starting past the read
    /// CCSDS header.
    pub fn from_be_bytes(buf: &[u8]) -> Result<(Self, &[u8]), ByteConversionError> {
        if buf.len() < Self::LENGTH {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: buf.len(),
                expected: CCSDS_HEADER_LEN,
            });
        }
        // Unwrap okay, this can not fail.
        let zc_header = zc::SpHeader::read_from_bytes(&buf[0..Self::LENGTH]).unwrap();
        Ok((Self::from(zc_header), &buf[Self::LENGTH..]))
    }

    /// Write the header to a raw buffer using big endian format. This function returns the
    /// remaining part of the passed slice starting past the written CCSDS header.
    pub fn write_to_be_bytes<'a>(
        &self,
        buf: &'a mut [u8],
    ) -> Result<&'a mut [u8], ByteConversionError> {
        if buf.len() < Self::LENGTH {
            return Err(ByteConversionError::ToSliceTooSmall {
                found: buf.len(),
                expected: CCSDS_HEADER_LEN,
            });
        }
        let zc_header: zc::SpHeader = zc::SpHeader::from(*self);
        // Unwrap okay, this can not fail.
        zc_header.write_to(&mut buf[0..Self::LENGTH]).unwrap();
        Ok(&mut buf[Self::LENGTH..])
    }

    /// Create a vector containing the CCSDS header.
    #[cfg(feature = "alloc")]
    pub fn to_vec(&self) -> alloc::vec::Vec<u8> {
        let mut vec = alloc::vec![0; Self::LENGTH];
        // This can not fail.
        self.write_to_be_bytes(&mut vec[..]).unwrap();
        vec
    }
}

impl CcsdsPacket for SpacePacketHeader {
    /// CCSDS version field.
    #[inline]
    fn ccsds_version(&self) -> u3 {
        self.version
    }

    /// Full packet length.
    #[inline]
    fn packet_len(&self) -> usize {
        self.packet_len()
    }

    /// CCSDS packet ID field.
    #[inline]
    fn packet_id(&self) -> PacketId {
        self.packet_id
    }

    /// CCSDS packet sequence control.
    #[inline]
    fn psc(&self) -> PacketSequenceControl {
        self.psc
    }

    /// CCSDS data length field.
    #[inline]
    fn data_len(&self) -> u16 {
        self.data_len
    }
}

impl CcsdsPrimaryHeader for SpacePacketHeader {
    #[inline]
    fn new_from_composite_fields(
        packet_id: PacketId,
        psc: PacketSequenceControl,
        data_len: u16,
        version: Option<u3>,
    ) -> Self {
        let mut version_to_set = u3::new(0b000);
        if let Some(version) = version {
            version_to_set = version;
        }
        SpHeader {
            version: version_to_set,
            packet_id,
            psc,
            data_len,
        }
    }
}

sph_from_other!(SpHeader, crate::zc::SpHeader);

/// [zerocopy] based CCSDS Space Packet Primary Header implementation.
pub mod zc {
    use crate::{CcsdsPacket, CcsdsPrimaryHeader, PacketId, PacketSequenceControl, VERSION_MASK};
    use arbitrary_int::traits::Integer;
    use arbitrary_int::u3;
    use zerocopy::byteorder::NetworkEndian;
    use zerocopy::{FromBytes, Immutable, IntoBytes, Unaligned, U16};

    /// [zerocopy] space packet header.
    #[derive(FromBytes, IntoBytes, Immutable, Unaligned, Debug)]
    #[repr(C)]
    pub struct SpHeader {
        version_packet_id: U16<NetworkEndian>,
        psc: U16<NetworkEndian>,
        data_len: U16<NetworkEndian>,
    }

    impl SpHeader {
        /// Generic constructor.
        pub fn new(
            packet_id: PacketId,
            psc: PacketSequenceControl,
            data_len: u16,
            version: Option<u3>,
        ) -> Self {
            let mut version_packet_id = packet_id.raw();
            if let Some(version) = version {
                version_packet_id = (version.as_u16() << 13) | packet_id.raw()
            }
            SpHeader {
                version_packet_id: U16::from(version_packet_id),
                psc: U16::from(psc.raw()),
                data_len: U16::from(data_len),
            }
        }
    }

    impl CcsdsPacket for SpHeader {
        /// CCSDS version field.
        #[inline]
        fn ccsds_version(&self) -> u3 {
            u3::new(((self.version_packet_id.get() >> 13) as u8) & 0b111)
        }

        /// CCSDS packet ID field.
        #[inline]
        fn packet_id(&self) -> PacketId {
            PacketId::from(self.packet_id_raw())
        }

        /// CCSDS packet sequence control field.
        #[inline]
        fn psc(&self) -> PacketSequenceControl {
            PacketSequenceControl::from(self.psc_raw())
        }

        /// CCSDS data length field.
        #[inline]
        fn data_len(&self) -> u16 {
            self.data_len.get()
        }

        #[inline]
        fn packet_id_raw(&self) -> u16 {
            self.version_packet_id.get() & (!VERSION_MASK)
        }

        #[inline]
        fn psc_raw(&self) -> u16 {
            self.psc.get()
        }
    }

    impl CcsdsPrimaryHeader for SpHeader {
        fn new_from_composite_fields(
            packet_id: PacketId,
            psc: PacketSequenceControl,
            data_len: u16,
            version: Option<u3>,
        ) -> Self {
            SpHeader::new(packet_id, psc, data_len, version)
        }
    }

    sph_from_other!(SpHeader, crate::SpHeader);
}

/// CCSDS packet creator with optional support for a CRC16 CCITT checksum appended to the
/// end of the packet and support for copying into the user buffer directly.
///
/// This packet creator variant reserves memory based on the required user data length specified
/// by the user and then provides mutable or shared access to that memory. This is useful
/// to avoid an additional slice for the user data and allow copying data directly
/// into the packet.
///
/// Please note that packet creation has to be completed using the [Self::finish] call.
#[derive(Debug)]
pub struct CcsdsPacketCreatorWithReservedData<'buf> {
    sp_header: SpHeader,
    buf: &'buf mut [u8],
    checksum: Option<ChecksumType>,
}

impl<'buf> CcsdsPacketCreatorWithReservedData<'buf> {
    /// CCSDS header length.
    pub const HEADER_LEN: usize = CCSDS_HEADER_LEN;

    /// Calculate the full CCSDS packet length for a given user data length and with a CRC16
    /// checksum.
    #[inline]
    pub fn packet_len_for_user_data_with_checksum(user_data_len: usize) -> Option<usize> {
        ccsds_packet_len_for_user_data_len(user_data_len, Some(ChecksumType::WithCrc16))
    }

    /// Generic constructor.
    pub fn new(
        mut sp_header: SpacePacketHeader,
        packet_type: PacketType,
        packet_data_len: usize,
        buf: &'buf mut [u8],
        checksum: Option<ChecksumType>,
    ) -> Result<Self, CcsdsPacketCreationError> {
        let full_packet_len = match checksum {
            Some(crc_type) => match crc_type {
                ChecksumType::WithCrc16 | ChecksumType::WithCrc16ButIgnored => {
                    CCSDS_HEADER_LEN + packet_data_len + 2
                }
            },
            None => {
                // Special case: At least one byte of user data is required.
                if packet_data_len == 0 {
                    CCSDS_HEADER_LEN + 1
                } else {
                    CCSDS_HEADER_LEN + packet_data_len
                }
            }
        };
        if full_packet_len > buf.len() {
            return Err(ByteConversionError::ToSliceTooSmall {
                found: buf.len(),
                expected: full_packet_len,
            }
            .into());
        }
        if full_packet_len - CCSDS_HEADER_LEN - 1 > u16::MAX as usize {
            return Err(InvalidPayloadLengthError(packet_data_len).into());
        }
        sp_header.data_len = (full_packet_len - CCSDS_HEADER_LEN - 1) as u16;
        sp_header.packet_id.packet_type = packet_type;

        Ok(Self {
            sp_header,
            buf: buf[0..full_packet_len].as_mut(),
            checksum,
        })
    }

    /// Constructor which always appends a CRC16 checksum at the packet end.
    pub fn new_with_checksum(
        sp_header: SpHeader,
        packet_type: PacketType,
        payload_len: usize,
        buf: &'buf mut [u8],
    ) -> Result<Self, CcsdsPacketCreationError> {
        Self::new(
            sp_header,
            packet_type,
            payload_len,
            buf,
            Some(ChecksumType::WithCrc16),
        )
    }

    /// Constructor for telemetry packets which always appends a CRC16 checksum at the packet end.
    pub fn new_tm_with_checksum(
        sp_header: SpHeader,
        payload_len: usize,
        buf: &'buf mut [u8],
    ) -> Result<Self, CcsdsPacketCreationError> {
        Self::new(
            sp_header,
            PacketType::Tm,
            payload_len,
            buf,
            Some(ChecksumType::WithCrc16),
        )
    }

    /// Constructor for telecommand packets which always appends a CRC16 checksum at the packet
    /// end.
    pub fn new_tc_with_checksum(
        sp_header: SpHeader,
        payload_len: usize,
        buf: &'buf mut [u8],
    ) -> Result<Self, CcsdsPacketCreationError> {
        Self::new(
            sp_header,
            PacketType::Tc,
            payload_len,
            buf,
            Some(ChecksumType::WithCrc16),
        )
    }
}

impl CcsdsPacketCreatorWithReservedData<'_> {
    /// Raw full buffer this packet is constructed in.
    #[inline]
    pub fn raw_buffer(&self) -> &[u8] {
        self.buf
    }

    /// Full packet length.
    #[inline]
    pub fn packet_len(&self) -> usize {
        <Self as CcsdsPacket>::packet_len(self)
    }

    /// Space packet header.
    #[inline]
    pub fn sp_header(&self) -> &SpHeader {
        &self.sp_header
    }

    /// [CcsdsPacketIdAndPsc] structure for this packet.
    #[inline]
    pub fn ccsds_packet_id_and_psc(&self) -> CcsdsPacketIdAndPsc {
        CcsdsPacketIdAndPsc::new_from_ccsds_packet(self)
    }

    /// Mutable access to the packet data field.
    #[inline]
    pub fn packet_data_mut(&mut self) -> &mut [u8] {
        let len = self.packet_len();
        match self.checksum {
            Some(ChecksumType::WithCrc16) | Some(ChecksumType::WithCrc16ButIgnored) => {
                &mut self.buf[CCSDS_HEADER_LEN..len - 2]
            }
            None => &mut self.buf[CCSDS_HEADER_LEN..len],
        }
    }

    /// Read-only access to the packet data field.
    #[inline]
    pub fn packet_data(&mut self) -> &[u8] {
        let len = self.packet_len();
        match self.checksum {
            Some(ChecksumType::WithCrc16) | Some(ChecksumType::WithCrc16ButIgnored) => {
                &self.buf[CCSDS_HEADER_LEN..len - 2]
            }
            None => &self.buf[CCSDS_HEADER_LEN..len],
        }
    }

    /// Finish the packet generation process.
    ///
    /// This packet writes the space packet header. It also calculates and appends the CRC
    /// checksum when configured to do so.
    pub fn finish(self) -> usize {
        self.sp_header
            .write_to_be_bytes(&mut self.buf[0..CCSDS_HEADER_LEN])
            .unwrap();
        let len = self.packet_len();
        match self.checksum {
            Some(ChecksumType::WithCrc16) => {
                let crc16 = CRC_CCITT_FALSE.checksum(&self.buf[0..len - 2]);
                self.buf[len - 2..len].copy_from_slice(&crc16.to_be_bytes());
            }
            None | Some(ChecksumType::WithCrc16ButIgnored) => (),
        };
        len
    }
}

impl CcsdsPacket for CcsdsPacketCreatorWithReservedData<'_> {
    /// CCSDS version field.
    #[inline]
    fn ccsds_version(&self) -> arbitrary_int::u3 {
        self.sp_header.ccsds_version()
    }

    /// CCSDS packet ID field.
    #[inline]
    fn packet_id(&self) -> PacketId {
        self.sp_header.packet_id()
    }

    /// CCSDS packet sequence control field.
    #[inline]
    fn psc(&self) -> PacketSequenceControl {
        self.sp_header.psc()
    }

    /// CCSDS data length field.
    #[inline]
    fn data_len(&self) -> u16 {
        self.sp_header.data_len()
    }
}

/// Simple combination of [PacketId] and [PacketSequenceControl] field of this packet.
///
/// This is not a standardized structure and should not be confused with the [PacketId] field.
/// It can be used for something like CCSDS packet identification in a hashmap or supplying
/// the ID of a telecommand for verifiation purposes.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CcsdsPacketIdAndPsc {
    /// CCSDS Packet ID.
    pub packet_id: PacketId,
    /// CCSDS Packet Sequence Control.
    pub psc: PacketSequenceControl,
}

impl Hash for CcsdsPacketIdAndPsc {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.packet_id.hash(state);
        self.psc.raw().hash(state);
    }
}

impl CcsdsPacketIdAndPsc {
    /// Generic constructor.
    #[inline]
    pub const fn new(packet_id: PacketId, psc: PacketSequenceControl) -> Self {
        Self { packet_id, psc }
    }

    /// Extract the CCSDS packet ID from the given [CcsdsPacket].
    #[inline]
    pub fn new_from_ccsds_packet<P: CcsdsPacket>(packet: &P) -> Self {
        Self {
            packet_id: packet.packet_id(),
            psc: packet.psc(),
        }
    }

    /// Raw numeric value.
    #[inline]
    pub const fn raw(&self) -> u32 {
        ((self.packet_id.raw() as u32) << 16) | self.psc.raw() as u32
    }
}

impl From<SpacePacketHeader> for CcsdsPacketIdAndPsc {
    #[inline]
    fn from(header: SpacePacketHeader) -> Self {
        Self {
            packet_id: header.packet_id,
            psc: header.psc,
        }
    }
}

impl From<&SpacePacketHeader> for CcsdsPacketIdAndPsc {
    #[inline]
    fn from(header: &SpacePacketHeader) -> Self {
        Self {
            packet_id: header.packet_id,
            psc: header.psc,
        }
    }
}

#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct CcsdsPacketCreatorCommon {
    sp_header: SpHeader,
    checksum: Option<ChecksumType>,
}

impl CcsdsPacketCreatorCommon {
    #[inline]
    pub fn len_written(&self, packet_data_len: usize) -> usize {
        ccsds_packet_len_for_user_data_len(packet_data_len, self.checksum).unwrap()
    }

    /// [CcsdsPacketIdAndPsc] structure for this packet.
    #[inline]
    pub fn ccsds_packet_id_and_psc(&self) -> CcsdsPacketIdAndPsc {
        CcsdsPacketIdAndPsc::from(self.sp_header)
    }

    pub fn calculate_data_len_field(
        packet_data_len: usize,
        checksum: Option<ChecksumType>,
    ) -> Result<usize, InvalidPayloadLengthError> {
        let sp_data_len = (packet_data_len
            + match checksum {
                Some(ChecksumType::WithCrc16) | Some(ChecksumType::WithCrc16ButIgnored) => 2,
                None => 0,
            }
            - 1) as u16;
        let full_packet_len = match checksum {
            Some(crc_type) => match crc_type {
                ChecksumType::WithCrc16 | ChecksumType::WithCrc16ButIgnored => {
                    CCSDS_HEADER_LEN + packet_data_len + 2
                }
            },
            None => {
                // Special case: At least one byte of user data is required.
                if packet_data_len == 0 {
                    CCSDS_HEADER_LEN + 1
                } else {
                    CCSDS_HEADER_LEN + packet_data_len
                }
            }
        };
        if full_packet_len - CCSDS_HEADER_LEN - 1 > u16::MAX as usize {
            return Err(InvalidPayloadLengthError(packet_data_len));
        }
        Ok(sp_data_len as usize)
    }

    pub fn new(
        mut sp_header: SpHeader,
        packet_type: PacketType,
        packet_data_len: usize,
        checksum: Option<ChecksumType>,
    ) -> Result<Self, InvalidPayloadLengthError> {
        sp_header.data_len = Self::calculate_data_len_field(packet_data_len, checksum)? as u16;
        sp_header.packet_id.packet_type = packet_type;
        Ok(Self {
            sp_header,
            checksum,
        })
    }

    /// Write the CCSDS packet to the provided buffer.
    pub fn write_to_bytes(
        &self,
        buf: &mut [u8],
        len_written: usize,
        packet_data: &[u8],
    ) -> Result<usize, ByteConversionError> {
        if len_written > buf.len() {
            return Err(ByteConversionError::ToSliceTooSmall {
                found: buf.len(),
                expected: len_written,
            });
        }
        self.sp_header
            .write_to_be_bytes(&mut buf[0..CCSDS_HEADER_LEN])?;
        buf[CCSDS_HEADER_LEN..CCSDS_HEADER_LEN + packet_data.len()].copy_from_slice(packet_data);
        match self.checksum {
            Some(ChecksumType::WithCrc16) => {
                let crc16 = CRC_CCITT_FALSE.checksum(&buf[0..len_written - 2]);
                buf[len_written - 2..len_written].copy_from_slice(&crc16.to_be_bytes());
            }
            None | Some(ChecksumType::WithCrc16ButIgnored) => (),
        };
        Ok(len_written)
    }

    /// Create a CCSDS packet as a vector.
    #[cfg(feature = "alloc")]
    pub fn to_vec(&self, len_written: usize, packet_data: &[u8]) -> alloc::vec::Vec<u8> {
        let mut vec = alloc::vec![0u8; len_written];
        // Can not fail, unless we messed up the len_written method..
        self.write_to_bytes(&mut vec, len_written, packet_data)
            .unwrap();
        vec
    }
}

/// CCSDS packet creator with optional support for a CRC16 CCITT checksum appended to the
/// end of the packet.
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CcsdsPacketCreator<'app_data> {
    common: CcsdsPacketCreatorCommon,
    packet_data: &'app_data [u8],
}

impl<'app_data> CcsdsPacketCreator<'app_data> {
    /// CCSDS header length.
    pub const HEADER_LEN: usize = CCSDS_HEADER_LEN;

    /// Helper function which can be used to determine the full packet length from the user
    /// data length, assuming there is a CRC16 appended at the packet.
    #[inline]
    pub fn packet_len_for_user_data_with_checksum(user_data_len: usize) -> Option<usize> {
        ccsds_packet_len_for_user_data_len(user_data_len, Some(ChecksumType::WithCrc16))
    }

    /// Generic constructor.
    pub fn new(
        sp_header: SpHeader,
        packet_type: PacketType,
        packet_data: &'app_data [u8],
        checksum: Option<ChecksumType>,
    ) -> Result<Self, CcsdsPacketCreationError> {
        let common =
            CcsdsPacketCreatorCommon::new(sp_header, packet_type, packet_data.len(), checksum)?;
        Ok(Self {
            packet_data,
            common,
        })
    }

    /// Constructor which always appends a CRC16 checksum at the packet end.
    pub fn new_with_checksum(
        sp_header: SpHeader,
        packet_type: PacketType,
        app_data: &'app_data [u8],
    ) -> Result<Self, CcsdsPacketCreationError> {
        Self::new(
            sp_header,
            packet_type,
            app_data,
            Some(ChecksumType::WithCrc16),
        )
    }

    /// Constructor for telemetry which always appends a CRC16 checksum at the packet end.
    pub fn new_tm_with_checksum(
        sp_header: SpHeader,
        app_data: &'app_data [u8],
    ) -> Result<Self, CcsdsPacketCreationError> {
        Self::new(
            sp_header,
            PacketType::Tm,
            app_data,
            Some(ChecksumType::WithCrc16),
        )
    }

    /// Constructor for telecommands which always appends a CRC16 checksum at the packet end.
    pub fn new_tc_with_checksum(
        sp_header: SpHeader,
        app_data: &'app_data [u8],
    ) -> Result<Self, CcsdsPacketCreationError> {
        Self::new(
            sp_header,
            PacketType::Tc,
            app_data,
            Some(ChecksumType::WithCrc16),
        )
    }
}

impl CcsdsPacketCreator<'_> {
    /// Full length when written to bytes.
    #[inline]
    pub fn len_written(&self) -> usize {
        self.common.len_written(self.packet_data.len())
    }

    /// Write the CCSDS packet to the provided buffer.
    pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        self.common
            .write_to_bytes(buf, self.len_written(), self.packet_data)
    }

    /// CCSDS space packet header.
    #[inline]
    pub fn sp_header(&self) -> &SpHeader {
        &self.common.sp_header
    }

    /// [CcsdsPacketIdAndPsc] of this packet.
    #[inline]
    pub fn ccsds_packet_id_and_psc(&self) -> CcsdsPacketIdAndPsc {
        self.common.ccsds_packet_id_and_psc()
    }

    /// Create a CCSDS packet as a vector.
    #[cfg(feature = "alloc")]
    pub fn to_vec(&self) -> alloc::vec::Vec<u8> {
        self.common.to_vec(self.len_written(), self.packet_data)
    }
}

impl CcsdsPacket for CcsdsPacketCreator<'_> {
    /// CCSDS version field.
    #[inline]
    fn ccsds_version(&self) -> arbitrary_int::u3 {
        self.common.sp_header.ccsds_version()
    }

    /// CCSDS packet ID field.
    #[inline]
    fn packet_id(&self) -> PacketId {
        self.common.sp_header.packet_id()
    }

    /// CCSDS packet sequence control field.
    #[inline]
    fn psc(&self) -> PacketSequenceControl {
        self.common.sp_header.psc()
    }

    /// CCSDS data length field.
    #[inline]
    fn data_len(&self) -> u16 {
        self.common.sp_header.data_len()
    }
}

/// CCSDS packet creator variant which owns the packet data.
#[cfg(feature = "alloc")]
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CcsdsPacketCreatorOwned {
    common: CcsdsPacketCreatorCommon,
    packet_data: alloc::vec::Vec<u8>,
}

#[cfg(feature = "alloc")]
impl CcsdsPacketCreatorOwned {
    /// CCSDS header length.
    pub const HEADER_LEN: usize = CCSDS_HEADER_LEN;

    /// Helper function which can be used to determine the full packet length from the user
    /// data length, assuming there is a CRC16 appended at the packet.
    #[inline]
    pub fn packet_len_for_user_data_with_checksum(user_data_len: usize) -> Option<usize> {
        ccsds_packet_len_for_user_data_len(user_data_len, Some(ChecksumType::WithCrc16))
    }

    /// Generic constructor.
    pub fn new(
        sp_header: SpHeader,
        packet_type: PacketType,
        packet_data: &[u8],
        checksum: Option<ChecksumType>,
    ) -> Result<Self, CcsdsPacketCreationError> {
        let common =
            CcsdsPacketCreatorCommon::new(sp_header, packet_type, packet_data.len(), checksum)?;
        Ok(Self {
            common,
            packet_data: packet_data.to_vec(),
        })
    }

    /// Constructor which always appends a CRC16 checksum at the packet end.
    pub fn new_with_checksum(
        sp_header: SpHeader,
        packet_type: PacketType,
        packet_data: &[u8],
    ) -> Result<Self, CcsdsPacketCreationError> {
        Self::new(
            sp_header,
            packet_type,
            packet_data,
            Some(ChecksumType::WithCrc16),
        )
    }

    /// Constructor for telemetry which always appends a CRC16 checksum at the packet end.
    pub fn new_tm_with_checksum(
        sp_header: SpHeader,
        packet_data: &[u8],
    ) -> Result<Self, CcsdsPacketCreationError> {
        Self::new(
            sp_header,
            PacketType::Tm,
            packet_data,
            Some(ChecksumType::WithCrc16),
        )
    }

    /// Constructor for telecommands which always appends a CRC16 checksum at the packet end.
    pub fn new_tc_with_checksum(
        sp_header: SpHeader,
        packet_data: &[u8],
    ) -> Result<Self, CcsdsPacketCreationError> {
        Self::new(
            sp_header,
            PacketType::Tc,
            packet_data,
            Some(ChecksumType::WithCrc16),
        )
    }

    /// Full length when written to bytes.
    pub fn len_written(&self) -> usize {
        self.common.len_written(self.packet_data.len())
    }

    /// Write the CCSDS packet to the provided buffer.
    pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        self.common
            .write_to_bytes(buf, self.len_written(), &self.packet_data)
    }

    /// CCSDS space packet header.
    #[inline]
    pub fn sp_header(&self) -> &SpHeader {
        &self.common.sp_header
    }

    /// [CcsdsPacketIdAndPsc] of this packet.
    #[inline]
    pub fn ccsds_packet_id_and_psc(&self) -> CcsdsPacketIdAndPsc {
        self.common.ccsds_packet_id_and_psc()
    }

    /// Create a CCSDS packet as a vector.
    #[cfg(feature = "alloc")]
    pub fn to_vec(&self) -> alloc::vec::Vec<u8> {
        self.common.to_vec(self.len_written(), &self.packet_data)
    }
}

#[cfg(feature = "alloc")]
impl CcsdsPacket for CcsdsPacketCreatorOwned {
    /// CCSDS version field.
    #[inline]
    fn ccsds_version(&self) -> arbitrary_int::u3 {
        self.common.sp_header.ccsds_version()
    }

    /// CCSDS packet ID field.
    #[inline]
    fn packet_id(&self) -> PacketId {
        self.common.sp_header.packet_id()
    }

    /// CCSDS packet sequence control field.
    #[inline]
    fn psc(&self) -> PacketSequenceControl {
        self.common.sp_header.psc()
    }

    /// CCSDS data length field.
    #[inline]
    fn data_len(&self) -> u16 {
        self.common.sp_header.data_len()
    }
}

/// CCSDS packet read error.
#[derive(thiserror::Error, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CcsdsPacketReadError {
    /// Byte conversion error.
    #[error("byte conversion: {0}")]
    ByteConversion(#[from] ByteConversionError),
    /// CRC error.
    #[error("CRC error")]
    CrcError,
}

/// CCSDS packet reader structure.
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CcsdsPacketReader<'buf> {
    sp_header: SpHeader,
    packet_data: &'buf [u8],
}

impl<'buf> CcsdsPacketReader<'buf> {
    /// CCSDS header length.
    pub const HEADER_LEN: usize = CCSDS_HEADER_LEN;

    /// Constructor which expects a CRC16 checksum.
    pub fn new_with_checksum(
        buf: &'buf [u8],
    ) -> Result<CcsdsPacketReader<'buf>, CcsdsPacketReadError> {
        Self::new(buf, Some(ChecksumType::WithCrc16))
    }

    /// Generic constructor.
    pub fn new(
        buf: &'buf [u8],
        checksum: Option<ChecksumType>,
    ) -> Result<Self, CcsdsPacketReadError> {
        let sp_header = SpHeader::from_be_bytes(&buf[0..CCSDS_HEADER_LEN])?.0;
        if sp_header.packet_len() > buf.len() {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: buf.len(),
                expected: sp_header.packet_len(),
            }
            .into());
        }
        let user_data = match checksum {
            Some(ChecksumType::WithCrc16) => {
                if CRC_CCITT_FALSE.checksum(&buf[0..sp_header.packet_len()]) != 0 {
                    return Err(CcsdsPacketReadError::CrcError);
                }
                &buf[CCSDS_HEADER_LEN..sp_header.packet_len() - 2]
            }
            Some(ChecksumType::WithCrc16ButIgnored) => {
                &buf[CCSDS_HEADER_LEN..sp_header.packet_len() - 2]
            }
            None => &buf[CCSDS_HEADER_LEN..sp_header.packet_len()],
        };
        Ok(Self {
            sp_header,
            packet_data: user_data,
        })
    }
}

impl CcsdsPacketReader<'_> {
    /// Space pacekt header.
    #[inline]
    pub fn sp_header(&self) -> &SpHeader {
        &self.sp_header
    }

    /// [CcsdsPacketIdAndPsc] structure for this packet.
    #[inline]
    pub fn ccsds_packet_id_and_psc(&self) -> CcsdsPacketIdAndPsc {
        CcsdsPacketIdAndPsc::new_from_ccsds_packet(self)
    }

    /// CCSDS packet type.
    #[inline]
    pub fn packet_type(&self) -> PacketType {
        self.sp_header.packet_id.packet_type
    }

    /// Read-only access to the packet data field.
    #[inline]
    pub fn packet_data(&self) -> &[u8] {
        self.packet_data
    }

    /// 11-bit Application Process ID field.
    #[inline]
    pub fn apid(&self) -> u11 {
        self.sp_header.apid()
    }

    /// CCSDS packet ID field.
    #[inline]
    pub fn packet_id(&self) -> PacketId {
        self.sp_header.packet_id()
    }

    /// Packet sequence control field.
    #[inline]
    pub fn psc(&self) -> PacketSequenceControl {
        self.sp_header.psc()
    }

    /// Full packet length with the CCSDS header.
    #[inline]
    pub fn packet_len(&self) -> usize {
        <Self as CcsdsPacket>::packet_len(self)
    }

    /// Packet data length field.
    #[inline]
    pub fn data_len(&self) -> u16 {
        self.sp_header.data_len()
    }
}

impl CcsdsPacket for CcsdsPacketReader<'_> {
    /// CCSDS version field.
    #[inline]
    fn ccsds_version(&self) -> arbitrary_int::u3 {
        self.sp_header.ccsds_version()
    }

    /// Packet ID field.
    #[inline]
    fn packet_id(&self) -> PacketId {
        self.packet_id()
    }

    /// Packet sequence control field.
    #[inline]
    fn psc(&self) -> PacketSequenceControl {
        self.psc()
    }

    /// Packet data length without the CCSDS header.
    #[inline]
    fn data_len(&self) -> u16 {
        self.data_len()
    }
}

#[cfg(all(test, feature = "std"))]
pub(crate) mod tests {
    use std::collections::HashSet;

    use super::*;
    use crate::crc::CRC_CCITT_FALSE;
    #[allow(unused_imports)]
    use crate::ByteConversionError;
    #[cfg(feature = "serde")]
    use crate::CcsdsPrimaryHeader;
    use crate::{SequenceFlags, SpHeader};
    use alloc::vec;
    use arbitrary_int::{u11, u14};
    #[cfg(feature = "serde")]
    use core::fmt::Debug;
    #[cfg(feature = "serde")]
    use postcard::{from_bytes, to_allocvec};
    #[cfg(feature = "serde")]
    use serde::{de::DeserializeOwned, Serialize};
    use zerocopy::FromBytes;

    const CONST_SP: SpHeader = SpHeader::new(
        PacketId::new_for_tc(true, u11::new(0x36)),
        PacketSequenceControl::new(SequenceFlags::ContinuationSegment, u14::new(0x88)),
        0x90,
    );

    const PACKET_ID_TM: PacketId = PacketId::new_for_tm(true, u11::new(0x22));

    #[cfg(feature = "serde")]
    pub(crate) fn generic_serde_test<T: Serialize + DeserializeOwned + PartialEq + Debug>(
        value: T,
    ) {
        let output: alloc::vec::Vec<u8> = to_allocvec(&value).unwrap();
        let output_converted_back: T = from_bytes(&output).unwrap();
        assert_eq!(output_converted_back, value);
    }

    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn verify_const_packet_id() {
        assert_eq!(PACKET_ID_TM.apid().value(), 0x22);
        assert!(PACKET_ID_TM.sec_header_flag);
        assert_eq!(PACKET_ID_TM.packet_type, PacketType::Tm);
        let const_tc_id = PacketId::new_for_tc(true, u11::new(0x23));
        assert_eq!(const_tc_id.packet_type, PacketType::Tc);
    }

    #[test]
    fn test_default_packet_id() {
        let id_default = PacketId::default();
        assert_eq!(id_default.packet_type, PacketType::Tm);
        assert_eq!(id_default.apid.value(), 0x000);
        assert!(!id_default.sec_header_flag);
    }

    #[test]
    fn test_packet_id_ctors() {
        let packet_id = PacketId::new(PacketType::Tc, true, u11::new(0x1ff));
        assert_eq!(packet_id.apid().value(), 0x1ff);
        assert_eq!(packet_id.packet_type, PacketType::Tc);
        assert!(packet_id.sec_header_flag);
        let packet_id_tc = PacketId::new_for_tc(true, u11::new(0x1ff));
        assert_eq!(packet_id_tc, packet_id);
        let packet_id_tm = PacketId::new_for_tm(true, u11::new(0x2ff));
        assert!(packet_id_tm.sec_header_flag);
        assert_eq!(packet_id_tm.packet_type, PacketType::Tm);
        assert_eq!(packet_id_tm.apid, u11::new(0x2ff));
    }

    #[test]
    fn verify_const_sp_header() {
        assert!(CONST_SP.sec_header_flag());
        assert_eq!(CONST_SP.apid().value(), 0x36);
        assert_eq!(
            CONST_SP.sequence_flags(),
            SequenceFlags::ContinuationSegment
        );
        assert_eq!(CONST_SP.seq_count().value(), 0x88);
        assert_eq!(CONST_SP.data_len, 0x90);
    }

    #[test]
    fn test_seq_flag_helpers() {
        assert_eq!(
            SequenceFlags::try_from(0b00).expect("SEQ flag creation failed"),
            SequenceFlags::ContinuationSegment
        );
        assert_eq!(
            SequenceFlags::try_from(0b01).expect("SEQ flag creation failed"),
            SequenceFlags::FirstSegment
        );
        assert_eq!(
            SequenceFlags::try_from(0b10).expect("SEQ flag creation failed"),
            SequenceFlags::LastSegment
        );
        assert_eq!(
            SequenceFlags::try_from(0b11).expect("SEQ flag creation failed"),
            SequenceFlags::Unsegmented
        );
        assert!(SequenceFlags::try_from(0b100).is_err());
    }

    #[test]
    fn test_packet_type_helper() {
        assert_eq!(PacketType::try_from(0b00).unwrap(), PacketType::Tm);
        assert_eq!(PacketType::try_from(0b01).unwrap(), PacketType::Tc);
        assert!(PacketType::try_from(0b10).is_err());
    }

    #[test]
    fn test_packet_id() {
        let packet_id = PacketId::new(PacketType::Tm, false, u11::new(0x42));
        assert_eq!(packet_id.raw(), 0x0042);
        let packet_id_from_raw = PacketId::from(packet_id.raw());
        assert_eq!(
            packet_type_in_raw_packet_id(packet_id.raw()),
            PacketType::Tm
        );
        assert_eq!(packet_id_from_raw, packet_id);
        let packet_id_from_new = PacketId::new(PacketType::Tm, false, u11::new(0x42));
        assert_eq!(packet_id_from_new, packet_id);
    }

    #[test]
    fn test_packet_seq_ctrl() {
        let psc = PacketSequenceControl::new(SequenceFlags::ContinuationSegment, u14::new(77));
        assert_eq!(psc.raw(), 77);
        let psc_from_raw = PacketSequenceControl::from(psc.raw());
        assert_eq!(psc_from_raw, psc);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_sph() {
        let sp_header = SpHeader::new_for_unseg_tc(u11::new(0x42), u14::new(12), 0);
        assert_eq!(sp_header.ccsds_version().value(), 0b000);
        assert!(sp_header.is_tc());
        assert!(!sp_header.sec_header_flag());
        assert_eq!(sp_header.packet_type(), PacketType::Tc);
        assert_eq!(sp_header.seq_count().value(), 12);
        assert_eq!(sp_header.apid().value(), 0x42);
        assert_eq!(sp_header.sequence_flags(), SequenceFlags::Unsegmented);
        assert_eq!(sp_header.data_len(), 0);
        let output = to_allocvec(&sp_header).unwrap();
        let sp_header: SpHeader = from_bytes(&output).unwrap();
        assert_eq!(sp_header.version.value(), 0b000);
        assert!(!sp_header.packet_id.sec_header_flag);
        assert_eq!(sp_header.packet_type(), PacketType::Tc);
        assert_eq!(sp_header.seq_count().value(), 12);
        assert_eq!(sp_header.apid().value(), 0x42);
        assert_eq!(sp_header.sequence_flags(), SequenceFlags::Unsegmented);
        assert_eq!(sp_header.packet_id_raw(), 0x1042);
        assert_eq!(sp_header.psc_raw(), 0xC00C);
        assert_eq!(sp_header.ccsds_version().value(), 0b000);
        assert_eq!(sp_header.data_len, 0);

        let sp_header = SpHeader::new_for_unseg_tm(u11::new(0x7), u14::new(22), 36);
        assert_eq!(sp_header.ccsds_version().value(), 0b000);
        assert!(sp_header.is_tm());
        assert!(!sp_header.sec_header_flag());
        assert_eq!(sp_header.packet_type(), PacketType::Tm);
        assert_eq!(sp_header.seq_count().value(), 22);
        assert_eq!(sp_header.apid().value(), 0x07);
        assert_eq!(sp_header.sequence_flags(), SequenceFlags::Unsegmented);
        assert_eq!(sp_header.packet_id_raw(), 0x0007);
        assert_eq!(sp_header.psc_raw(), 0xC016);
        assert_eq!(sp_header.data_len(), 36);
        assert_eq!(sp_header.ccsds_version().value(), 0b000);

        let from_comp_fields = SpHeader::new_from_composite_fields(
            PacketId::new(PacketType::Tc, true, u11::new(0x42)),
            PacketSequenceControl::new(SequenceFlags::Unsegmented, u14::new(0x7)),
            0,
            None,
        );
        assert_eq!(from_comp_fields.packet_type(), PacketType::Tc);
        assert_eq!(from_comp_fields.apid().value(), 0x42);
        assert!(from_comp_fields.sec_header_flag());
        assert_eq!(
            from_comp_fields.sequence_flags(),
            SequenceFlags::Unsegmented
        );
        assert_eq!(from_comp_fields.seq_count().value(), 0x7);
        assert_eq!(from_comp_fields.data_len(), 0);
    }

    #[test]
    fn test_setters() {
        let mut sp_header =
            SpHeader::new_for_tc(u11::new(0x42), SequenceFlags::Unsegmented, u14::new(25), 0);
        sp_header.set_apid(u11::new(0x12));
        assert_eq!(sp_header.apid().as_u16(), 0x12);
        sp_header.set_sec_header_flag();
        assert!(sp_header.sec_header_flag());
        sp_header.clear_sec_header_flag();
        assert!(!sp_header.sec_header_flag());
        assert_eq!(sp_header.packet_type(), PacketType::Tc);
        sp_header.set_packet_type(PacketType::Tm);
        assert_eq!(sp_header.packet_type(), PacketType::Tm);
        sp_header.set_seq_count(u14::new(0x45));
        assert_eq!(sp_header.seq_count().as_u16(), 0x45);
    }

    #[test]
    fn test_tc_ctor() {
        let sp_header =
            SpHeader::new_for_tc(u11::new(0x42), SequenceFlags::Unsegmented, u14::new(25), 0);
        verify_sp_fields(PacketType::Tc, &sp_header);
    }

    #[test]
    fn test_tc_ctor_unseg() {
        let sp_header = SpHeader::new_for_unseg_tc(u11::new(0x42), u14::new(25), 0);
        verify_sp_fields(PacketType::Tc, &sp_header);
    }

    #[test]
    fn test_tc_ctor_unseg_const() {
        let sp_header = SpHeader::new_for_unseg_tc(u11::new(0x42), u14::new(25), 0);
        verify_sp_fields(PacketType::Tc, &sp_header);
    }

    #[test]
    fn test_tm_ctor() {
        let sp_header =
            SpHeader::new_for_tm(u11::new(0x42), SequenceFlags::Unsegmented, u14::new(25), 0);
        verify_sp_fields(PacketType::Tm, &sp_header);
    }

    #[test]
    fn test_tm_ctor_const() {
        let sp_header =
            SpHeader::new_for_tm(u11::new(0x42), SequenceFlags::Unsegmented, u14::new(25), 0);
        verify_sp_fields(PacketType::Tm, &sp_header);
    }

    #[test]
    fn test_tm_ctor_unseg() {
        let sp_header = SpHeader::new_for_unseg_tm(u11::new(0x42), u14::new(25), 0);
        verify_sp_fields(PacketType::Tm, &sp_header);
    }

    fn verify_sp_fields(ptype: PacketType, sp_header: &SpHeader) {
        assert_eq!(sp_header.packet_type(), ptype);
        assert_eq!(sp_header.sequence_flags(), SequenceFlags::Unsegmented);
        assert_eq!(sp_header.apid().value(), 0x42);
        assert_eq!(sp_header.seq_count(), u14::new(25));
        assert_eq!(sp_header.data_len(), 0);
    }

    #[test]
    fn test_zc_sph() {
        use zerocopy::IntoBytes;

        let sp_header = SpHeader::new_for_unseg_tc(u11::MAX, u14::MAX, 0);
        assert_eq!(sp_header.packet_type(), PacketType::Tc);
        assert_eq!(sp_header.apid().value(), 0x7FF);
        assert_eq!(sp_header.data_len(), 0);
        assert_eq!(sp_header.ccsds_version().value(), 0b000);
        assert!(sp_header.is_tc());
        let sp_header_zc = zc::SpHeader::from(sp_header);
        let slice = sp_header_zc.as_bytes();
        assert_eq!(slice.len(), 6);
        assert_eq!(slice[0], 0x17);
        assert_eq!(slice[1], 0xFF);
        assert_eq!(slice[2], 0xFF);
        assert_eq!(slice[3], 0xFF);
        assert_eq!(slice[4], 0x00);
        assert_eq!(slice[5], 0x00);

        let mut slice = [0; 6];
        sp_header_zc.write_to(slice.as_mut_slice()).unwrap();
        assert_eq!(slice.len(), 6);
        assert_eq!(slice[0], 0x17);
        assert_eq!(slice[1], 0xFF);
        assert_eq!(slice[2], 0xFF);
        assert_eq!(slice[3], 0xFF);
        assert_eq!(slice[4], 0x00);
        assert_eq!(slice[5], 0x00);

        let mut test_vec = vec![0_u8; 6];
        let slice = test_vec.as_mut_slice();
        sp_header_zc.write_to(slice).unwrap();
        let slice = test_vec.as_slice();
        assert_eq!(slice.len(), 6);
        assert_eq!(slice[0], 0x17);
        assert_eq!(slice[1], 0xFF);
        assert_eq!(slice[2], 0xFF);
        assert_eq!(slice[3], 0xFF);
        assert_eq!(slice[4], 0x00);
        assert_eq!(slice[5], 0x00);

        let sp_header = zc::SpHeader::read_from_bytes(slice);
        assert!(sp_header.is_ok());
        let sp_header = sp_header.unwrap();
        assert_eq!(sp_header.ccsds_version().value(), 0b000);
        assert_eq!(sp_header.packet_id_raw(), 0x17FF);
        assert_eq!(sp_header.apid().value(), 0x7FF);
        assert_eq!(sp_header.packet_type(), PacketType::Tc);
        assert_eq!(sp_header.data_len(), 0);
    }

    #[test]
    fn packet_id_ord_partial_ord() {
        let packet_id_small = PacketId::from(1_u16);
        let packet_id_larger = PacketId::from(2_u16);
        assert!(packet_id_small < packet_id_larger);
        assert!(packet_id_larger > packet_id_small);
        assert_eq!(
            packet_id_small.cmp(&packet_id_larger),
            core::cmp::Ordering::Less
        );
    }

    #[test]
    fn packet_id_hashable() {
        let mut id_set = HashSet::new();
        id_set.insert(PacketId::from(1_u16));
    }

    #[test]
    fn sp_header_from_apid() {
        let sp_header = SpHeader::new_from_apid(u11::new(0x03));
        assert_eq!(sp_header.apid().value(), 0x03);
        assert_eq!(sp_header.data_len(), 0);
    }

    #[cfg(feature = "defmt")]
    fn is_defmt_format<T: defmt::Format>(_t: T) {}

    #[test]
    #[cfg(feature = "defmt")]
    fn test_defmt_format() {
        is_defmt_format(ByteConversionError::ToSliceTooSmall {
            found: 1,
            expected: 2,
        });
    }

    #[test]
    fn test_sp_header_as_vec() {
        let sp_header = SpHeader::new_for_unseg_tc(u11::new(0x42), u14::new(25), 1);
        let sp_header_as_vec = sp_header.to_vec();
        let sp_header_read_back = SpHeader::from_be_bytes(&sp_header_as_vec)
            .expect("Error reading back SP header")
            .0;
        assert_eq!(sp_header, sp_header_read_back);
    }

    #[test]
    fn test_ccsds_size_function() {
        assert_eq!(ccsds_packet_len_for_user_data_len(1, None).unwrap(), 7);
        // Special case: One dummy byte is required.
        assert_eq!(ccsds_packet_len_for_user_data_len(0, None).unwrap(), 7);
        assert_eq!(
            ccsds_packet_len_for_user_data_len(1, Some(ChecksumType::WithCrc16)).unwrap(),
            9
        );
        assert_eq!(
            ccsds_packet_len_for_user_data_len_with_checksum(1).unwrap(),
            9
        );
    }

    #[test]
    fn test_ccsds_size_function_invalid_size_no_checksum() {
        // This works, because the data field is the user data length minus 1.
        assert!(ccsds_packet_len_for_user_data_len(u16::MAX as usize + 1, None).is_some());
        // This does not work, data field length exceeded.
        assert!(ccsds_packet_len_for_user_data_len(u16::MAX as usize + 2, None).is_none());
    }

    #[test]
    fn test_ccsds_size_function_invalid_size_with_checksum() {
        // 2 less bytes available because of the checksum.
        assert!(ccsds_packet_len_for_user_data_len(
            u16::MAX as usize - 1,
            Some(ChecksumType::WithCrc16)
        )
        .is_some());
        // This is too much.
        assert!(ccsds_packet_len_for_user_data_len(
            u16::MAX as usize,
            Some(ChecksumType::WithCrc16)
        )
        .is_none());
    }

    #[test]
    fn test_ccsds_creator_api() {
        let mut buf: [u8; 32] = [0; 32];
        let apid = u11::new(0x1);
        let packet_type = PacketType::Tc;
        let mut packet_creator = CcsdsPacketCreatorWithReservedData::new(
            SpacePacketHeader::new_from_apid(apid),
            packet_type,
            4,
            &mut buf,
            Some(ChecksumType::WithCrc16),
        )
        .unwrap();
        assert_eq!(packet_creator.packet_len(), 12);
        assert_eq!(packet_creator.raw_buffer().len(), 12);
        assert_eq!(packet_creator.data_len(), 5);
        assert_eq!(packet_creator.apid().value(), 0x1);
        assert_eq!(
            packet_creator.packet_id(),
            PacketId::new(packet_type, false, apid)
        );
        assert_eq!(
            packet_creator.psc(),
            PacketSequenceControl::new(SequenceFlags::Unsegmented, u14::new(0))
        );
        assert_eq!(packet_creator.packet_data_mut(), &mut [0, 0, 0, 0]);
        assert_eq!(packet_creator.packet_data(), &[0, 0, 0, 0]);
        assert_eq!(packet_creator.ccsds_version(), u3::new(0b000));
    }

    #[test]
    fn test_ccsds_creator_api_no_checksum() {
        let mut buf: [u8; 32] = [0; 32];
        let apid = u11::new(0x1);
        let packet_type = PacketType::Tm;
        let mut packet_creator = CcsdsPacketCreatorWithReservedData::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tm,
            4,
            &mut buf,
            None,
        )
        .unwrap();
        assert_eq!(packet_creator.packet_len(), 10);
        assert_eq!(packet_creator.data_len(), 3);
        assert_eq!(packet_creator.apid().value(), 0x1);
        assert_eq!(
            packet_creator.packet_id(),
            PacketId::new(packet_type, false, apid)
        );
        assert_eq!(
            packet_creator.psc(),
            PacketSequenceControl::new(SequenceFlags::Unsegmented, u14::new(0))
        );
        assert_eq!(packet_creator.packet_data_mut(), &mut [0, 0, 0, 0]);
        assert_eq!(packet_creator.packet_data(), &[0, 0, 0, 0]);
    }

    #[test]
    fn test_ccsds_creator_creation_with_reserved_data_alt_ctor() {
        let mut buf: [u8; 32] = [0; 32];
        let data = [1, 2, 3, 4];
        let mut packet_creator = CcsdsPacketCreatorWithReservedData::new_with_checksum(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tc,
            4,
            &mut buf,
        )
        .unwrap();
        packet_creator.packet_data_mut().copy_from_slice(&data);
        let written_len = packet_creator.finish();
        assert_eq!(
            CcsdsPacketCreatorWithReservedData::packet_len_for_user_data_with_checksum(4).unwrap(),
            written_len
        );
        assert_eq!(CRC_CCITT_FALSE.checksum(&buf[0..written_len]), 0);
        let sp_header = SpacePacketHeader::from_be_bytes(
            &buf[0..CcsdsPacketCreatorWithReservedData::HEADER_LEN],
        )
        .unwrap()
        .0;
        assert_eq!(sp_header.apid().value(), 0x1);
        assert_eq!(buf[6], 1);
        assert_eq!(buf[7], 2);
        assert_eq!(buf[8], 3);
        assert_eq!(buf[9], 4);
        assert_eq!(buf[12], 0);
    }

    #[test]
    fn test_ccsds_creator_creation_with_reserved_data() {
        let mut buf: [u8; 32] = [0; 32];
        let data = [1, 2, 3, 4];
        let mut packet_creator = CcsdsPacketCreatorWithReservedData::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tc,
            4,
            &mut buf,
            Some(ChecksumType::WithCrc16),
        )
        .unwrap();
        packet_creator.packet_data_mut().copy_from_slice(&data);
        let written_len = packet_creator.finish();
        assert_eq!(
            CcsdsPacketCreatorWithReservedData::packet_len_for_user_data_with_checksum(4).unwrap(),
            written_len
        );
        assert_eq!(CRC_CCITT_FALSE.checksum(&buf[0..written_len]), 0);
        let sp_header = SpacePacketHeader::from_be_bytes(
            &buf[0..CcsdsPacketCreatorWithReservedData::HEADER_LEN],
        )
        .unwrap()
        .0;
        assert_eq!(sp_header.apid().value(), 0x1);
        assert_eq!(sp_header.packet_type(), PacketType::Tc);
        assert_eq!(buf[6], 1);
        assert_eq!(buf[7], 2);
        assert_eq!(buf[8], 3);
        assert_eq!(buf[9], 4);
        assert_eq!(buf[12], 0);
    }

    #[test]
    fn test_ccsds_creator_creation_empty_user_data_no_checksum() {
        let mut buf: [u8; 32] = [0; 32];
        let packet_creator = CcsdsPacketCreatorWithReservedData::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tc,
            0,
            &mut buf,
            None,
        )
        .unwrap();
        // Special case.
        assert_eq!(packet_creator.packet_len(), 7);
        packet_creator.finish();
        let reader = CcsdsPacketReader::new(&buf[0..7], None).unwrap();
        // Enforced 1 byte packet length.
        assert_eq!(reader.packet_data(), &[0]);
        assert_eq!(reader.packet_len(), 7);
    }

    #[test]
    fn test_ccsds_creator_creation_ignored_checksum() {
        let mut buf: [u8; 32] = [0; 32];
        let data = [1, 2, 3, 4, 5];
        let mut packet_creator = CcsdsPacketCreatorWithReservedData::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tc,
            data.len(),
            &mut buf,
            Some(ChecksumType::WithCrc16ButIgnored),
        )
        .unwrap();
        packet_creator.packet_data_mut().copy_from_slice(&data);
        // Special case.
        assert_eq!(packet_creator.packet_len(), 13);
        packet_creator.finish();
        let reader =
            CcsdsPacketReader::new(&buf[0..13], Some(ChecksumType::WithCrc16ButIgnored)).unwrap();
        // Enforced 1 byte packet length.
        assert_eq!(reader.packet_data(), &data);
        assert_eq!(reader.packet_len(), 13);
    }

    #[test]
    fn test_ccsds_creator_creation_buf_too_small() {
        let mut buf: [u8; 8] = [0; 8];
        let packet_creator = CcsdsPacketCreatorWithReservedData::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tc,
            4,
            &mut buf,
            None,
        );
        assert!(packet_creator.is_err());
        matches!(
            packet_creator.unwrap_err(),
            CcsdsPacketCreationError::ByteConversion(ByteConversionError::ToSliceTooSmall {
                found: 8,
                expected: 10
            })
        );
    }

    #[test]
    fn test_ccsds_creator_creation_with_reserved_data_tc_api() {
        let mut buf: [u8; 32] = [0; 32];
        let data = [1, 2, 3, 4];
        let mut packet_creator = CcsdsPacketCreatorWithReservedData::new_tc_with_checksum(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            4,
            &mut buf,
        )
        .unwrap();
        packet_creator.packet_data_mut().copy_from_slice(&data);
        let written_len = packet_creator.finish();
        assert_eq!(
            CcsdsPacketCreatorWithReservedData::packet_len_for_user_data_with_checksum(4).unwrap(),
            written_len
        );
        assert_eq!(CRC_CCITT_FALSE.checksum(&buf[0..written_len]), 0);
        let sp_header = SpacePacketHeader::from_be_bytes(
            &buf[0..CcsdsPacketCreatorWithReservedData::HEADER_LEN],
        )
        .unwrap()
        .0;
        assert_eq!(sp_header.apid().value(), 0x1);
        assert_eq!(sp_header.packet_type(), PacketType::Tc);
        assert_eq!(buf[6], 1);
        assert_eq!(buf[7], 2);
        assert_eq!(buf[8], 3);
        assert_eq!(buf[9], 4);
        assert_eq!(buf[12], 0);
    }

    #[test]
    fn test_ccsds_creator_creation_with_reserved_data_tm_api() {
        let mut buf: [u8; 32] = [0; 32];
        let data = [1, 2, 3, 4];
        let mut packet_creator = CcsdsPacketCreatorWithReservedData::new_tm_with_checksum(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            4,
            &mut buf,
        )
        .unwrap();
        packet_creator.packet_data_mut().copy_from_slice(&data);
        let written_len = packet_creator.finish();
        assert_eq!(
            CcsdsPacketCreatorWithReservedData::packet_len_for_user_data_with_checksum(4).unwrap(),
            written_len
        );
        assert_eq!(CRC_CCITT_FALSE.checksum(&buf[0..written_len]), 0);
        let sp_header = SpacePacketHeader::from_be_bytes(
            &buf[0..CcsdsPacketCreatorWithReservedData::HEADER_LEN],
        )
        .unwrap()
        .0;
        assert_eq!(sp_header.apid().value(), 0x1);
        assert_eq!(sp_header.packet_type(), PacketType::Tm);
        assert_eq!(buf[6], 1);
        assert_eq!(buf[7], 2);
        assert_eq!(buf[8], 3);
        assert_eq!(buf[9], 4);
        assert_eq!(buf[12], 0);
    }

    #[test]
    fn test_ccsds_creator_creation_with_reserved_data_no_checksum() {
        let mut buf: [u8; 32] = [0; 32];
        let data = [1, 2, 3, 4];
        let mut packet_creator = CcsdsPacketCreatorWithReservedData::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tc,
            4,
            &mut buf,
            None,
        )
        .unwrap();
        let sph = *packet_creator.sp_header();
        packet_creator.packet_data_mut().copy_from_slice(&data);
        assert_eq!(
            packet_creator.ccsds_packet_id_and_psc(),
            CcsdsPacketIdAndPsc::from(sph)
        );
        let written_len = packet_creator.finish();
        assert_eq!(written_len, 10);
        let sp_header = SpacePacketHeader::from_be_bytes(
            &buf[0..CcsdsPacketCreatorWithReservedData::HEADER_LEN],
        )
        .unwrap()
        .0;
        assert_eq!(sp_header.apid().value(), 0x1);
        assert_eq!(buf[6], 1);
        assert_eq!(buf[7], 2);
        assert_eq!(buf[8], 3);
        assert_eq!(buf[9], 4);
        assert_eq!(buf[10], 0);
        assert_eq!(buf[11], 0);
    }

    fn generic_ccsds_creator_test(alt_api: bool, owned: bool) {
        let data = [1, 2, 3, 4];
        let mut sp_header = SpacePacketHeader::new_from_apid(u11::new(0x1));
        sp_header.set_packet_type(PacketType::Tc);

        let packet_raw = match (alt_api, owned) {
            (true, true) => CcsdsPacketCreatorOwned::new(
                sp_header,
                PacketType::Tc,
                &data,
                Some(ChecksumType::WithCrc16),
            )
            .unwrap()
            .to_vec(),
            (true, false) => CcsdsPacketCreator::new(
                sp_header,
                PacketType::Tc,
                &data,
                Some(ChecksumType::WithCrc16),
            )
            .unwrap()
            .to_vec(),
            (false, true) => {
                CcsdsPacketCreatorOwned::new_with_checksum(sp_header, PacketType::Tc, &data)
                    .unwrap()
                    .to_vec()
            }
            (false, false) => {
                CcsdsPacketCreator::new_with_checksum(sp_header, PacketType::Tc, &data)
                    .unwrap()
                    .to_vec()
            }
        };
        assert_eq!(CRC_CCITT_FALSE.checksum(&packet_raw), 0);
        let sp_header_from_raw = SpacePacketHeader::from_be_bytes(
            &packet_raw[0..CcsdsPacketCreatorWithReservedData::HEADER_LEN],
        )
        .unwrap()
        .0;
        assert_eq!(sp_header_from_raw.packet_id(), sp_header.packet_id());
        assert_eq!(sp_header_from_raw.psc(), sp_header.psc());
        assert_eq!(sp_header.apid().value(), 0x1);
        assert_eq!(sp_header.packet_type(), PacketType::Tc);
        assert_eq!(packet_raw[6], 1);
        assert_eq!(packet_raw[7], 2);
        assert_eq!(packet_raw[8], 3);
        assert_eq!(packet_raw[9], 4);
    }

    #[test]
    fn test_ccsds_creator_creation_0() {
        generic_ccsds_creator_test(false, false);
    }

    #[test]
    fn test_ccsds_creator_creation_1() {
        generic_ccsds_creator_test(false, true);
    }

    #[test]
    fn test_ccsds_creator_creation_2() {
        generic_ccsds_creator_test(true, false);
    }

    #[test]
    fn test_ccsds_creator_creation_3() {
        generic_ccsds_creator_test(true, true);
    }

    #[test]
    fn test_ccsds_creator_ignored_checksum() {
        let data = [1, 2, 3, 4];
        let mut sp_header = SpacePacketHeader::new_from_apid(u11::new(0x1));
        sp_header.set_packet_type(PacketType::Tc);
        let packet_raw = CcsdsPacketCreatorOwned::new(
            sp_header,
            PacketType::Tc,
            &data,
            Some(ChecksumType::WithCrc16ButIgnored),
        )
        .unwrap()
        .to_vec();
        let reader =
            CcsdsPacketReader::new(&packet_raw, Some(ChecksumType::WithCrc16ButIgnored)).unwrap();
        assert_eq!(reader.packet_data(), data);
    }

    fn generic_test_creator(packet_raw: &[u8], sp_header: &SpHeader, packet_type: PacketType) {
        assert_eq!(CRC_CCITT_FALSE.checksum(packet_raw), 0);
        let sp_header_from_raw = SpacePacketHeader::from_be_bytes(
            &packet_raw[0..CcsdsPacketCreatorWithReservedData::HEADER_LEN],
        )
        .unwrap()
        .0;
        assert_eq!(sp_header_from_raw, *sp_header);
        assert_eq!(sp_header.packet_type(), packet_type);
        assert_eq!(packet_raw[6], 1);
        assert_eq!(packet_raw[7], 2);
        assert_eq!(packet_raw[8], 3);
        assert_eq!(packet_raw[9], 4);
    }

    #[test]
    fn test_ccsds_creator_creation_alt_tc() {
        let data = [1, 2, 3, 4];
        let packet_creator = CcsdsPacketCreator::new_tc_with_checksum(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            &data,
        )
        .unwrap();
        let packet_raw = packet_creator.to_vec();
        generic_test_creator(&packet_raw, packet_creator.sp_header(), PacketType::Tc);
    }

    #[test]
    fn test_ccsds_creator_creation_alt_tc_owned() {
        let data = [1, 2, 3, 4];
        let packet_creator = CcsdsPacketCreatorOwned::new_tc_with_checksum(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            &data,
        )
        .unwrap();
        let packet_raw = packet_creator.to_vec();
        generic_test_creator(&packet_raw, packet_creator.sp_header(), PacketType::Tc);
    }

    #[test]
    fn test_ccsds_creator_creation_alt_tm() {
        let data = [1, 2, 3, 4];
        let packet_creator = CcsdsPacketCreator::new_tm_with_checksum(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            &data,
        )
        .unwrap();
        let packet_raw = packet_creator.to_vec();
        generic_test_creator(&packet_raw, packet_creator.sp_header(), PacketType::Tm);
    }

    #[test]
    fn test_ccsds_creator_creation_alt_tm_owned() {
        let data = [1, 2, 3, 4];
        let packet_creator = CcsdsPacketCreatorOwned::new_tm_with_checksum(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            &data,
        )
        .unwrap();
        let packet_raw = packet_creator.to_vec();
        generic_test_creator(&packet_raw, packet_creator.sp_header(), PacketType::Tm);
    }

    fn generic_ccsds_reader_test(
        packet_data: &[u8],
        packet_raw: &[u8],
        packet_type: PacketType,
        sp_header: SpHeader,
    ) {
        assert_eq!(
            CcsdsPacketCreator::packet_len_for_user_data_with_checksum(4).unwrap(),
            packet_raw.len()
        );
        let reader = CcsdsPacketReader::new_with_checksum(packet_raw).unwrap();
        assert_eq!(*reader.sp_header(), sp_header);
        assert_eq!(reader.packet_data(), packet_data);
        assert_eq!(reader.apid(), u11::new(0x1));
        assert_eq!(
            reader.packet_id(),
            PacketId::new(packet_type, false, u11::new(0x1))
        );
        assert_eq!(
            reader.psc(),
            PacketSequenceControl::new(SequenceFlags::Unsegmented, u14::new(0x0))
        );
        assert_eq!(reader.packet_len(), packet_raw.len());
        assert_eq!(reader.packet_type(), packet_type);
        assert_eq!(reader.data_len() as usize, packet_raw.len() - 7);
    }

    #[test]
    fn test_ccsds_reader_tc() {
        let data = [1, 2, 3, 4];
        let packet_type = PacketType::Tc;
        let packet_creator = CcsdsPacketCreator::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            packet_type,
            &data,
            Some(ChecksumType::WithCrc16),
        )
        .unwrap();
        let sp_header = packet_creator.sp_header();
        generic_ccsds_reader_test(&data, &packet_creator.to_vec(), packet_type, *sp_header);
    }

    #[test]
    fn test_ccsds_reader_tc_owned_creator() {
        let data = [1, 2, 3, 4];
        let packet_type = PacketType::Tc;
        let packet_creator = CcsdsPacketCreatorOwned::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            packet_type,
            &data,
            Some(ChecksumType::WithCrc16),
        )
        .unwrap();
        let sp_header = packet_creator.sp_header();
        generic_ccsds_reader_test(&data, &packet_creator.to_vec(), packet_type, *sp_header);
    }

    #[test]
    fn test_ccsds_reader_tm() {
        let data = [1, 2, 3, 4];
        let packet_type = PacketType::Tm;
        let packet_creator = CcsdsPacketCreator::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            packet_type,
            &data,
            Some(ChecksumType::WithCrc16),
        )
        .unwrap();
        let sp_header = packet_creator.sp_header();
        generic_ccsds_reader_test(&data, &packet_creator.to_vec(), packet_type, *sp_header);
    }

    #[test]
    fn test_ccsds_reader_tm_owned_creator() {
        let data = [1, 2, 3, 4];
        let packet_type = PacketType::Tm;
        let packet_creator = CcsdsPacketCreatorOwned::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            packet_type,
            &data,
            Some(ChecksumType::WithCrc16),
        )
        .unwrap();
        let sp_header = packet_creator.sp_header();
        generic_ccsds_reader_test(&data, &packet_creator.to_vec(), packet_type, *sp_header);
    }

    fn generic_test_no_checksum(packet_raw: &[u8], packet_data: &[u8], sp_header: SpHeader) {
        let reader = CcsdsPacketReader::new(packet_raw, None).unwrap();
        assert_eq!(*reader.sp_header(), sp_header);
        assert_eq!(reader.packet_data(), packet_data);
        assert_eq!(reader.apid(), u11::new(0x1));
        assert_eq!(
            reader.packet_id(),
            PacketId::new(PacketType::Tc, false, u11::new(0x1))
        );
        assert_eq!(
            reader.psc(),
            PacketSequenceControl::new(SequenceFlags::Unsegmented, u14::new(0x0))
        );
        assert_eq!(reader.packet_len(), packet_raw.len());
        assert_eq!(reader.packet_type(), PacketType::Tc);
        assert_eq!(reader.data_len() as usize, packet_raw.len() - 7);
    }

    #[test]
    fn test_ccsds_reader_no_checksum() {
        let data = [1, 2, 3, 4];
        let packet_creator = CcsdsPacketCreator::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tc,
            &data,
            None,
        )
        .unwrap();
        let sp_header = packet_creator.sp_header();
        assert_eq!(
            packet_creator.ccsds_packet_id_and_psc(),
            CcsdsPacketIdAndPsc::from(*sp_header)
        );
        assert_eq!(
            packet_creator.ccsds_packet_id_and_psc(),
            CcsdsPacketIdAndPsc::from(sp_header)
        );
        let packet_raw = packet_creator.to_vec();
        generic_test_no_checksum(&packet_raw, &data, *sp_header);
    }

    #[test]
    fn test_ccsds_reader_no_checksum_owned() {
        let data = [1, 2, 3, 4];
        let packet_creator = CcsdsPacketCreatorOwned::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tc,
            &data,
            None,
        )
        .unwrap();
        let sp_header = packet_creator.sp_header();
        assert_eq!(
            packet_creator.ccsds_packet_id_and_psc(),
            CcsdsPacketIdAndPsc::from(*sp_header)
        );
        assert_eq!(
            packet_creator.ccsds_packet_id_and_psc(),
            CcsdsPacketIdAndPsc::from(sp_header)
        );
        let packet_raw = packet_creator.to_vec();
        generic_test_no_checksum(&packet_raw, &data, *sp_header);
    }

    #[test]
    fn test_ccsds_reader_buf_too_small() {
        let data = [1, 2, 3, 4];
        let packet_creator = CcsdsPacketCreator::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tc,
            &data,
            None,
        )
        .unwrap();
        let packet_raw = packet_creator.to_vec();
        let reader_error = CcsdsPacketReader::new(&packet_raw[0..8], None);
        assert!(reader_error.is_err());
        let error = reader_error.unwrap_err();
        matches!(
            error,
            CcsdsPacketReadError::ByteConversion(ByteConversionError::FromSliceTooSmall {
                found: 8,
                expected: 10
            })
        );
    }

    #[test]
    fn test_ccsds_reader_buf_too_small_owned() {
        let data = [1, 2, 3, 4];
        let packet_creator = CcsdsPacketCreatorOwned::new(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            PacketType::Tc,
            &data,
            None,
        )
        .unwrap();
        let packet_raw = packet_creator.to_vec();
        let reader_error = CcsdsPacketReader::new(&packet_raw[0..8], None);
        assert!(reader_error.is_err());
        let error = reader_error.unwrap_err();
        matches!(
            error,
            CcsdsPacketReadError::ByteConversion(ByteConversionError::FromSliceTooSmall {
                found: 8,
                expected: 10
            })
        );
    }

    #[test]
    fn test_ccsds_checksum_error() {
        let data = [1, 2, 3, 4];
        let packet_creator = CcsdsPacketCreator::new_tc_with_checksum(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            &data,
        )
        .unwrap();
        let mut packet_raw = packet_creator.to_vec();
        *packet_raw.last_mut().unwrap() = 0;
        let reader_error = CcsdsPacketReader::new_with_checksum(&packet_raw);
        assert!(reader_error.is_err());
        assert_eq!(reader_error.unwrap_err(), CcsdsPacketReadError::CrcError);
    }
    #[test]
    fn test_ccsds_checksum_ignored() {
        let data = [1, 2, 3, 4];
        let packet_creator = CcsdsPacketCreator::new_tc_with_checksum(
            SpacePacketHeader::new_from_apid(u11::new(0x1)),
            &data,
        )
        .unwrap();
        let mut packet_raw = packet_creator.to_vec();
        *packet_raw.last_mut().unwrap() = 0;
        let reader =
            CcsdsPacketReader::new(&packet_raw, Some(ChecksumType::WithCrc16ButIgnored)).unwrap();
        assert_eq!(reader.packet_data(), data);
    }

    #[test]
    fn sp_header_to_buf_too_small() {
        let sph = SpacePacketHeader::new_from_apid(u11::new(0x01));
        let mut buf: [u8; 5] = [0; 5];
        assert_eq!(
            sph.write_to_be_bytes(&mut buf).unwrap_err(),
            ByteConversionError::ToSliceTooSmall {
                found: 5,
                expected: 6
            }
        );
    }

    #[test]
    fn sp_header_from_buf_too_small() {
        let buf: [u8; 5] = [0; 5];
        let sph = SpacePacketHeader::from_be_bytes(&buf);
        assert_eq!(
            sph.unwrap_err(),
            ByteConversionError::FromSliceTooSmall {
                found: 5,
                expected: 6
            }
        );
    }

    #[test]
    fn sp_header_default() {
        let sph = SpacePacketHeader::default();
        assert_eq!(sph.packet_id(), PacketId::default());
        assert_eq!(sph.apid().value(), 0);
        assert_eq!(
            sph.psc(),
            PacketSequenceControl::new(SequenceFlags::Unsegmented, u14::new(0))
        );
        assert_eq!(sph.data_len(), 0);
    }

    #[test]
    fn ccsds_packet_id() {
        let packet_id = PacketId::new_for_tc(false, u11::new(0x5));
        let psc = PacketSequenceControl::new(SequenceFlags::Unsegmented, u14::new(0));
        let sph = SpacePacketHeader::new(packet_id, psc, 0);
        let id = CcsdsPacketIdAndPsc::new_from_ccsds_packet(&sph);

        assert_eq!(id.packet_id, packet_id);
        assert_eq!(id.psc, psc);
        assert_eq!(
            id.raw(),
            ((id.packet_id.raw() as u32) << 16) | id.psc.raw() as u32
        );
        let id_from = CcsdsPacketIdAndPsc::from(sph);
        assert_eq!(id_from, id);

        // ID is hashable.
        use std::collections::hash_map::DefaultHasher;
        let mut hasher = DefaultHasher::new();
        id.hash(&mut hasher);
    }
}