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
//! Generic CFDP type-length-value (TLV) abstraction as specified in CFDP 5.1.9.
use crate::cfdp::lv::{
    generic_len_check_data_serialization, generic_len_check_deserialization, Lv, MIN_LV_LEN,
};
use crate::cfdp::TlvLvError;
use crate::util::{UnsignedByteField, UnsignedByteFieldError, UnsignedEnum};
use crate::ByteConversionError;
#[cfg(feature = "alloc")]
use alloc::vec;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "alloc")]
pub use alloc_mod::*;
use num_enum::{IntoPrimitive, TryFromPrimitive};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use super::{InvalidTlvTypeFieldError, TlvLvDataTooLargeError};

pub mod msg_to_user;

/// Minimum length of a type-length-value structure, including type and length fields.
pub const MIN_TLV_LEN: usize = 2;

/// Trait for generic TLV structures.
pub trait GenericTlv {
    /// TLV type field.
    fn tlv_type_field(&self) -> TlvTypeField;

    /// Checks whether the type field contains one of the standard types specified in the CFDP
    /// standard and is part of the [TlvType] enum.
    #[inline]
    fn is_standard_tlv(&self) -> bool {
        if let TlvTypeField::Standard(_) = self.tlv_type_field() {
            return true;
        }
        false
    }

    /// Returns the standard TLV type if the TLV field is not a custom field
    #[inline]
    fn tlv_type(&self) -> Option<TlvType> {
        if let TlvTypeField::Standard(tlv_type) = self.tlv_type_field() {
            Some(tlv_type)
        } else {
            None
        }
    }
}

/// Readable TLV structure trait.
pub trait ReadableTlv {
    /// Value field of the TLV.
    fn value(&self) -> &[u8];

    /// Checks whether the value field is empty.
    #[inline]
    fn is_empty(&self) -> bool {
        self.value().is_empty()
    }

    /// Helper method to retrieve the length of the value. Simply calls the [slice::len] method of
    /// [Self::value]
    #[inline]
    fn len_value(&self) -> usize {
        self.value().len()
    }

    /// Returns the full raw length, including the length byte.
    #[inline]
    fn len_full(&self) -> usize {
        self.len_value() + 2
    }
}

/// Writable TLV structure trait.
pub trait WritableTlv {
    /// Write the TLV to bytes.
    fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;

    /// Length of the written TLV.
    fn len_written(&self) -> usize;

    /// Convenience method to write the TLV to an owned [alloc::vec::Vec].
    #[cfg(feature = "alloc")]
    fn to_vec(&self) -> Vec<u8> {
        let mut buf = vec![0; self.len_written()];
        self.write_to_bytes(&mut buf).unwrap();
        buf
    }
}

/// TLV type.
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum TlvType {
    /// Filestore request.
    FilestoreRequest = 0x00,
    /// Filestore response.
    FilestoreResponse = 0x01,
    /// Message to user.
    MsgToUser = 0x02,
    /// Fault handler.
    FaultHandler = 0x04,
    /// Flow label.
    FlowLabel = 0x05,
    /// Entity ID.
    EntityId = 0x06,
}

/// TLV type field variants.
///
/// This allows specifying custom variants as well.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum TlvTypeField {
    /// Standard TLV types.
    Standard(TlvType),
    /// Custom TLV type.
    Custom(u8),
}

/// Filestore action codes as specified in the standard.
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum FilestoreActionCode {
    /// Create file.
    CreateFile = 0b0000,
    /// Delete file.
    DeleteFile = 0b0001,
    /// Rename file.
    RenameFile = 0b0010,
    /// This operation appends one file to another. The first specified name will form the first
    /// part of the new file and the name of the new file. This function can be used to get
    /// similar functionality to the UNIX cat utility (albeit for only two files).
    AppendFile = 0b0011,
    /// This operation replaces the content of the first specified file with the content of
    /// the secondly specified file.
    ReplaceFile = 0b0100,
    /// Create directory.
    CreateDirectory = 0b0101,
    /// Remove directory.
    RemoveDirectory = 0b0110,
    /// Deny file.
    DenyFile = 0b0111,
    /// Deny directory.
    DenyDirectory = 0b1000,
}

impl From<u8> for TlvTypeField {
    fn from(value: u8) -> Self {
        match TlvType::try_from(value) {
            Ok(tlv_type) => TlvTypeField::Standard(tlv_type),
            Err(_) => TlvTypeField::Custom(value),
        }
    }
}

impl From<TlvTypeField> for u8 {
    fn from(value: TlvTypeField) -> Self {
        match value {
            TlvTypeField::Standard(std) => std as u8,
            TlvTypeField::Custom(custom) => custom,
        }
    }
}

/// Generic CFDP type-length-value (TLV) abstraction as specified in CFDP 5.1.9.
///
/// Please note that this class is zero-copy and does not generate a copy of the value data for
/// both the regular [Self::new] constructor and the [Self::from_bytes] constructor.
///
/// # Lifetimes
///  * `data`: If the TLV is generated from a raw bytestream, this will be the lifetime of
///    the raw bytestream. If the TLV is generated from a raw slice or a similar data reference,
///    this will be the lifetime of that data reference.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Tlv<'data> {
    tlv_type_field: TlvTypeField,
    #[cfg_attr(feature = "serde", serde(borrow))]
    lv: Lv<'data>,
}

impl<'data> Tlv<'data> {
    /// Minimum length of a TLV structure, including type and length fields.
    pub const MIN_LEN: usize = MIN_TLV_LEN;

    /// Generic constructor for a TLV structure.
    pub fn new(tlv_type: TlvType, data: &[u8]) -> Result<Tlv<'_>, TlvLvDataTooLargeError> {
        Ok(Tlv {
            tlv_type_field: TlvTypeField::Standard(tlv_type),
            lv: Lv::new(data)?,
        })
    }

    /// Constructor for a TLV with a custom type field.
    pub fn new_with_custom_type(
        tlv_type: u8,
        data: &[u8],
    ) -> Result<Tlv<'_>, TlvLvDataTooLargeError> {
        Ok(Tlv {
            tlv_type_field: TlvTypeField::Custom(tlv_type),
            lv: Lv::new(data)?,
        })
    }

    /// Creates a TLV with an empty value field.
    pub fn new_empty(tlv_type: TlvType) -> Tlv<'data> {
        Tlv {
            tlv_type_field: TlvTypeField::Standard(tlv_type),
            lv: Lv::new_empty(),
        }
    }

    /// Creates a TLV give a raw bytestream. Please note that is is not necessary to pass the
    /// bytestream with the exact size of the expected TLV. This function will take care
    /// of parsing the length byte, and the length of the parsed TLV can be retrieved using
    /// [Self::len_full].
    pub fn from_bytes(buf: &'data [u8]) -> Result<Tlv<'data>, ByteConversionError> {
        generic_len_check_deserialization(buf, MIN_TLV_LEN)?;
        let mut tlv = Self {
            tlv_type_field: TlvTypeField::from(buf[0]),
            lv: Lv::from_bytes(&buf[MIN_LV_LEN..])?,
        };
        // We re-use this field so we do not need an additional struct field to store the raw start
        // of the TLV.
        tlv.lv.raw_data = Some(buf);
        Ok(tlv)
    }

    /// If the TLV was generated from a raw bytestream using [Self::from_bytes], the raw start
    /// of the TLV can be retrieved with this method.
    #[inline]
    pub fn raw_data(&self) -> Option<&[u8]> {
        self.lv.raw_data()
    }

    /// Converts to an owned TLV variant, allocating memory for the value field.
    #[cfg(feature = "alloc")]
    pub fn to_owned(&self) -> TlvOwned {
        TlvOwned {
            tlv_type_field: self.tlv_type_field,
            data: self.value().to_vec(),
        }
    }
}

#[cfg(feature = "alloc")]
impl PartialEq<TlvOwned> for Tlv<'_> {
    fn eq(&self, other: &TlvOwned) -> bool {
        self.tlv_type_field == other.tlv_type_field && self.value() == other.value()
    }
}

impl ReadableTlv for Tlv<'_> {
    fn value(&self) -> &[u8] {
        self.lv.value()
    }
}

impl WritableTlv for Tlv<'_> {
    fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        generic_len_check_data_serialization(buf, self.value().len(), MIN_TLV_LEN)?;
        buf[0] = self.tlv_type_field.into();
        self.lv.write_to_be_bytes_no_len_check(&mut buf[1..]);
        Ok(self.len_full())
    }

    #[inline]
    fn len_written(&self) -> usize {
        self.len_full()
    }
}

impl GenericTlv for Tlv<'_> {
    #[inline]
    fn tlv_type_field(&self) -> TlvTypeField {
        self.tlv_type_field
    }
}

/// Component of the TLV module which require [alloc] support.
#[cfg(feature = "alloc")]
pub mod alloc_mod {
    use super::*;

    /// Owned variant of [Tlv] which is consequently [Clone]able and does not have a lifetime
    /// associated to a data slice.
    #[derive(Debug, Clone, PartialEq, Eq)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
    pub struct TlvOwned {
        pub(crate) tlv_type_field: TlvTypeField,
        pub(crate) data: Vec<u8>,
    }

    impl TlvOwned {
        /// Generic constructor.
        pub fn new(tlv_type: TlvType, data: &[u8]) -> Self {
            Self {
                tlv_type_field: TlvTypeField::Standard(tlv_type),
                data: data.to_vec(),
            }
        }

        /// Generic constructor with a custom TLV type.
        pub fn new_with_custom_type(tlv_type: u8, data: &[u8]) -> Self {
            Self {
                tlv_type_field: TlvTypeField::Custom(tlv_type),
                data: data.to_vec(),
            }
        }

        /// Creates a TLV with an empty value field.
        pub fn new_empty(tlv_type: TlvType) -> Self {
            Self {
                tlv_type_field: TlvTypeField::Standard(tlv_type),
                data: Vec::new(),
            }
        }

        /// Write to a byte slice.
        pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
            generic_len_check_data_serialization(buf, self.data.len(), MIN_TLV_LEN)?;
            buf[0] = self.tlv_type_field.into();
            buf[1] = self.data.len() as u8;
            buf[2..2 + self.data.len()].copy_from_slice(&self.data);
            Ok(self.len_written())
        }

        #[inline]
        fn len_written(&self) -> usize {
            self.data.len() + 2
        }

        /// Convert to [Tlv]
        pub fn as_tlv(&self) -> Tlv<'_> {
            Tlv {
                tlv_type_field: self.tlv_type_field,
                // The API should ensure that the data length is never to large, so the unwrap for the
                // LV creation should never be an issue.
                lv: Lv::new(&self.data).expect("lv creation failed unexpectedly"),
            }
        }
    }

    impl ReadableTlv for TlvOwned {
        #[inline]
        fn value(&self) -> &[u8] {
            &self.data
        }
    }

    impl WritableTlv for TlvOwned {
        fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
            self.write_to_bytes(buf)
        }

        #[inline]
        fn len_written(&self) -> usize {
            self.len_written()
        }
    }

    impl GenericTlv for TlvOwned {
        #[inline]
        fn tlv_type_field(&self) -> TlvTypeField {
            self.tlv_type_field
        }
    }

    impl From<Tlv<'_>> for TlvOwned {
        fn from(value: Tlv<'_>) -> Self {
            value.to_owned()
        }
    }

    impl PartialEq<Tlv<'_>> for TlvOwned {
        fn eq(&self, other: &Tlv) -> bool {
            self.tlv_type_field == other.tlv_type_field && self.data == other.value()
        }
    }
}

/// Entity ID TLV.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct EntityIdTlv {
    entity_id: UnsignedByteField,
}

impl EntityIdTlv {
    /// Constructor.
    #[inline]
    pub fn new(entity_id: UnsignedByteField) -> Self {
        Self { entity_id }
    }

    fn len_check(buf: &[u8]) -> Result<(), ByteConversionError> {
        if buf.len() < 2 {
            return Err(ByteConversionError::ToSliceTooSmall {
                found: buf.len(),
                expected: 2,
            });
        }
        Ok(())
    }

    /// Entity ID.
    #[inline]
    pub fn entity_id(&self) -> &UnsignedByteField {
        &self.entity_id
    }

    /// Length of the value field.
    #[inline]
    pub fn len_value(&self) -> usize {
        self.entity_id.size()
    }

    /// Full length of the TLV, including type and length fields.
    #[inline]
    pub fn len_full(&self) -> usize {
        2 + self.entity_id.size()
    }

    /// Create from a raw bytestream.
    pub fn from_bytes(buf: &[u8]) -> Result<Self, TlvLvError> {
        Self::len_check(buf)?;
        verify_tlv_type(buf[0], TlvType::EntityId)?;
        let len = buf[1];
        if len != 1 && len != 2 && len != 4 && len != 8 {
            return Err(TlvLvError::InvalidValueLength(len as usize));
        }
        // Okay to unwrap here. The checks before make sure that the deserialization never fails
        let entity_id = UnsignedByteField::new_from_be_bytes(len as usize, &buf[2..]).unwrap();
        Ok(Self { entity_id })
    }

    /// Convert to a generic [Tlv], which also erases the programmatic type information.
    pub fn to_tlv(self, buf: &mut [u8]) -> Result<Tlv<'_>, ByteConversionError> {
        Self::len_check(buf)?;
        self.entity_id
            .write_to_be_bytes(&mut buf[2..2 + self.entity_id.size()])?;
        // Can't fail.
        Ok(Tlv::new(TlvType::EntityId, &buf[2..2 + self.entity_id.size()]).unwrap())
    }

    fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        Self::len_check(buf)?;
        buf[0] = TlvType::EntityId as u8;
        buf[1] = self.entity_id.size() as u8;
        Ok(2 + self.entity_id.write_to_be_bytes(&mut buf[2..])?)
    }

    #[inline]
    fn len_written(&self) -> usize {
        self.len_full()
    }
}

impl WritableTlv for EntityIdTlv {
    fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        self.write_to_bytes(buf)
    }

    #[inline]
    fn len_written(&self) -> usize {
        self.len_written()
    }
}

impl GenericTlv for EntityIdTlv {
    #[inline]
    fn tlv_type_field(&self) -> TlvTypeField {
        TlvTypeField::Standard(TlvType::EntityId)
    }
}

impl TryFrom<Tlv<'_>> for EntityIdTlv {
    type Error = TlvLvError;

    fn try_from(value: Tlv) -> Result<Self, TlvLvError> {
        match value.tlv_type_field {
            TlvTypeField::Standard(tlv_type) => {
                if tlv_type != TlvType::EntityId {
                    return Err(InvalidTlvTypeFieldError {
                        found: tlv_type as u8,
                        expected: Some(TlvType::EntityId as u8),
                    }
                    .into());
                }
            }
            TlvTypeField::Custom(val) => {
                return Err(InvalidTlvTypeFieldError {
                    found: val,
                    expected: Some(TlvType::EntityId as u8),
                }
                .into());
            }
        }
        let len_value = value.value().len();
        if len_value != 1 && len_value != 2 && len_value != 4 && len_value != 8 {
            return Err(TlvLvError::InvalidValueLength(len_value));
        }
        Ok(Self::new(
            UnsignedByteField::new_from_be_bytes(len_value, value.value()).map_err(
                |e| match e {
                    UnsignedByteFieldError::ByteConversionError(e) => e,
                    // This can not happen, we checked for the length validity, and the data is always smaller than
                    // 255 bytes.
                    _ => panic!("unexpected error"),
                },
            )?,
        ))
    }
}

/// Does the [FilestoreActionCode] have a second filename?
#[inline]
pub fn fs_request_has_second_filename(action_code: FilestoreActionCode) -> bool {
    if action_code == FilestoreActionCode::RenameFile
        || action_code == FilestoreActionCode::AppendFile
        || action_code == FilestoreActionCode::ReplaceFile
    {
        return true;
    }
    false
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
struct FilestoreTlvBase<'first_name, 'second_name> {
    pub action_code: FilestoreActionCode,
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub first_name: Lv<'first_name>,
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub second_name: Option<Lv<'second_name>>,
}

impl FilestoreTlvBase<'_, '_> {
    #[inline]
    fn base_len_value(&self) -> usize {
        let mut len = 1 + self.first_name.len_full();
        if let Some(second_name) = self.second_name {
            len += second_name.len_full();
        }
        len
    }
}

/// Filestore request TLV.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FilestoreRequestTlv<'first_name, 'second_name> {
    #[cfg_attr(feature = "serde", serde(borrow))]
    base: FilestoreTlvBase<'first_name, 'second_name>,
}

impl<'first_name, 'second_name> FilestoreRequestTlv<'first_name, 'second_name> {
    /// Constructor for file creation.
    pub fn new_create_file(file_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
        Self::new(FilestoreActionCode::CreateFile, file_name, None)
    }

    /// Constructor for file deletion.
    pub fn new_delete_file(file_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
        Self::new(FilestoreActionCode::DeleteFile, file_name, None)
    }

    /// Constructor for file renaming.
    pub fn new_rename_file(
        source_name: Lv<'first_name>,
        target_name: Lv<'second_name>,
    ) -> Result<Self, TlvLvError> {
        Self::new(
            FilestoreActionCode::RenameFile,
            source_name,
            Some(target_name),
        )
    }

    /// This operation appends one file to another. The first specified name will form the first
    /// part of the new file and the name of the new file. This function can be used to get
    /// similar functionality to the UNIX cat utility (albeit for only two files).
    pub fn new_append_file(
        first_file: Lv<'first_name>,
        second_file: Lv<'second_name>,
    ) -> Result<Self, TlvLvError> {
        Self::new(
            FilestoreActionCode::AppendFile,
            first_file,
            Some(second_file),
        )
    }

    /// This operation replaces the content of the first specified file with the content of
    /// the secondly specified file. This function can be used to get similar functionality to
    /// the UNIX copy (cp) utility if the target file already exists.
    pub fn new_replace_file(
        replaced_file: Lv<'first_name>,
        new_file: Lv<'second_name>,
    ) -> Result<Self, TlvLvError> {
        Self::new(
            FilestoreActionCode::ReplaceFile,
            replaced_file,
            Some(new_file),
        )
    }

    /// Constructor for directory creation.
    pub fn new_create_directory(dir_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
        Self::new(FilestoreActionCode::CreateDirectory, dir_name, None)
    }

    /// Constructor for directory removal.
    pub fn new_remove_directory(dir_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
        Self::new(FilestoreActionCode::RemoveDirectory, dir_name, None)
    }

    /// Constructor for file denial.
    pub fn new_deny_file(file_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
        Self::new(FilestoreActionCode::DenyFile, file_name, None)
    }

    /// Constructor for directory denial.
    pub fn new_deny_directory(dir_name: Lv<'first_name>) -> Result<Self, TlvLvError> {
        Self::new(FilestoreActionCode::DenyDirectory, dir_name, None)
    }

    /// This function will return [None] if the respective action code requires two names but
    /// only one is passed. It will also returns [None] if the cumulative length of the first
    /// name and the second name exceeds 255 bytes.
    ///
    /// Two file paths are required for the rename, append and replace filestore request.
    pub fn new(
        action_code: FilestoreActionCode,
        first_name: Lv<'first_name>,
        second_name: Option<Lv<'second_name>>,
    ) -> Result<Self, TlvLvError> {
        let mut base_value_len = first_name.len_full();
        if fs_request_has_second_filename(action_code) {
            if second_name.is_none() {
                return Err(TlvLvError::SecondNameMissing);
            }
            base_value_len += second_name.as_ref().unwrap().len_full();
        }
        if base_value_len > u8::MAX as usize {
            return Err(TlvLvError::InvalidValueLength(base_value_len));
        }
        Ok(Self {
            base: FilestoreTlvBase {
                action_code,
                first_name,
                second_name,
            },
        })
    }

    /// Action code.
    #[inline]
    pub fn action_code(&self) -> FilestoreActionCode {
        self.base.action_code
    }

    /// First name as [Lv].
    #[inline]
    pub fn first_name(&self) -> Lv<'first_name> {
        self.base.first_name
    }

    /// First name as optional [Lv].
    #[inline]
    pub fn second_name(&self) -> Option<Lv<'second_name>> {
        self.base.second_name
    }

    /// Length of the value field.
    #[inline]
    pub fn len_value(&self) -> usize {
        self.base.base_len_value()
    }

    /// Full TLV length.
    #[inline]
    pub fn len_full(&self) -> usize {
        2 + self.len_value()
    }

    /// Construct from a raw bytestream.
    pub fn from_bytes<'longest: 'first_name + 'second_name>(
        buf: &'longest [u8],
    ) -> Result<Self, TlvLvError> {
        if buf.len() < 2 {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: buf.len(),
                expected: 2,
            }
            .into());
        }
        verify_tlv_type(buf[0], TlvType::FilestoreRequest)?;
        let len = buf[1] as usize;
        let mut current_idx = 2;
        let action_code = FilestoreActionCode::try_from((buf[2] >> 4) & 0b1111)
            .map_err(|_| TlvLvError::InvalidFilestoreActionCode((buf[2] >> 4) & 0b1111))?;
        current_idx += 1;
        let first_name = Lv::from_bytes(&buf[current_idx..])?;
        let mut second_name = None;

        current_idx += first_name.len_full();
        if fs_request_has_second_filename(action_code) {
            if current_idx >= 2 + len {
                return Err(TlvLvError::SecondNameMissing);
            }
            second_name = Some(Lv::from_bytes(&buf[current_idx..])?);
        }
        Ok(Self {
            base: FilestoreTlvBase {
                action_code,
                first_name,
                second_name,
            },
        })
    }

    fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        if buf.len() < self.len_full() {
            return Err(ByteConversionError::ToSliceTooSmall {
                found: buf.len(),
                expected: self.len_full(),
            });
        }
        buf[0] = TlvType::FilestoreRequest as u8;
        buf[1] = self.len_value() as u8;
        buf[2] = (self.base.action_code as u8) << 4;
        let mut current_idx = 3;
        // Length checks were already performed.
        self.base.first_name.write_to_be_bytes_no_len_check(
            &mut buf[current_idx..current_idx + self.base.first_name.len_full()],
        );
        current_idx += self.base.first_name.len_full();
        if let Some(second_name) = self.base.second_name {
            second_name.write_to_be_bytes_no_len_check(
                &mut buf[current_idx..current_idx + second_name.len_full()],
            );
            current_idx += second_name.len_full();
        }
        Ok(current_idx)
    }

    #[inline]
    fn len_written(&self) -> usize {
        self.len_full()
    }
}

impl WritableTlv for FilestoreRequestTlv<'_, '_> {
    fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        self.write_to_bytes(buf)
    }

    #[inline]
    fn len_written(&self) -> usize {
        self.len_written()
    }
}

impl GenericTlv for FilestoreRequestTlv<'_, '_> {
    #[inline]
    fn tlv_type_field(&self) -> TlvTypeField {
        TlvTypeField::Standard(TlvType::FilestoreRequest)
    }
}

/// Filestore response TLV.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct FilestoreResponseTlv<'first_name, 'second_name, 'fs_msg> {
    #[cfg_attr(feature = "serde", serde(borrow))]
    base: FilestoreTlvBase<'first_name, 'second_name>,
    status_code: u8,
    #[cfg_attr(feature = "serde", serde(borrow))]
    filestore_message: Lv<'fs_msg>,
}

impl<'first_name, 'second_name, 'fs_msg> FilestoreResponseTlv<'first_name, 'second_name, 'fs_msg> {
    /// This function will return [None] if the respective action code requires two names but
    /// only one is passed. It will also returns [None] if the cumulative length of the first
    /// name and the second name exceeds 255 bytes.
    ///
    /// Two file paths are required for the rename, append and replace filestore request.
    pub fn new_no_filestore_message(
        action_code: FilestoreActionCode,
        status_code: u8,
        first_name: Lv<'first_name>,
        second_name: Option<Lv<'second_name>>,
    ) -> Result<Self, TlvLvError> {
        Self::new(
            action_code,
            status_code,
            first_name,
            second_name,
            Lv::new_empty(),
        )
    }

    /// Generic constructor.
    pub fn new(
        action_code: FilestoreActionCode,
        status_code: u8,
        first_name: Lv<'first_name>,
        second_name: Option<Lv<'second_name>>,
        filestore_message: Lv<'fs_msg>,
    ) -> Result<Self, TlvLvError> {
        let mut base_value_len = first_name.len_full();
        if Self::has_second_filename(action_code) {
            if second_name.is_none() {
                return Err(TlvLvError::SecondNameMissing);
            }
            base_value_len += second_name.as_ref().unwrap().len_full();
        }
        if base_value_len > u8::MAX as usize {
            return Err(TlvLvError::InvalidValueLength(base_value_len));
        }
        Ok(Self {
            base: FilestoreTlvBase {
                action_code,
                first_name,
                second_name,
            },
            status_code,
            filestore_message,
        })
    }

    /// Check whether this response has a second filename.
    pub fn has_second_filename(action_code: FilestoreActionCode) -> bool {
        if action_code == FilestoreActionCode::RenameFile
            || action_code == FilestoreActionCode::AppendFile
            || action_code == FilestoreActionCode::ReplaceFile
        {
            return true;
        }
        false
    }

    /// Action code.
    #[inline]
    pub fn action_code(&self) -> FilestoreActionCode {
        self.base.action_code
    }

    /// Status code.
    #[inline]
    pub fn status_code(&self) -> u8 {
        self.status_code
    }

    /// First name as [Lv].
    #[inline]
    pub fn first_name(&self) -> Lv<'first_name> {
        self.base.first_name
    }

    /// Optional second name as [Lv].
    #[inline]
    pub fn second_name(&self) -> Option<Lv<'second_name>> {
        self.base.second_name
    }

    /// Length of the value field.
    #[inline]
    pub fn len_value(&self) -> usize {
        self.base.base_len_value() + self.filestore_message.len_full()
    }

    /// Full length of the TLV.
    #[inline]
    pub fn len_full(&self) -> usize {
        2 + self.len_value()
    }

    /// Construct from a raw bytestream.
    pub fn from_bytes<'buf: 'first_name + 'second_name + 'fs_msg>(
        buf: &'buf [u8],
    ) -> Result<Self, TlvLvError> {
        if buf.len() < 2 {
            return Err(ByteConversionError::FromSliceTooSmall {
                found: buf.len(),
                expected: 2,
            }
            .into());
        }
        verify_tlv_type(buf[0], TlvType::FilestoreResponse)?;
        let len = buf[1] as usize;
        let mut current_idx = 2;
        let len_check = |current_idx: &mut usize, add_len: usize| -> Result<(), TlvLvError> {
            if *current_idx + add_len > buf.len() {
                return Err(ByteConversionError::FromSliceTooSmall {
                    found: buf.len(),
                    expected: *current_idx,
                }
                .into());
            }
            Ok(())
        };
        len_check(&mut current_idx, len)?;
        let action_code = FilestoreActionCode::try_from((buf[2] >> 4) & 0b1111)
            .map_err(|_| TlvLvError::InvalidFilestoreActionCode((buf[2] >> 4) & 0b1111))?;
        let status_code = buf[2] & 0b1111;
        current_idx += 1;
        let first_name = Lv::from_bytes(&buf[current_idx..])?;
        len_check(&mut current_idx, first_name.len_full())?;
        current_idx += first_name.len_full();

        let mut second_name = None;
        if Self::has_second_filename(action_code) {
            if current_idx >= 2 + len {
                return Err(TlvLvError::SecondNameMissing);
            }
            let second_name_lv = Lv::from_bytes(&buf[current_idx..])?;
            current_idx += second_name_lv.len_full();
            second_name = Some(second_name_lv);
        }
        let filestore_message = Lv::from_bytes(&buf[current_idx..])?;
        len_check(&mut current_idx, filestore_message.len_full())?;
        Ok(Self {
            base: FilestoreTlvBase {
                action_code,
                first_name,
                second_name,
            },
            status_code,
            filestore_message,
        })
    }

    fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        if buf.len() < self.len_full() {
            return Err(ByteConversionError::ToSliceTooSmall {
                found: buf.len(),
                expected: self.len_full(),
            });
        }
        buf[0] = TlvType::FilestoreResponse as u8;
        buf[1] = self.len_value() as u8;
        buf[2] = ((self.base.action_code as u8) << 4) | (self.status_code & 0b1111);
        let mut current_idx = 3;
        // Length checks were already performed.
        self.base.first_name.write_to_be_bytes_no_len_check(
            &mut buf[current_idx..current_idx + self.base.first_name.len_full()],
        );
        current_idx += self.base.first_name.len_full();
        if let Some(second_name) = self.base.second_name {
            current_idx += second_name.write_to_be_bytes_no_len_check(
                &mut buf[current_idx..current_idx + second_name.len_full()],
            );
        }
        current_idx += self.filestore_message.write_to_be_bytes_no_len_check(
            &mut buf[current_idx..current_idx + self.filestore_message.len_full()],
        );
        Ok(current_idx)
    }

    fn len_written(&self) -> usize {
        self.len_full()
    }
}

impl WritableTlv for FilestoreResponseTlv<'_, '_, '_> {
    fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
        self.write_to_bytes(buf)
    }

    #[inline]
    fn len_written(&self) -> usize {
        self.len_written()
    }
}

impl GenericTlv for FilestoreResponseTlv<'_, '_, '_> {
    #[inline]
    fn tlv_type_field(&self) -> TlvTypeField {
        TlvTypeField::Standard(TlvType::FilestoreResponse)
    }
}

pub(crate) fn verify_tlv_type(
    raw_type: u8,
    expected_tlv_type: TlvType,
) -> Result<(), InvalidTlvTypeFieldError> {
    let tlv_type = TlvType::try_from(raw_type).map_err(|_| InvalidTlvTypeFieldError {
        found: raw_type,
        expected: Some(expected_tlv_type.into()),
    })?;
    if tlv_type != expected_tlv_type {
        return Err(InvalidTlvTypeFieldError {
            found: tlv_type as u8,
            expected: Some(expected_tlv_type as u8),
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cfdp::lv::Lv;
    use crate::cfdp::tlv::{FilestoreActionCode, FilestoreRequestTlv, Tlv, TlvType, TlvTypeField};
    use crate::cfdp::TlvLvError;
    use crate::util::{UbfU16, UbfU8, UnsignedEnum};
    use alloc::string::ToString;

    const TLV_TEST_STR_0: &str = "hello.txt";
    const TLV_TEST_STR_1: &str = "hello2.txt";

    #[test]
    fn test_basic() {
        let entity_id = UbfU8::new(5);
        let mut buf: [u8; 4] = [0; 4];
        assert!(entity_id.write_to_be_bytes(&mut buf).is_ok());
        let tlv_res = Tlv::new(TlvType::EntityId, &buf[0..1]);
        assert!(tlv_res.is_ok());
        let tlv_res = tlv_res.unwrap();
        assert_eq!(
            tlv_res.tlv_type_field(),
            TlvTypeField::Standard(TlvType::EntityId)
        );
        assert_eq!(tlv_res.len_full(), 3);
        assert_eq!(tlv_res.value().len(), 1);
        assert_eq!(tlv_res.len_value(), 1);
        assert!(!tlv_res.is_empty());
        assert_eq!(tlv_res.value()[0], 5);
    }

    #[test]
    fn test_serialization() {
        let entity_id = UbfU8::new(5);
        let mut buf: [u8; 4] = [0; 4];
        assert!(entity_id.write_to_be_bytes(&mut buf).is_ok());
        let tlv_res = Tlv::new(TlvType::EntityId, &buf[0..1]);
        assert!(tlv_res.is_ok());
        let tlv_res = tlv_res.unwrap();
        let mut ser_buf: [u8; 4] = [0; 4];
        assert!(tlv_res.write_to_bytes(&mut ser_buf).is_ok());
        assert_eq!(ser_buf[0], TlvType::EntityId as u8);
        assert_eq!(ser_buf[1], 1);
        assert_eq!(ser_buf[2], 5);
    }

    #[test]
    fn test_deserialization() {
        let entity_id = UbfU8::new(5);
        let mut buf: [u8; 4] = [0; 4];
        assert!(entity_id.write_to_be_bytes(&mut buf[2..]).is_ok());
        buf[0] = TlvType::EntityId as u8;
        buf[1] = 1;
        let tlv_from_raw = Tlv::from_bytes(&buf);
        assert!(tlv_from_raw.is_ok());
        let tlv_from_raw = tlv_from_raw.unwrap();
        assert!(tlv_from_raw.raw_data().is_some());
        assert_eq!(tlv_from_raw.raw_data().unwrap(), buf);
        assert_eq!(
            tlv_from_raw.tlv_type_field(),
            TlvTypeField::Standard(TlvType::EntityId)
        );
        assert_eq!(tlv_from_raw.value().len(), 1);
        assert_eq!(tlv_from_raw.len_full(), 3);
        assert_eq!(tlv_from_raw.value()[0], 5);
    }

    #[test]
    fn test_entity_id_tlv() {
        let entity_id = UbfU16::new(0x0102);
        let entity_id_tlv = EntityIdTlv::new(entity_id.into());
        let mut buf: [u8; 16] = [0; 16];
        let written_len = entity_id_tlv.write_to_bytes(&mut buf).unwrap();
        assert_eq!(written_len, entity_id_tlv.len_full());
        assert_eq!(entity_id_tlv.len_value(), 2);
        assert!(entity_id_tlv.is_standard_tlv());
        assert_eq!(entity_id_tlv.tlv_type().unwrap(), TlvType::EntityId);
        assert_eq!(buf[0], TlvType::EntityId as u8);
        assert_eq!(buf[1], 2);
        assert_eq!(u16::from_be_bytes(buf[2..4].try_into().unwrap()), 0x0102);
        let entity_id_as_vec = entity_id_tlv.to_vec();
        assert_eq!(entity_id_as_vec, buf[0..written_len].to_vec());
    }

    #[test]
    fn test_entity_id_from_generic_tlv() {
        let entity_id = UbfU16::new(0x0102);
        let entity_id_tlv = EntityIdTlv::new(entity_id.into());
        let mut buf: [u8; 16] = [0; 16];
        let entity_id_as_tlv: Tlv = entity_id_tlv.to_tlv(&mut buf).unwrap();
        let entity_id_converted_back: EntityIdTlv = entity_id_as_tlv.try_into().unwrap();
        assert_eq!(entity_id_converted_back, entity_id_tlv);
    }

    #[test]
    fn test_entity_id_from_raw() {
        let entity_id = UbfU16::new(0x0102);
        let entity_id_tlv = EntityIdTlv::new(entity_id.into());
        let mut buf: [u8; 16] = [0; 16];
        let _ = entity_id_tlv.write_to_bytes(&mut buf).unwrap();
        let entity_tlv_from_raw =
            EntityIdTlv::from_bytes(&buf).expect("creating entity ID TLV failed");
        assert_eq!(entity_tlv_from_raw, entity_id_tlv);
        assert_eq!(entity_tlv_from_raw.entity_id(), &entity_id.into());
    }

    #[test]
    fn test_empty() {
        let tlv_empty = Tlv::new_empty(TlvType::MsgToUser);
        assert_eq!(tlv_empty.value().len(), 0);
        assert!(tlv_empty.is_empty());
        assert_eq!(tlv_empty.len_full(), 2);
        assert!(tlv_empty.value().is_empty());
        assert_eq!(
            tlv_empty.tlv_type_field(),
            TlvTypeField::Standard(TlvType::MsgToUser)
        );
    }

    #[test]
    fn test_empty_serialization() {
        let tlv_empty = Tlv::new_empty(TlvType::MsgToUser);
        let mut buf: [u8; 4] = [0; 4];
        assert!(tlv_empty.write_to_bytes(&mut buf).is_ok());
        assert_eq!(buf[0], TlvType::MsgToUser as u8);
        assert_eq!(buf[1], 0);
    }

    #[test]
    fn test_empty_deserialization() {
        let mut buf: [u8; 4] = [0; 4];
        buf[0] = TlvType::MsgToUser as u8;
        buf[1] = 0;
        let tlv_empty = Tlv::from_bytes(&buf);
        assert!(tlv_empty.is_ok());
        let tlv_empty = tlv_empty.unwrap();
        assert!(tlv_empty.is_empty());
        assert_eq!(tlv_empty.value().len(), 0);
        assert_eq!(
            tlv_empty.tlv_type_field(),
            TlvTypeField::Standard(TlvType::MsgToUser)
        );
        assert_eq!(tlv_empty.len_full(), 2);
        assert!(tlv_empty.value().is_empty());
    }

    #[test]
    fn test_write_buf_too_small() {
        let mut buf: [u8; 2] = [0; 2];
        let fs_request =
            FilestoreRequestTlv::new_create_file(Lv::new_from_str(TLV_TEST_STR_0).unwrap())
                .unwrap();
        let error = fs_request.write_to_bytes(&mut buf);
        assert!(error.is_err());
        let error = error.unwrap_err();
        if let ByteConversionError::ToSliceTooSmall { found, expected } = error {
            assert_eq!(found, 2);
            assert_eq!(expected, 13);
        } else {
            panic!("unexpected error {:?}", error);
        }
    }

    #[test]
    fn test_read_from_buf_too_small() {
        let buf: [u8; 1] = [0; 1];
        let error = FilestoreRequestTlv::from_bytes(&buf);
        assert!(error.is_err());
        let error = error.unwrap_err();
        if let TlvLvError::ByteConversion(ByteConversionError::FromSliceTooSmall {
            found,
            expected,
        }) = error
        {
            assert_eq!(found, 1);
            assert_eq!(expected, 2);
        } else {
            panic!("unexpected error {:?}", error);
        }
    }

    #[test]
    fn test_buf_too_large() {
        let buf_too_large: [u8; u8::MAX as usize + 1] = [0; u8::MAX as usize + 1];
        let tlv_res = Tlv::new(TlvType::MsgToUser, &buf_too_large);
        assert!(tlv_res.is_err());
        let error = tlv_res.unwrap_err();
        match error {
            TlvLvDataTooLargeError(size) => {
                assert_eq!(size, u8::MAX as usize + 1);
                assert_eq!(
                    error.to_string(),
                    "data with size 256 larger than allowed 255 bytes"
                );
            }
        }
    }

    #[test]
    fn test_deserialization_custom_tlv_type() {
        let mut buf: [u8; 4] = [0; 4];
        buf[0] = 3;
        buf[1] = 1;
        buf[2] = 5;
        let tlv = Tlv::from_bytes(&buf);
        assert!(tlv.is_ok());
        let tlv = tlv.unwrap();
        assert_eq!(tlv.tlv_type_field(), TlvTypeField::Custom(3));
        assert!(!tlv.is_standard_tlv());
        assert_eq!(tlv.value().len(), 1);
        assert_eq!(tlv.len_full(), 3);
    }

    fn generic_fs_request_test_one_file(
        action_code: FilestoreActionCode,
    ) -> FilestoreRequestTlv<'static, 'static> {
        assert!(!fs_request_has_second_filename(action_code));
        let first_name = Lv::new_from_str(TLV_TEST_STR_0).unwrap();
        let fs_request = match action_code {
            FilestoreActionCode::CreateFile => FilestoreRequestTlv::new_create_file(first_name),
            FilestoreActionCode::DeleteFile => FilestoreRequestTlv::new_delete_file(first_name),
            FilestoreActionCode::CreateDirectory => {
                FilestoreRequestTlv::new_create_directory(first_name)
            }
            FilestoreActionCode::RemoveDirectory => {
                FilestoreRequestTlv::new_remove_directory(first_name)
            }
            FilestoreActionCode::DenyFile => FilestoreRequestTlv::new_deny_file(first_name),
            FilestoreActionCode::DenyDirectory => {
                FilestoreRequestTlv::new_deny_directory(first_name)
            }
            _ => panic!("invalid action code"),
        };
        assert!(fs_request.is_ok());
        let fs_request = fs_request.unwrap();
        assert_eq!(fs_request.len_value(), 1 + first_name.len_full());
        assert_eq!(fs_request.len_full(), fs_request.len_value() + 2);
        assert_eq!(fs_request.action_code(), action_code);
        assert_eq!(fs_request.first_name(), first_name);
        assert_eq!(fs_request.second_name(), None);
        fs_request
    }

    fn generic_fs_request_test_two_files(
        action_code: FilestoreActionCode,
    ) -> FilestoreRequestTlv<'static, 'static> {
        assert!(fs_request_has_second_filename(action_code));
        let first_name = Lv::new_from_str(TLV_TEST_STR_0).unwrap();
        let second_name = Lv::new_from_str(TLV_TEST_STR_1).unwrap();
        let fs_request = match action_code {
            FilestoreActionCode::ReplaceFile => {
                FilestoreRequestTlv::new_replace_file(first_name, second_name)
            }
            FilestoreActionCode::AppendFile => {
                FilestoreRequestTlv::new_append_file(first_name, second_name)
            }
            FilestoreActionCode::RenameFile => {
                FilestoreRequestTlv::new_rename_file(first_name, second_name)
            }
            _ => panic!("invalid action code"),
        };
        assert!(fs_request.is_ok());
        let fs_request = fs_request.unwrap();
        assert_eq!(
            fs_request.len_value(),
            1 + first_name.len_full() + second_name.len_full()
        );
        assert_eq!(
            fs_request.tlv_type_field(),
            TlvTypeField::Standard(TlvType::FilestoreRequest)
        );
        assert_eq!(fs_request.len_full(), fs_request.len_value() + 2);
        assert_eq!(fs_request.len_written(), fs_request.len_full());
        assert_eq!(fs_request.action_code(), action_code);
        assert_eq!(fs_request.first_name(), first_name);
        assert!(fs_request.second_name().is_some());
        assert_eq!(fs_request.second_name().unwrap(), second_name);
        fs_request
    }

    #[test]
    fn test_fs_request_basic_create_file() {
        generic_fs_request_test_one_file(FilestoreActionCode::CreateFile);
    }

    #[test]
    fn test_fs_request_basic_delete() {
        generic_fs_request_test_one_file(FilestoreActionCode::DeleteFile);
    }

    #[test]
    fn test_fs_request_basic_create_dir() {
        generic_fs_request_test_one_file(FilestoreActionCode::CreateDirectory);
    }

    #[test]
    fn test_fs_request_basic_remove_dir() {
        generic_fs_request_test_one_file(FilestoreActionCode::RemoveDirectory);
    }

    #[test]
    fn test_fs_request_basic_deny_file() {
        generic_fs_request_test_one_file(FilestoreActionCode::DenyFile);
    }

    #[test]
    fn test_fs_request_basic_deny_dir() {
        generic_fs_request_test_one_file(FilestoreActionCode::DenyDirectory);
    }

    #[test]
    fn test_fs_request_basic_append_file() {
        generic_fs_request_test_two_files(FilestoreActionCode::AppendFile);
    }

    #[test]
    fn test_fs_request_basic_rename_file() {
        generic_fs_request_test_two_files(FilestoreActionCode::RenameFile);
    }

    #[test]
    fn test_fs_request_basic_replace_file() {
        generic_fs_request_test_two_files(FilestoreActionCode::ReplaceFile);
    }

    fn check_fs_request_first_part(
        buf: &[u8],
        action_code: FilestoreActionCode,
        expected_val_len: u8,
    ) -> usize {
        assert_eq!(buf[0], TlvType::FilestoreRequest as u8);
        assert_eq!(buf[1], expected_val_len);
        assert_eq!((buf[2] >> 4) & 0b1111, action_code as u8);
        let lv = Lv::from_bytes(&buf[3..]);
        assert!(lv.is_ok());
        let lv = lv.unwrap();
        assert_eq!(lv.value_as_str().unwrap().unwrap(), TLV_TEST_STR_0);
        3 + lv.len_full()
    }

    #[test]
    fn test_fs_request_serialization_one_file() {
        let req = generic_fs_request_test_one_file(FilestoreActionCode::CreateFile);
        let mut buf: [u8; 64] = [0; 64];
        let res = req.write_to_bytes(&mut buf);
        assert!(res.is_ok());
        let written = res.unwrap();
        assert_eq!(written, 3 + 1 + TLV_TEST_STR_0.len());
        assert_eq!(written, req.len_full());
        check_fs_request_first_part(
            &buf,
            FilestoreActionCode::CreateFile,
            1 + 1 + TLV_TEST_STR_0.len() as u8,
        );
    }

    #[test]
    fn test_fs_request_deserialization_one_file() {
        let req = generic_fs_request_test_one_file(FilestoreActionCode::CreateFile);
        let mut buf: [u8; 64] = [0; 64];
        let res = req.write_to_bytes(&mut buf);
        assert!(res.is_ok());
        let req_conv_back = FilestoreRequestTlv::from_bytes(&buf);
        assert!(req_conv_back.is_ok());
        let req_conv_back = req_conv_back.unwrap();
        assert_eq!(req_conv_back, req);
    }

    #[test]
    fn test_fs_request_serialization_two_files() {
        let req = generic_fs_request_test_two_files(FilestoreActionCode::RenameFile);
        let mut buf: [u8; 64] = [0; 64];
        let res = req.write_to_bytes(&mut buf);
        assert!(res.is_ok());
        let written = res.unwrap();
        assert_eq!(written, req.len_full());
        assert_eq!(
            written,
            3 + 1 + TLV_TEST_STR_0.len() + 1 + TLV_TEST_STR_1.len()
        );
        let current_idx = check_fs_request_first_part(
            &buf,
            FilestoreActionCode::RenameFile,
            1 + 1 + TLV_TEST_STR_0.len() as u8 + 1 + TLV_TEST_STR_1.len() as u8,
        );
        let second_lv = Lv::from_bytes(&buf[current_idx..]);
        assert!(second_lv.is_ok());
        let second_lv = second_lv.unwrap();
        assert_eq!(second_lv.value_as_str().unwrap().unwrap(), TLV_TEST_STR_1);
        assert_eq!(current_idx + second_lv.len_full(), req.len_full());
    }

    #[test]
    fn test_fs_request_deserialization_two_files() {
        let req = generic_fs_request_test_two_files(FilestoreActionCode::RenameFile);
        let mut buf: [u8; 64] = [0; 64];
        req.write_to_bytes(&mut buf).unwrap();
        let req_conv_back = FilestoreRequestTlv::from_bytes(&buf);
        assert!(req_conv_back.is_ok());
        let req_conv_back = req_conv_back.unwrap();
        assert_eq!(req_conv_back, req);
    }

    #[test]
    fn test_fs_response_state_one_path() {
        let lv_0 = Lv::new_from_str(TLV_TEST_STR_0).unwrap();
        let response = FilestoreResponseTlv::new_no_filestore_message(
            FilestoreActionCode::CreateFile,
            0b0001,
            lv_0,
            None,
        )
        .expect("creating response failed");
        assert_eq!(response.status_code(), 0b0001);
        assert_eq!(response.action_code(), FilestoreActionCode::CreateFile);
        assert_eq!(response.first_name(), lv_0);
        assert!(response.second_name().is_none());
    }
    #[test]
    fn test_fs_response_state_two_paths() {
        let lv_0 = Lv::new_from_str(TLV_TEST_STR_0).unwrap();
        let lv_1 = Lv::new_from_str(TLV_TEST_STR_1).unwrap();
        let response = FilestoreResponseTlv::new_no_filestore_message(
            FilestoreActionCode::RenameFile,
            0b0001,
            lv_0,
            Some(lv_1),
        )
        .expect("creating response failed");
        assert_eq!(response.status_code(), 0b0001);
        assert_eq!(response.action_code(), FilestoreActionCode::RenameFile);
        assert_eq!(response.first_name(), lv_0);
        assert!(response.second_name().is_some());
        assert!(response.second_name().unwrap() == lv_1);
        assert_eq!(
            response.len_full(),
            2 + 1 + lv_0.len_full() + lv_1.len_full() + 1
        );
    }

    #[test]
    fn test_fs_response_serialization() {
        let lv_0 = Lv::new_from_str(TLV_TEST_STR_0).unwrap();
        let response = FilestoreResponseTlv::new_no_filestore_message(
            FilestoreActionCode::CreateFile,
            0b0001,
            lv_0,
            None,
        )
        .expect("creating response failed");
        let mut buf: [u8; 32] = [0; 32];
        let written_len = response.write_to_bytes(&mut buf).unwrap();
        assert_eq!(written_len, 2 + 1 + lv_0.len_full() + 1);
        assert_eq!(buf[0], TlvType::FilestoreResponse as u8);
        assert_eq!(buf[1], written_len as u8 - 2);
        assert_eq!(
            (buf[2] >> 4) & 0b1111,
            FilestoreActionCode::CreateFile as u8
        );
        assert_eq!(buf[2] & 0b1111, 0b0001);
        let lv_read_back = Lv::from_bytes(&buf[3..]).unwrap();
        assert_eq!(lv_0, lv_read_back);
        let current_idx = 3 + lv_0.len_full();
        let fs_msg_empty = Lv::from_bytes(&buf[current_idx..]).unwrap();
        assert!(fs_msg_empty.is_empty());
    }

    #[test]
    fn test_fs_response_deserialization() {
        let lv_0 = Lv::new_from_str(TLV_TEST_STR_0).unwrap();
        let response = FilestoreResponseTlv::new_no_filestore_message(
            FilestoreActionCode::CreateFile,
            0b0001,
            lv_0,
            None,
        )
        .expect("creating response failed");
        let mut buf: [u8; 32] = [0; 32];
        response.write_to_bytes(&mut buf).unwrap();
        let response_read_back = FilestoreResponseTlv::from_bytes(&buf).unwrap();
        assert_eq!(response_read_back, response);
    }

    #[test]
    fn test_entity_it_tlv_to_tlv() {
        let entity_id = UbfU16::new(0x0102);
        let entity_id_tlv = EntityIdTlv::new(entity_id.into());
        let mut binding = [0; 16];
        let tlv = entity_id_tlv.to_tlv(&mut binding).unwrap();
        assert_eq!(
            tlv.tlv_type_field(),
            TlvTypeField::Standard(TlvType::EntityId)
        );
        assert_eq!(tlv.len_full(), 4);
        assert_eq!(tlv.len_value(), 2);
        assert_eq!(tlv.value(), &[0x01, 0x02]);
    }

    #[test]
    fn test_invalid_tlv_conversion() {
        let msg_to_user_tlv = Tlv::new_empty(TlvType::MsgToUser);
        let error = EntityIdTlv::try_from(msg_to_user_tlv);
        assert!(error.is_err());
        let error = error.unwrap_err();
        if let TlvLvError::InvalidTlvTypeField(InvalidTlvTypeFieldError { found, expected }) = error
        {
            assert_eq!(found, TlvType::MsgToUser as u8);
            assert_eq!(expected, Some(TlvType::EntityId as u8));
            assert_eq!(
                error.to_string(),
                "invalid TLV type field, found 2, expected Some(6)"
            );
        } else {
            panic!("unexpected error");
        }
    }

    #[test]
    fn test_entity_id_invalid_value_len() {
        let entity_id = UbfU16::new(0x0102);
        let entity_id_tlv = EntityIdTlv::new(entity_id.into());
        let mut buf: [u8; 32] = [0; 32];
        entity_id_tlv.write_to_bytes(&mut buf).unwrap();
        buf[1] = 12;
        let error = EntityIdTlv::from_bytes(&buf);
        assert!(error.is_err());
        let error = error.unwrap_err();
        if let TlvLvError::InvalidValueLength(len) = error {
            assert_eq!(len, 12);
            assert_eq!(error.to_string(), "invalid value length 12");
        } else {
            panic!("unexpected error");
        }
    }

    #[test]
    fn test_custom_tlv() {
        let custom_tlv = Tlv::new_with_custom_type(20, &[]).unwrap();
        assert!(custom_tlv.tlv_type().is_none());
        if let TlvTypeField::Custom(val) = custom_tlv.tlv_type_field() {
            assert_eq!(val, 20);
        } else {
            panic!("unexpected type field");
        }
        let tlv_as_vec = custom_tlv.to_vec();
        assert_eq!(tlv_as_vec.len(), 2);
        assert_eq!(tlv_as_vec[0], 20);
        assert_eq!(tlv_as_vec[1], 0);
    }

    #[test]
    fn test_tlv_to_owned() {
        let entity_id = UbfU8::new(5);
        let mut buf: [u8; 4] = [0; 4];
        assert!(entity_id.write_to_be_bytes(&mut buf).is_ok());
        let tlv_res = Tlv::new(TlvType::EntityId, &buf[0..1]);
        assert!(tlv_res.is_ok());
        let tlv_res = tlv_res.unwrap();
        let tlv_owned = tlv_res.to_owned();
        assert_eq!(tlv_res, tlv_owned);
        let tlv_owned_from_conversion: TlvOwned = tlv_res.into();
        assert_eq!(tlv_owned_from_conversion, tlv_owned);
        assert_eq!(tlv_owned_from_conversion, tlv_res);
    }

    #[test]
    fn test_owned_tlv() {
        let entity_id = UbfU8::new(5);
        let mut buf: [u8; 4] = [0; 4];
        assert!(entity_id.write_to_be_bytes(&mut buf).is_ok());
        let tlv_res = TlvOwned::new(TlvType::EntityId, &buf[0..1]);
        assert_eq!(
            tlv_res.tlv_type_field(),
            TlvTypeField::Standard(TlvType::EntityId)
        );
        assert_eq!(tlv_res.len_full(), 3);
        assert_eq!(tlv_res.value().len(), 1);
        assert_eq!(tlv_res.len_value(), 1);
        assert!(!tlv_res.is_empty());
        assert_eq!(tlv_res.value()[0], 5);
    }

    #[test]
    fn test_owned_tlv_empty() {
        let tlv_res = TlvOwned::new_empty(TlvType::FlowLabel);
        assert_eq!(
            tlv_res.tlv_type_field(),
            TlvTypeField::Standard(TlvType::FlowLabel)
        );
        assert_eq!(tlv_res.len_full(), 2);
        assert_eq!(tlv_res.value().len(), 0);
        assert_eq!(tlv_res.len_value(), 0);
        assert!(tlv_res.is_empty());
    }

    #[test]
    fn test_owned_tlv_custom_type() {
        let tlv_res = TlvOwned::new_with_custom_type(32, &[]);
        assert_eq!(tlv_res.tlv_type_field(), TlvTypeField::Custom(32));
        assert_eq!(tlv_res.len_full(), 2);
        assert_eq!(tlv_res.value().len(), 0);
        assert_eq!(tlv_res.len_value(), 0);
        assert!(tlv_res.is_empty());
    }

    #[test]
    fn test_owned_tlv_conversion_to_bytes() {
        let entity_id = UbfU8::new(5);
        let mut buf: [u8; 4] = [0; 4];
        assert!(entity_id.write_to_be_bytes(&mut buf).is_ok());
        let tlv_res = Tlv::new(TlvType::EntityId, &buf[0..1]);
        assert!(tlv_res.is_ok());
        let tlv_res = tlv_res.unwrap();
        let tlv_owned_from_conversion: TlvOwned = tlv_res.into();
        assert_eq!(tlv_res.to_vec(), tlv_owned_from_conversion.to_vec());
    }
}