uds_protocol 0.0.2

A library for encoding and decoding UDS (ISO 14229) messages
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
use byteorder::{ReadBytesExt, WriteBytesExt};
use std::io::Read;

use crate::{DataFormatIdentifier, Error, SingleValueWireFormat, WireFormat};

///////////////////////////////////////// - Request - ///////////////////////////////////////////////////
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum FileOperationMode {
    // 0x00, 0x07-0xFF Reserved for future definition by ISO
    ISOSAEReserved(u8),
    /// Add a file to the server
    AddFile = 0x01,
    /// Delete the specified file from the server
    DeleteFile = 0x02,
    /// Replace the specified file on the server, if it does not exist, add it
    ReplaceFile = 0x03,
    /// Read the specified file from the server (upload)
    ReadFile = 0x04,
    /// Read the directory from the server
    /// Implies that the request does not include a `fileName`
    ReadDir = 0x05,
    /// Resume a file transfer at the returned `filePosition` indicator
    /// The file must already exist in the ECU's filesystem
    ResumeFile = 0x06,
}

impl From<FileOperationMode> for u8 {
    fn from(value: FileOperationMode) -> Self {
        match value {
            FileOperationMode::ISOSAEReserved(value) => value,
            FileOperationMode::AddFile => 0x01,
            FileOperationMode::DeleteFile => 0x02,
            FileOperationMode::ReplaceFile => 0x03,
            FileOperationMode::ReadFile => 0x04,
            FileOperationMode::ReadDir => 0x05,
            FileOperationMode::ResumeFile => 0x06,
        }
    }
}

impl TryFrom<u8> for FileOperationMode {
    type Error = Error;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0x01 => Ok(Self::AddFile),
            0x02 => Ok(Self::DeleteFile),
            0x03 => Ok(Self::ReplaceFile),
            0x04 => Ok(Self::ReadFile),
            0x05 => Ok(Self::ReadDir),
            0x06 => Ok(Self::ResumeFile),
            0x00 | 0x07..=0xFF => Ok(Self::ISOSAEReserved(value)),
        }
    }
}

/// Holds the sizes of the file to be transferred (if applicable)
/// Used for both [`RequestFileTransferRequest`] and [`RequestFileTransferResponse`]
///
/// |              | [AddFile] | [DeleteFile] | [ReplaceFile] | [ReadFile] | [ReadDir] | [ResumeFile] |
/// |--------------|-----------|--------------|---------------|------------|-----------|--------------|
/// |**[Request]** | Yes       |              | Yes           |            |           | Yes          |
/// |**[Response]**|           |              |               | Yes        |           |              |
///
/// [AddFile]: FileOperationMode::AddFile
/// [DeleteFile]: FileOperationMode::DeleteFile
/// [ReplaceFile]: FileOperationMode::ReplaceFile
/// [ReadFile]: FileOperationMode::ReadFile
/// [ReadDir]: FileOperationMode::ReadDir
/// [ResumeFile]: FileOperationMode::ResumeFile
/// [Request]: RequestFileTransferRequest (RequestFileTransferRequest)
/// [Response]: RequestFileTransferResponse (RequestFileTransferResponse)
#[allow(clippy::struct_field_names)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Clone, Debug, PartialEq)]
pub struct SizePayload {
    /// Length in bytes for both `file_size_uncompressed` and `file_size_compressed`
    ///
    /// Not included in the *Request* message if `mode_of_operation` is one of:
    ///  * `DeleteFile` (0x02)
    ///  * `ReadFile` (0x04)
    ///  * `ReadDir` (0x05)
    ///
    /// Not included in the *Response* message if `mode_of_operation` is one of:
    ///    * `DeleteFile` (0x02)
    pub file_size_parameter_length: u8,

    /// Specifies the size of the uncompressed file in bytes.
    ///
    /// Not included in the request message if `mode_of_operation` is one of:
    ///     * `DeleteFile` (0x02)
    ///     * `ReadFile` (0x04)
    ///     * `ReadDir` (0x05)
    pub file_size_uncompressed: u128,

    /// Specifies the size of the compressed file in bytes
    ///
    /// Not included in the request message if `mode_of_operation` is one of:
    ///     * `DeleteFile` (0x02)
    ///     * `ReadFile` (0x04)
    ///     * `ReadDir` (0x05)
    pub file_size_compressed: u128,
}

impl WireFormat for SizePayload {
    fn decode<T: std::io::Read>(reader: &mut T) -> Result<Option<Self>, Error> {
        let file_size_parameter_length = reader.read_u8()?;
        let mut file_size_uncompressed = vec![0; file_size_parameter_length as usize];
        let mut file_size_compressed = vec![0; file_size_parameter_length as usize];

        reader.read_exact(&mut file_size_uncompressed)?;
        reader.read_exact(&mut file_size_compressed)?;

        Ok(Some(Self {
            file_size_parameter_length,
            file_size_uncompressed: u128::from_be_bytes({
                let mut bytes = [0; 16];
                bytes[16 - file_size_parameter_length as usize..]
                    .copy_from_slice(&file_size_uncompressed);
                bytes
            }),
            file_size_compressed: u128::from_be_bytes({
                let mut bytes = [0; 16];
                bytes[16 - file_size_parameter_length as usize..]
                    .copy_from_slice(&file_size_compressed);
                bytes
            }),
        }))
    }

    fn required_size(&self) -> usize {
        1 + (2 * self.file_size_parameter_length as usize)
    }

    fn encode<T: std::io::Write>(&self, writer: &mut T) -> Result<usize, Error> {
        // Always write the file size as 1 byte
        writer.write_u8(self.file_size_parameter_length)?;
        // write the file size only as many bytes as needed
        // Slice off only the number of bytes we need from the end of the file_size bytes
        let uncompressed = self.file_size_uncompressed.to_be_bytes();
        let compressed = self.file_size_compressed.to_be_bytes();
        // file_size_uncompressed
        let mut bytes: Vec<u8> = Vec::new();
        bytes.extend_from_slice(&uncompressed[16 - self.file_size_parameter_length as usize..]);
        // file_size_compressed
        bytes.extend_from_slice(&compressed[16 - self.file_size_parameter_length as usize..]);

        writer.write_all(&bytes)?;

        Ok(self.required_size())
    }
}
impl SingleValueWireFormat for SizePayload {}

/// Payload used for all [`RequestFileTransfer` requests][RequestFileTransferRequest]
///
/// #### ***Request*** Message
/// |               | [AddFile] | [DeleteFile] | [ReplaceFile] | [ReadFile] | [ReadDir] | [ResumeFile] |
/// |---------------|-----------|--------------|---------------|------------|-----------|--------------|
/// |**[Request]**  | Yes       | Yes          | Yes           | Yes        | Yes       | Yes          |
///
/// [AddFile]: FileOperationMode::AddFile
/// [DeleteFile]: FileOperationMode::DeleteFile
/// [ReplaceFile]: FileOperationMode::ReplaceFile
/// [ReadFile]: FileOperationMode::ReadFile
/// [ReadDir]: FileOperationMode::ReadDir
/// [ResumeFile]: FileOperationMode::ResumeFile
/// [Request]: RequestFileTransferRequest (RequestFileTransferRequest)
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Clone, Debug, PartialEq)]
pub struct NamePayload {
    /// 0x01 - 0x06, the type of operation to be applied to the file or directory specified in `file_path_and_name`
    ///
    /// Duplicated as we need to read and store it somewhere
    mode_of_operation: FileOperationMode,

    /// Length in bytes of the `file_path_and_name` field
    file_path_and_name_length: u16,

    /// The path and name of the file or directory on the server
    file_path_and_name: String,
}

impl WireFormat for NamePayload {
    fn decode<T: std::io::Read>(reader: &mut T) -> Result<Option<Self>, Error> {
        let mode_of_operation = FileOperationMode::try_from(reader.read_u8()?)?;
        let file_path_and_name_length = reader.read_u16::<byteorder::BigEndian>()?;

        // Read # of bytes specified by `file_path_and_name_length`
        let mut file_path_and_name = String::new();
        reader
            .take(u64::from(file_path_and_name_length))
            .read_to_string(&mut file_path_and_name)?;

        Ok(Some(Self {
            mode_of_operation,
            file_path_and_name_length,
            file_path_and_name,
        }))
    }

    fn required_size(&self) -> usize {
        1 + 2 + self.file_path_and_name.len()
    }

    fn encode<T: std::io::Write>(&self, writer: &mut T) -> Result<usize, Error> {
        // Write the mode of operation
        writer.write_u8((self.mode_of_operation).into())?;
        // Write the file path and name length
        writer.write_u16::<byteorder::BigEndian>(self.file_path_and_name_length)?;
        // Write the file path and name
        writer.write_all(self.file_path_and_name.as_bytes())?;
        Ok(self.required_size())
    }
}
impl SingleValueWireFormat for NamePayload {}
/// A request to the server to transfer a file, either upload or download.
///
/// Capabilities:
///   * Receive information about the file system on the server
///   * Send/Receive files to/from the server
///
/// Available as an alternative to [`crate::RequestDownloadRequest`] and [`crate::RequestUploadRequest`]
/// if the server implements a file system for data storage
///
/// Use [`crate::UdsServiceType::TransferData`] to send the file data to the server and [`crate::UdsServiceType::RequestTransferExit`] to end the transfer
///
/// If this service is used to delete files or directories on the server,
/// there is no need to use the `TransferData` or [`crate::UdsServiceType::RequestTransferExit`] services.
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum RequestFileTransferRequest {
    /// Add a file to the server
    AddFile(NamePayload, DataFormatIdentifier, SizePayload),

    /// Delete the specified file from the server
    DeleteFile(NamePayload),

    /// Replace the specified file on the server, if it does not exist, add it
    ReplaceFile(NamePayload, DataFormatIdentifier, SizePayload),

    /// Read the specified file from the server (upload)
    ReadFile(NamePayload, DataFormatIdentifier),

    /// Read the directory from the server
    /// Implies that the request does not include a `fileName`
    ReadDir(NamePayload),

    /// Resume a file transfer at the returned `filePosition` indicator
    /// The file must already exist in the ECU's filesystem
    ResumeFile(NamePayload, DataFormatIdentifier, SizePayload),
}

impl SingleValueWireFormat for RequestFileTransferRequest {}

impl WireFormat for RequestFileTransferRequest {
    fn decode<T: std::io::Read>(reader: &mut T) -> Result<Option<Self>, Error> {
        let name_payload = NamePayload::decode_single_value(reader)?;

        // read the filename
        Ok(Some(match name_payload.mode_of_operation {
            // Complicated
            FileOperationMode::AddFile => Self::AddFile(
                name_payload,
                DataFormatIdentifier::decode_single_value(reader)?,
                SizePayload::decode_single_value(reader)?,
            ),
            FileOperationMode::ReplaceFile => Self::ReplaceFile(
                name_payload,
                DataFormatIdentifier::decode_single_value(reader)?,
                SizePayload::decode_single_value(reader)?,
            ),
            FileOperationMode::ResumeFile => Self::ResumeFile(
                name_payload,
                DataFormatIdentifier::decode_single_value(reader)?,
                SizePayload::decode_single_value(reader)?,
            ),
            FileOperationMode::ReadFile => Self::ReadFile(
                name_payload,
                DataFormatIdentifier::decode_single_value(reader)?,
            ),
            FileOperationMode::ReadDir => Self::ReadDir(name_payload),
            FileOperationMode::DeleteFile => Self::DeleteFile(name_payload),
            FileOperationMode::ISOSAEReserved(_) => {
                return Err(Error::InvalidFileOperationMode(
                    name_payload.mode_of_operation.into(),
                ));
            }
        }))
    }

    fn required_size(&self) -> usize {
        match self {
            Self::AddFile(name_payload, data_format_identifier, file_size_payload)
            | Self::ReplaceFile(name_payload, data_format_identifier, file_size_payload)
            | Self::ResumeFile(name_payload, data_format_identifier, file_size_payload) => {
                name_payload.required_size()
                    + data_format_identifier.required_size()
                    + file_size_payload.required_size()
            }
            Self::ReadFile(name_payload, data_format_identifier) => {
                name_payload.required_size() + data_format_identifier.required_size()
            }
            Self::DeleteFile(name_payload) | Self::ReadDir(name_payload) => {
                name_payload.required_size()
            }
        }
    }

    fn encode<T: std::io::Write>(&self, writer: &mut T) -> Result<usize, Error> {
        let mut len = 0;
        Ok(match self {
            Self::AddFile(name_payload, data_format_identifier, file_size_payload)
            | Self::ReplaceFile(name_payload, data_format_identifier, file_size_payload)
            | Self::ResumeFile(name_payload, data_format_identifier, file_size_payload) => {
                len += name_payload.encode(writer)?;
                len += data_format_identifier.encode(writer)?;
                len += file_size_payload.encode(writer)?;
                len
            }
            Self::ReadFile(name_payload, data_format_identifier) => {
                len += name_payload.encode(writer)?;
                len += data_format_identifier.encode(writer)?;
                len
            }
            Self::DeleteFile(name_payload) | Self::ReadDir(name_payload) => {
                len += name_payload.encode(writer)?;
                len
            }
        })
    }
}

///////////////////////////////////////// - Response - ///////////////////////////////////////////////////

/// Sent by the server to inform the client of the maximum number of bytes to include in each `TransferData` request message
///
/// |               | [AddFile] | [DeleteFile] | [ReplaceFile] | [ReadFile] | [ReadDir] | [ResumeFile] |
/// |---------------|-----------|--------------|---------------|------------|-----------|--------------|
/// |**[Response]** | Yes       |              | Yes           | Yes        | Yes       | Yes          |
///
/// [AddFile]: FileOperationMode::AddFile
/// [DeleteFile]: FileOperationMode::DeleteFile
/// [ReplaceFile]: FileOperationMode::ReplaceFile
/// [ReadFile]: FileOperationMode::ReadFile
/// [ReadDir]: FileOperationMode::ReadDir
/// [ResumeFile]: FileOperationMode::ResumeFile
/// [Response]: RequestFileTransferRequest (RequestFileTransferResponse)
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Clone, Debug, PartialEq)]
pub struct SentDataPayload {
    /// Not related to `RequestDownload`
    length_format_identifier: u8,
    /// This parameter is used by the requestFileTransfer positive response message to inform the client how many
    /// data bytes (maxNumberOfBlockLength) to include in each `TransferData` request message from the client or how
    /// many data bytes the server will include in a `TransferData` positive response when uploading data. This length
    /// reflects the complete message length, including the service identifier and the data parameters present in the
    /// `TransferData` request message or positive response message. This parameter allows either the client to adapt to
    /// the receive buffer size of the server before it starts transferring data to the server or to indicate how many data
    /// bytes will be included in each `TransferData` positive response in the event that data is uploaded. A server is
    /// required to accept transferData requests that are equal in length to its reported maxNumberOfBlockLength. It is
    /// server specific what transferData request lengths less than maxNumberOfBlockLength are accepted (if any).
    ///
    /// NOTE The last transferData request within a given block can be required to be less than
    /// maxNumberOfBlockLength. It is not allowed for a server to write additional data bytes (i.e. pad bytes) not
    /// contained within the transferData message (either in a compressed or uncompressed format), as this would
    /// affect the memory address of where the subsequent transferData request data would be written.
    /// If the modeOfOperation parameter equals to 0x02 (`DeleteFile`) this parameter shall be not be included in the
    /// response message.
    pub max_number_of_block_length: Vec<u8>,
}

impl SingleValueWireFormat for SentDataPayload {}
impl WireFormat for SentDataPayload {
    fn decode<T: std::io::Read>(reader: &mut T) -> Result<Option<Self>, Error> {
        let length_format_identifier = reader.read_u8()?;

        let mut max_number_of_block_length: Vec<u8> = vec![0; length_format_identifier as usize];
        reader.read_exact(&mut max_number_of_block_length)?;
        Ok(Some(Self {
            length_format_identifier,
            max_number_of_block_length,
        }))
    }

    fn required_size(&self) -> usize {
        1 + self.max_number_of_block_length.len()
    }

    fn encode<T: std::io::Write>(&self, writer: &mut T) -> Result<usize, Error> {
        writer.write_u8(self.length_format_identifier)?;
        writer.write_all(&self.max_number_of_block_length)?;
        Ok(self.required_size())
    }
}

/// Used to inform the client of the size of the file to be transferred
///
/// |               | [AddFile] | [DeleteFile] | [ReplaceFile] | [ReadFile] | [ReadDir] | [ResumeFile] |
/// |---------------|-----------|--------------|---------------|------------|-----------|--------------|
/// |**[Response]** |           |              |               | Yes        |           |              |
///
/// [AddFile]: FileOperationMode::AddFile
/// [DeleteFile]: FileOperationMode::DeleteFile
/// [ReplaceFile]: FileOperationMode::ReplaceFile
/// [ReadFile]: FileOperationMode::ReadFile
/// [ReadDir]: FileOperationMode::ReadDir
/// [ResumeFile]: FileOperationMode::ResumeFile
/// [Response]: RequestFileTransferRequest (RequestFileTransferResponse)
#[allow(clippy::struct_field_names)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Clone, Debug, PartialEq)]
pub struct FileSizePayload {
    pub file_size_parameter_length: u16,
    pub file_size_uncompressed: u128,
    pub file_size_compressed: u128,
}

impl WireFormat for FileSizePayload {
    fn decode<T: std::io::Read>(reader: &mut T) -> Result<Option<Self>, Error> {
        let file_size_parameter_length = reader.read_u16::<byteorder::BE>()?;
        let mut file_size_uncompressed = vec![0; file_size_parameter_length as usize];
        let mut file_size_compressed = vec![0; file_size_parameter_length as usize];

        reader.read_exact(&mut file_size_uncompressed)?;
        reader.read_exact(&mut file_size_compressed)?;

        Ok(Some(Self {
            file_size_parameter_length,
            file_size_uncompressed: u128::from_be_bytes({
                let mut bytes = [0; 16];
                bytes[16 - file_size_parameter_length as usize..]
                    .copy_from_slice(&file_size_uncompressed);
                bytes
            }),
            file_size_compressed: u128::from_be_bytes({
                let mut bytes = [0; 16];
                bytes[16 - file_size_parameter_length as usize..]
                    .copy_from_slice(&file_size_compressed);
                bytes
            }),
        }))
    }

    fn required_size(&self) -> usize {
        2 + (2 * self.file_size_parameter_length as usize)
    }

    fn encode<T: std::io::Write>(&self, writer: &mut T) -> Result<usize, Error> {
        // Always write the file size as 1 byte

        writer.write_u16::<byteorder::BE>(self.file_size_parameter_length)?;
        // write the file size only as many bytes as needed
        // Slice off only the number of bytes we need from the end of the file_size bytes
        let uncompressed = self.file_size_uncompressed.to_be_bytes();
        let compressed = self.file_size_compressed.to_be_bytes();
        // file_size_uncompressed
        let mut bytes: Vec<u8> = Vec::new();
        bytes.extend_from_slice(&uncompressed[16 - self.file_size_parameter_length as usize..]);
        // file_size_compressed
        bytes.extend_from_slice(&compressed[16 - self.file_size_parameter_length as usize..]);

        writer.write_all(&bytes)?;

        Ok(self.required_size())
    }
}
impl SingleValueWireFormat for FileSizePayload {}

/// Used to inform the client of the size of the directory to be transferred
///
/// |               | [AddFile] | [DeleteFile] | [ReplaceFile] | [ReadFile] | [ReadDir] | [ResumeFile] |
/// |---------------|-----------|--------------|---------------|------------|-----------|--------------|
/// |**[Response]** |           |              |               |            | Yes       |              |
///
/// [AddFile]: FileOperationMode::AddFile
/// [DeleteFile]: FileOperationMode::DeleteFile
/// [ReplaceFile]: FileOperationMode::ReplaceFile
/// [ReadFile]: FileOperationMode::ReadFile
/// [ReadDir]: FileOperationMode::ReadDir
/// [ResumeFile]: FileOperationMode::ResumeFile
/// [Response]: RequestFileTransferRequest (RequestFileTransferResponse)
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Clone, Debug, PartialEq)]
pub struct DirSizePayload {
    pub dir_info_parameter_length: u16,
    pub dir_info_length: u128,
}

impl SingleValueWireFormat for DirSizePayload {}
impl WireFormat for DirSizePayload {
    fn decode<T: std::io::Read>(reader: &mut T) -> Result<Option<Self>, Error> {
        let dir_info_parameter_length = reader.read_u16::<byteorder::BigEndian>()?;
        let mut dir_info_length = vec![0; dir_info_parameter_length as usize];
        reader.read_exact(&mut dir_info_length)?;

        Ok(Some(Self {
            dir_info_parameter_length,
            dir_info_length: u128::from_be_bytes({
                let mut bytes = [0; 16];
                bytes[16 - dir_info_parameter_length as usize..].copy_from_slice(&dir_info_length);
                bytes
            }),
        }))
    }

    fn required_size(&self) -> usize {
        2 + self.dir_info_parameter_length as usize
    }

    fn encode<T: std::io::Write>(&self, writer: &mut T) -> Result<usize, Error> {
        let mut len = 0;
        writer.write_u16::<byteorder::BigEndian>(self.dir_info_parameter_length)?;
        len += 2;
        // write the file size only as many bytes as needed
        // Slice off only the number of bytes we need from the end of the file_size bytes
        let dir_info_length = self.dir_info_length.to_be_bytes();
        let mut bytes: Vec<u8> = Vec::new();

        bytes.extend_from_slice(&dir_info_length[16 - self.dir_info_parameter_length as usize..]);
        writer.write_all(&bytes)?;

        len += bytes.len();

        Ok(len)
    }
}

/// Used to inform the client of the byte position within the file at which the Tester will resume downloading after an initial download is suspended
///
/// |               | [AddFile] | [DeleteFile] | [ReplaceFile] | [ReadFile] | [ReadDir] | [ResumeFile] |
/// |---------------|-----------|--------------|---------------|------------|-----------|--------------|
/// |**[Response]** |           |              |               |            |           | Yes          |
///
/// [AddFile]: FileOperationMode::AddFile
/// [DeleteFile]: FileOperationMode::DeleteFile
/// [ReplaceFile]: FileOperationMode::ReplaceFile
/// [ReadFile]: FileOperationMode::ReadFile
/// [ReadDir]: FileOperationMode::ReadDir
/// [ResumeFile]: FileOperationMode::ResumeFile
/// [Response]: RequestFileTransferRequest (RequestFileTransferResponse)
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PositionPayload {
    /// Specifies the byte position within the file at which the Tester will resume downloading after an initial download is suspended
    /// A download is suspended when the ECU stops receiving [`crate::TransferDataRequest`] requests and does not receive the
    /// [`crate::RequestTransferExitRequest`] request to end the transfer before returning to the default session
    ///
    /// Fixed size: 8 bytes
    ///
    /// Not included for [`AddFile`][FileOperationMode::AddFile], [`DeleteFile`][FileOperationMode::DeleteFile], [`ReplaceFile`][FileOperationMode::ReplaceFile], [`ReadFile`][FileOperationMode::ReadFile], or [`ReadDir`][FileOperationMode::ReadDir]
    /// Only present if `mode_of_operation` is [`ResumeFile`][FileOperationMode::ResumeFile] (for ISO 14229-1:2020)
    pub file_position: u64,
}

impl SingleValueWireFormat for PositionPayload {}
impl WireFormat for PositionPayload {
    fn decode<T: std::io::Read>(reader: &mut T) -> Result<Option<Self>, Error> {
        Ok(Some(Self {
            file_position: reader.read_u64::<byteorder::BigEndian>()?,
        }))
    }
    // For PositionPayload
    fn required_size(&self) -> usize {
        8
    }

    fn encode<T: std::io::Write>(&self, writer: &mut T) -> Result<usize, Error> {
        writer.write_u64::<byteorder::BigEndian>(self.file_position)?;
        Ok(8)
    }
}

/// Response to a [`RequestFileTransferRequest`] from the server
///
/// The server will respond with a [`RequestFileTransferResponse`] to indicate the status of the request
/// [`DataFormatIdentifier`] - Echoes the value of the request
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum RequestFileTransferResponse {
    AddFile(FileOperationMode, SentDataPayload, DataFormatIdentifier),
    DeleteFile(FileOperationMode),
    ReplaceFile(FileOperationMode, SentDataPayload, DataFormatIdentifier),
    ReadFile(
        FileOperationMode,
        SentDataPayload,
        DataFormatIdentifier,
        FileSizePayload,
    ),
    ReadDir(
        FileOperationMode,
        SentDataPayload,
        DataFormatIdentifier,
        DirSizePayload,
    ),
    ResumeFile(
        FileOperationMode,
        SentDataPayload,
        DataFormatIdentifier,
        PositionPayload,
    ),
}

impl SingleValueWireFormat for RequestFileTransferResponse {}
impl WireFormat for RequestFileTransferResponse {
    fn decode<T: std::io::Read>(reader: &mut T) -> Result<Option<Self>, Error> {
        // Read the mode of operation
        let mode_of_operation = FileOperationMode::try_from(reader.read_u8()?)?;
        Ok(Some(match mode_of_operation {
            FileOperationMode::AddFile => Self::AddFile(
                mode_of_operation,
                SentDataPayload::decode_single_value(reader)?,
                DataFormatIdentifier::decode_single_value(reader)?,
            ),
            FileOperationMode::DeleteFile => Self::DeleteFile(mode_of_operation),
            FileOperationMode::ReplaceFile => Self::ReplaceFile(
                mode_of_operation,
                SentDataPayload::decode_single_value(reader)?,
                DataFormatIdentifier::decode_single_value(reader)?,
            ),
            FileOperationMode::ReadFile => Self::ReadFile(
                mode_of_operation,
                SentDataPayload::decode_single_value(reader)?,
                DataFormatIdentifier::decode_single_value(reader)?,
                FileSizePayload::decode_single_value(reader)?,
            ),
            FileOperationMode::ReadDir => Self::ReadDir(
                mode_of_operation,
                SentDataPayload::decode_single_value(reader)?,
                DataFormatIdentifier::decode_single_value(reader)?,
                DirSizePayload::decode_single_value(reader)?,
            ),
            FileOperationMode::ResumeFile => Self::ResumeFile(
                mode_of_operation,
                SentDataPayload::decode_single_value(reader)?,
                DataFormatIdentifier::decode_single_value(reader)?,
                PositionPayload::decode_single_value(reader)?,
            ),
            FileOperationMode::ISOSAEReserved(_) => {
                return Err(Error::InvalidFileOperationMode(mode_of_operation.into()));
            }
        }))
    }

    // For RequestFileTransferResponse
    fn required_size(&self) -> usize {
        match self {
            Self::AddFile(_, sent_data, data_format)
            | Self::ReplaceFile(_, sent_data, data_format) => {
                1 + sent_data.required_size() + data_format.required_size()
            }
            Self::DeleteFile(_) => 1,
            Self::ReadFile(_, sent_data, data_format, file_size) => {
                1 + sent_data.required_size()
                    + data_format.required_size()
                    + file_size.required_size()
            }
            Self::ReadDir(_, sent_data, data_format, dir_size) => {
                1 + sent_data.required_size()
                    + data_format.required_size()
                    + dir_size.required_size()
            }
            Self::ResumeFile(_, sent_data, data_format, position) => {
                1 + sent_data.required_size()
                    + data_format.required_size()
                    + position.required_size()
            }
        }
    }
    fn encode<T: std::io::Write>(&self, writer: &mut T) -> Result<usize, Error> {
        // Every variant has a mode of operation
        let mut len = 1;

        match self {
            Self::AddFile(mode_of_operation, sent_data_payload, data_format_identifier)
            | Self::ReplaceFile(mode_of_operation, sent_data_payload, data_format_identifier) => {
                writer.write_u8((*mode_of_operation).into())?;
                len += sent_data_payload.encode(writer)?;
                len += data_format_identifier.encode(writer)?;
            }
            Self::DeleteFile(mode_of_operation) => {
                writer.write_u8((*mode_of_operation).into())?;
            }
            Self::ReadFile(
                mode_of_operation,
                sent_data_payload,
                data_format_identifier,
                size_payload,
            ) => {
                writer.write_u8((*mode_of_operation).into())?;
                len += sent_data_payload.encode(writer)?;
                len += data_format_identifier.encode(writer)?;
                len += size_payload.encode(writer)?;
            }
            Self::ReadDir(
                mode_of_operation,
                sent_data_payload,
                data_format_identifier,
                dir_size_payload,
            ) => {
                writer.write_u8((*mode_of_operation).into())?;
                len += sent_data_payload.encode(writer)?;
                len += data_format_identifier.encode(writer)?;
                len += dir_size_payload.encode(writer)?;
            }
            Self::ResumeFile(
                mode_of_operation,
                sent_data_payload,
                data_format_identifier,
                position_payload,
            ) => {
                writer.write_u8((*mode_of_operation).into())?;
                len += sent_data_payload.encode(writer)?;
                len += data_format_identifier.encode(writer)?;
                len += position_payload.encode(writer)?;
            }
        }
        Ok(len)
    }
}

#[cfg(test)]
mod request_tests {
    use super::*;
    use crate::param_length_u128;

    // helper function to get some bytes to read from
    #[allow(clippy::cast_possible_truncation)]
    fn get_bytes(mode: FileOperationMode, file_name: &str, file_size: u128) -> Vec<u8> {
        let mut bytes: Vec<u8> = Vec::new();
        bytes.push(mode.into()); // AddFile (u8)
        // write file_name len as 2 bytes
        bytes
            .write_u16::<byteorder::BigEndian>(file_name.len() as u16)
            .unwrap();
        bytes.extend_from_slice(file_name.as_bytes());

        if mode != FileOperationMode::DeleteFile && mode != FileOperationMode::ReadDir {
            bytes.push(0x00); // No compression or encryption (u8)
        }
        // only add file size if not DeleteFile, ReadDir, or ReadFile
        if mode != FileOperationMode::DeleteFile
            && mode != FileOperationMode::ReadDir
            && mode != FileOperationMode::ReadFile
        {
            // count the number of bytes occupied by the file size
            let num = param_length_u128(file_size) as u8;
            // use write exact
            bytes.write_u8(num).unwrap();
            // write the file size only as many bytes as needed
            // Slice off only the number of bytes we need from the end of the file_size bytes
            let source = file_size.to_be_bytes();
            // file_size_uncompressed
            bytes.extend_from_slice(&source[16 - num as usize..]);
            // file_size_compressed
            bytes.extend_from_slice(&source[16 - num as usize..]);
        }
        bytes
    }

    #[test]
    #[allow(clippy::cast_possible_truncation)]
    #[allow(clippy::cast_lossless)]
    fn add_file() {
        let compare_string = "test.txt";
        let file_size: u128 = (u64::MAX as u128) + 1000u128;
        let bytes = get_bytes(FileOperationMode::AddFile, compare_string, file_size);
        let req: crate::RequestFileTransferRequest =
            RequestFileTransferRequest::decode(&mut bytes.as_slice())
                .unwrap()
                .unwrap();

        let mut written_bytes = Vec::new();
        let written = req.encode(&mut written_bytes).unwrap();
        assert_eq!(written, written_bytes.len());
        assert_eq!(written, req.required_size());

        match req {
            RequestFileTransferRequest::AddFile(pl, data_format_pl, file_size_pl) => {
                assert_eq!(pl.mode_of_operation, FileOperationMode::AddFile);
                assert_eq!(pl.file_path_and_name_length, compare_string.len() as u16);
                assert_eq!(pl.file_path_and_name, compare_string);
                assert_eq!(data_format_pl, DataFormatIdentifier::new(0, 0).unwrap());
                assert_eq!(file_size_pl.file_size_parameter_length, 9);
                assert_eq!(file_size_pl.file_size_uncompressed, file_size);
                assert_eq!(file_size_pl.file_size_compressed, file_size);
            }
            _ => panic!("Expected AddFile"),
        }
    }

    #[test]
    #[allow(clippy::cast_possible_truncation)]
    fn delete_file() {
        let compare_string = "/var/tmp/delete_file.bin";
        let bytes = get_bytes(FileOperationMode::DeleteFile, compare_string, 0);
        let req = RequestFileTransferRequest::decode(&mut bytes.as_slice())
            .unwrap()
            .unwrap();

        let mut written_bytes = Vec::new();
        let written = req.encode(&mut written_bytes).unwrap();
        assert_eq!(written, written_bytes.len());
        assert_eq!(written, req.required_size());

        match req {
            RequestFileTransferRequest::DeleteFile(pl) => {
                assert_eq!(pl.mode_of_operation, FileOperationMode::DeleteFile);
                assert_eq!(pl.file_path_and_name_length, compare_string.len() as u16);
                assert_eq!(pl.file_path_and_name, compare_string);
            }
            _ => panic!("Expected DeleteFile"),
        }
    }

    #[test]
    #[allow(clippy::cast_possible_truncation)]
    fn write_add_file() {
        let compare_string = "test.txt";
        let file_size: u128 = 0x1234;
        let bytes = get_bytes(FileOperationMode::AddFile, compare_string, file_size);
        let req = RequestFileTransferRequest::decode(&mut bytes.as_slice())
            .unwrap()
            .unwrap();

        let mut bytes = Vec::new();
        let written = req.encode(&mut bytes).unwrap();
        assert_eq!(written, bytes.len());
        assert_eq!(written, req.required_size());

        // Should be equivalent to our helper function
        let expected_bytes = get_bytes(FileOperationMode::AddFile, compare_string, file_size);
        assert_eq!(bytes, expected_bytes);
    }

    #[test]
    #[allow(clippy::cast_possible_truncation)]
    fn write_delete_file() {
        let compare_string = "/var/tmp/delete_file.bin";
        let req = RequestFileTransferRequest::DeleteFile(NamePayload {
            mode_of_operation: FileOperationMode::DeleteFile,
            file_path_and_name_length: compare_string.len() as u16,
            file_path_and_name: compare_string.to_string(),
        });
        let mut bytes = Vec::new();
        let written = req.encode(&mut bytes).unwrap();
        // Should be equivalent to our helper function
        let expected_bytes = get_bytes(FileOperationMode::DeleteFile, compare_string, 0);
        assert_eq!(bytes, expected_bytes);
        assert_eq!(bytes.len(), written);
        assert_eq!(req.required_size(), written);
    }

    #[test]
    #[allow(clippy::cast_possible_truncation)]
    fn replace_file() {
        let compare_string = "/opt/testing/replace_file.bin";
        let file_size: u128 = 0x1234;
        let bytes = get_bytes(FileOperationMode::ReplaceFile, compare_string, file_size);
        let req = RequestFileTransferRequest::decode_single_value(&mut bytes.as_slice()).unwrap();

        let mut written_bytes = Vec::new();
        let written = req.encode(&mut written_bytes).unwrap();
        assert_eq!(written, written_bytes.len());
        assert_eq!(written, req.required_size());

        match req {
            RequestFileTransferRequest::ReplaceFile(pl, data_format_pl, file_size_pl) => {
                assert_eq!(pl.mode_of_operation, FileOperationMode::ReplaceFile);
                assert_eq!(pl.file_path_and_name_length, compare_string.len() as u16);
                assert_eq!(pl.file_path_and_name, compare_string);
                assert_eq!(data_format_pl, DataFormatIdentifier::new(0, 0).unwrap());
                assert_eq!(file_size_pl.file_size_parameter_length, 2);
                assert_eq!(file_size_pl.file_size_uncompressed, file_size);
                assert_eq!(file_size_pl.file_size_compressed, file_size);
            }
            _ => panic!("Expected ReplaceFile"),
        }
    }

    #[test]
    #[allow(clippy::cast_possible_truncation)]
    fn read_file() {
        let compare_string = "/opt/testing/just_reading_stuff.txt";
        let file_size: u128 = 0x0;
        let bytes = get_bytes(FileOperationMode::ReadFile, compare_string, file_size);
        let req = RequestFileTransferRequest::decode_single_value(&mut bytes.as_slice()).unwrap();

        let mut written_bytes = Vec::new();
        let written = req.encode(&mut written_bytes).unwrap();
        assert_eq!(written, written_bytes.len());
        assert_eq!(written, req.required_size());

        match req {
            RequestFileTransferRequest::ReadFile(pl, data_format_pl) => {
                assert_eq!(pl.mode_of_operation, FileOperationMode::ReadFile);
                assert_eq!(pl.file_path_and_name_length, compare_string.len() as u16);
                assert_eq!(pl.file_path_and_name, compare_string);
                assert_eq!(data_format_pl, DataFormatIdentifier::new(0, 0).unwrap());
            }
            _ => panic!("Expected ReadFile"),
        }
    }

    #[test]
    #[allow(clippy::cast_possible_truncation)]
    fn resume_file() {
        let compare_string = "/var/tmp/resume_file.bin";
        let file_size = 0x1234;
        let bytes = get_bytes(FileOperationMode::ResumeFile, compare_string, file_size);
        let req = RequestFileTransferRequest::decode_single_value(&mut bytes.as_slice()).unwrap();
        let mut written_bytes = Vec::new();
        let written = req.encode(&mut written_bytes).unwrap();
        assert_eq!(written, written_bytes.len());
        assert_eq!(written, req.required_size());

        match req {
            RequestFileTransferRequest::ResumeFile(pl, data_format_pl, file_size_pl) => {
                assert_eq!(pl.mode_of_operation, FileOperationMode::ResumeFile);
                assert_eq!(pl.file_path_and_name_length, compare_string.len() as u16);
                assert_eq!(pl.file_path_and_name, compare_string);
                assert_eq!(data_format_pl, DataFormatIdentifier::new(0, 0).unwrap());
                assert_eq!(file_size_pl.file_size_parameter_length, 2);
                assert_eq!(file_size_pl.file_size_uncompressed, file_size);
                assert_eq!(file_size_pl.file_size_compressed, file_size);
            }
            _ => panic!("Expected ResumeFile"),
        }
    }

    #[test]
    fn test_file_operation_mode() {
        use FileOperationMode::*;
        assert_eq!(AddFile, FileOperationMode::try_from(0x01).unwrap());
        assert_eq!(DeleteFile, FileOperationMode::try_from(0x02).unwrap());
        assert_eq!(ReplaceFile, FileOperationMode::try_from(0x03).unwrap());
        assert_eq!(ReadFile, FileOperationMode::try_from(0x04).unwrap());
        assert_eq!(ReadDir, FileOperationMode::try_from(0x05).unwrap());
        assert_eq!(ResumeFile, FileOperationMode::try_from(0x06).unwrap());
        assert_eq!(
            ISOSAEReserved(0x07),
            FileOperationMode::try_from(0x07).unwrap()
        );
    }
}

#[cfg(test)]
mod response_tests {

    use crate::{param_length_u32, param_length_u128};

    use super::*;

    fn get_bytes(
        mode: FileOperationMode,
        max_block_len: u32,
        data_format: u8,
        file_size: u128,
        file_position: u64,
    ) -> Vec<u8> {
        let mut bytes: Vec<u8> = Vec::new();
        bytes.push(mode.into());

        // SentDataPayload
        if mode != FileOperationMode::DeleteFile {
            let len_max_block_len = param_length_u32(max_block_len);
            bytes.write_u8(len_max_block_len).unwrap();
            let source = max_block_len.to_be_bytes();
            bytes.extend_from_slice(&source[4 - len_max_block_len as usize..]);

            let mut data_format = data_format;
            if mode == FileOperationMode::ReadDir {
                data_format = 0x00;
            }
            // DataFormatIdentifier
            bytes.write_u8(data_format).unwrap();
        }

        // File or dir size
        let num = param_length_u128(file_size);
        if mode == FileOperationMode::ReadFile {
            print!("{mode:?}");

            bytes.write_u16::<byteorder::BE>(num).unwrap();
            let source = file_size.to_be_bytes();
            // Compressed
            bytes.extend_from_slice(&source[16 - num as usize..]);
            // Uncompressed
            bytes.extend_from_slice(&source[16 - num as usize..]);
        } else if mode == FileOperationMode::ReadDir {
            bytes.write_u16::<byteorder::BE>(num).unwrap();
            let source = file_size.to_be_bytes();
            // Compressed
            bytes.extend_from_slice(&source[16 - num as usize..]);
        }

        if mode == FileOperationMode::ResumeFile {
            bytes.write_u64::<byteorder::BE>(file_position).unwrap();
        }
        bytes
    }

    #[test]
    fn response_add() {
        let bytes = get_bytes(FileOperationMode::AddFile, 0x1234, 0x00, 0x1234, 0);
        let reader = &mut &bytes[..];
        let resp = RequestFileTransferResponse::decode_single_value(reader).unwrap();
        assert!(reader.is_empty());

        let mut written_bytes = Vec::new();
        let written = resp.encode(&mut written_bytes).unwrap();
        assert_eq!(written, bytes.len());
        assert_eq!(resp.required_size(), bytes.len());

        match resp {
            RequestFileTransferResponse::AddFile(mode, sent_data, data_format) => {
                assert_eq!(mode, FileOperationMode::AddFile);
                assert_eq!(sent_data.length_format_identifier, 2);
                assert_eq!(sent_data.max_number_of_block_length, vec![0x12, 0x34]);
                assert_eq!(data_format, DataFormatIdentifier::new(0, 0).unwrap());
            }
            _ => panic!("Expected AddFile"),
        }
    }

    #[test]
    fn delete_file() {
        let bytes = get_bytes(FileOperationMode::DeleteFile, 0, 0, 0, 0);
        let reader = &mut &bytes[..];
        let resp = RequestFileTransferResponse::decode_single_value(reader).unwrap();
        assert!(reader.is_empty());

        let mut written_bytes = Vec::new();
        let written = resp.encode(&mut written_bytes).unwrap();
        assert_eq!(written, bytes.len());
        assert_eq!(resp.required_size(), bytes.len());

        match resp {
            RequestFileTransferResponse::DeleteFile(mode) => {
                assert_eq!(mode, FileOperationMode::DeleteFile);
            }
            _ => panic!("Expected DeleteFile"),
        }
    }

    #[test]
    fn replace_file() {
        let bytes = get_bytes(FileOperationMode::ReplaceFile, 0x1_1234, 0, 0, 0);
        let reader = &mut &bytes[..];
        let resp = RequestFileTransferResponse::decode_single_value(reader).unwrap();
        assert!(reader.is_empty());

        let mut written_bytes = Vec::new();
        let written = resp.encode(&mut written_bytes).unwrap();
        assert_eq!(written, bytes.len());
        assert_eq!(resp.required_size(), bytes.len());

        match resp {
            RequestFileTransferResponse::ReplaceFile(mode, sent_data, data_format) => {
                assert_eq!(mode, FileOperationMode::ReplaceFile);
                assert_eq!(sent_data.length_format_identifier, 3);
                assert_eq!(sent_data.max_number_of_block_length, vec![0x01, 0x12, 0x34]);
                assert_eq!(data_format, DataFormatIdentifier::new(0, 0).unwrap());
            }
            _ => panic!("Expected ReplaceFile"),
        }
    }

    #[test]
    fn read_file() {
        let bytes = get_bytes(FileOperationMode::ReadFile, 0x1, 0x11, 0x11_1111_1111, 0);
        let reader = &mut &bytes[..];
        let resp = RequestFileTransferResponse::decode_single_value(reader).unwrap();
        assert!(reader.is_empty());

        let mut written_bytes = Vec::new();
        let written = resp.encode(&mut written_bytes).unwrap();
        assert_eq!(written, bytes.len());
        assert_eq!(resp.required_size(), bytes.len());

        match resp {
            RequestFileTransferResponse::ReadFile(mode, sent_data, df, size) => {
                assert_eq!(mode, FileOperationMode::ReadFile);
                assert_eq!(sent_data.length_format_identifier, 1);
                assert_eq!(sent_data.max_number_of_block_length, vec![0x01]);
                assert_eq!(df, DataFormatIdentifier::new(0x01, 0x01).unwrap());
                assert_eq!(size.file_size_parameter_length, 5);
                assert_eq!(size.file_size_uncompressed, 0x11_1111_1111);
                assert_eq!(size.file_size_compressed, 0x11_1111_1111);
            }
            _ => panic!("Expected ReadFile"),
        }
    }

    #[test]
    fn read_dir() {
        let bytes = get_bytes(FileOperationMode::ReadDir, 0x1_1234, 0, 0x11_1111_1111, 0);
        let reader = &mut &bytes[..];
        let resp = RequestFileTransferResponse::decode_single_value(reader).unwrap();
        assert!(reader.is_empty());

        let mut written_bytes = Vec::new();
        let written = resp.encode(&mut written_bytes).unwrap();
        assert_eq!(written, bytes.len());
        assert_eq!(resp.required_size(), bytes.len());

        match resp {
            RequestFileTransferResponse::ReadDir(mode, sent_data, df, size) => {
                assert_eq!(mode, FileOperationMode::ReadDir);
                assert_eq!(sent_data.length_format_identifier, 3);
                assert_eq!(sent_data.max_number_of_block_length, vec![0x01, 0x12, 0x34]);
                assert_eq!(df, DataFormatIdentifier::new(0, 0).unwrap());
                assert_eq!(size.dir_info_parameter_length, 5);
                assert_eq!(size.dir_info_length, 0x11_1111_1111);
            }
            _ => panic!("Expected ReadDir"),
        }
    }

    #[test]
    fn resume_file() {
        let bytes = get_bytes(
            FileOperationMode::ResumeFile,
            0x1_1234,
            0x11,
            0x11_1111_1111,
            0x1234_5678_9ABC_DEF0,
        );
        let reader = &mut &bytes[..];
        let resp = RequestFileTransferResponse::decode_single_value(reader).unwrap();
        assert!(reader.is_empty());

        let mut written_bytes = Vec::new();
        let written = resp.encode(&mut written_bytes).unwrap();
        assert_eq!(written, bytes.len());
        assert_eq!(resp.required_size(), bytes.len());

        match resp {
            RequestFileTransferResponse::ResumeFile(mode, sent_data, df, pos) => {
                assert_eq!(mode, FileOperationMode::ResumeFile);
                assert_eq!(sent_data.length_format_identifier, 3);
                assert_eq!(sent_data.max_number_of_block_length, vec![0x01, 0x12, 0x34]);
                assert_eq!(df, DataFormatIdentifier::new(1, 1).unwrap());
                assert_eq!(pos.file_position, 0x1234_5678_9ABC_DEF0);
            }
            _ => panic!("Expected ResumeFile"),
        }
    }
}