zipatch-rs 1.6.0

Parser for FFXIV ZiPatch patch files
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
//! Integration tests for the [`InMemoryFs`] backing.
//!
//! Originally written to exercise the long-removed `ApplyMode::DryRun`
//! enum, these tests now drive the apply layer through the in-memory
//! vfs — the canonical replacement for "walk every chunk, validate
//! every CRC, decompress every DEFLATE block, but don't touch the host
//! filesystem". The host-side `tempdir` remains the install root the
//! apply layer believes it is writing to; assertions confirm that the
//! tempdir stays empty (because the vfs swallows the writes) while the
//! in-memory backing surfaces them via its `snapshot_files` accessor.

mod common;

use std::io::Cursor;
use std::ops::ControlFlow;
use std::sync::{Arc, Mutex};

use common::{
    FileBlock, snapshot_tree, sqpk_add_data_body, sqpk_addfile_body, sqpk_delete_file_body,
    sqpk_expand_data_body, sqpk_target_info_body, wrap_patch,
};
use zipatch_rs::apply::InMemoryFs;
use zipatch_rs::index::{
    FilesystemOp, PartExpected, PartSource, PatchRef, PatchSourceKind, Plan, Region, Target,
    TargetPath,
};
use zipatch_rs::test_utils::MemoryPatchSource;
use zipatch_rs::test_utils::make_chunk;
use zipatch_rs::{
    ApplyConfig, ApplyError, ApplyObserver, ChunkEvent, IndexApplier, Platform, ZiPatchReader,
};

fn synth_patch() -> Vec<u8> {
    wrap_patch(vec![
        make_chunk(
            b"SQPK",
            &sqpk_addfile_body(
                "out/raw.dat",
                0,
                &[FileBlock {
                    is_compressed: false,
                    decompressed: b"raw block bytes".to_vec(),
                }],
            ),
        ),
        make_chunk(
            b"SQPK",
            &sqpk_addfile_body(
                "out/zipped.dat",
                0,
                &[FileBlock {
                    is_compressed: true,
                    decompressed: vec![0xCDu8; 4096],
                }],
            ),
        ),
    ])
}

#[test]
fn in_memory_apply_leaves_host_untouched_but_records_writes() {
    let patch = synth_patch();

    let tmp = tempfile::tempdir().unwrap();
    let before = snapshot_tree(tmp.path());
    assert!(before.is_empty(), "pre-condition: tempdir must start empty");

    let fs = InMemoryFs::new();
    let mut ctx = ApplyConfig::new(tmp.path())
        .with_vfs(fs.clone())
        .into_session();

    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect("in-memory apply of a clean patch must succeed");

    let after = snapshot_tree(tmp.path());
    assert!(
        after.is_empty(),
        "in-memory vfs must leave the install tree untouched; found {after:?}"
    );
    let mem = fs.snapshot_files();
    assert_eq!(mem.len(), 2, "two AddFile chunks => two in-memory files");
}

#[test]
fn in_memory_apply_propagates_crc_mismatch() {
    let mut patch = synth_patch();
    let last_idx = patch.len() - 2;
    patch[last_idx] ^= 0xFF;

    let tmp = tempfile::tempdir().unwrap();
    let mut ctx = ApplyConfig::new(tmp.path())
        .with_vfs(InMemoryFs::new())
        .into_session();

    let err = {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect_err("CRC-corrupted patch must fail under in-memory apply");
    assert!(
        matches!(
            err,
            ApplyError::Parse(zipatch_rs::ParseError::ChecksumMismatch { .. })
        ),
        "expected ChecksumMismatch, got {err:?}",
    );
}

#[test]
fn in_memory_and_std_apply_both_succeed_on_clean_patch() {
    let patch = synth_patch();

    let wet_tmp = tempfile::tempdir().unwrap();
    let mut wet_ctx = ApplyConfig::new(wet_tmp.path()).into_session();
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        wet_ctx.apply_patch(reader)
    }
    .expect("std apply must succeed");

    let dry_tmp = tempfile::tempdir().unwrap();
    let fs = InMemoryFs::new();
    let mut dry_ctx = ApplyConfig::new(dry_tmp.path())
        .with_vfs(fs.clone())
        .into_session();
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        dry_ctx.apply_patch(reader)
    }
    .expect("in-memory apply must succeed for the same patch");

    assert!(
        !snapshot_tree(wet_tmp.path()).is_empty(),
        "std apply must have produced files (sanity check)"
    );
    assert!(
        snapshot_tree(dry_tmp.path()).is_empty(),
        "in-memory apply must produce no host-side files"
    );
    assert!(
        !fs.snapshot_files().is_empty(),
        "in-memory apply must record the writes in the vfs"
    );
}

/// SQPK 'F' `RemoveAll` body.
fn sqpk_removeall_body(expansion_id: u16) -> Vec<u8> {
    let mut cmd = Vec::new();
    cmd.push(b'R');
    cmd.extend_from_slice(&[0u8; 2]);
    cmd.extend_from_slice(&0u64.to_be_bytes());
    cmd.extend_from_slice(&0u64.to_be_bytes());
    cmd.extend_from_slice(&0u32.to_be_bytes());
    cmd.extend_from_slice(&expansion_id.to_be_bytes());
    cmd.extend_from_slice(&[0u8; 2]);

    let mut body = Vec::new();
    let inner_size = (5 + cmd.len()) as i32;
    body.extend_from_slice(&inner_size.to_be_bytes());
    body.push(b'F');
    body.extend_from_slice(&cmd);
    body
}

#[test]
fn in_memory_removeall_against_missing_install_is_silent_ok() {
    let patch = wrap_patch(vec![make_chunk(b"SQPK", &sqpk_removeall_body(0))]);

    let tmp = tempfile::tempdir().unwrap();
    let mut ctx = ApplyConfig::new(tmp.path())
        .with_vfs(InMemoryFs::new())
        .into_session();
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect("RemoveAll against a missing in-memory install must return Ok");
}

#[test]
fn in_memory_delete_file_missing_requires_ignore_missing() {
    let patch = wrap_patch(vec![make_chunk(
        b"SQPK",
        &sqpk_delete_file_body("does/not/exist.bin"),
    )]);

    // ignore_missing=true → ok
    let tmp = tempfile::tempdir().unwrap();
    let ctx = ApplyConfig::new(tmp.path())
        .with_vfs(InMemoryFs::new())
        .with_ignore_missing(true);
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect("DeleteFile missing with ignore_missing must succeed");

    // ignore_missing=false → NotFound error from the vfs surfaces
    let tmp = tempfile::tempdir().unwrap();
    let ctx = ApplyConfig::new(tmp.path()).with_vfs(InMemoryFs::new());
    let err = {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect_err("DeleteFile missing without ignore_missing must fail");
    assert!(matches!(err, ApplyError::Io { .. }), "got {err:?}");
}

fn deld_body(name: &str) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&(name.len() as u32).to_be_bytes());
    b.extend_from_slice(name.as_bytes());
    b
}

#[test]
fn in_memory_delete_directory_missing_requires_ignore_missing() {
    let patch = wrap_patch(vec![make_chunk(b"DELD", &deld_body("missing_dir"))]);

    let tmp = tempfile::tempdir().unwrap();
    let ctx = ApplyConfig::new(tmp.path())
        .with_vfs(InMemoryFs::new())
        .with_ignore_missing(true);
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect("DeleteDirectory missing with ignore_missing must succeed");

    let tmp = tempfile::tempdir().unwrap();
    let ctx = ApplyConfig::new(tmp.path()).with_vfs(InMemoryFs::new());
    let err = {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect_err("DeleteDirectory missing without ignore_missing must fail");
    assert!(matches!(err, ApplyError::Io { .. }), "got {err:?}");
}

#[derive(Default, Clone)]
struct RecordingObserver {
    events: Arc<Mutex<Vec<ChunkEvent>>>,
}

impl ApplyObserver for RecordingObserver {
    fn on_chunk_applied(&mut self, ev: ChunkEvent) -> ControlFlow<(), ()> {
        self.events.lock().unwrap().push(ev);
        ControlFlow::Continue(())
    }
}

#[test]
fn in_memory_observer_callbacks_match_std_run() {
    let patch = synth_patch();

    let wet_events = Arc::new(Mutex::new(Vec::new()));
    let wet_tmp = tempfile::tempdir().unwrap();
    let wet_ctx = ApplyConfig::new(wet_tmp.path()).with_observer(RecordingObserver {
        events: Arc::clone(&wet_events),
    });
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        wet_ctx.apply_patch(reader)
    }
    .expect("std apply must succeed");

    let dry_events = Arc::new(Mutex::new(Vec::new()));
    let dry_tmp = tempfile::tempdir().unwrap();
    let dry_ctx = ApplyConfig::new(dry_tmp.path())
        .with_vfs(InMemoryFs::new())
        .with_observer(RecordingObserver {
            events: Arc::clone(&dry_events),
        });
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        dry_ctx.apply_patch(reader)
    }
    .expect("in-memory apply must succeed");

    let wet = wet_events.lock().unwrap().clone();
    let dry = dry_events.lock().unwrap().clone();
    assert_eq!(
        wet, dry,
        "observer event sequences must be identical between std and in-memory backings"
    );
    assert!(
        !wet.is_empty(),
        "sanity: observer must have received events"
    );
}

fn generic_target(rel: &str, regions: Vec<Region>) -> Target {
    let final_size = regions
        .last()
        .map_or(0, |r| r.target_offset + u64::from(r.length));
    Target::new(TargetPath::Generic(rel.to_owned()), final_size, regions)
}

fn raw_region(target_offset: u64, len: u32, src_offset: u64) -> Region {
    Region::new(
        target_offset,
        len,
        PartSource::Patch {
            patch_idx: zipatch_rs::newtypes::PatchIndex::new(0),
            offset: src_offset,
            kind: PatchSourceKind::Raw { len },
            decoded_skip: 0,
        },
        PartExpected::SizeOnly,
    )
}

#[test]
fn in_memory_indexed_apply_leaves_install_empty_but_writes_to_vfs() {
    let mut src_buf = vec![0u8; 256];
    src_buf[0..16].fill(0x11);
    src_buf[100..116].fill(0x22);
    let src = MemoryPatchSource::new(src_buf);

    let targets = vec![
        generic_target("a.bin", vec![raw_region(0, 16, 0)]),
        generic_target("b.bin", vec![raw_region(0, 16, 100)]),
    ];
    let plan = Plan::new(
        Platform::Win32,
        vec![PatchRef::new("synthetic", None)],
        targets,
        vec![],
    );

    let events = Arc::new(Mutex::new(Vec::new()));
    let observer = RecordingObserver {
        events: Arc::clone(&events),
    };

    let tmp = tempfile::tempdir().unwrap();
    let fs = InMemoryFs::new();
    IndexApplier::new(src, tmp.path())
        .with_vfs(fs.clone())
        .with_observer(observer)
        .execute(&plan)
        .expect("in-memory indexed apply must succeed");

    assert!(
        snapshot_tree(tmp.path()).is_empty(),
        "in-memory indexed apply must leave the host tree empty"
    );
    assert_eq!(
        fs.snapshot_files().len(),
        2,
        "two targets must produce two in-memory files"
    );
    assert!(
        !events.lock().unwrap().is_empty(),
        "in-memory indexed apply must still drive per-target observer events"
    );
}

// ---------------------------------------------------------------------------
// SQPK chunk variant coverage in-memory: host fs stays clean
// ---------------------------------------------------------------------------

fn sqpk_delete_data_body_local(
    main_id: u16,
    sub_id: u16,
    file_id: u32,
    block_offset_raw: u32,
    block_count: u32,
) -> Vec<u8> {
    let mut cmd = Vec::new();
    cmd.extend_from_slice(&[0u8; 3]);
    cmd.extend_from_slice(&main_id.to_be_bytes());
    cmd.extend_from_slice(&sub_id.to_be_bytes());
    cmd.extend_from_slice(&file_id.to_be_bytes());
    cmd.extend_from_slice(&block_offset_raw.to_be_bytes());
    cmd.extend_from_slice(&block_count.to_be_bytes());
    cmd.extend_from_slice(&[0u8; 4]);

    let mut body = Vec::new();
    let inner_size = (5 + cmd.len()) as i32;
    body.extend_from_slice(&inner_size.to_be_bytes());
    body.push(b'D');
    body.extend_from_slice(&cmd);
    body
}

fn sqpk_header_body_local(
    file_kind: u8,
    header_kind: u8,
    main_id: u16,
    sub_id: u16,
    file_id: u32,
    header_data: &[u8; 1024],
) -> Vec<u8> {
    let mut cmd = Vec::new();
    cmd.push(file_kind);
    cmd.push(header_kind);
    cmd.push(0);
    cmd.extend_from_slice(&main_id.to_be_bytes());
    cmd.extend_from_slice(&sub_id.to_be_bytes());
    cmd.extend_from_slice(&file_id.to_be_bytes());
    cmd.extend_from_slice(header_data);

    let mut body = Vec::new();
    let inner_size = (5 + cmd.len()) as i32;
    body.extend_from_slice(&inner_size.to_be_bytes());
    body.push(b'H');
    body.extend_from_slice(&cmd);
    body
}

fn sqpk_makedir_body_local(path: &str) -> Vec<u8> {
    let mut path_bytes = path.as_bytes().to_vec();
    path_bytes.push(0);

    let mut cmd = Vec::new();
    cmd.push(b'M');
    cmd.extend_from_slice(&[0u8; 2]);
    cmd.extend_from_slice(&0u64.to_be_bytes());
    cmd.extend_from_slice(&0u64.to_be_bytes());
    cmd.extend_from_slice(&(path_bytes.len() as u32).to_be_bytes());
    cmd.extend_from_slice(&0u16.to_be_bytes());
    cmd.extend_from_slice(&[0u8; 2]);
    cmd.extend_from_slice(&path_bytes);

    let mut body = Vec::new();
    let inner_size = (5 + cmd.len()) as i32;
    body.extend_from_slice(&inner_size.to_be_bytes());
    body.push(b'F');
    body.extend_from_slice(&cmd);
    body
}

#[test]
fn in_memory_add_data_does_not_touch_host() {
    let payload = vec![0u8; 128];
    let patch = wrap_patch(vec![
        make_chunk(b"SQPK", &sqpk_target_info_body(0)),
        make_chunk(b"SQPK", &sqpk_add_data_body(0, 0, 0, 0, &payload, 0)),
    ]);

    let tmp = tempfile::tempdir().unwrap();
    let mut ctx = ApplyConfig::new(tmp.path())
        .with_vfs(InMemoryFs::new())
        .into_session();
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect("AddData in-memory must succeed");

    assert!(
        snapshot_tree(tmp.path()).is_empty(),
        "AddData in-memory must not create host files"
    );
}

#[test]
fn in_memory_delete_data_does_not_touch_host() {
    let patch = wrap_patch(vec![
        make_chunk(b"SQPK", &sqpk_target_info_body(0)),
        make_chunk(b"SQPK", &sqpk_delete_data_body_local(0, 0, 0, 0, 1)),
    ]);

    let tmp = tempfile::tempdir().unwrap();
    let mut ctx = ApplyConfig::new(tmp.path())
        .with_vfs(InMemoryFs::new())
        .into_session();
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect("DeleteData in-memory must succeed");

    assert!(snapshot_tree(tmp.path()).is_empty());
}

#[test]
fn in_memory_expand_data_does_not_touch_host() {
    let patch = wrap_patch(vec![
        make_chunk(b"SQPK", &sqpk_target_info_body(0)),
        make_chunk(b"SQPK", &sqpk_expand_data_body(0, 0, 0, 0, 1)),
    ]);

    let tmp = tempfile::tempdir().unwrap();
    let mut ctx = ApplyConfig::new(tmp.path())
        .with_vfs(InMemoryFs::new())
        .into_session();
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect("ExpandData in-memory must succeed");

    assert!(snapshot_tree(tmp.path()).is_empty());
}

#[test]
fn in_memory_header_does_not_touch_host() {
    let patch = wrap_patch(vec![
        make_chunk(b"SQPK", &sqpk_target_info_body(0)),
        make_chunk(
            b"SQPK",
            &sqpk_header_body_local(b'D', b'V', 0, 0, 0, &[0u8; 1024]),
        ),
    ]);

    let tmp = tempfile::tempdir().unwrap();
    let mut ctx = ApplyConfig::new(tmp.path())
        .with_vfs(InMemoryFs::new())
        .into_session();
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect("Header in-memory must succeed");

    assert!(snapshot_tree(tmp.path()).is_empty());
}

#[test]
fn in_memory_makedirtree_does_not_create_host_directories() {
    let patch = wrap_patch(vec![make_chunk(
        b"SQPK",
        &sqpk_makedir_body_local("sqpack/ex1/0a0000"),
    )]);

    let tmp = tempfile::tempdir().unwrap();
    let fs = InMemoryFs::new();
    let mut ctx = ApplyConfig::new(tmp.path())
        .with_vfs(fs.clone())
        .into_session();
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect("MakeDirTree in-memory must succeed");

    assert!(
        snapshot_tree(tmp.path()).is_empty(),
        "MakeDirTree must not create host directories"
    );
    assert!(
        !tmp.path().join("sqpack").exists(),
        "MakeDirTree must not reach through to the host fs"
    );
    // The vfs records the directory creation, though.
    let dirs = fs.snapshot_dirs();
    assert!(
        dirs.iter().any(|d| d.ends_with("sqpack/ex1/0a0000")),
        "in-memory vfs must have recorded the directory tree; got {dirs:?}"
    );
}

// ---------------------------------------------------------------------------
// Error paths preserved
// ---------------------------------------------------------------------------

#[test]
fn in_memory_unsupported_platform_surfaces_error() {
    let payload = vec![0u8; 128];
    let patch = wrap_patch(vec![
        make_chunk(b"SQPK", &sqpk_target_info_body(99)),
        make_chunk(b"SQPK", &sqpk_add_data_body(0, 0, 0, 0, &payload, 0)),
    ]);

    let tmp = tempfile::tempdir().unwrap();
    let mut ctx = ApplyConfig::new(tmp.path())
        .with_vfs(InMemoryFs::new())
        .into_session();
    let err = {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect_err("Unknown platform must surface UnsupportedPlatform");

    assert!(
        matches!(err, ApplyError::UnsupportedPlatform(_)),
        "expected UnsupportedPlatform, got {err:?}"
    );
}

fn sqpk_addfile_body_with_bad_deflate(path: &str) -> Vec<u8> {
    let mut path_bytes = path.as_bytes().to_vec();
    path_bytes.push(0);

    let decompressed_size: i32 = 256;
    let garbage: Vec<u8> = vec![0xFF, 0xFE, 0xFD, 0x00, 0x01, 0x02, 0x03, 0x04];

    let header_size: i32 = 16;
    let compressed_size: i32 = garbage.len() as i32;
    let block_len = ((garbage.len() as u32 + 16 + 143) & !127) as usize;
    let pad = block_len - 16 - garbage.len();

    let mut cmd = Vec::new();
    cmd.push(b'A');
    cmd.extend_from_slice(&[0u8; 2]);
    cmd.extend_from_slice(&0u64.to_be_bytes());
    cmd.extend_from_slice(&(decompressed_size as u64).to_be_bytes());
    cmd.extend_from_slice(&(path_bytes.len() as u32).to_be_bytes());
    cmd.extend_from_slice(&0u16.to_be_bytes());
    cmd.extend_from_slice(&[0u8; 2]);
    cmd.extend_from_slice(&path_bytes);

    cmd.extend_from_slice(&header_size.to_le_bytes());
    cmd.extend_from_slice(&0u32.to_le_bytes());
    cmd.extend_from_slice(&compressed_size.to_le_bytes());
    cmd.extend_from_slice(&decompressed_size.to_le_bytes());
    cmd.extend_from_slice(&garbage);
    cmd.extend_from_slice(&vec![0u8; pad]);

    let mut body = Vec::new();
    let inner_size = (5 + cmd.len()) as i32;
    body.extend_from_slice(&inner_size.to_be_bytes());
    body.push(b'F');
    body.extend_from_slice(&cmd);
    body
}

#[test]
fn in_memory_corrupted_deflate_block_surfaces_decompress_error() {
    let patch = wrap_patch(vec![make_chunk(
        b"SQPK",
        &sqpk_addfile_body_with_bad_deflate("out/bad.dat"),
    )]);

    let tmp = tempfile::tempdir().unwrap();
    let mut ctx = ApplyConfig::new(tmp.path())
        .with_vfs(InMemoryFs::new())
        .into_session();
    let err = {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        ctx.apply_patch(reader)
    }
    .expect_err("Corrupted DEFLATE block must surface an error");

    assert!(
        matches!(
            err,
            ApplyError::Parse(zipatch_rs::ParseError::Decompress { .. })
        ),
        "expected Decompress error, got {err:?}"
    );
}

// ---------------------------------------------------------------------------
// Indexed apply fs_ops coverage in-memory
// ---------------------------------------------------------------------------

#[test]
fn in_memory_indexed_apply_delete_file_missing_surfaces_not_found() {
    // Unlike the old dry-run, the indexed apply's fs_op DeleteFile demotes
    // NotFound to a trace! and continues — see `apply_fs_ops` in
    // src/index/apply.rs. That demotion stands: pre-truncate hints are
    // legitimately NotFound on a fresh install. So this test pins that
    // contract under the in-memory vfs.
    let src = MemoryPatchSource::new(Vec::new());

    let plan = Plan::new(
        Platform::Win32,
        vec![PatchRef::new("synthetic", None)],
        vec![],
        vec![FilesystemOp::DeleteFile("does/not/exist.bin".into())],
    );

    let tmp = tempfile::tempdir().unwrap();
    IndexApplier::new(src, tmp.path())
        .with_vfs(InMemoryFs::new())
        .execute(&plan)
        .expect("indexed DeleteFile fs_op must demote NotFound to a no-op");
}

#[test]
fn in_memory_indexed_apply_delete_dir_missing_propagates() {
    // Indexed apply does NOT demote NotFound for DeleteDir (no analogous
    // pre-truncate hint), so the in-memory vfs's NotFound surfaces.
    let src = MemoryPatchSource::new(Vec::new());

    let plan = Plan::new(
        Platform::Win32,
        vec![PatchRef::new("synthetic", None)],
        vec![],
        vec![FilesystemOp::DeleteDir("does/not/exist".into())],
    );

    let tmp = tempfile::tempdir().unwrap();
    let err = IndexApplier::new(src, tmp.path())
        .with_vfs(InMemoryFs::new())
        .execute(&plan)
        .expect_err("indexed DeleteDir against missing dir must fail");
    assert!(
        matches!(err, zipatch_rs::IndexError::Io { .. }),
        "got {err:?}"
    );
}

#[test]
fn in_memory_indexed_apply_with_remove_all_fs_op_against_missing_expansion_is_ok() {
    let src = MemoryPatchSource::new(Vec::new());

    let plan = Plan::new(
        Platform::Win32,
        vec![PatchRef::new("synthetic", None)],
        vec![],
        vec![FilesystemOp::RemoveAllInExpansion(0)],
    );

    let tmp = tempfile::tempdir().unwrap();
    IndexApplier::new(src, tmp.path())
        .with_vfs(InMemoryFs::new())
        .execute(&plan)
        .expect("RemoveAllInExpansion against missing expansion must return Ok");
}

#[test]
fn in_memory_indexed_apply_make_dir_tree_records_in_vfs() {
    let src = MemoryPatchSource::new(Vec::new());

    let plan = Plan::new(
        Platform::Win32,
        vec![PatchRef::new("synthetic", None)],
        vec![],
        vec![FilesystemOp::MakeDirTree("sqpack/ex1".into())],
    );

    let tmp = tempfile::tempdir().unwrap();
    let fs = InMemoryFs::new();
    IndexApplier::new(src, tmp.path())
        .with_vfs(fs.clone())
        .execute(&plan)
        .expect("MakeDirTree fs_op must succeed");

    assert!(
        !tmp.path().join("sqpack").exists(),
        "in-memory vfs must not reach through to the host"
    );
    let dirs = fs.snapshot_dirs();
    assert!(
        dirs.iter().any(|d| d.ends_with("sqpack/ex1")),
        "vfs must record the directory tree; got {dirs:?}"
    );
}

// ---------------------------------------------------------------------------
// In-memory vs std equivalence: end-to-end byte-for-byte
// ---------------------------------------------------------------------------

#[test]
fn in_memory_apply_produces_same_bytes_as_std_apply() {
    let patch = synth_patch();

    let std_tmp = tempfile::tempdir().unwrap();
    let mut std_ctx = ApplyConfig::new(std_tmp.path()).into_session();
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        std_ctx.apply_patch(reader)
    }
    .expect("std apply must succeed");

    let mem_tmp = tempfile::tempdir().unwrap();
    let fs = InMemoryFs::new();
    let mut mem_ctx = ApplyConfig::new(mem_tmp.path())
        .with_vfs(fs.clone())
        .into_session();
    {
        let reader = ZiPatchReader::new(Cursor::new(&patch)).unwrap();
        mem_ctx.apply_patch(reader)
    }
    .expect("in-memory apply must succeed");

    // Compare every file in the std-side tree against the in-memory vfs.
    let mem_files = fs.snapshot_files();
    let mut compared = 0usize;
    for entry in walkdir(std_tmp.path()) {
        let rel = entry.strip_prefix(std_tmp.path()).unwrap();
        let mem_path = mem_tmp.path().join(rel);
        let std_bytes = std::fs::read(&entry).unwrap();
        let mem_bytes = mem_files
            .get(&mem_path)
            .unwrap_or_else(|| panic!("in-memory vfs missing {mem_path:?}"));
        assert_eq!(
            &std_bytes, mem_bytes,
            "std and in-memory bytes must match for {rel:?}"
        );
        compared += 1;
    }
    assert!(compared > 0, "sanity: must have compared at least one file");
}

fn walkdir(root: &std::path::Path) -> Vec<std::path::PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if path.is_file() {
                out.push(path);
            }
        }
    }
    out
}