systemless 0.70.0

High-Level Emulation for classic Macintosh applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
//! Installer VISE 3.x archive parsing and decompression.
//!
//! Classic Macintosh Installer VISE 3.5/3.6 Lite applications keep the
//! complete install tree in an `SVCT` data fork. Each catalog entry carries
//! the destination hierarchy, Finder type/creator, and compressed data and
//! resource fork locations.

use std::borrow::Cow;
use std::io::Read;

use flate2::read::DeflateDecoder;
use flate2::{Decompress, FlushDecompress, Status};

use crate::trap::types::decode_mac_roman;

const VISE_MAGIC: &[u8; 4] = b"SVCT";
const VISE_CATALOG_MAGIC: &[u8; 4] = b"CVCT";
const VISE_HEADER_LEN: usize = 44;
const VISE_CATALOG_HEADER_LEN: usize = 20;
const VISE_VERSION_35: u32 = 0x8001_0201;
const VISE_VERSION_35_LITE: u32 = 0x8001_0202;
const VISE_VERSION_36_LITE: u32 = 0x8001_0300;
const VISE_VERSION_36_FULL: u32 = 0x8001_0304;
const VISE_VERSION_EXTENDED_CATALOG: u32 = 0x8001_0307;
const VISE_VERSION_PACKED_CATALOG: u32 = 0x8001_0308;
const VISE_DIRECTORY_RECORD_LEN: usize = 78;
const VISE_FILE_RECORD_LEN: usize = 120;
const VISE_EXTENDED_CATALOG_PREFIX_LEN: usize = 80;
const VISE_EXTENDED_DIRECTORY_SUFFIX_LEN: usize = 66;
const VISE_EXTENDED_FILE_SUFFIX_LEN: usize = 62;
const VISE_PACKED_DIRECTORY_SUFFIX_LEN: usize = 70;
const VISE_PACKED_FILE_SUFFIX_LEN: usize = 66;
// The uncompressed 0x80010304 CVCT catalog adds these suffixes after each
// fixed record. Observed in the public Macintosh Myth demo installer:
// https://www.vintageapplemac.com/files/games/Myth%20Demo%20Installer.sit
const VISE_36_FULL_DIRECTORY_SUFFIX_LEN: usize = 22;
const VISE_36_FULL_FILE_SUFFIX_LEN: usize = 16;

// Installer VISE 3 archive layout and transform reference:
// ScummVM `common/compression/vise.cpp`, GPL-3.0-or-later, as of
// https://github.com/scummvm/scummvm/blob/209976fdaa3d3081ed22d82bfbae606177f21534/common/compression/vise.cpp
// The table is the inverse byte substitution used by VISE before its raw
// DEFLATE stream is decoded.
const VISE_DEOBFUSCATION_TABLE: [u8; 256] = [
    0x6a, 0xb7, 0x36, 0xec, 0x15, 0xd9, 0xc8, 0x73, 0xe8, 0x38, 0x9a, 0xdf, 0x21, 0x25, 0xd0, 0xcc,
    0xfd, 0xdc, 0x16, 0xd7, 0xe3, 0x43, 0x05, 0xc5, 0x8f, 0x48, 0xda, 0xf2, 0x3f, 0x10, 0x23, 0x6c,
    0x77, 0x7c, 0xf9, 0xa0, 0xa3, 0xe9, 0xed, 0x46, 0x8b, 0xd8, 0xac, 0x54, 0xce, 0x2d, 0x19, 0x5e,
    0x6d, 0x7d, 0x87, 0x5d, 0xfa, 0x5b, 0x9b, 0xe0, 0xc7, 0xee, 0x9f, 0x52, 0xa9, 0xb9, 0x0a, 0xd1,
    0xfe, 0x78, 0x76, 0x4a, 0x3d, 0x44, 0x5a, 0x96, 0x90, 0x1f, 0x26, 0x9d, 0x58, 0x1b, 0x8e, 0x57,
    0x59, 0xc3, 0x0b, 0x6b, 0xfc, 0x1d, 0xe6, 0xa2, 0x7f, 0x92, 0x4f, 0x40, 0xb4, 0x06, 0x72, 0x4d,
    0xf4, 0x34, 0xaa, 0xd2, 0x49, 0xad, 0xef, 0x22, 0x1a, 0xb5, 0xba, 0xbf, 0x29, 0x68, 0x89, 0x93,
    0x3e, 0x32, 0x04, 0xf5, 0xde, 0xe1, 0x6f, 0xfb, 0x67, 0xe4, 0x7e, 0x08, 0xaf, 0xf0, 0xab, 0x41,
    0x82, 0xea, 0x50, 0x0f, 0x2a, 0xc6, 0x35, 0xb3, 0xa8, 0xca, 0xe5, 0x4c, 0x45, 0x8a, 0x97, 0xae,
    0xd6, 0x66, 0x27, 0x53, 0xc9, 0x1c, 0x3c, 0x03, 0x99, 0xc1, 0x09, 0x2e, 0x69, 0x37, 0x8d, 0x2f,
    0x60, 0xc2, 0xa6, 0x18, 0x4e, 0x7a, 0xb8, 0xcf, 0xa7, 0x3a, 0x17, 0xd5, 0x9e, 0xf1, 0x84, 0x51,
    0x0d, 0xa4, 0x64, 0xc4, 0x1e, 0xb1, 0x30, 0x98, 0xbb, 0x79, 0x01, 0xf6, 0x62, 0x0e, 0xb2, 0x63,
    0x91, 0xcb, 0xff, 0x80, 0x71, 0xe7, 0xd4, 0x00, 0xdb, 0x75, 0x2c, 0xbd, 0x39, 0x33, 0x94, 0xbc,
    0x8c, 0x3b, 0xb6, 0x20, 0x85, 0x24, 0x88, 0x2b, 0x70, 0x83, 0x6e, 0x7b, 0x9c, 0xbe, 0x14, 0x47,
    0x65, 0x4b, 0x56, 0x81, 0xf8, 0x12, 0x11, 0x28, 0xeb, 0x55, 0x74, 0xa1, 0x31, 0xf7, 0xb0, 0x13,
    0x86, 0xdd, 0x5f, 0x42, 0xd3, 0x02, 0x61, 0x95, 0x0c, 0x5c, 0xa5, 0xcd, 0xc0, 0x07, 0xe2, 0xf3,
];

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ViseArchive<'a> {
    pub dirs: Vec<String>,
    pub entries: Vec<ViseEntry<'a>>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ViseEntry<'a> {
    pub path: String,
    pub file_type: [u8; 4],
    pub creator: [u8; 4],
    pub external: bool,
    pub data_packed: &'a [u8],
    pub rsrc_packed: &'a [u8],
    pub data_packed_offset: usize,
    pub rsrc_packed_offset: usize,
    pub unpacked_offset: usize,
    pub data_unpacked_offset: usize,
    pub rsrc_unpacked_offset: usize,
    pub data_unpacked_len: usize,
    pub rsrc_unpacked_len: usize,
}

#[derive(Clone, Debug)]
struct ViseDirectory {
    path: String,
}

pub fn parse_vise(data: &[u8]) -> Option<Result<ViseArchive<'_>, String>> {
    data.starts_with(VISE_MAGIC)
        .then(|| parse_vise_result(data))
}

pub(crate) fn continuation_bytes(data: &[u8]) -> Option<&[u8]> {
    let header = data.get(..VISE_HEADER_LEN)?;
    (header.starts_with(VISE_MAGIC) && read_u32(header, 36, "catalog offset").ok()? == 0)
        .then(|| &data[VISE_HEADER_LEN..])
}

pub(crate) fn join_segments(primary: &[u8], continuations: &[&[u8]]) -> Result<Vec<u8>, String> {
    let header = range(primary, 0, VISE_HEADER_LEN, "primary header")?;
    if !header.starts_with(VISE_MAGIC) {
        return Err("primary segment is missing the SVCT signature".to_string());
    }
    let version = read_u32(header, 16, "archive version")?;
    let catalog_offset = read_u32(header, 36, "catalog offset")? as usize;
    let mut continuation_payloads = Vec::with_capacity(continuations.len());
    for (index, continuation) in continuations.iter().enumerate() {
        let payload = continuation_bytes(continuation)
            .ok_or_else(|| format!("VISE continuation segment {} has a catalog", index + 2))?;
        continuation_payloads.push(payload);
    }

    let mut patched = primary.to_vec();
    let catalog = range(
        &patched,
        catalog_offset,
        VISE_CATALOG_HEADER_LEN,
        "catalog header",
    )?;
    if !catalog.starts_with(VISE_CATALOG_MAGIC) {
        return Err(format!(
            "missing CVCT catalog signature at 0x{catalog_offset:X}"
        ));
    }
    let entry_count = read_u16(catalog, 16, "catalog entry count")? as usize;
    let mut cursor = catalog_offset + VISE_CATALOG_HEADER_LEN;
    if version == VISE_VERSION_EXTENDED_CATALOG {
        range(
            &patched,
            cursor,
            VISE_EXTENDED_CATALOG_PREFIX_LEN,
            "extended catalog prefix",
        )?;
        cursor += VISE_EXTENDED_CATALOG_PREFIX_LEN;
    }
    for index in 0..entry_count {
        let magic = range(&patched, cursor, 4, &format!("catalog entry {index} magic"))?;
        let kind = magic[0];
        if &magic[1..] != b"VCT" {
            return Err(format!("catalog entry {index} has invalid magic"));
        }
        cursor += 4;
        match kind {
            b'D' => {
                let record = range(
                    &patched,
                    cursor,
                    VISE_DIRECTORY_RECORD_LEN,
                    &format!("directory {index} record"),
                )?;
                let name_len = record[76] as usize;
                cursor += VISE_DIRECTORY_RECORD_LEN;
                if version == VISE_VERSION_36_LITE {
                    cursor += 6;
                } else if version == VISE_VERSION_EXTENDED_CATALOG {
                    cursor += VISE_EXTENDED_DIRECTORY_SUFFIX_LEN;
                }
                range(&patched, cursor, name_len, "directory name")?;
                cursor += name_len;
            }
            b'F' => {
                let record_offset = cursor;
                let record = range(
                    &patched,
                    record_offset,
                    VISE_FILE_RECORD_LEN,
                    &format!("file {index} record"),
                )?;
                let name_len = record[118] as usize;
                let segment_number = read_u16(record, 94, "file segment number")? as usize;
                if segment_number > 1 {
                    let segment_index = segment_number - 2;
                    let segment = continuation_payloads.get(segment_index).ok_or_else(|| {
                        format!("file {index} requires missing VISE segment {segment_number}")
                    })?;
                    let original_offset = read_u32(record, 96, "file payload offset")? as usize;
                    let segment_end = segment
                        .len()
                        .checked_add(VISE_HEADER_LEN)
                        .ok_or_else(|| "VISE segment length overflow".to_string())?;
                    if original_offset < VISE_HEADER_LEN || original_offset > segment_end {
                        return Err(format!(
                            "file {index} has invalid segment {segment_number} offset 0x{original_offset:X}"
                        ));
                    }
                    let prior_payload_len = continuation_payloads[..segment_index]
                        .iter()
                        .try_fold(0usize, |total, payload| total.checked_add(payload.len()))
                        .ok_or_else(|| "VISE segment offset overflow".to_string())?;
                    let normalized_offset = catalog_offset
                        .checked_add(prior_payload_len)
                        .and_then(|offset| offset.checked_add(original_offset - VISE_HEADER_LEN))
                        .ok_or_else(|| "VISE normalized file offset overflow".to_string())?;
                    let normalized_offset = u32::try_from(normalized_offset)
                        .map_err(|_| "VISE normalized file offset exceeds 32 bits".to_string())?;
                    patched[record_offset + 94..record_offset + 96]
                        .copy_from_slice(&1u16.to_be_bytes());
                    patched[record_offset + 96..record_offset + 100]
                        .copy_from_slice(&normalized_offset.to_be_bytes());
                }
                cursor += VISE_FILE_RECORD_LEN;
                if version == VISE_VERSION_EXTENDED_CATALOG {
                    cursor += VISE_EXTENDED_FILE_SUFFIX_LEN;
                }
                range(&patched, cursor, name_len, "file name")?;
                cursor += name_len;
            }
            other => {
                return Err(format!(
                    "catalog entry {index} has unsupported kind 0x{other:02X}"
                ));
            }
        }
    }

    let continuation_len = continuation_payloads
        .iter()
        .try_fold(0usize, |total, payload| total.checked_add(payload.len()))
        .ok_or_else(|| "VISE continuation length overflow".to_string())?;
    let normalized_catalog_offset = catalog_offset
        .checked_add(continuation_len)
        .ok_or_else(|| "VISE normalized catalog offset overflow".to_string())?;
    let mut joined = Vec::with_capacity(
        primary
            .len()
            .checked_add(continuation_len)
            .ok_or_else(|| "VISE joined length overflow".to_string())?,
    );
    joined.extend_from_slice(&patched[..catalog_offset]);
    for payload in continuation_payloads {
        joined.extend_from_slice(payload);
    }
    joined.extend_from_slice(&patched[catalog_offset..]);
    let normalized_catalog_offset = u32::try_from(normalized_catalog_offset)
        .map_err(|_| "VISE normalized catalog offset exceeds 32 bits".to_string())?;
    joined[36..40].copy_from_slice(&normalized_catalog_offset.to_be_bytes());
    Ok(joined)
}

fn parse_vise_result(data: &[u8]) -> Result<ViseArchive<'_>, String> {
    let header = range(data, 0, VISE_HEADER_LEN, "header")?;
    let version = read_u32(header, 16, "archive version")?;
    if !matches!(
        version,
        VISE_VERSION_35
            | VISE_VERSION_35_LITE
            | VISE_VERSION_36_LITE
            | VISE_VERSION_36_FULL
            | VISE_VERSION_EXTENDED_CATALOG
            | VISE_VERSION_PACKED_CATALOG
    ) {
        return Err(format!("unsupported archive version 0x{version:08X}"));
    }

    let catalog_offset = read_u32(header, 36, "catalog offset")? as usize;
    let catalog = range(
        data,
        catalog_offset,
        VISE_CATALOG_HEADER_LEN,
        "catalog header",
    )?;
    if !catalog.starts_with(VISE_CATALOG_MAGIC) {
        return Err(format!(
            "missing CVCT catalog signature at 0x{catalog_offset:X}"
        ));
    }
    let entry_count = read_u16(catalog, 16, "catalog entry count")? as usize;
    let extended_catalog = matches!(
        version,
        VISE_VERSION_EXTENDED_CATALOG | VISE_VERSION_PACKED_CATALOG
    );
    let mut cursor = catalog_offset + VISE_CATALOG_HEADER_LEN;
    if extended_catalog {
        let prefix = range(
            data,
            cursor,
            VISE_EXTENDED_CATALOG_PREFIX_LEN,
            "extended catalog prefix",
        )?;
        if !prefix.starts_with(b"PACK") {
            return Err("extended catalog is missing PACK prefix".to_string());
        }
        cursor += VISE_EXTENDED_CATALOG_PREFIX_LEN;
    }
    let catalog_records: Cow<'_, [u8]> = if version == VISE_VERSION_PACKED_CATALOG {
        let packed_len = read_u32(catalog, 4, "packed catalog length")? as usize;
        let packed = range(data, cursor, packed_len, "packed catalog records")?;
        let mut swapped = packed.to_vec();
        for pair in swapped.chunks_exact_mut(2) {
            pair.swap(0, 1);
        }
        // The 0x80010308 catalog stores the same DVCT/FVCT records as the
        // extended layout in a word-swapped, raw DEFLATE stream. Bound output
        // by the largest possible record and Pascal name for each entry.
        let max_len = entry_count
            .checked_mul(4 + VISE_FILE_RECORD_LEN + VISE_PACKED_FILE_SUFFIX_LEN + 255)
            .ok_or_else(|| "packed catalog size overflow".to_string())?;
        let mut decoded = vec![0; max_len + 1];
        let mut decompressor = Decompress::new(false);
        let status = decompressor
            .decompress(&swapped, &mut decoded, FlushDecompress::Finish)
            .map_err(|error| format!("packed catalog decompression failed: {error}"))?;
        if decompressor.total_out() as usize > max_len {
            return Err("packed catalog exceeds its entry limit".to_string());
        }
        if status != Status::StreamEnd {
            return Err("packed catalog has an incomplete DEFLATE stream".to_string());
        }
        if swapped[decompressor.total_in() as usize..]
            .iter()
            .any(|byte| *byte != 0)
        {
            return Err("packed catalog has nonzero trailing data".to_string());
        }
        decoded.truncate(decompressor.total_out() as usize);
        cursor = 0;
        Cow::Owned(decoded)
    } else {
        Cow::Borrowed(data)
    };
    let catalog_data = catalog_records.as_ref();
    let mut dirs = Vec::<ViseDirectory>::new();
    let mut entries = Vec::<ViseEntry<'_>>::new();

    for index in 0..entry_count {
        let magic = range(
            catalog_data,
            cursor,
            4,
            &format!("catalog entry {index} magic"),
        )?;
        cursor += 4;
        if &magic[1..4] != b"VCT" {
            return Err(format!(
                "catalog entry {index} has invalid magic {:?}",
                magic
            ));
        }

        match magic[0] {
            b'D' => {
                let record = range(
                    catalog_data,
                    cursor,
                    VISE_DIRECTORY_RECORD_LEN,
                    &format!("directory {index} record"),
                )?;
                cursor += VISE_DIRECTORY_RECORD_LEN;
                let parent = read_u16(record, 68, "directory parent")? as usize;
                let name_len = record[76] as usize;
                if matches!(version, VISE_VERSION_36_LITE | VISE_VERSION_36_FULL) {
                    let suffix_len = if version == VISE_VERSION_36_FULL {
                        VISE_36_FULL_DIRECTORY_SUFFIX_LEN
                    } else {
                        6
                    };
                    range(
                        catalog_data,
                        cursor,
                        suffix_len,
                        "VISE 3.6 directory extension",
                    )?;
                    cursor += suffix_len;
                } else if extended_catalog {
                    let suffix_len = if version == VISE_VERSION_PACKED_CATALOG {
                        VISE_PACKED_DIRECTORY_SUFFIX_LEN
                    } else {
                        VISE_EXTENDED_DIRECTORY_SUFFIX_LEN
                    };
                    range(
                        catalog_data,
                        cursor,
                        suffix_len,
                        "extended directory suffix",
                    )?;
                    cursor += suffix_len;
                }
                let name =
                    decode_catalog_name(catalog_data, &mut cursor, name_len, "directory name")?;
                let path = child_path(&dirs, parent, &name, "directory")?;
                dirs.push(ViseDirectory { path });
            }
            b'F' => {
                let record = range(
                    catalog_data,
                    cursor,
                    VISE_FILE_RECORD_LEN,
                    &format!("file {index} record"),
                )?;
                cursor += VISE_FILE_RECORD_LEN;
                let parent = read_u16(record, 92, "file parent")? as usize;
                // Full VISE 3.5 can distribute a file beside the installer
                // instead of embedding it. Such records have segment zero and
                // the external-copy flag at +112; their old packed offsets and
                // sizes are not ranges in the distributed archive.
                let external = version == VISE_VERSION_35
                    && read_u16(record, 94, "file segment number")? == 0
                    && record[112] == 1;
                let packed_offset = read_u32(record, 96, "file payload offset")? as usize;
                let declared_data_packed_len = read_u32(record, 64, "packed data length")? as usize;
                let data_unpacked_len = read_u32(record, 68, "data length")? as usize;
                let declared_rsrc_packed_len =
                    read_u32(record, 72, "packed resource length")? as usize;
                let rsrc_unpacked_len = read_u32(record, 76, "resource length")? as usize;
                let name_len = record[118] as usize;
                let mut file_type = [0; 4];
                file_type.copy_from_slice(&record[40..44]);
                let mut creator = [0; 4];
                creator.copy_from_slice(&record[44..48]);
                if version == VISE_VERSION_36_FULL {
                    range(
                        catalog_data,
                        cursor,
                        VISE_36_FULL_FILE_SUFFIX_LEN,
                        "VISE 3.6 full file suffix",
                    )?;
                    cursor += VISE_36_FULL_FILE_SUFFIX_LEN;
                } else if extended_catalog {
                    let suffix_len = if version == VISE_VERSION_PACKED_CATALOG {
                        VISE_PACKED_FILE_SUFFIX_LEN
                    } else {
                        VISE_EXTENDED_FILE_SUFFIX_LEN
                    };
                    range(catalog_data, cursor, suffix_len, "extended file suffix")?;
                    cursor += suffix_len;
                }
                let name = decode_catalog_name(catalog_data, &mut cursor, name_len, "file name")?;
                let path = child_path(&dirs, parent, &name, "file")?;
                // Grouped records share one compressed stream. Flag 0x10 also
                // appears in extended catalogs, where fork offsets still refer
                // to positions within that stream.
                let is_grouped = (record[8] & 0x10) != 0
                    || (!extended_catalog
                        && data_unpacked_len == 0
                        && rsrc_unpacked_len != 0
                        && declared_data_packed_len != 0);
                let (
                    data_packed_offset,
                    data_packed_len,
                    data_unpacked_offset,
                    rsrc_packed_offset,
                    rsrc_packed_len,
                    rsrc_unpacked_offset,
                ) = if is_grouped {
                    let d_off = if data_unpacked_len > 0 {
                        read_u32(record, 100, "data unpacked offset")? as usize
                    } else {
                        0
                    };
                    let r_off = if rsrc_unpacked_len > 0 {
                        if data_unpacked_len > 0 {
                            d_off + data_unpacked_len
                        } else {
                            read_u32(record, 104, "grouped resource offset")? as usize
                        }
                    } else {
                        0
                    };
                    (
                        packed_offset,
                        if data_unpacked_len > 0 {
                            declared_data_packed_len
                        } else {
                            0
                        },
                        d_off,
                        packed_offset,
                        if rsrc_unpacked_len > 0 {
                            declared_data_packed_len
                        } else {
                            0
                        },
                        r_off,
                    )
                } else {
                    let rsrc_offset = packed_offset
                        .checked_add(declared_data_packed_len)
                        .ok_or_else(|| format!("{path} resource offset overflow"))?;
                    (
                        packed_offset,
                        declared_data_packed_len,
                        0,
                        rsrc_offset,
                        declared_rsrc_packed_len,
                        0,
                    )
                };

                let data_packed = if external || data_packed_len == 0 {
                    &[][..]
                } else {
                    range(
                        data,
                        data_packed_offset,
                        data_packed_len,
                        &format!("{path} data stream"),
                    )?
                };
                let rsrc_packed = if external || rsrc_packed_len == 0 {
                    &[][..]
                } else {
                    range(
                        data,
                        rsrc_packed_offset,
                        rsrc_packed_len,
                        &format!("{path} resource stream"),
                    )?
                };
                let unpacked_offset = if data_unpacked_len > 0 {
                    data_unpacked_offset
                } else {
                    rsrc_unpacked_offset
                };

                entries.push(ViseEntry {
                    path,
                    file_type,
                    creator,
                    external,
                    data_packed,
                    rsrc_packed,
                    data_packed_offset,
                    rsrc_packed_offset,
                    unpacked_offset,
                    data_unpacked_offset,
                    rsrc_unpacked_offset,
                    data_unpacked_len,
                    rsrc_unpacked_len,
                });
            }
            kind => {
                return Err(format!(
                    "catalog entry {index} has unsupported kind 0x{kind:02X}"
                ));
            }
        }
    }

    if version == VISE_VERSION_PACKED_CATALOG
        && cursor != catalog_data.len()
        && !catalog_data[cursor..].starts_with(b"PACK")
    {
        return Err("packed catalog has an unexpected trailer".to_string());
    }

    Ok(ViseArchive {
        dirs: dirs.into_iter().map(|dir| dir.path).collect(),
        entries,
    })
}

pub fn decode_vise_fork(packed: &[u8], expected_len: usize) -> Result<Vec<u8>, String> {
    if expected_len == 0 {
        return Ok(Vec::new());
    }
    if packed.is_empty() {
        return Err(format!(
            "compressed stream is empty but declares {expected_len} output bytes"
        ));
    }

    let mut transformed = packed.to_vec();
    for pair in transformed.chunks_exact_mut(2) {
        pair.swap(0, 1);
    }
    for byte in &mut transformed {
        *byte = VISE_DEOBFUSCATION_TABLE[*byte as usize];
    }

    // VISE's `Dcmp` resource emits a headerless DEFLATE stream. ScummVM notes
    // that stored blocks are word-aligned by VISE; compressible application
    // payloads use ordinary blocks accepted by the standard decoder.
    let mut decoder = DeflateDecoder::new(transformed.as_slice());
    let mut output = Vec::with_capacity(expected_len);
    // VISE catalog sizes are authoritative. Its original decompressor, and
    // ScummVM's compatible implementation, stop after filling exactly this
    // output buffer even if the encoded bitstream can yield more bytes.
    let standard_result = decoder.read_to_end(&mut output);
    if standard_result.is_ok() && output.len() >= expected_len {
        output.truncate(expected_len);
        return Ok(output);
    }

    let concatenated_result = decode_concatenated_deflate(&transformed, expected_len);
    if let Ok(mut concatenated) = concatenated_result {
        concatenated.truncate(expected_len);
        return Ok(concatenated);
    }
    let concatenated_error = concatenated_result.unwrap_err();

    // Installer VISE's decompressor consumes 16-bit words. Unlike RFC 1951,
    // its stored blocks skip to the next word boundary rather than merely the
    // next byte boundary. Standard DEFLATE handles virtually every fork; this
    // fallback covers grouped streams that contain those word-aligned blocks.
    decode_vise_word_aligned_deflate(&transformed, expected_len).map_err(|error| {
        let standard = standard_result.map_or_else(
            |decode_error| format!("standard DEFLATE failed: {decode_error}"),
            |_| format!("standard DEFLATE produced only {} bytes", output.len()),
        );
        format!(
            "{standard}; concatenated DEFLATE failed: {concatenated_error}; VISE DEFLATE failed: {error}"
        )
    })
}

#[cfg(test)]
pub(crate) fn make_test_archive(name: &str, data_fork: &[u8], resource_fork: &[u8]) -> Vec<u8> {
    use flate2::{write::DeflateEncoder, Compression};
    use std::io::Write;

    fn encode(bytes: &[u8]) -> Vec<u8> {
        let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(bytes).unwrap();
        let mut encoded = encoder.finish().unwrap();
        let mut inverse = [0u8; 256];
        for (index, decoded) in VISE_DEOBFUSCATION_TABLE.iter().copied().enumerate() {
            inverse[decoded as usize] = index as u8;
        }
        for byte in &mut encoded {
            *byte = inverse[*byte as usize];
        }
        for pair in encoded.chunks_exact_mut(2) {
            pair.swap(0, 1);
        }
        encoded
    }

    assert!(name.len() <= u8::MAX as usize);
    let packed_data = encode(data_fork);
    let packed_rsrc = encode(resource_fork);
    let payload_offset = VISE_HEADER_LEN;
    let catalog_offset = payload_offset + packed_data.len() + packed_rsrc.len();
    let mut archive = vec![0u8; VISE_HEADER_LEN];
    archive[..4].copy_from_slice(VISE_MAGIC);
    archive[16..20].copy_from_slice(&VISE_VERSION_35_LITE.to_be_bytes());
    archive[36..40].copy_from_slice(&(catalog_offset as u32).to_be_bytes());
    archive.extend_from_slice(&packed_data);
    archive.extend_from_slice(&packed_rsrc);
    let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
    catalog[..4].copy_from_slice(VISE_CATALOG_MAGIC);
    catalog[16..18].copy_from_slice(&1u16.to_be_bytes());
    archive.extend_from_slice(&catalog);
    archive.extend_from_slice(b"FVCT");
    let mut file = [0u8; VISE_FILE_RECORD_LEN];
    file[40..44].copy_from_slice(b"APPL");
    file[44..48].copy_from_slice(b"TEST");
    file[64..68].copy_from_slice(&(packed_data.len() as u32).to_be_bytes());
    file[68..72].copy_from_slice(&(data_fork.len() as u32).to_be_bytes());
    file[72..76].copy_from_slice(&(packed_rsrc.len() as u32).to_be_bytes());
    file[76..80].copy_from_slice(&(resource_fork.len() as u32).to_be_bytes());
    file[96..100].copy_from_slice(&(payload_offset as u32).to_be_bytes());
    file[118] = name.len() as u8;
    archive.extend_from_slice(&file);
    archive.extend_from_slice(name.as_bytes());
    archive
}

fn decode_concatenated_deflate(data: &[u8], required_len: usize) -> Result<Vec<u8>, String> {
    let mut output = Vec::with_capacity(required_len);
    let mut offset = 0usize;
    while offset < data.len() && output.len() < required_len {
        let mut decoder = DeflateDecoder::new(&data[offset..]);
        let before = output.len();
        decoder
            .read_to_end(&mut output)
            .map_err(|error| format!("member at 0x{offset:X}: {error}"))?;
        let consumed = decoder.total_in() as usize;
        if consumed == 0 {
            return Err(format!("member at 0x{offset:X} consumed no input"));
        }
        offset = offset
            .checked_add(consumed)
            .ok_or_else(|| "concatenated DEFLATE offset overflow".to_string())?;
        // Each independently-finalized stream starts on the next 16-bit word,
        // matching the VISE decompressor's word-at-a-time input contract.
        offset = offset
            .checked_add(1)
            .ok_or_else(|| "concatenated DEFLATE alignment overflow".to_string())?
            & !1;
        if output.len() == before && output.len() < required_len {
            return Err(format!("member at 0x{offset:X} produced no output"));
        }
    }
    if output.len() < required_len {
        return Err(format!(
            "concatenated streams produced {} bytes, expected at least {required_len}",
            output.len()
        ));
    }
    Ok(output)
}

fn decode_vise_word_aligned_deflate(data: &[u8], required_len: usize) -> Result<Vec<u8>, String> {
    let mut bits = DeflateBitReader::new(data);
    let mut output = Vec::with_capacity(required_len);

    loop {
        let is_final = bits.read_bits(1)? != 0;
        let block_type = bits.read_bits(2)?;
        match block_type {
            0 => {
                bits.align_to_word()?;
                let len = bits.read_bits(16)? as u16;
                let inverse_len = bits.read_bits(16)? as u16;
                if len != !inverse_len {
                    return Err(format!(
                        "stored block length check failed ({len} != !{inverse_len})"
                    ));
                }
                for _ in 0..len {
                    output.push(bits.read_bits(8)? as u8);
                    if output.len() == required_len {
                        return Ok(output);
                    }
                }
                // The next block also starts on a word boundary when LEN is odd.
                bits.align_to_word()?;
            }
            1 => {
                let (literal_lengths, distance_lengths) = fixed_huffman_lengths();
                decode_huffman_block(
                    &mut bits,
                    &mut output,
                    required_len,
                    &HuffmanTree::new(&literal_lengths)?,
                    &HuffmanTree::new(&distance_lengths)?,
                )?;
            }
            2 => {
                let (literal_lengths, distance_lengths) = dynamic_huffman_lengths(&mut bits)?;
                decode_huffman_block(
                    &mut bits,
                    &mut output,
                    required_len,
                    &HuffmanTree::new(&literal_lengths)?,
                    &HuffmanTree::new(&distance_lengths)?,
                )?;
            }
            _ => return Err("reserved DEFLATE block type".to_string()),
        }
        if output.len() >= required_len {
            output.truncate(required_len);
            return Ok(output);
        }
        if is_final {
            return Err(format!(
                "stream ended after {} bytes, expected at least {required_len}",
                output.len()
            ));
        }
    }
}

struct DeflateBitReader<'a> {
    data: &'a [u8],
    bit_pos: usize,
}

impl<'a> DeflateBitReader<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data, bit_pos: 0 }
    }

    fn read_bits(&mut self, count: u8) -> Result<u32, String> {
        let end = self
            .bit_pos
            .checked_add(count as usize)
            .ok_or_else(|| "DEFLATE bit offset overflow".to_string())?;
        if end > self.data.len() * 8 {
            return Err("DEFLATE input truncated".to_string());
        }
        let mut value = 0u32;
        for bit_index in 0..count {
            let byte = self.data[self.bit_pos / 8];
            let bit = (byte >> (self.bit_pos % 8)) & 1;
            value |= u32::from(bit) << bit_index;
            self.bit_pos += 1;
        }
        Ok(value)
    }

    fn align_to_word(&mut self) -> Result<(), String> {
        self.bit_pos = self
            .bit_pos
            .checked_add(15)
            .ok_or_else(|| "DEFLATE word alignment overflow".to_string())?
            & !15;
        if self.bit_pos > self.data.len() * 8 {
            return Err("DEFLATE input truncated at word boundary".to_string());
        }
        Ok(())
    }
}

struct HuffmanTree {
    codes_by_len: Vec<Vec<(u16, u16)>>,
    max_len: u8,
}

impl HuffmanTree {
    fn new(lengths: &[u8]) -> Result<Self, String> {
        let max_len = lengths.iter().copied().max().unwrap_or(0);
        if max_len == 0 || max_len > 15 {
            return Err(format!("invalid Huffman maximum code length {max_len}"));
        }
        let mut counts = vec![0u16; max_len as usize + 1];
        for &len in lengths {
            if len != 0 {
                counts[len as usize] += 1;
            }
        }
        let mut next_code = vec![0u16; max_len as usize + 1];
        let mut code = 0u16;
        for len in 1..=max_len as usize {
            code = (code + counts[len - 1]) << 1;
            next_code[len] = code;
        }
        let mut codes_by_len = vec![Vec::new(); max_len as usize + 1];
        for (symbol, &len) in lengths.iter().enumerate() {
            if len == 0 {
                continue;
            }
            let canonical = next_code[len as usize];
            next_code[len as usize] += 1;
            codes_by_len[len as usize].push((reverse_low_bits(canonical, len), symbol as u16));
        }
        Ok(Self {
            codes_by_len,
            max_len,
        })
    }

    fn decode(&self, bits: &mut DeflateBitReader<'_>) -> Result<u16, String> {
        let mut code = 0u16;
        for len in 1..=self.max_len {
            code |= (bits.read_bits(1)? as u16) << (len - 1);
            if let Some((_, symbol)) = self.codes_by_len[len as usize]
                .iter()
                .find(|(candidate, _)| *candidate == code)
            {
                return Ok(*symbol);
            }
        }
        Err("invalid Huffman code".to_string())
    }
}

fn reverse_low_bits(mut code: u16, len: u8) -> u16 {
    let mut reversed = 0u16;
    for _ in 0..len {
        reversed = (reversed << 1) | (code & 1);
        code >>= 1;
    }
    reversed
}

fn fixed_huffman_lengths() -> (Vec<u8>, Vec<u8>) {
    let mut literal_lengths = vec![0u8; 288];
    literal_lengths[0..144].fill(8);
    literal_lengths[144..256].fill(9);
    literal_lengths[256..280].fill(7);
    literal_lengths[280..288].fill(8);
    (literal_lengths, vec![5; 32])
}

fn dynamic_huffman_lengths(bits: &mut DeflateBitReader<'_>) -> Result<(Vec<u8>, Vec<u8>), String> {
    const CODE_LENGTH_ORDER: [usize; 19] = [
        16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
    ];
    let literal_count = bits.read_bits(5)? as usize + 257;
    let distance_count = bits.read_bits(5)? as usize + 1;
    let code_length_count = bits.read_bits(4)? as usize + 4;
    let mut code_lengths = vec![0u8; 19];
    for &index in &CODE_LENGTH_ORDER[..code_length_count] {
        code_lengths[index] = bits.read_bits(3)? as u8;
    }
    let code_length_tree = HuffmanTree::new(&code_lengths)?;
    let total = literal_count + distance_count;
    let mut lengths = Vec::with_capacity(total);
    while lengths.len() < total {
        match code_length_tree.decode(bits)? {
            symbol @ 0..=15 => lengths.push(symbol as u8),
            16 => {
                let previous = *lengths
                    .last()
                    .ok_or_else(|| "repeat code 16 has no previous length".to_string())?;
                let repeat = bits.read_bits(2)? as usize + 3;
                lengths.extend(std::iter::repeat_n(previous, repeat));
            }
            17 => {
                let repeat = bits.read_bits(3)? as usize + 3;
                lengths.extend(std::iter::repeat_n(0, repeat));
            }
            18 => {
                let repeat = bits.read_bits(7)? as usize + 11;
                lengths.extend(std::iter::repeat_n(0, repeat));
            }
            symbol => return Err(format!("invalid code-length symbol {symbol}")),
        }
        if lengths.len() > total {
            return Err("dynamic Huffman lengths exceed declared count".to_string());
        }
    }
    Ok((
        lengths[..literal_count].to_vec(),
        lengths[literal_count..].to_vec(),
    ))
}

fn decode_huffman_block(
    bits: &mut DeflateBitReader<'_>,
    output: &mut Vec<u8>,
    required_len: usize,
    literal_tree: &HuffmanTree,
    distance_tree: &HuffmanTree,
) -> Result<(), String> {
    const LENGTH_BASE: [usize; 29] = [
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115,
        131, 163, 195, 227, 258,
    ];
    const LENGTH_EXTRA: [u8; 29] = [
        0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
    ];
    const DISTANCE_BASE: [usize; 30] = [
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
        2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
    ];
    const DISTANCE_EXTRA: [u8; 30] = [
        0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12,
        13, 13,
    ];

    loop {
        match literal_tree.decode(bits)? {
            literal @ 0..=255 => {
                output.push(literal as u8);
                if output.len() == required_len {
                    return Ok(());
                }
            }
            256 => return Ok(()),
            length_symbol @ 257..=285 => {
                let length_index = (length_symbol - 257) as usize;
                let length = LENGTH_BASE[length_index]
                    + bits.read_bits(LENGTH_EXTRA[length_index])? as usize;
                let distance_symbol = distance_tree.decode(bits)? as usize;
                if distance_symbol >= DISTANCE_BASE.len() {
                    return Err(format!("invalid distance symbol {distance_symbol}"));
                }
                let distance = DISTANCE_BASE[distance_symbol]
                    + bits.read_bits(DISTANCE_EXTRA[distance_symbol])? as usize;
                if distance == 0 || distance > output.len() {
                    return Err(format!(
                        "invalid back-reference distance {distance} at output {}",
                        output.len()
                    ));
                }
                for _ in 0..length {
                    let byte = output[output.len() - distance];
                    output.push(byte);
                    if output.len() == required_len {
                        return Ok(());
                    }
                }
            }
            symbol => return Err(format!("invalid literal/length symbol {symbol}")),
        }
    }
}

fn child_path(
    dirs: &[ViseDirectory],
    parent: usize,
    name: &str,
    kind: &str,
) -> Result<String, String> {
    validate_component(name, kind)?;
    if parent == 0 {
        return Ok(name.to_string());
    }
    let parent_dir = dirs
        .get(parent - 1)
        .ok_or_else(|| format!("{kind} {name:?} has invalid parent directory {parent}"))?;
    Ok(format!("{}/{}", parent_dir.path, name))
}

fn validate_component(name: &str, kind: &str) -> Result<(), String> {
    if name.is_empty()
        || name == "."
        || name == ".."
        || name.contains('/')
        || name.contains(':')
        || name.contains('\0')
    {
        return Err(format!("unsafe VISE {kind} component {name:?}"));
    }
    Ok(())
}

fn decode_catalog_name(
    data: &[u8],
    cursor: &mut usize,
    len: usize,
    label: &str,
) -> Result<String, String> {
    let bytes = range(data, *cursor, len, label)?;
    *cursor = cursor
        .checked_add(len)
        .ok_or_else(|| format!("{label} offset overflow"))?;
    let name = decode_mac_roman(bytes);
    Ok(crate::trap::dispatch::TrapDispatcher::encode_hfs_component_for_vfs(&name))
}

fn range<'a>(data: &'a [u8], offset: usize, len: usize, label: &str) -> Result<&'a [u8], String> {
    let end = offset
        .checked_add(len)
        .ok_or_else(|| format!("{label} range overflow"))?;
    data.get(offset..end).ok_or_else(|| {
        format!(
            "{label} range 0x{offset:X}..0x{end:X} exceeds len {}",
            data.len()
        )
    })
}

fn read_u16(data: &[u8], offset: usize, label: &str) -> Result<u16, String> {
    Ok(u16::from_be_bytes(
        range(data, offset, 2, label)?.try_into().unwrap(),
    ))
}

fn read_u32(data: &[u8], offset: usize, label: &str) -> Result<u32, String> {
    Ok(u32::from_be_bytes(
        range(data, offset, 4, label)?.try_into().unwrap(),
    ))
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use flate2::{write::DeflateEncoder, Compression};
    use std::io::Write;

    pub(crate) fn encode_vise_fork(bytes: &[u8]) -> Vec<u8> {
        let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(bytes).unwrap();
        let mut encoded = encoder.finish().unwrap();
        let mut inverse = [0u8; 256];
        for (index, decoded) in VISE_DEOBFUSCATION_TABLE.iter().copied().enumerate() {
            inverse[decoded as usize] = index as u8;
        }
        for byte in &mut encoded {
            *byte = inverse[*byte as usize];
        }
        for pair in encoded.chunks_exact_mut(2) {
            pair.swap(0, 1);
        }
        encoded
    }

    #[test]
    fn parses_catalog_paths_and_decodes_both_forks() {
        let data_fork = b"installed application data";
        let resource_fork = b"installed application resources";
        let packed_data = encode_vise_fork(data_fork);
        let packed_rsrc = encode_vise_fork(resource_fork);
        let payload_offset = VISE_HEADER_LEN;
        let catalog_offset = payload_offset + packed_data.len() + packed_rsrc.len();
        let mut archive = vec![0u8; VISE_HEADER_LEN];
        archive[0..4].copy_from_slice(VISE_MAGIC);
        archive[16..20].copy_from_slice(&VISE_VERSION_35_LITE.to_be_bytes());
        archive[36..40].copy_from_slice(&(catalog_offset as u32).to_be_bytes());
        archive.extend_from_slice(&packed_data);
        archive.extend_from_slice(&packed_rsrc);
        let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
        catalog[0..4].copy_from_slice(VISE_CATALOG_MAGIC);
        catalog[16..18].copy_from_slice(&2u16.to_be_bytes());
        archive.extend_from_slice(&catalog);
        archive.extend_from_slice(b"DVCT");
        let mut directory = [0u8; VISE_DIRECTORY_RECORD_LEN];
        directory[76] = 4;
        archive.extend_from_slice(&directory);
        archive.extend_from_slice(b"Game");
        archive.extend_from_slice(b"FVCT");
        let mut file = [0u8; VISE_FILE_RECORD_LEN];
        file[40..44].copy_from_slice(b"APPL");
        file[44..48].copy_from_slice(b"TEST");
        file[64..68].copy_from_slice(&(packed_data.len() as u32).to_be_bytes());
        file[68..72].copy_from_slice(&(data_fork.len() as u32).to_be_bytes());
        file[72..76].copy_from_slice(&(packed_rsrc.len() as u32).to_be_bytes());
        file[76..80].copy_from_slice(&(resource_fork.len() as u32).to_be_bytes());
        file[92..94].copy_from_slice(&1u16.to_be_bytes());
        file[96..100].copy_from_slice(&(payload_offset as u32).to_be_bytes());
        file[100..104].copy_from_slice(&346u32.to_be_bytes());
        file[118] = 7;
        archive.extend_from_slice(&file);
        archive.extend_from_slice(b"Runtime");

        let parsed = parse_vise(&archive).unwrap().unwrap();
        assert_eq!(parsed.dirs, ["Game"]);
        assert_eq!(parsed.entries.len(), 1);
        let entry = &parsed.entries[0];
        assert_eq!(entry.path, "Game/Runtime");
        assert_eq!(entry.file_type, *b"APPL");
        assert_eq!(entry.creator, *b"TEST");
        assert_eq!(entry.unpacked_offset, 0);
        assert_eq!(
            decode_vise_fork(entry.data_packed, entry.data_unpacked_len).unwrap(),
            data_fork
        );
        assert_eq!(
            decode_vise_fork(entry.rsrc_packed, entry.rsrc_unpacked_len).unwrap(),
            resource_fork
        );
    }

    #[test]
    fn parses_full_vise_35_catalog_layout() {
        let payload = b"VISE 3.5 installed file";
        let packed = encode_vise_fork(payload);
        let payload_offset = VISE_HEADER_LEN;
        let catalog_offset = payload_offset + packed.len();
        let mut archive = vec![0u8; VISE_HEADER_LEN];
        archive[0..4].copy_from_slice(VISE_MAGIC);
        archive[16..20].copy_from_slice(&VISE_VERSION_35.to_be_bytes());
        archive[36..40].copy_from_slice(&(catalog_offset as u32).to_be_bytes());
        archive.extend_from_slice(&packed);

        let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
        catalog[0..4].copy_from_slice(VISE_CATALOG_MAGIC);
        catalog[16..18].copy_from_slice(&1u16.to_be_bytes());
        archive.extend_from_slice(&catalog);
        archive.extend_from_slice(b"FVCT");
        let mut file = [0u8; VISE_FILE_RECORD_LEN];
        file[40..44].copy_from_slice(b"APPL");
        file[44..48].copy_from_slice(b"TEST");
        file[64..68].copy_from_slice(&(packed.len() as u32).to_be_bytes());
        file[68..72].copy_from_slice(&(payload.len() as u32).to_be_bytes());
        file[94..96].copy_from_slice(&1u16.to_be_bytes());
        file[96..100].copy_from_slice(&(payload_offset as u32).to_be_bytes());
        file[118] = 7;
        archive.extend_from_slice(&file);
        archive.extend_from_slice(b"Runtime");

        let parsed = parse_vise(&archive).unwrap().unwrap();
        assert_eq!(parsed.entries[0].path, "Runtime");
        assert_eq!(
            decode_vise_fork(
                parsed.entries[0].data_packed,
                parsed.entries[0].data_unpacked_len,
            )
            .unwrap(),
            payload
        );
    }

    #[test]
    fn joins_crossing_and_later_segment_file_streams() {
        let crossing_data = b"a compressed stream split across installer disks";
        let later_data = b"a file stored wholly on the second disk";
        let crossing_packed = encode_vise_fork(crossing_data);
        let later_packed = encode_vise_fork(later_data);
        let split = crossing_packed.len() / 2;
        let payload_offset = VISE_HEADER_LEN;
        let catalog_offset = payload_offset + split;

        let mut primary = vec![0u8; VISE_HEADER_LEN];
        primary[0..4].copy_from_slice(VISE_MAGIC);
        primary[16..20].copy_from_slice(&VISE_VERSION_35.to_be_bytes());
        primary[36..40].copy_from_slice(&(catalog_offset as u32).to_be_bytes());
        primary.extend_from_slice(&crossing_packed[..split]);
        let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
        catalog[0..4].copy_from_slice(VISE_CATALOG_MAGIC);
        catalog[16..18].copy_from_slice(&2u16.to_be_bytes());
        primary.extend_from_slice(&catalog);

        primary.extend_from_slice(b"FVCT");
        let mut crossing_file = [0u8; VISE_FILE_RECORD_LEN];
        crossing_file[40..44].copy_from_slice(b"TEXT");
        crossing_file[44..48].copy_from_slice(b"TEST");
        crossing_file[64..68].copy_from_slice(&(crossing_packed.len() as u32).to_be_bytes());
        crossing_file[68..72].copy_from_slice(&(crossing_data.len() as u32).to_be_bytes());
        crossing_file[94..96].copy_from_slice(&1u16.to_be_bytes());
        crossing_file[96..100].copy_from_slice(&(payload_offset as u32).to_be_bytes());
        crossing_file[118] = 8;
        primary.extend_from_slice(&crossing_file);
        primary.extend_from_slice(b"Crossing");

        primary.extend_from_slice(b"FVCT");
        let mut later_file = [0u8; VISE_FILE_RECORD_LEN];
        later_file[40..44].copy_from_slice(b"TEXT");
        later_file[44..48].copy_from_slice(b"TEST");
        later_file[64..68].copy_from_slice(&(later_packed.len() as u32).to_be_bytes());
        later_file[68..72].copy_from_slice(&(later_data.len() as u32).to_be_bytes());
        later_file[94..96].copy_from_slice(&2u16.to_be_bytes());
        let later_segment_offset = VISE_HEADER_LEN + crossing_packed.len().saturating_sub(split);
        later_file[96..100].copy_from_slice(&(later_segment_offset as u32).to_be_bytes());
        later_file[118] = 5;
        primary.extend_from_slice(&later_file);
        primary.extend_from_slice(b"Later");

        let mut continuation = vec![0u8; VISE_HEADER_LEN];
        continuation[0..4].copy_from_slice(VISE_MAGIC);
        continuation[16..20].copy_from_slice(&VISE_VERSION_35.to_be_bytes());
        continuation.extend_from_slice(&crossing_packed[split..]);
        continuation.extend_from_slice(&later_packed);

        let joined = join_segments(&primary, &[&continuation]).unwrap();
        let parsed = parse_vise(&joined).unwrap().unwrap();
        assert_eq!(parsed.entries.len(), 2);
        assert_eq!(
            decode_vise_fork(
                parsed.entries[0].data_packed,
                parsed.entries[0].data_unpacked_len,
            )
            .unwrap(),
            crossing_data
        );
        assert_eq!(
            decode_vise_fork(
                parsed.entries[1].data_packed,
                parsed.entries[1].data_unpacked_len,
            )
            .unwrap(),
            later_data
        );
    }

    #[test]
    fn parses_classic_resource_only_stream_at_the_file_payload_offset() {
        let prefix = b"earlier grouped resource";
        let resource_fork = b"resource-only VISE payload";
        let grouped_resources = [prefix.as_slice(), resource_fork.as_slice()].concat();
        let packed_rsrc = encode_vise_fork(&grouped_resources);
        let payload_offset = VISE_HEADER_LEN;
        let catalog_offset = payload_offset + packed_rsrc.len();
        let mut archive = vec![0u8; VISE_HEADER_LEN];
        archive[0..4].copy_from_slice(VISE_MAGIC);
        archive[16..20].copy_from_slice(&VISE_VERSION_35_LITE.to_be_bytes());
        archive[36..40].copy_from_slice(&(catalog_offset as u32).to_be_bytes());
        archive.extend_from_slice(&packed_rsrc);

        let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
        catalog[0..4].copy_from_slice(VISE_CATALOG_MAGIC);
        catalog[16..18].copy_from_slice(&1u16.to_be_bytes());
        archive.extend_from_slice(&catalog);
        archive.extend_from_slice(b"FVCT");
        let mut file = [0u8; VISE_FILE_RECORD_LEN];
        file[40..44].copy_from_slice(b"RSRC");
        file[44..48].copy_from_slice(b"TEST");
        file[64..68].copy_from_slice(&(packed_rsrc.len() as u32).to_be_bytes());
        file[72..76].copy_from_slice(&(grouped_resources.len() as u32).to_be_bytes());
        file[76..80].copy_from_slice(&(resource_fork.len() as u32).to_be_bytes());
        file[96..100].copy_from_slice(&(payload_offset as u32).to_be_bytes());
        file[104..108].copy_from_slice(&(prefix.len() as u32).to_be_bytes());
        file[118] = 7;
        archive.extend_from_slice(&file);
        archive.extend_from_slice(b"Control");

        let parsed = parse_vise(&archive).unwrap().unwrap();
        let entry = &parsed.entries[0];
        assert!(entry.data_packed.is_empty());
        assert_eq!(entry.rsrc_packed, packed_rsrc);
        assert_eq!(entry.unpacked_offset, prefix.len());
        let decoded = decode_vise_fork(
            entry.rsrc_packed,
            entry.unpacked_offset + entry.rsrc_unpacked_len,
        )
        .unwrap();
        assert_eq!(
            &decoded[entry.unpacked_offset..entry.unpacked_offset + entry.rsrc_unpacked_len],
            resource_fork
        );
    }

    #[test]
    fn parses_extended_catalog_records() {
        let data_fork = b"extended catalog payload";
        let packed_data = encode_vise_fork(data_fork);
        let payload_offset = VISE_HEADER_LEN;
        let catalog_offset = payload_offset + packed_data.len();
        let mut archive = vec![0u8; VISE_HEADER_LEN];
        archive[0..4].copy_from_slice(VISE_MAGIC);
        archive[16..20].copy_from_slice(&VISE_VERSION_EXTENDED_CATALOG.to_be_bytes());
        archive[36..40].copy_from_slice(&(catalog_offset as u32).to_be_bytes());
        archive.extend_from_slice(&packed_data);

        let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
        catalog[0..4].copy_from_slice(VISE_CATALOG_MAGIC);
        catalog[16..18].copy_from_slice(&2u16.to_be_bytes());
        archive.extend_from_slice(&catalog);
        let mut prefix = [0u8; VISE_EXTENDED_CATALOG_PREFIX_LEN];
        prefix[0..4].copy_from_slice(b"PACK");
        archive.extend_from_slice(&prefix);

        archive.extend_from_slice(b"DVCT");
        let mut directory = [0u8; VISE_DIRECTORY_RECORD_LEN];
        directory[76] = 4;
        archive.extend_from_slice(&directory);
        archive.extend_from_slice(&[0u8; VISE_EXTENDED_DIRECTORY_SUFFIX_LEN]);
        archive.extend_from_slice(b"Game");

        archive.extend_from_slice(b"FVCT");
        let mut file = [0u8; VISE_FILE_RECORD_LEN];
        file[40..44].copy_from_slice(b"APPL");
        file[44..48].copy_from_slice(b"TEST");
        file[64..68].copy_from_slice(&(packed_data.len() as u32).to_be_bytes());
        file[68..72].copy_from_slice(&(data_fork.len() as u32).to_be_bytes());
        file[92..94].copy_from_slice(&1u16.to_be_bytes());
        file[96..100].copy_from_slice(&(payload_offset as u32).to_be_bytes());
        // Ungrouped records decode from byte zero even when this catalog
        // metadata field is smaller than the decompressed data length.
        file[100..104].copy_from_slice(&3u32.to_be_bytes());
        file[118] = 7;
        archive.extend_from_slice(&file);
        archive.extend_from_slice(&[0u8; VISE_EXTENDED_FILE_SUFFIX_LEN]);
        archive.extend_from_slice(b"Runtime");

        let parsed = parse_vise(&archive).unwrap().unwrap();
        assert_eq!(parsed.dirs, ["Game"]);
        assert_eq!(parsed.entries.len(), 1);
        let entry = &parsed.entries[0];
        assert_eq!(entry.path, "Game/Runtime");
        assert_eq!(entry.unpacked_offset, 0);
        assert_eq!(
            decode_vise_fork(entry.data_packed, entry.data_unpacked_len).unwrap(),
            data_fork
        );
    }

    #[test]
    fn parses_grouped_extended_catalog_record() {
        let data_fork = b"extended grouped data";
        let resource_fork = b"extended grouped resources";
        let shared = [data_fork.as_slice(), resource_fork.as_slice()].concat();
        let packed = encode_vise_fork(&shared);
        let catalog_offset = VISE_HEADER_LEN + packed.len();
        let mut archive = vec![0u8; VISE_HEADER_LEN];
        archive[..4].copy_from_slice(VISE_MAGIC);
        archive[16..20].copy_from_slice(&VISE_VERSION_EXTENDED_CATALOG.to_be_bytes());
        archive[36..40].copy_from_slice(&(catalog_offset as u32).to_be_bytes());
        archive.extend_from_slice(&packed);

        let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
        catalog[..4].copy_from_slice(VISE_CATALOG_MAGIC);
        catalog[16..18].copy_from_slice(&1u16.to_be_bytes());
        archive.extend_from_slice(&catalog);
        let mut prefix = [0u8; VISE_EXTENDED_CATALOG_PREFIX_LEN];
        prefix[..4].copy_from_slice(b"PACK");
        archive.extend_from_slice(&prefix);
        archive.extend_from_slice(b"FVCT");
        let mut file = [0u8; VISE_FILE_RECORD_LEN];
        file[8] = 0x10;
        file[40..44].copy_from_slice(b"TEXT");
        file[44..48].copy_from_slice(b"ttxt");
        file[64..68].copy_from_slice(&(packed.len() as u32).to_be_bytes());
        file[68..72].copy_from_slice(&(data_fork.len() as u32).to_be_bytes());
        file[72..76].copy_from_slice(&(shared.len() as u32).to_be_bytes());
        file[76..80].copy_from_slice(&(resource_fork.len() as u32).to_be_bytes());
        file[96..100].copy_from_slice(&(VISE_HEADER_LEN as u32).to_be_bytes());
        file[104..108].copy_from_slice(&(data_fork.len() as u32).to_be_bytes());
        file[118] = 6;
        archive.extend_from_slice(&file);
        archive.extend_from_slice(&[0u8; VISE_EXTENDED_FILE_SUFFIX_LEN]);
        archive.extend_from_slice(b"ReadMe");

        let parsed = parse_vise(&archive).unwrap().unwrap();
        let entry = &parsed.entries[0];
        assert_eq!(entry.path, "ReadMe");
        assert_eq!(entry.data_packed, packed);
        assert_eq!(entry.rsrc_packed, packed);
        assert_eq!(entry.rsrc_unpacked_offset, data_fork.len());
        let decoded = decode_vise_fork(entry.data_packed, shared.len()).unwrap();
        assert_eq!(&decoded[..data_fork.len()], data_fork);
        assert_eq!(&decoded[entry.rsrc_unpacked_offset..], resource_fork);
    }

    #[test]
    fn parses_grouped_classic_records_with_shared_stream() {
        let file1_data = b"first file data fork contents";
        let file1_rsrc = b"first file rsrc";
        let file2_data = b"second file data fork contents";
        let mut shared_stream = Vec::new();
        shared_stream.extend_from_slice(file1_data);
        shared_stream.extend_from_slice(file1_rsrc);
        shared_stream.extend_from_slice(file2_data);
        let total_unpacked_len = shared_stream.len();
        let packed = encode_vise_fork(&shared_stream);

        let payload_offset = VISE_HEADER_LEN;
        let catalog_offset = payload_offset + packed.len();
        let mut archive = vec![0u8; VISE_HEADER_LEN];
        archive[0..4].copy_from_slice(VISE_MAGIC);
        archive[16..20].copy_from_slice(&VISE_VERSION_35_LITE.to_be_bytes());
        archive[36..40].copy_from_slice(&(catalog_offset as u32).to_be_bytes());
        archive.extend_from_slice(&packed);

        let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
        catalog[0..4].copy_from_slice(VISE_CATALOG_MAGIC);
        catalog[16..18].copy_from_slice(&2u16.to_be_bytes());
        archive.extend_from_slice(&catalog);

        // File 1
        archive.extend_from_slice(b"FVCT");
        let mut file1 = [0u8; VISE_FILE_RECORD_LEN];
        file1[8] = 0x10; // grouped flag
        file1[40..44].copy_from_slice(b"TEXT");
        file1[44..48].copy_from_slice(b"ttxt");
        file1[64..68].copy_from_slice(&(packed.len() as u32).to_be_bytes());
        file1[68..72].copy_from_slice(&(file1_data.len() as u32).to_be_bytes());
        file1[72..76].copy_from_slice(&(total_unpacked_len as u32).to_be_bytes());
        file1[76..80].copy_from_slice(&(file1_rsrc.len() as u32).to_be_bytes());
        file1[96..100].copy_from_slice(&(payload_offset as u32).to_be_bytes());
        file1[100..104].copy_from_slice(&0u32.to_be_bytes());
        file1[104..108].copy_from_slice(&(file1_data.len() as u32).to_be_bytes());
        file1[118] = 5;
        archive.extend_from_slice(&file1);
        archive.extend_from_slice(b"File1");

        // File 2
        archive.extend_from_slice(b"FVCT");
        let mut file2 = [0u8; VISE_FILE_RECORD_LEN];
        file2[8] = 0x10; // grouped flag
        file2[40..44].copy_from_slice(b"TEXT");
        file2[44..48].copy_from_slice(b"ttxt");
        file2[64..68].copy_from_slice(&(packed.len() as u32).to_be_bytes());
        file2[68..72].copy_from_slice(&(file2_data.len() as u32).to_be_bytes());
        file2[72..76].copy_from_slice(&(total_unpacked_len as u32).to_be_bytes());
        file2[76..80].copy_from_slice(&0u32.to_be_bytes());
        file2[96..100].copy_from_slice(&(payload_offset as u32).to_be_bytes());
        let file2_offset = (file1_data.len() + file1_rsrc.len()) as u32;
        file2[100..104].copy_from_slice(&file2_offset.to_be_bytes());
        file2[104..108].copy_from_slice(&0u32.to_be_bytes());
        file2[118] = 5;
        archive.extend_from_slice(&file2);
        archive.extend_from_slice(b"File2");

        let parsed = parse_vise(&archive).unwrap().unwrap();
        assert_eq!(parsed.entries.len(), 2);

        let e1 = &parsed.entries[0];
        assert_eq!(e1.path, "File1");
        assert_eq!(e1.data_packed, packed.as_slice());
        assert_eq!(e1.rsrc_packed, packed.as_slice());
        assert_eq!(e1.data_unpacked_offset, 0);
        assert_eq!(e1.rsrc_unpacked_offset, file1_data.len());
        assert_eq!(e1.data_unpacked_len, file1_data.len());
        assert_eq!(e1.rsrc_unpacked_len, file1_rsrc.len());

        let decoded = decode_vise_fork(e1.data_packed, total_unpacked_len).unwrap();
        assert_eq!(
            &decoded[e1.data_unpacked_offset..e1.data_unpacked_offset + e1.data_unpacked_len],
            file1_data
        );
        assert_eq!(
            &decoded[e1.rsrc_unpacked_offset..e1.rsrc_unpacked_offset + e1.rsrc_unpacked_len],
            file1_rsrc
        );

        let e2 = &parsed.entries[1];
        assert_eq!(e2.path, "File2");
        assert_eq!(e2.data_packed, packed.as_slice());
        assert!(e2.rsrc_packed.is_empty());
        assert_eq!(
            e2.data_unpacked_offset,
            (file1_data.len() + file1_rsrc.len())
        );
        assert_eq!(e2.data_unpacked_len, file2_data.len());
        assert_eq!(e2.rsrc_unpacked_len, 0);
        assert_eq!(
            &decoded[e2.data_unpacked_offset..e2.data_unpacked_offset + e2.data_unpacked_len],
            file2_data
        );
    }

    #[test]
    fn decodes_catalog_names_with_literal_slashes() {
        let mut archive = vec![0u8; VISE_HEADER_LEN];
        archive[0..4].copy_from_slice(VISE_MAGIC);
        archive[16..20].copy_from_slice(&VISE_VERSION_35_LITE.to_be_bytes());
        archive[36..40].copy_from_slice(&(VISE_HEADER_LEN as u32).to_be_bytes());

        let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
        catalog[0..4].copy_from_slice(VISE_CATALOG_MAGIC);
        catalog[16..18].copy_from_slice(&2u16.to_be_bytes());
        archive.extend_from_slice(&catalog);

        archive.extend_from_slice(b"DVCT");
        let mut dir = [0u8; VISE_DIRECTORY_RECORD_LEN];
        dir[76] = 11;
        archive.extend_from_slice(&dir);
        archive.extend_from_slice(b"MS Word/RTF");

        archive.extend_from_slice(b"FVCT");
        let mut file = [0u8; VISE_FILE_RECORD_LEN];
        file[40..44].copy_from_slice(b"TEXT");
        file[44..48].copy_from_slice(b"ttxt");
        file[92..94].copy_from_slice(&1u16.to_be_bytes()); // parent is dir 1
        file[118] = 10;
        archive.extend_from_slice(&file);
        archive.extend_from_slice(b"Manual 1/2");

        let parsed = parse_vise(&archive).unwrap().unwrap();
        assert_eq!(parsed.dirs.len(), 1);
        assert_eq!(parsed.dirs[0], "MS Word\u{F02F}RTF");
        assert_eq!(parsed.entries.len(), 1);
        assert_eq!(
            parsed.entries[0].path,
            "MS Word\u{F02F}RTF/Manual 1\u{F02F}2"
        );
    }

    #[test]
    fn rejects_traversal_in_catalog_components() {
        assert_eq!(
            validate_component("..", "file").unwrap_err(),
            "unsafe VISE file component \"..\""
        );
        assert!(validate_component("Volume:Game", "file").is_err());
    }

    #[test]
    fn parses_packed_extended_catalog_and_bounds_decompression() {
        let game_data = b"PowerPC application payload";
        let packed_game = encode_vise_fork(game_data);
        let payload_offset = VISE_HEADER_LEN;
        let catalog_offset = payload_offset + packed_game.len();
        let mut archive = vec![0u8; VISE_HEADER_LEN];
        archive[0..4].copy_from_slice(VISE_MAGIC);
        archive[16..20].copy_from_slice(&VISE_VERSION_PACKED_CATALOG.to_be_bytes());
        archive[36..40].copy_from_slice(&(catalog_offset as u32).to_be_bytes());
        archive.extend_from_slice(&packed_game);

        let mut records = Vec::new();
        records.extend_from_slice(b"DVCT");
        let mut directory = [0u8; VISE_DIRECTORY_RECORD_LEN];
        directory[76] = 4;
        records.extend_from_slice(&directory);
        records.extend_from_slice(&[0u8; VISE_PACKED_DIRECTORY_SUFFIX_LEN]);
        records.extend_from_slice(b"Game");

        records.extend_from_slice(b"FVCT");
        let mut file = [0u8; VISE_FILE_RECORD_LEN];
        file[40..44].copy_from_slice(b"APPL");
        file[44..48].copy_from_slice(b"TEST");
        file[64..68].copy_from_slice(&(packed_game.len() as u32).to_be_bytes());
        file[68..72].copy_from_slice(&(game_data.len() as u32).to_be_bytes());
        file[92..94].copy_from_slice(&1u16.to_be_bytes());
        file[96..100].copy_from_slice(&(payload_offset as u32).to_be_bytes());
        file[118] = 7;
        records.extend_from_slice(&file);
        records.extend_from_slice(&[0u8; VISE_PACKED_FILE_SUFFIX_LEN]);
        records.extend_from_slice(b"Runtime");
        records.extend_from_slice(b"PACK");

        let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(&records).unwrap();
        let mut packed_records = encoder.finish().unwrap();
        for pair in packed_records.chunks_exact_mut(2) {
            pair.swap(0, 1);
        }
        let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
        catalog[0..4].copy_from_slice(VISE_CATALOG_MAGIC);
        catalog[4..8].copy_from_slice(&(packed_records.len() as u32).to_be_bytes());
        catalog[16..18].copy_from_slice(&2u16.to_be_bytes());
        archive.extend_from_slice(&catalog);
        let mut prefix = [0u8; VISE_EXTENDED_CATALOG_PREFIX_LEN];
        prefix[0..4].copy_from_slice(b"PACK");
        archive.extend_from_slice(&prefix);
        archive.extend_from_slice(&packed_records);

        let parsed = parse_vise(&archive).unwrap().unwrap();
        assert_eq!(parsed.dirs, ["Game"]);
        assert_eq!(parsed.entries.len(), 1);
        let entry = &parsed.entries[0];
        assert_eq!(entry.path, "Game/Runtime");
        assert_eq!(entry.file_type, *b"APPL");
        assert_eq!(
            decode_vise_fork(entry.data_packed, game_data.len()).unwrap(),
            game_data
        );

        let mut excessive = archive.clone();
        excessive[catalog_offset + 16..catalog_offset + 18].copy_from_slice(&0u16.to_be_bytes());
        assert!(parse_vise(&excessive).unwrap().is_err());

        let mut truncated = archive;
        truncated[catalog_offset + 4..catalog_offset + 8]
            .copy_from_slice(&((packed_records.len() - 2) as u32).to_be_bytes());
        assert!(parse_vise(&truncated).unwrap().is_err());
    }

    #[test]
    fn decodes_word_aligned_stored_blocks_with_odd_payload() {
        // VISE pads both the stored header and its odd-length payload to a
        // 16-bit boundary before reading the next block.
        let stream = [
            0x00, 0x00, // nonfinal stored block, word-aligned LEN
            0x03, 0x00, 0xFC, 0xFF, b'a', b'b', b'c', 0x00, // odd-length pad
            0x01, 0x00, // final stored block, word-aligned LEN
            0x02, 0x00, 0xFD, 0xFF, b'd', b'e',
        ];
        let mut inverse = [0u8; 256];
        for (encoded, decoded) in VISE_DEOBFUSCATION_TABLE.iter().copied().enumerate() {
            inverse[decoded as usize] = encoded as u8;
        }
        let mut packed: Vec<u8> = stream.iter().map(|byte| inverse[*byte as usize]).collect();
        for pair in packed.chunks_exact_mut(2) {
            pair.swap(0, 1);
        }
        assert_eq!(decode_vise_fork(&packed, 5).unwrap(), b"abcde");
    }

    #[test]
    fn parses_vise_0304_directory_and_file_suffixes() {
        let original = make_test_archive("Game", b"powerpc payload", b"resource fork");
        let catalog_offset = read_u32(&original, 36, "catalog offset").unwrap() as usize;
        let file_record_start = catalog_offset + VISE_CATALOG_HEADER_LEN + 4;
        let mut file =
            original[file_record_start..file_record_start + VISE_FILE_RECORD_LEN].to_vec();
        file[92..94].copy_from_slice(&1u16.to_be_bytes());

        let mut archive = original[..catalog_offset].to_vec();
        archive[16..20].copy_from_slice(&VISE_VERSION_36_FULL.to_be_bytes());
        let mut catalog = [0u8; VISE_CATALOG_HEADER_LEN];
        catalog[..4].copy_from_slice(VISE_CATALOG_MAGIC);
        catalog[16..18].copy_from_slice(&2u16.to_be_bytes());
        archive.extend_from_slice(&catalog);
        archive.extend_from_slice(b"DVCT");
        let mut directory = [0u8; VISE_DIRECTORY_RECORD_LEN];
        directory[76] = 6;
        archive.extend_from_slice(&directory);
        archive.extend_from_slice(&[0u8; VISE_36_FULL_DIRECTORY_SUFFIX_LEN]);
        archive.extend_from_slice(b"Folder");
        archive.extend_from_slice(b"FVCT");
        archive.extend_from_slice(&file);
        archive.extend_from_slice(&[0u8; VISE_36_FULL_FILE_SUFFIX_LEN]);
        archive.extend_from_slice(b"Game");

        let parsed = parse_vise(&archive).unwrap().unwrap();
        assert_eq!(parsed.dirs, ["Folder"]);
        assert_eq!(parsed.entries.len(), 1);
        let game = &parsed.entries[0];
        assert_eq!(game.path, "Folder/Game");
        assert_eq!(
            decode_vise_fork(game.data_packed, game.data_unpacked_len).unwrap(),
            b"powerpc payload"
        );
        assert_eq!(
            decode_vise_fork(game.rsrc_packed, game.rsrc_unpacked_len).unwrap(),
            b"resource fork"
        );
    }
}