ewf-image 0.1.1

Pure-Rust library for reading and writing EWF/E01 forensic disk images.
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
use crate::types::{
    SingleFileAttribute, SingleFileEntry, SingleFileEntryType, SingleFileExtent,
    SingleFilePermission, SingleFilePermissionGroup, SingleFileSource, SingleFileSubject,
    SingleFilesInfo,
};
use crate::{EwfError, Result};

/// Path separator used by EWF2 logical single-file catalogs.
///
/// Paths are represented with tab-separated entry names. A leading separator
/// refers to the root entry.
pub const SINGLE_FILE_PATH_SEPARATOR: char = '\t';
const EXTENDED_ATTRIBUTES_HEADER: &[u8; 37] = &[
    0x00, 0x00, 0x00, 0x00, 0x01, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x41, 0x00, 0x74,
    0x00, 0x74, 0x00, 0x72, 0x00, 0x69, 0x00, 0x62, 0x00, 0x75, 0x00, 0x74, 0x00, 0x65, 0x00, 0x73,
    0x00, 0x00, 0x00, 0x00, 0x00,
];

impl SingleFilesInfo {
    /// Returns the catalog entry at a single-file path.
    ///
    /// # Errors
    ///
    /// Returns an error if the path contains an empty entry name.
    pub fn entry_by_path(&self, path: &str) -> Result<Option<&SingleFileEntry>> {
        self.root.child_by_path(path)
    }

    /// Returns a source record by its source identifier.
    pub fn source_by_identifier(&self, identifier: i32) -> Option<&SingleFileSource> {
        self.sources
            .iter()
            .find(|source| source.identifier == Some(identifier))
    }

    /// Returns a source record by its source table index.
    pub fn source_by_index(&self, index: i32) -> Option<&SingleFileSource> {
        usize::try_from(index)
            .ok()
            .and_then(|index| self.sources.get(index))
    }

    /// Returns the source record associated with a catalog entry.
    pub fn source_for_entry(&self, entry: &SingleFileEntry) -> Option<&SingleFileSource> {
        let identifier = entry.source_identifier?;
        if identifier < 1 {
            return None;
        }
        self.source_by_index(identifier)
    }

    /// Returns a subject record by its subject identifier.
    pub fn subject_by_identifier(&self, identifier: u32) -> Option<&SingleFileSubject> {
        self.subjects
            .iter()
            .find(|subject| subject.identifier == Some(identifier))
    }

    /// Returns the subject record associated with a catalog entry.
    pub fn subject_for_entry(&self, entry: &SingleFileEntry) -> Option<&SingleFileSubject> {
        self.subject_by_identifier(entry.subject_identifier?)
    }

    /// Returns the number of permission groups.
    pub fn number_of_permission_groups(&self) -> usize {
        self.permission_groups.len()
    }

    /// Returns a permission group by its table index.
    pub fn permission_group_by_index(&self, index: i32) -> Option<&SingleFilePermissionGroup> {
        usize::try_from(index)
            .ok()
            .and_then(|index| self.permission_groups.get(index))
    }

    /// Returns the permission group associated with a catalog entry.
    pub fn permission_group_for_entry(
        &self,
        entry: &SingleFileEntry,
    ) -> Option<&SingleFilePermissionGroup> {
        self.permission_group_by_index(entry.permission_group_index?)
    }

    /// Returns access-control entries associated with a catalog entry.
    pub fn access_control_entries_for_entry(
        &self,
        entry: &SingleFileEntry,
    ) -> &[SingleFilePermission] {
        self.permission_group_for_entry(entry)
            .map_or(&[], |group| group.permissions.as_slice())
    }

    /// Returns the number of access-control entries for a catalog entry.
    pub fn number_of_access_control_entries_for_entry(&self, entry: &SingleFileEntry) -> usize {
        self.access_control_entries_for_entry(entry).len()
    }

    /// Returns one access-control entry for a catalog entry by index.
    pub fn access_control_entry_for_entry(
        &self,
        entry: &SingleFileEntry,
        index: usize,
    ) -> Option<&SingleFilePermission> {
        self.access_control_entries_for_entry(entry).get(index)
    }
}

impl SingleFileSource {
    /// Returns the source identifier.
    pub fn identifier(&self) -> Option<i32> {
        self.identifier
    }

    /// Returns the source name.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Returns the evidence number associated with the source.
    pub fn evidence_number(&self) -> Option<&str> {
        self.evidence_number.as_deref()
    }

    /// Returns the source location.
    pub fn location(&self) -> Option<&str> {
        self.location.as_deref()
    }

    /// Returns the source device GUID.
    pub fn device_guid(&self) -> Option<&str> {
        self.device_guid.as_deref()
    }

    /// Returns the primary source device GUID.
    pub fn primary_device_guid(&self) -> Option<&str> {
        self.primary_device_guid.as_deref()
    }

    /// Returns the source manufacturer.
    pub fn manufacturer(&self) -> Option<&str> {
        self.manufacturer.as_deref()
    }

    /// Returns the source model.
    pub fn model(&self) -> Option<&str> {
        self.model.as_deref()
    }

    /// Returns the source serial number.
    pub fn serial_number(&self) -> Option<&str> {
        self.serial_number.as_deref()
    }

    /// Returns the source domain.
    pub fn domain(&self) -> Option<&str> {
        self.domain.as_deref()
    }

    /// Returns the source IP address.
    pub fn ip_address(&self) -> Option<&str> {
        self.ip_address.as_deref()
    }

    /// Returns the source MAC address.
    pub fn mac_address(&self) -> Option<&str> {
        self.mac_address.as_deref()
    }

    /// Returns the source size in bytes.
    pub fn size(&self) -> Option<u64> {
        self.size
    }

    /// Returns the source drive type code.
    pub fn drive_type(&self) -> Option<char> {
        self.drive_type
    }

    /// Returns the source logical offset.
    pub fn logical_offset(&self) -> Option<i64> {
        self.logical_offset
    }

    /// Returns the source physical offset.
    pub fn physical_offset(&self) -> Option<i64> {
        self.physical_offset
    }

    /// Returns the source acquisition timestamp.
    pub fn acquisition_time(&self) -> Option<i64> {
        self.acquisition_time
    }

    /// Returns the source MD5 hash string.
    pub fn md5_hash(&self) -> Option<&str> {
        self.md5.as_deref()
    }

    /// Returns the source SHA1 hash string.
    pub fn sha1_hash(&self) -> Option<&str> {
        self.sha1.as_deref()
    }
}

impl SingleFileEntry {
    /// Returns the entry identifier.
    pub fn identifier(&self) -> Option<u64> {
        self.identifier
    }

    /// Returns the entry type.
    pub fn entry_type(&self) -> Option<SingleFileEntryType> {
        self.file_entry_type
    }

    /// Returns the raw entry flags.
    pub fn flags(&self) -> Option<u32> {
        self.flags
    }

    /// Returns the entry GUID.
    pub fn guid(&self) -> Option<&str> {
        self.guid.as_deref()
    }

    /// Returns the logical media offset for entry data.
    pub fn media_data_offset(&self) -> Option<i64> {
        self.logical_offset
    }

    /// Returns the entry data size in bytes.
    pub fn media_data_size(&self) -> Option<u64> {
        self.size
    }

    /// Returns the physical source offset for entry data.
    pub fn physical_offset(&self) -> Option<i64> {
        self.physical_offset
    }

    /// Returns the duplicate-data logical media offset.
    pub fn duplicate_media_data_offset(&self) -> Option<i64> {
        self.duplicate_data_offset
    }

    /// Returns the associated source identifier.
    pub fn source_identifier(&self) -> Option<i32> {
        self.source_identifier
    }

    /// Returns the associated subject identifier.
    pub fn subject_identifier(&self) -> Option<u32> {
        self.subject_identifier
    }

    /// Returns the associated permission group index.
    pub fn permission_group_index(&self) -> Option<i32> {
        self.permission_group_index
    }

    /// Returns the raw record type.
    pub fn record_type(&self) -> Option<u32> {
        self.record_type
    }

    /// Returns the entry name.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Returns the short entry name.
    pub fn short_name(&self) -> Option<&str> {
        self.short_name.as_deref()
    }

    /// Returns the entry size in bytes.
    pub fn size(&self) -> Option<u64> {
        self.size
    }

    /// Returns the creation timestamp.
    pub fn creation_time(&self) -> Option<i64> {
        self.creation_time
    }

    /// Returns the modification timestamp.
    pub fn modification_time(&self) -> Option<i64> {
        self.modification_time
    }

    /// Returns the access timestamp.
    pub fn access_time(&self) -> Option<i64> {
        self.access_time
    }

    /// Returns the entry metadata modification timestamp.
    pub fn entry_modification_time(&self) -> Option<i64> {
        self.entry_modification_time
    }

    /// Returns the deletion timestamp.
    pub fn deletion_time(&self) -> Option<i64> {
        self.deletion_time
    }

    /// Returns the entry MD5 hash string.
    pub fn md5_hash(&self) -> Option<&str> {
        self.md5.as_deref()
    }

    /// Returns the entry SHA1 hash string.
    pub fn sha1_hash(&self) -> Option<&str> {
        self.sha1.as_deref()
    }

    /// Returns the number of child entries.
    pub fn number_of_sub_file_entries(&self) -> usize {
        self.children.len()
    }

    /// Returns a child entry by index.
    pub fn sub_file_entry(&self, index: usize) -> Option<&SingleFileEntry> {
        self.children.get(index)
    }

    /// Returns a child entry by name.
    pub fn sub_file_entry_by_name(&self, name: &str) -> Option<&SingleFileEntry> {
        self.child_by_name(name)
    }

    /// Returns a descendant entry by single-file path.
    ///
    /// # Errors
    ///
    /// Returns an error if the path contains an empty entry name.
    pub fn sub_file_entry_by_path(&self, path: &str) -> Result<Option<&SingleFileEntry>> {
        self.child_by_path(path)
    }

    /// Returns the number of data extents.
    pub fn number_of_extents(&self) -> usize {
        self.extents.len()
    }

    /// Returns a data extent by index.
    pub fn extent(&self, index: usize) -> Option<&SingleFileExtent> {
        self.extents.get(index)
    }

    /// Returns the number of extended attributes.
    pub fn number_of_attributes(&self) -> usize {
        self.attributes.len()
    }

    /// Returns an extended attribute by index.
    pub fn attribute(&self, index: usize) -> Option<&SingleFileAttribute> {
        self.attributes.get(index)
    }

    /// Returns a direct child entry by name.
    pub fn child_by_name(&self, name: &str) -> Option<&SingleFileEntry> {
        self.children
            .iter()
            .find(|child| child.name.as_deref() == Some(name))
    }

    /// Returns a descendant entry by single-file path.
    ///
    /// # Errors
    ///
    /// Returns an error if the path contains an empty entry name.
    pub fn child_by_path(&self, path: &str) -> Result<Option<&SingleFileEntry>> {
        entry_by_path(self, path)
    }
}

impl SingleFilePermission {
    /// Returns the permission name.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Returns the permission identifier.
    pub fn identifier(&self) -> Option<&str> {
        self.identifier.as_deref()
    }

    /// Returns the permission property type.
    pub fn property_type(&self) -> Option<u32> {
        self.property_type
    }

    /// Returns the access mask.
    pub fn access_mask(&self) -> Option<u32> {
        self.access_mask
    }

    /// Returns the ACE flags.
    pub fn flags(&self) -> Option<u32> {
        self.ace_flags
    }
}

impl SingleFilePermissionGroup {
    /// Returns the group name.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Returns the group identifier.
    pub fn identifier(&self) -> Option<&str> {
        self.identifier.as_deref()
    }

    /// Returns the group property type.
    pub fn property_type(&self) -> Option<u32> {
        self.property_type
    }

    /// Returns the group access mask.
    pub fn access_mask(&self) -> Option<u32> {
        self.access_mask
    }

    /// Returns the group ACE flags.
    pub fn flags(&self) -> Option<u32> {
        self.ace_flags
    }

    /// Returns the number of permissions in the group.
    pub fn number_of_entries(&self) -> usize {
        self.permissions.len()
    }

    /// Returns a permission in the group by table index.
    pub fn entry_by_index(&self, index: i32) -> Option<&SingleFilePermission> {
        usize::try_from(index)
            .ok()
            .and_then(|index| self.permissions.get(index))
    }
}

impl SingleFileAttribute {
    /// Returns the attribute name.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Returns the attribute value.
    pub fn value(&self) -> Option<&str> {
        self.value.as_deref()
    }
}

pub(crate) fn parse_ewf2_single_files_data(data: &[u8]) -> Result<SingleFilesInfo> {
    let lines = decode_utf16le_lines(data)?;
    if lines.first().map(String::as_str) != Some("5") {
        return Err(EwfError::Malformed(
            "EWF2 single files data has unsupported category count".into(),
        ));
    }

    let mut category_index = 1;

    let (data_size, next_category_index) = parse_record_category(&lines, category_index)?;
    category_index = next_category_index;
    let (permission_groups, next_category_index) =
        parse_permission_groups_category(&lines, category_index)?;
    category_index = next_category_index;
    let (sources, next_category_index) = parse_sources_category(&lines, category_index)?;
    category_index = next_category_index;
    let (subjects, entry_index) = parse_subjects_category(&lines, category_index)?;

    require_category_at(&lines, entry_index, "entry", "entry category")?;
    let types_line_index = entry_index
        .checked_add(2)
        .ok_or_else(|| EwfError::Malformed("EWF2 single files entry index overflow".into()))?;
    let mut cursor = entry_index
        .checked_add(3)
        .ok_or_else(|| EwfError::Malformed("EWF2 single files entry index overflow".into()))?;
    if types_line_index >= lines.len() {
        return Err(EwfError::Malformed(
            "EWF2 single files entry category is truncated".into(),
        ));
    }

    parse_category_entry_count(&lines[entry_index + 1], "EWF2 single files entry count")?;
    let types = parse_type_line(
        &lines[types_line_index],
        "EWF2 single files entry category types",
    )?;

    let data_size = data_size.unwrap_or(
        u64::try_from(data.len())
            .map_err(|_| EwfError::Malformed("single files data size overflow".into()))?,
    );
    let root = parse_entry(&lines, &types, &mut cursor)?;
    require_empty_category_terminator(
        &lines,
        cursor,
        "EWF2 single files entry category terminator",
    )?;
    Ok(SingleFilesInfo {
        data_size,
        root,
        sources,
        subjects,
        permission_groups,
    })
}

fn entry_by_path<'a>(
    mut entry: &'a SingleFileEntry,
    path: &str,
) -> Result<Option<&'a SingleFileEntry>> {
    let mut rest = path
        .strip_prefix(SINGLE_FILE_PATH_SEPARATOR)
        .unwrap_or(path);
    if rest.is_empty() {
        return Ok(Some(entry));
    }

    while !rest.is_empty() {
        let (segment, next_rest) = match rest.find([SINGLE_FILE_PATH_SEPARATOR, '\0']) {
            Some(separator_index) => {
                let separator_size = rest[separator_index..]
                    .chars()
                    .next()
                    .expect("separator index points to a character")
                    .len_utf8();
                (
                    &rest[..separator_index],
                    &rest[separator_index + separator_size..],
                )
            }
            None => (rest, ""),
        };
        if segment.is_empty() {
            return Err(EwfError::Malformed(
                "single file path is missing entry name".into(),
            ));
        }

        entry = match entry.child_by_name(segment) {
            Some(child) => child,
            None => return Ok(None),
        };
        rest = next_rest;
    }

    Ok(Some(entry))
}

fn parse_sources_category(
    lines: &[String],
    category_index: usize,
) -> Result<(Vec<SingleFileSource>, usize)> {
    require_category_at(lines, category_index, "srce", "source category")?;
    let (types, entry_count, mut cursor) = parse_category_header(lines, category_index, "srce")?;

    let root = parse_source_row(&types, get_line(lines, cursor, "EWF2 source root")?)?;
    cursor += 1;
    let mut sources = Vec::with_capacity(entry_count.saturating_add(1));
    sources.push(root);

    for source_index in 0..entry_count {
        let child_count = parse_child_entry_count(
            get_line(lines, cursor, "EWF2 source child count")?,
            "EWF2 source child count",
        )?;
        if child_count != 0 {
            return Err(EwfError::Malformed(
                "EWF2 source entries cannot have children".into(),
            ));
        }
        cursor += 1;

        let source = parse_source_row(&types, get_line(lines, cursor, "EWF2 source row")?)?;
        let expected_identifier = source_index
            .checked_add(1)
            .and_then(|identifier| i32::try_from(identifier).ok())
            .ok_or_else(|| EwfError::Malformed("EWF2 source identifier index overflow".into()))?;
        if source.identifier != Some(expected_identifier) {
            return Err(EwfError::Malformed(
                "EWF2 source identifier does not match source index".into(),
            ));
        }
        sources.push(source);
        cursor += 1;
    }
    require_empty_category_terminator(
        lines,
        cursor,
        "EWF2 single files source category terminator",
    )?;
    Ok((
        sources,
        next_category_index(cursor, "EWF2 source category terminator")?,
    ))
}

fn parse_subjects_category(
    lines: &[String],
    category_index: usize,
) -> Result<(Vec<SingleFileSubject>, usize)> {
    require_category_at(lines, category_index, "sub", "subject category")?;
    let (types, entry_count, mut cursor) = parse_category_header(lines, category_index, "sub")?;

    let root = parse_subject_row(&types, get_line(lines, cursor, "EWF2 subject root")?)?;
    cursor += 1;
    let mut subjects = Vec::with_capacity(entry_count.saturating_add(1));
    subjects.push(root);

    for _ in 0..entry_count {
        let child_count = parse_child_entry_count(
            get_line(lines, cursor, "EWF2 subject child count")?,
            "EWF2 subject child count",
        )?;
        if child_count != 0 {
            return Err(EwfError::Malformed(
                "EWF2 subject entries cannot have children".into(),
            ));
        }
        cursor += 1;

        let subject = parse_subject_row(&types, get_line(lines, cursor, "EWF2 subject row")?)?;
        subjects.push(subject);
        cursor += 1;
    }
    require_empty_category_terminator(
        lines,
        cursor,
        "EWF2 single files subject category terminator",
    )?;
    Ok((
        subjects,
        next_category_index(cursor, "EWF2 subject category terminator")?,
    ))
}

fn parse_permission_groups_category(
    lines: &[String],
    category_index: usize,
) -> Result<(Vec<SingleFilePermissionGroup>, usize)> {
    require_category_at(lines, category_index, "perm", "permission category")?;
    let (types, entry_count, mut cursor) = parse_category_header(lines, category_index, "perm")?;

    let root_permission = parse_permission_row(
        &types,
        get_line(lines, cursor, "EWF2 permission category root")?,
    )?;
    require_permission_group_type(&root_permission, "EWF2 permission category root")?;
    cursor += 1;
    let mut groups = Vec::with_capacity(entry_count);

    for _ in 0..entry_count {
        let permission_count = parse_child_entry_count(
            get_line(lines, cursor, "EWF2 permission group child count")?,
            "EWF2 permission group child count",
        )?;
        cursor += 1;

        let group_permission = parse_permission_row(
            &types,
            get_line(lines, cursor, "EWF2 permission group row")?,
        )?;
        require_permission_group_type(&group_permission, "EWF2 permission group row")?;
        cursor += 1;
        let mut group = permission_group_from_permission(group_permission, permission_count);

        for _ in 0..permission_count {
            let child_count = parse_child_entry_count(
                get_line(lines, cursor, "EWF2 permission child count")?,
                "EWF2 permission child count",
            )?;
            if child_count != 0 {
                return Err(EwfError::Malformed(
                    "EWF2 permission entries cannot have children".into(),
                ));
            }
            cursor += 1;

            let permission =
                parse_permission_row(&types, get_line(lines, cursor, "EWF2 permission row")?)?;
            group.permissions.push(permission);
            cursor += 1;
        }
        groups.push(group);
    }
    require_empty_category_terminator(
        lines,
        cursor,
        "EWF2 single files permission category terminator",
    )?;
    Ok((
        groups,
        next_category_index(cursor, "EWF2 permission category terminator")?,
    ))
}

fn require_category_at(lines: &[String], index: usize, name: &str, label: &str) -> Result<()> {
    let line = get_line(lines, index, &format!("EWF2 single files {label}"))?;
    if line != name {
        return Err(EwfError::Malformed(format!(
            "EWF2 single files {label} is missing or out of order"
        )));
    }
    Ok(())
}

fn next_category_index(index: usize, label: &str) -> Result<usize> {
    index
        .checked_add(1)
        .ok_or_else(|| EwfError::Malformed(format!("{label} index overflow")))
}

fn parse_record_category(lines: &[String], category_index: usize) -> Result<(Option<u64>, usize)> {
    require_category_at(lines, category_index, "rec", "record category")?;
    let types_line_index = category_index
        .checked_add(1)
        .ok_or_else(|| EwfError::Malformed("EWF2 record category index overflow".into()))?;
    let values_line_index = category_index
        .checked_add(2)
        .ok_or_else(|| EwfError::Malformed("EWF2 record category index overflow".into()))?;
    let types = parse_type_line(
        get_line(lines, types_line_index, "EWF2 record category types")?,
        "EWF2 record category types",
    )?;
    let values: Vec<&str> = get_line(lines, values_line_index, "EWF2 record category values")?
        .split('\t')
        .collect();
    let terminator_index = category_index
        .checked_add(3)
        .ok_or_else(|| EwfError::Malformed("EWF2 record category index overflow".into()))?;

    require_empty_category_terminator(
        lines,
        terminator_index,
        "EWF2 single files record category terminator",
    )?;
    let next_category_index =
        next_category_index(terminator_index, "EWF2 record category terminator")?;

    for (index, value_type) in types.iter().enumerate() {
        if *value_type != "tb" {
            continue;
        }
        let Some(value) = values.get(index).copied().filter(|value| !value.is_empty()) else {
            return Ok((None, next_category_index));
        };
        return Ok((
            parse_u64(value, "record data size").map(Some)?,
            next_category_index,
        ));
    }
    Ok((None, next_category_index))
}

fn parse_category_header<'a>(
    lines: &'a [String],
    category_index: usize,
    label: &str,
) -> Result<(Vec<&'a str>, usize, usize)> {
    let count_line_index = category_index
        .checked_add(1)
        .ok_or_else(|| EwfError::Malformed(format!("EWF2 {label} category index overflow")))?;
    let types_line_index = category_index
        .checked_add(2)
        .ok_or_else(|| EwfError::Malformed(format!("EWF2 {label} category index overflow")))?;
    let copy_count_line_index = category_index
        .checked_add(3)
        .ok_or_else(|| EwfError::Malformed(format!("EWF2 {label} category index overflow")))?;
    let root_line_index = category_index
        .checked_add(4)
        .ok_or_else(|| EwfError::Malformed(format!("EWF2 {label} category index overflow")))?;

    let entry_count = parse_category_entry_count(
        get_line(lines, count_line_index, "EWF2 category count")?,
        "EWF2 category count",
    )?;
    let types = parse_type_line(
        get_line(lines, types_line_index, "EWF2 category types")?,
        &format!("EWF2 {label} category types"),
    )?;
    let copy_entry_count = parse_child_entry_count(
        get_line(lines, copy_count_line_index, "EWF2 category copy count")?,
        "EWF2 category copy count",
    )?;
    if copy_entry_count != entry_count {
        return Err(EwfError::Malformed(format!(
            "EWF2 {label} category entry count mismatch"
        )));
    }
    Ok((types, entry_count, root_line_index))
}

fn parse_source_row(types: &[&str], row: &str) -> Result<SingleFileSource> {
    let values = split_exact_typed_values(types, row, "EWF2 source row")?;
    let mut source = SingleFileSource::default();
    for (value_type, value) in types.iter().zip(values.iter()) {
        if value.is_empty() {
            continue;
        }
        match *value_type {
            "ah" => source.md5 = parse_serialized_base16_string(value, "source MD5 hash")?,
            "aq" => source.acquisition_time = Some(parse_i64(value, "source acquisition time")?),
            "do" => source.domain = Some((*value).to_owned()),
            "dt" => source.drive_type = Some(parse_single_char(value, "source drive type")?),
            "ev" => source.evidence_number = Some((*value).to_owned()),
            "gu" => {
                source.device_guid = parse_serialized_base16_string(value, "source device GUID")?;
            }
            "id" => source.identifier = Some(parse_non_negative_i32(value, "source identifier")?),
            "ip" => source.ip_address = Some((*value).to_owned()),
            "lo" => source.logical_offset = Some(parse_i64(value, "source logical offset")?),
            "loc" => source.location = Some((*value).to_owned()),
            "ma" => {
                source.mac_address = parse_serialized_base16_string(value, "source MAC address")?;
            }
            "mfr" => source.manufacturer = Some((*value).to_owned()),
            "mo" => source.model = Some((*value).to_owned()),
            "n" => source.name = Some((*value).to_owned()),
            "pgu" => {
                source.primary_device_guid =
                    parse_serialized_base16_string(value, "source primary device GUID")?;
            }
            "po" => source.physical_offset = Some(parse_i64(value, "source physical offset")?),
            "se" => source.serial_number = Some((*value).to_owned()),
            "sh" => source.sha1 = parse_serialized_base16_string(value, "source SHA1 hash")?,
            "tb" => source.size = Some(parse_u64(value, "source size")?),
            _ => {}
        }
    }
    Ok(source)
}

fn parse_subject_row(types: &[&str], row: &str) -> Result<SingleFileSubject> {
    let values = split_exact_typed_values(types, row, "EWF2 subject row")?;
    let mut subject = SingleFileSubject::default();
    for (value_type, value) in types.iter().zip(values.iter()) {
        if value.is_empty() {
            continue;
        }
        match *value_type {
            "id" => subject.identifier = Some(parse_u32(value, "subject identifier")?),
            "n" => subject.name = Some((*value).to_owned()),
            _ => {}
        }
    }
    Ok(subject)
}

fn parse_permission_row(types: &[&str], row: &str) -> Result<SingleFilePermission> {
    let values = split_exact_typed_values(types, row, "EWF2 permission row")?;
    let mut permission = SingleFilePermission::default();
    for (value_type, value) in types.iter().zip(values.iter()) {
        if value.is_empty() {
            continue;
        }
        match *value_type {
            "n" => permission.name = Some((*value).to_owned()),
            "nta" => permission.access_mask = Some(parse_u32(value, "permission access mask")?),
            "nti" => permission.ace_flags = Some(parse_u32(value, "permission ACE flags")?),
            "pr" | "pt" => {
                permission.property_type = Some(parse_u32(value, "permission property type")?);
            }
            "s" => permission.identifier = Some((*value).to_owned()),
            _ => {}
        }
    }
    Ok(permission)
}

fn require_permission_group_type(permission: &SingleFilePermission, label: &str) -> Result<()> {
    if permission.property_type != Some(10) {
        return Err(EwfError::Malformed(format!(
            "{label} has unsupported permission group type"
        )));
    }
    Ok(())
}

fn permission_group_from_permission(
    permission: SingleFilePermission,
    permission_count: usize,
) -> SingleFilePermissionGroup {
    SingleFilePermissionGroup {
        name: permission.name,
        identifier: permission.identifier,
        property_type: permission.property_type,
        access_mask: permission.access_mask,
        ace_flags: permission.ace_flags,
        permissions: Vec::with_capacity(permission_count),
    }
}

fn split_typed_values<'a>(types: &[&str], row: &'a str) -> Vec<&'a str> {
    let mut values: Vec<&str> = row.split('\t').collect();
    values.truncate(types.len());
    values.resize(types.len(), "");
    values
}

fn split_exact_typed_values<'a>(types: &[&str], row: &'a str, label: &str) -> Result<Vec<&'a str>> {
    let values: Vec<&str> = row.split('\t').collect();
    if values.len() != types.len() {
        return Err(EwfError::Malformed(format!(
            "{label} value count does not match type count"
        )));
    }
    Ok(values)
}

fn parse_type_line<'a>(line: &'a str, label: &str) -> Result<Vec<&'a str>> {
    let types: Vec<&str> = line.split('\t').collect();
    if types.is_empty() || types.iter().any(|value_type| value_type.is_empty()) {
        return Err(EwfError::Malformed(format!("{label} has empty type")));
    }
    Ok(types)
}

fn parse_category_entry_count(line: &str, label: &str) -> Result<usize> {
    let (first, second) = parse_number_pair(line, label)?;
    if second != 1 {
        return Err(EwfError::Malformed(format!(
            "{label} has unsupported category count shape"
        )));
    }
    usize::try_from(first).map_err(|_| EwfError::Malformed(format!("{label} does not fit usize")))
}

fn parse_child_entry_count(line: &str, label: &str) -> Result<usize> {
    let (first, second) = parse_number_pair(line, label)?;
    if first != 0 {
        return Err(EwfError::Malformed(format!(
            "{label} has unsupported child count shape"
        )));
    }
    Ok(second)
}

fn parse_file_entry_child_count(line: &str, label: &str) -> Result<usize> {
    let (parent_value, child_count) = parse_number_pair(line, label)?;
    if parent_value != 0 && parent_value != 26 {
        return Err(EwfError::Malformed(format!(
            "{label} has unsupported parent value"
        )));
    }
    Ok(child_count)
}

fn get_line<'a>(lines: &'a [String], index: usize, label: &str) -> Result<&'a str> {
    lines
        .get(index)
        .map(String::as_str)
        .ok_or_else(|| EwfError::Malformed(format!("{label} is truncated")))
}

fn require_empty_category_terminator(lines: &[String], cursor: usize, label: &str) -> Result<()> {
    if !get_line(lines, cursor, label)?.is_empty() {
        return Err(EwfError::Malformed(format!("{label} is not empty")));
    }
    Ok(())
}

fn parse_single_char(value: &str, label: &str) -> Result<char> {
    let mut characters = value.chars();
    let character = characters
        .next()
        .ok_or_else(|| EwfError::Malformed(format!("{label} is empty")))?;
    if characters.next().is_some() {
        return Err(EwfError::Malformed(format!(
            "{label} has more than one character"
        )));
    }
    Ok(character)
}

fn decode_utf16le_lines(data: &[u8]) -> Result<Vec<String>> {
    if !data.len().is_multiple_of(2) {
        return Err(EwfError::Malformed(
            "EWF2 single files data has odd UTF-16 size".into(),
        ));
    }

    let units: Vec<u16> = data
        .chunks_exact(2)
        .map(|chunk| u16::from_le_bytes(chunk.try_into().expect("chunk size checked")))
        .collect();
    let text = String::from_utf16(&units)
        .map_err(|_| EwfError::Malformed("EWF2 single files data is not valid UTF-16LE".into()))?;
    let text = text.strip_prefix('\u{feff}').unwrap_or(&text);

    Ok(text
        .split('\n')
        .map(|line| line.strip_suffix('\r').unwrap_or(line).to_owned())
        .collect())
}

fn parse_entry(lines: &[String], types: &[&str], cursor: &mut usize) -> Result<SingleFileEntry> {
    let count_line = lines
        .get(*cursor)
        .ok_or_else(|| EwfError::Malformed("EWF2 single file entry missing count".into()))?;
    let child_count =
        parse_file_entry_child_count(count_line, "EWF2 single file entry child count")?;
    *cursor = cursor
        .checked_add(1)
        .ok_or_else(|| EwfError::Malformed("EWF2 single file entry index overflow".into()))?;

    let value_line = lines
        .get(*cursor)
        .ok_or_else(|| EwfError::Malformed("EWF2 single file entry missing values".into()))?;
    let values = split_typed_values(types, value_line);
    *cursor = cursor
        .checked_add(1)
        .ok_or_else(|| EwfError::Malformed("EWF2 single file entry index overflow".into()))?;

    let mut entry = SingleFileEntry::default();
    for (value_type, value) in types.iter().zip(values.iter()) {
        apply_entry_value(&mut entry, value_type, value)?;
    }

    for _ in 0..child_count {
        let child = parse_entry(lines, types, cursor)?;
        entry.children.push(child);
    }
    Ok(entry)
}

fn apply_entry_value(entry: &mut SingleFileEntry, value_type: &str, value: &str) -> Result<()> {
    if value.is_empty() {
        return Ok(());
    }

    match value_type {
        "ac" => entry.access_time = Some(parse_i64(value, "access time")?),
        "be" => entry.extents = parse_binary_extents(value)?,
        "cid" => entry.record_type = Some(parse_u32(value, "record type")?),
        "cr" => entry.creation_time = Some(parse_i64(value, "creation time")?),
        "dl" => entry.deletion_time = Some(parse_i64(value, "deletion time")?),
        "du" => entry.duplicate_data_offset = Some(parse_i64(value, "duplicate data offset")?),
        "ea" => entry.attributes = parse_extended_attributes(value)?,
        "ha" => entry.md5 = parse_serialized_base16_string(value, "MD5 hash")?,
        "id" => entry.identifier = Some(parse_u64(value, "identifier")?),
        "lo" => entry.logical_offset = Some(parse_i64(value, "logical offset")?),
        "ls" => entry.size = Some(parse_u64(value, "file size")?),
        "mid" => entry.guid = parse_serialized_base16_string(value, "GUID")?,
        "mo" => entry.entry_modification_time = Some(parse_i64(value, "entry modification time")?),
        "n" => entry.name = Some(value.to_owned()),
        "opr" => entry.flags = Some(parse_u32(value, "entry flags")?),
        "p" => {
            entry.file_entry_type = Some(match value {
                "f" => SingleFileEntryType::File,
                "d" => SingleFileEntryType::Directory,
                _ => SingleFileEntryType::Unknown,
            });
        }
        "pm" => entry.permission_group_index = Some(parse_i32(value, "permission group index")?),
        "po" => entry.physical_offset = Some(parse_i64(value, "physical offset")?),
        "sha" => entry.sha1 = parse_serialized_base16_string(value, "SHA1 hash")?,
        "snh" => entry.short_name = Some(parse_short_name(value)?),
        "src" => {
            entry.source_identifier = Some(parse_non_negative_i32(value, "source identifier")?);
        }
        "sub" => entry.subject_identifier = Some(parse_u32(value, "subject identifier")?),
        "wr" => entry.modification_time = Some(parse_i64(value, "modification time")?),
        _ => {}
    }
    Ok(())
}

fn parse_binary_extents(value: &str) -> Result<Vec<SingleFileExtent>> {
    let mut parts = value.split(' ').filter(|part| !part.is_empty()).peekable();
    let extent_count = parts
        .next()
        .ok_or_else(|| EwfError::Malformed("EWF2 single files extents missing count".into()))
        .and_then(|part| parse_hex_usize(part, "extent count"))?;
    let mut extents = Vec::with_capacity(extent_count);

    while parts.peek().is_some() {
        let sparse = if parts.peek() == Some(&"S") {
            parts.next();
            true
        } else {
            false
        };
        let data_offset = parts
            .next()
            .ok_or_else(|| EwfError::Malformed("EWF2 single files extent missing offset".into()))
            .and_then(|part| parse_hex_u64(part, "extent offset"))?;
        let data_size = parts
            .next()
            .ok_or_else(|| EwfError::Malformed("EWF2 single files extent missing size".into()))
            .and_then(|part| parse_hex_u64(part, "extent size"))?;
        extents.push(SingleFileExtent {
            data_offset,
            data_size,
            sparse,
        });
    }

    if extents.len() != extent_count {
        return Err(EwfError::Malformed(
            "EWF2 single files extent count mismatch".into(),
        ));
    }
    Ok(extents)
}

fn parse_short_name(value: &str) -> Result<String> {
    let mut parts = value.split(' ');
    let declared_size = parts
        .next()
        .ok_or_else(|| EwfError::Malformed("short name is missing size".into()))?;
    let short_name = parts
        .next()
        .ok_or_else(|| EwfError::Malformed("short name is missing value".into()))?;
    if parts.next().is_some() {
        return Err(EwfError::Malformed(
            "short name has unsupported value count".into(),
        ));
    }
    let declared_size = parse_u64(declared_size, "short name size")?;
    let actual_size = short_name
        .len()
        .checked_add(1)
        .ok_or_else(|| EwfError::Malformed("short name size overflow".into()))?;
    let actual_size = u64::try_from(actual_size)
        .map_err(|_| EwfError::Malformed("short name size does not fit u64".into()))?;
    if declared_size != actual_size {
        return Err(EwfError::Malformed(
            "short name size does not match value size".into(),
        ));
    }
    Ok(short_name.to_owned())
}

fn parse_extended_attributes(value: &str) -> Result<Vec<SingleFileAttribute>> {
    let data = parse_hex_byte_stream(value, "extended attributes")?;
    if data.is_empty() {
        return Ok(Vec::new());
    }
    if data.len() < EXTENDED_ATTRIBUTES_HEADER.len()
        || &data[..EXTENDED_ATTRIBUTES_HEADER.len()] != EXTENDED_ATTRIBUTES_HEADER
    {
        return Err(EwfError::Malformed(
            "EWF2 single files extended attributes header is unsupported".into(),
        ));
    }

    let mut attributes = Vec::new();
    let mut offset = 0_usize;
    while offset < data.len() {
        let (attribute, read_size) = parse_extended_attribute_record(&data[offset..])?;
        offset = offset
            .checked_add(read_size)
            .ok_or_else(|| EwfError::Malformed("extended attribute offset overflow".into()))?;
        if !attribute.is_branch {
            attributes.push(SingleFileAttribute {
                name: attribute.name,
                value: attribute.value,
            });
        }
    }
    Ok(attributes)
}

struct ParsedExtendedAttribute {
    name: Option<String>,
    value: Option<String>,
    is_branch: bool,
}

fn parse_extended_attribute_record(data: &[u8]) -> Result<(ParsedExtendedAttribute, usize)> {
    if data.len() < 13 {
        return Err(EwfError::Malformed(
            "EWF2 single files extended attribute is truncated".into(),
        ));
    }

    let is_branch = data[4] != 0;
    let name_units = u32::from_le_bytes(data[5..9].try_into().expect("slice length checked"));
    let value_units = u32::from_le_bytes(data[9..13].try_into().expect("slice length checked"));
    let name_size = utf16_byte_size(name_units, "extended attribute name")?;
    let value_size = utf16_byte_size(value_units, "extended attribute value")?;
    let value_offset = 13_usize
        .checked_add(name_size)
        .ok_or_else(|| EwfError::Malformed("extended attribute value offset overflow".into()))?;
    let end_offset = value_offset
        .checked_add(value_size)
        .ok_or_else(|| EwfError::Malformed("extended attribute end offset overflow".into()))?;
    if data.len() < end_offset {
        return Err(EwfError::Malformed(
            "EWF2 single files extended attribute is truncated".into(),
        ));
    }

    let name = decode_optional_utf16le_string(&data[13..value_offset], "extended attribute name")?;
    let value = decode_optional_utf16le_string(
        &data[value_offset..end_offset],
        "extended attribute value",
    )?;

    Ok((
        ParsedExtendedAttribute {
            name,
            value,
            is_branch,
        },
        end_offset,
    ))
}

fn utf16_byte_size(units: u32, label: &str) -> Result<usize> {
    let units = usize::try_from(units)
        .map_err(|_| EwfError::Malformed(format!("{label} size does not fit usize")))?;
    units
        .checked_mul(2)
        .ok_or_else(|| EwfError::Malformed(format!("{label} size overflow")))
}

fn decode_optional_utf16le_string(data: &[u8], label: &str) -> Result<Option<String>> {
    if data.is_empty() {
        return Ok(None);
    }
    if !data.len().is_multiple_of(2) {
        return Err(EwfError::Malformed(format!("{label} has odd UTF-16 size")));
    }

    let units: Vec<u16> = data
        .chunks_exact(2)
        .map(|chunk| u16::from_le_bytes(chunk.try_into().expect("chunk size checked")))
        .collect();
    let mut text = String::from_utf16(&units)
        .map_err(|_| EwfError::Malformed(format!("{label} is not valid UTF-16LE")))?;
    if text.ends_with('\0') {
        text.pop();
    }
    if text.is_empty() {
        Ok(None)
    } else {
        Ok(Some(text))
    }
}

fn parse_hex_byte_stream(value: &str, label: &str) -> Result<Vec<u8>> {
    let hex: String = value
        .chars()
        .filter(|character| !character.is_whitespace())
        .collect();
    if !hex.len().is_multiple_of(2) {
        return Err(EwfError::Malformed(format!(
            "EWF2 single files {label} has odd hexadecimal size"
        )));
    }

    (0..hex.len())
        .step_by(2)
        .map(|index| {
            u8::from_str_radix(&hex[index..index + 2], 16).map_err(|_| {
                EwfError::Malformed(format!(
                    "invalid EWF2 single files {label} hexadecimal value"
                ))
            })
        })
        .collect()
}

fn parse_serialized_base16_string(value: &str, label: &str) -> Result<Option<String>> {
    if !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(EwfError::Malformed(format!(
            "invalid EWF2 single files {label} hexadecimal value"
        )));
    }
    if value.bytes().all(|byte| byte == b'0') {
        Ok(None)
    } else {
        Ok(Some(value.to_ascii_lowercase()))
    }
}

fn parse_number_pair(line: &str, label: &str) -> Result<(u64, usize)> {
    let mut parts = line.split('\t');
    let first = parts
        .next()
        .ok_or_else(|| EwfError::Malformed(format!("{label} is missing first value")))?;
    let second = parts
        .next()
        .ok_or_else(|| EwfError::Malformed(format!("{label} is missing second value")))?;
    if parts.next().is_some() {
        return Err(EwfError::Malformed(format!("{label} has too many values")));
    }
    let first = parse_u64(first, label)?;
    let second = parse_u64(second, label)?;
    let second = usize::try_from(second)
        .map_err(|_| EwfError::Malformed(format!("{label} does not fit usize")))?;
    Ok((first, second))
}

fn parse_hex_usize(value: &str, label: &str) -> Result<usize> {
    let value = parse_hex_u64(value, label)?;
    usize::try_from(value)
        .map_err(|_| EwfError::Malformed(format!("EWF2 single files {label} out of bounds")))
}

fn parse_hex_u64(value: &str, label: &str) -> Result<u64> {
    u64::from_str_radix(value, 16)
        .map_err(|_| EwfError::Malformed(format!("invalid EWF2 single files {label} value")))
}

fn parse_u64(value: &str, label: &str) -> Result<u64> {
    value
        .parse()
        .map_err(|_| EwfError::Malformed(format!("invalid EWF2 single files {label} value")))
}

fn parse_u32(value: &str, label: &str) -> Result<u32> {
    parse_u64(value, label).and_then(|value| {
        u32::try_from(value)
            .map_err(|_| EwfError::Malformed(format!("EWF2 single files {label} out of bounds")))
    })
}

fn parse_i64(value: &str, label: &str) -> Result<i64> {
    value
        .parse()
        .map_err(|_| EwfError::Malformed(format!("invalid EWF2 single files {label} value")))
}

fn parse_i32(value: &str, label: &str) -> Result<i32> {
    parse_i64(value, label).and_then(|value| {
        i32::try_from(value)
            .map_err(|_| EwfError::Malformed(format!("EWF2 single files {label} out of bounds")))
    })
}

fn parse_non_negative_i32(value: &str, label: &str) -> Result<i32> {
    let value = parse_i32(value, label)?;
    if value < 0 {
        return Err(EwfError::Malformed(format!(
            "EWF2 single files {label} out of bounds"
        )));
    }
    Ok(value)
}