zipatch-rs 1.4.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
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
//! Parser and applier for FFXIV `ZiPatch` (`.patch`) binary files.
//!
//! `zipatch-rs` decodes the binary patch format that Square Enix ships for
//! Final Fantasy XIV and writes the decoded changes to a local game installation.
//! The library never touches the network — it operates entirely on byte streams
//! you supply.
//!
//! # Architecture
//!
//! The crate is split into three layers that share types but are otherwise
//! independent:
//!
//! ## Layer 1 — I/O primitives (`reader`)
//!
//! `reader::ReadExt` is a crate-internal extension trait that adds typed
//! big- and little-endian reads on top of [`std::io::Read`]. It is not part
//! of the public API; the parsing layer uses it exclusively.
//!
//! ## Layer 2 — Parsing ([`chunk`])
//!
//! [`ZiPatchReader`] is an [`Iterator`] over [`Chunk`] values. Construct it
//! from any [`std::io::Read`] source (a [`std::fs::File`], a
//! [`std::io::Cursor<Vec<u8>>`], a network stream, …). It validates the
//! 12-byte file magic on construction, then yields one [`Chunk`] per
//! [`Iterator::next`] call until it sees the `EOF_` terminator or hits an
//! error.
//!
//! Nothing in the parsing layer allocates file handles, stats paths, or
//! performs I/O against the install tree. Parse-only users can consume
//! [`ZiPatchReader`] without ever importing [`apply`].
//!
//! ## Layer 3 — Applying ([`apply`])
//!
//! The [`Apply`] trait bridges parsing and application: every [`Chunk`]
//! variant implements it, and each implementation writes the patch change to
//! disk via an [`ApplyContext`]. [`ApplyContext`] holds the install root, the
//! target [`Platform`], behavioural flags, and an internal file-handle cache
//! that avoids re-opening the same `.dat` file for every chunk.
//!
//! # Quick start
//!
//! The most common usage: open a patch file, build a context, apply every
//! chunk in stream order.
//!
//! ```no_run
//! use std::fs::File;
//! use zipatch_rs::{ApplyContext, ZiPatchReader};
//!
//! let patch_file = File::open("H2017.07.11.0000.0000a.patch").unwrap();
//! let mut ctx = ApplyContext::new("/opt/ffxiv/game");
//!
//! ZiPatchReader::new(patch_file)
//!     .unwrap()
//!     .apply_to(&mut ctx)
//!     .unwrap();
//! ```
//!
//! # Inspecting a patch without applying it
//!
//! Iterate the reader directly to inspect chunks without touching the
//! filesystem:
//!
//! ```no_run
//! use zipatch_rs::{Chunk, ZiPatchReader};
//! use std::fs::File;
//!
//! let reader = ZiPatchReader::new(File::open("patch.patch").unwrap()).unwrap();
//! for chunk in reader {
//!     match chunk.unwrap() {
//!         Chunk::FileHeader(h) => println!("patch version: {:?}", h),
//!         Chunk::AddDirectory(d) => println!("mkdir {}", d.name),
//!         Chunk::Sqpk(cmd) => println!("sqpk: {cmd:?}"),
//!         _ => {}
//!     }
//! }
//! ```
//!
//! # In-memory doctest
//!
//! The following example builds a minimal well-formed patch in memory — magic
//! header, one `ADIR` chunk (which creates a directory), and an `EOF_`
//! terminator — then applies it to a temporary directory. This mirrors the
//! technique used in the crate's own unit tests.
//!
//! ```rust
//! use std::io::Cursor;
//! use zipatch_rs::{ApplyContext, Chunk, ZiPatchReader};
//!
//! // ZiPatch file magic: \x91ZIPATCH\r\n\x1a\n
//! const MAGIC: [u8; 12] = [
//!     0x91, 0x5A, 0x49, 0x50, 0x41, 0x54, 0x43, 0x48,
//!     0x0D, 0x0A, 0x1A, 0x0A,
//! ];
//!
//! /// Wrap `tag + body` into a length-prefixed, CRC32-verified chunk frame.
//! fn make_chunk(tag: &[u8; 4], body: &[u8]) -> Vec<u8> {
//!     // CRC is computed over tag ++ body (NOT including the leading body_len).
//!     let mut crc_input = Vec::new();
//!     crc_input.extend_from_slice(tag);
//!     crc_input.extend_from_slice(body);
//!     let crc = crc32fast::hash(&crc_input);
//!
//!     let mut out = Vec::new();
//!     out.extend_from_slice(&(body.len() as u32).to_be_bytes()); // body_len: u32 BE
//!     out.extend_from_slice(tag);                                // tag: 4 bytes
//!     out.extend_from_slice(body);                               // body: body_len bytes
//!     out.extend_from_slice(&crc.to_be_bytes());                 // crc32: u32 BE
//!     out
//! }
//!
//! // ADIR body: big-endian u32 name length followed by the name bytes.
//! let mut adir_body = Vec::new();
//! adir_body.extend_from_slice(&7u32.to_be_bytes()); // name_len
//! adir_body.extend_from_slice(b"created");          // name
//!
//! // Assemble the full patch stream.
//! let mut patch = Vec::new();
//! patch.extend_from_slice(&MAGIC);
//! patch.extend_from_slice(&make_chunk(b"ADIR", &adir_body));
//! patch.extend_from_slice(&make_chunk(b"EOF_", &[]));
//!
//! // Apply to a temporary directory.
//! let tmp = tempfile::tempdir().unwrap();
//! let mut ctx = ApplyContext::new(tmp.path());
//! ZiPatchReader::new(Cursor::new(patch))
//!     .unwrap()
//!     .apply_to(&mut ctx)
//!     .unwrap();
//!
//! assert!(tmp.path().join("created").is_dir());
//! ```
//!
//! # Error handling
//!
//! Every fallible operation returns [`Result<T>`], which is an alias for
//! `std::result::Result<T, `[`ZiPatchError`]`>`. Parse errors and apply
//! errors share the same type so callers need only one error arm.
//!
//! # Progress and cancellation
//!
//! [`ApplyContext::with_observer`] installs an [`ApplyObserver`] that is
//! called after each chunk applies (with the chunk index, tag, and running
//! byte count from [`ZiPatchReader::bytes_read`]) and polled inside long-
//! running chunks for cancellation. Returning
//! [`std::ops::ControlFlow::Break`] from a per-chunk callback, or `true`
//! from [`ApplyObserver::should_cancel`], aborts the apply call with
//! [`ZiPatchError::Cancelled`]. Parsing-only consumers and existing
//! [`apply_to`](ZiPatchReader::apply_to) callers that never install an
//! observer pay nothing — the default is a no-op.
//!
//! # Tracing
//!
//! The library emits structured [`tracing`] events and spans across the
//! parse, plan-build, apply, and verify entry points. Levels follow a
//! "one event per logical operation at `info!`, per-target/per-fs-op at
//! `debug!`, per-region/byte-level work at `trace!`" cadence. The top-level
//! spans (`apply_patch`, `apply_plan`, `build_plan_patch`, `compute_crc32`,
//! `verify_plan`, `verify_hashes`) are emitted at the `info` level so a subscriber configured
//! at the default level can scope output via span filtering, while per-target
//! sub-spans (`apply_target`) emit at `debug`. Recoverable anomalies — stale
//! manifest entries, unknown platform IDs, missing-but-ignored files — fire
//! `warn!`; errors are returned via [`ZiPatchError`] rather than logged. No
//! subscriber is configured here — that is the consumer's responsibility.
//!
//! [`tracing`]: https://docs.rs/tracing

#![deny(missing_docs)]

/// Filesystem application of parsed chunks ([`Apply`], [`ApplyContext`]).
pub mod apply;
/// Wire-format chunk types and the [`ZiPatchReader`] iterator.
pub mod chunk;
/// Error type returned by parsing and applying ([`ZiPatchError`]).
pub mod error;
/// Indexed-apply plan model and single-patch builder
/// ([`Plan`], [`PlanBuilder`]).
pub mod index;
pub(crate) mod reader;
/// Post-apply integrity verification against caller-supplied file hashes.
pub mod verify;

/// Shared chunk-framing fixtures for unit and integration tests.
///
/// Exposed under `#[cfg(test)]` to all tests in this crate, and behind the
/// `test-utils` feature flag to downstream consumers. **Not part of the
/// stable public API** — see the module rustdoc for details.
#[cfg(any(test, feature = "test-utils"))]
pub mod test_utils;

/// Fuzz-only re-exports of crate-internal primitives.
///
/// `cfg(fuzzing)` is set automatically by cargo-fuzz when compiling a fuzz
/// target — it is never set in normal `cargo build` / `cargo test` / CI builds.
/// Nothing exported from this module is part of the public API.
#[cfg(fuzzing)]
#[doc(hidden)]
pub mod fuzz_internal {
    pub use crate::reader::ReadExt;
}

pub use apply::{
    Apply, ApplyContext, ApplyMode, ApplyObserver, Checkpoint, CheckpointPolicy, CheckpointSink,
    ChunkEvent, InFlightAddFile, IndexedCheckpoint, NoopCheckpointSink, NoopObserver,
    SequentialCheckpoint,
};
pub use chunk::{Chunk, ZiPatchReader};
pub use error::ZiPatchError;
pub use index::{IndexApplier, Plan, PlanBuilder, Verifier};

#[cfg(any(test, feature = "test-utils"))]
pub use index::MemoryPatchSource;

/// Crate-wide `Result` alias parameterised over [`ZiPatchError`].
pub type Result<T> = std::result::Result<T, ZiPatchError>;

/// Run the apply loop from `start_index` to `EOF_`, emitting a chunk-boundary
/// checkpoint after each successful apply.
///
/// Factored out of [`ZiPatchReader::apply_to`] so [`ZiPatchReader::resume_apply_to`]
/// can drive the same loop after fast-forwarding. The caller is responsible
/// for any pre-loop work (parsing the magic, fast-forwarding past completed
/// chunks, resuming an in-flight `AddFile`).
///
/// Returns the number of chunks applied **by this call** (not including any
/// chunks skipped by the fast-forward).
fn run_apply_loop<R: std::io::Read>(
    reader: &mut chunk::ZiPatchReader<R>,
    ctx: &mut apply::ApplyContext,
    start_index: u64,
) -> Result<u64> {
    use apply::Apply;
    use std::ops::ControlFlow;
    let mut index = start_index;
    while let Some(chunk) = reader.next() {
        let chunk = chunk?;
        ctx.current_chunk_index = index;
        ctx.current_chunk_bytes_read = reader.bytes_read();
        chunk.apply(ctx)?;
        let bytes_read = reader.bytes_read();
        let tag = reader
            .last_tag()
            .expect("last_tag is set whenever next() yielded Some(Ok(_))");
        let next_chunk_index = index + 1;
        let checkpoint = apply::Checkpoint::Sequential(apply::SequentialCheckpoint {
            schema_version: apply::SequentialCheckpoint::CURRENT_SCHEMA_VERSION,
            next_chunk_index,
            bytes_read,
            patch_name: ctx.patch_name.clone(),
            patch_size: ctx.patch_size,
            in_flight: None,
        });
        tracing::debug!(
            next_chunk_index,
            bytes_read,
            in_flight = false,
            "apply_to: checkpoint recorded"
        );
        ctx.record_checkpoint(&checkpoint)?;
        let event = apply::ChunkEvent {
            index: index as usize,
            kind: tag,
            bytes_read,
        };
        if let ControlFlow::Break(()) = ctx.observer.on_chunk_applied(event) {
            return Err(ZiPatchError::Cancelled);
        }
        index += 1;
    }
    Ok(index - start_index)
}

impl<R: std::io::Read> chunk::ZiPatchReader<R> {
    /// Iterate every chunk in the patch stream and apply each one to `ctx`.
    ///
    /// This is the primary high-level entry point for applying a patch. It
    /// drives the [`ZiPatchReader`] iterator to completion, calling
    /// [`Apply::apply`] on each yielded [`Chunk`] in stream order.
    ///
    /// Chunks **must** be applied in order — the `ZiPatch` format is a
    /// sequential log and later chunks may depend on filesystem state produced
    /// by earlier ones (e.g. a directory created by an `ADIR` chunk that a
    /// subsequent `SQPK AddFile` writes into).
    ///
    /// # Errors
    ///
    /// Stops at the first parse or apply error and returns it immediately.
    /// Any filesystem changes already applied by earlier chunks are **not**
    /// rolled back — the format does not provide transactional semantics.
    ///
    /// Possible error variants:
    /// - [`ZiPatchError::Io`] — underlying I/O failure (read or write).
    /// - [`ZiPatchError::InvalidMagic`] — caught at construction, not here.
    /// - [`ZiPatchError::UnknownChunkTag`] — an unrecognised 4-byte tag was
    ///   encountered.
    /// - [`ZiPatchError::ChecksumMismatch`] — a chunk's CRC32 did not match.
    /// - [`ZiPatchError::TruncatedPatch`] — the stream ended before `EOF_`.
    /// - [`ZiPatchError::NegativeFileOffset`] — a `SqpkFile` chunk carried a
    ///   negative offset.
    /// - [`ZiPatchError::Decompress`] — a compressed block could not be
    ///   inflated.
    /// - [`ZiPatchError::UnsupportedPlatform`] — a `SqpkTargetInfo` chunk
    ///   declared a `platform_id` outside `0`/`1`/`2`, and a subsequent SQPK
    ///   data chunk requested `SqPack` `.dat`/`.index` path resolution.
    /// - [`ZiPatchError::Cancelled`] — an installed
    ///   [`ApplyObserver`] requested cancellation.
    ///
    /// # Panics
    ///
    /// Never panics under normal operation. The internal
    /// [`ZiPatchReader::last_tag`] is unwrapped after a successful
    /// [`Iterator::next`] — this is an internal invariant of the iterator
    /// (every `Some(Ok(_))` updates the tag) and would only fail on a bug
    /// in this crate.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::fs::File;
    /// use zipatch_rs::{ApplyContext, ZiPatchReader};
    ///
    /// let mut ctx = ApplyContext::new("/opt/ffxiv/game");
    /// ZiPatchReader::new(File::open("update.patch").unwrap())
    ///     .unwrap()
    ///     .apply_to(&mut ctx)
    ///     .unwrap();
    /// ```
    pub fn apply_to(mut self, ctx: &mut apply::ApplyContext) -> Result<()> {
        let span = tracing::info_span!("apply_patch");
        let _enter = span.enter();
        let started = std::time::Instant::now();
        ctx.patch_name = self.patch_name().map(str::to_owned);
        ctx.patch_size = None;
        // Run the chunk loop in an IIFE so the outer function can flush the
        // file-handle cache on the way out — both on success (to make the
        // durability guarantee meaningful: returning `Ok` implies the writes
        // reached the OS) and on error (so partial progress, e.g. mid-stream
        // cancellation, is observable in the filesystem). A flush failure
        // only escapes when there was no primary error to begin with;
        // otherwise the primary error takes precedence.
        let result = run_apply_loop(&mut self, ctx, 0);
        let flush_result = ctx.flush();
        let (final_result, chunks_applied) = match (result, flush_result) {
            (Ok(n), Ok(())) => (Ok(()), n),
            (Ok(_), Err(e)) => (Err(ZiPatchError::Io(e)), 0),
            (Err(e), _) => (Err(e), 0),
        };
        if final_result.is_ok() {
            tracing::info!(
                chunks = chunks_applied,
                bytes_read = self.bytes_read(),
                resumed_from_chunk = tracing::field::Empty,
                elapsed_ms = started.elapsed().as_millis() as u64,
                "apply_to: patch applied"
            );
        }
        final_result
    }
}

impl<R: std::io::Read + std::io::Seek> chunk::ZiPatchReader<R> {
    /// Resume a previously interrupted apply from a [`SequentialCheckpoint`].
    ///
    /// When `from` is `None`, behaves identically to
    /// [`Self::apply_to`] except for the return type: a successful run
    /// returns the final [`SequentialCheckpoint`] (with
    /// `next_chunk_index` equal to the total number of chunks consumed,
    /// including the `EOF_` terminator-driven loop exit).
    ///
    /// When `from` is `Some`, the driver fast-forwards the parser past
    /// `from.next_chunk_index` chunks **without applying them**, then resumes
    /// the apply loop. If `from.in_flight` is also `Some`, the next chunk
    /// (which must be the in-flight `SqpkFile::AddFile`) is resumed
    /// mid-stream: the target file's existing partial content is preserved
    /// and the chunk's remaining blocks are streamed in starting at
    /// `in_flight.block_idx`.
    ///
    /// # Stale-checkpoint detection
    ///
    /// If `from.patch_name` does not match the value supplied via
    /// [`Self::with_patch_name`], or `from.patch_size` does not match the
    /// total byte length of the underlying reader, the driver emits a
    /// `warn!` and starts a clean apply from chunk 0 — the same precedent
    /// as the stale-manifest path in indexed apply. The returned
    /// checkpoint in that case carries the new run's identity.
    ///
    /// # `ignore_missing` and chunk-N safety
    ///
    /// The apply loop never re-applies a chunk whose effects already
    /// landed: chunk-boundary checkpoints are recorded **after** the
    /// chunk's apply call has returned, so `next_chunk_index = N` means
    /// chunks `[0, N)` are confirmed done. There is therefore no need to
    /// flip [`ApplyContext::ignore_missing`] just for the resume boundary
    /// — a `DeleteFile` or `DeleteDirectory` at chunk `N` is still a
    /// first attempt and follows the caller's pre-existing flag setting.
    ///
    /// # In-flight `AddFile` safety check
    ///
    /// When resuming an in-flight `AddFile`, the driver stats the target
    /// file. If the file is missing, or its on-disk length is less than
    /// the checkpoint's `bytes_into_target` (e.g. the partial file was
    /// truncated, deleted, or replaced since the crash), the in-flight
    /// state is discarded with a `warn!` and the chunk is re-applied
    /// from block 0. This is
    /// the only failure mode where a `from.in_flight` is silently
    /// ignored; a target-path or file-offset mismatch on the resumed
    /// chunk produces the same behaviour.
    ///
    /// # Completion checkpoints
    ///
    /// A successful run returns a final checkpoint whose
    /// `next_chunk_index` is one past the last chunk in the patch — i.e.
    /// the index the apply loop *would* read next if there were more
    /// chunks. Replaying that final checkpoint through this method
    /// returns [`ZiPatchError::TruncatedPatch`]: the fast-forward will
    /// run out of chunks before reaching `next_chunk_index`. Consumers
    /// should detect "patch fully applied" from the `Ok(_)` return of
    /// the first call (or whatever marker their persistence layer
    /// records alongside the checkpoint) rather than by passing the
    /// completion checkpoint back here.
    ///
    /// # Errors
    ///
    /// Same vocabulary as [`Self::apply_to`], plus
    /// [`ZiPatchError::SchemaVersionMismatch`] when `from.schema_version`
    /// does not equal [`apply::SequentialCheckpoint::CURRENT_SCHEMA_VERSION`].
    /// The driver refuses to interpret a checkpoint whose layout this
    /// build cannot represent.
    ///
    /// # Panics
    ///
    /// Never panics under normal operation. Internal invariants are the
    /// same as [`Self::apply_to`].
    pub fn resume_apply_to(
        mut self,
        ctx: &mut apply::ApplyContext,
        from: Option<&apply::SequentialCheckpoint>,
    ) -> Result<apply::SequentialCheckpoint> {
        let span = tracing::info_span!("resume_apply_to");
        let _enter = span.enter();
        let started = std::time::Instant::now();

        if let Some(cp) = from {
            if cp.schema_version != apply::SequentialCheckpoint::CURRENT_SCHEMA_VERSION {
                return Err(ZiPatchError::SchemaVersionMismatch {
                    kind: "sequential-checkpoint",
                    found: cp.schema_version,
                    expected: apply::SequentialCheckpoint::CURRENT_SCHEMA_VERSION,
                });
            }
        }

        let reader_name = self.patch_name().map(str::to_owned);
        let total_size = stream_total_size(&mut self)?;
        ctx.patch_name.clone_from(&reader_name);
        ctx.patch_size = Some(total_size);

        let effective_from = from.and_then(|cp| {
            let name_match = cp.patch_name == reader_name;
            // `None` on the checkpoint means the recording driver did not
            // know the size (the `apply_to` Read-only path). Only declare a
            // mismatch when both sides carry a value and they disagree.
            let size_match = match cp.patch_size {
                Some(sz) => sz == total_size,
                None => true,
            };
            if name_match && size_match {
                Some(cp)
            } else {
                tracing::warn!(
                    expected_patch_name = ?reader_name,
                    expected_patch_size = total_size,
                    checkpoint_patch_name = ?cp.patch_name,
                    checkpoint_patch_size = ?cp.patch_size,
                    "resume_apply_to: stale checkpoint, restarting from chunk 0"
                );
                None
            }
        });

        let resumed_from_chunk = effective_from.map(|cp| cp.next_chunk_index);
        let skipped_bytes_at_start = effective_from.map_or(0, |cp| cp.bytes_read);
        let has_in_flight = effective_from
            .and_then(|cp| cp.in_flight.as_ref())
            .is_some();

        if let Some(cp) = effective_from {
            tracing::info!(
                patch_name = ?reader_name,
                skipped_chunks = cp.next_chunk_index,
                skipped_bytes = cp.bytes_read,
                has_in_flight,
                "resume_apply_to: resuming patch"
            );
            fast_forward(&mut self, cp.next_chunk_index, cp.bytes_read)?;
        }

        let start_index = effective_from.map_or(0, |cp| cp.next_chunk_index);
        let in_flight = effective_from.and_then(|cp| cp.in_flight.clone());

        let result: Result<u64> = (|| {
            if let Some(in_flight) = in_flight {
                resume_in_flight_chunk(&mut self, ctx, start_index, &in_flight)?;
                run_apply_loop(&mut self, ctx, start_index + 1).map(|n| n + 1)
            } else {
                run_apply_loop(&mut self, ctx, start_index)
            }
        })();

        let flush_result = ctx.flush();
        let (final_result, chunks_applied) = match (result, flush_result) {
            (Ok(n), Ok(())) => (Ok(()), n),
            (Ok(_), Err(e)) => (Err(ZiPatchError::Io(e)), 0),
            (Err(e), _) => (Err(e), 0),
        };

        match final_result {
            Ok(()) => {
                let bytes_read = self.bytes_read();
                if let Some(from_chunk) = resumed_from_chunk {
                    tracing::info!(
                        chunks = chunks_applied,
                        bytes_read,
                        resumed_from_chunk = from_chunk,
                        skipped_bytes = skipped_bytes_at_start,
                        elapsed_ms = started.elapsed().as_millis() as u64,
                        "resume_apply_to: patch applied"
                    );
                } else {
                    tracing::info!(
                        chunks = chunks_applied,
                        bytes_read,
                        resumed_from_chunk = tracing::field::Empty,
                        elapsed_ms = started.elapsed().as_millis() as u64,
                        "resume_apply_to: patch applied"
                    );
                }
                Ok(apply::SequentialCheckpoint {
                    schema_version: apply::SequentialCheckpoint::CURRENT_SCHEMA_VERSION,
                    next_chunk_index: start_index + chunks_applied,
                    bytes_read,
                    patch_name: reader_name,
                    patch_size: Some(total_size),
                    in_flight: None,
                })
            }
            Err(e) => Err(e),
        }
    }
}

/// Total byte length of the patch stream, measured by seeking the underlying
/// source. Returns the cursor to its original position.
fn stream_total_size<R: std::io::Read + std::io::Seek>(
    reader: &mut chunk::ZiPatchReader<R>,
) -> Result<u64> {
    use std::io::Seek;
    let inner = reader.inner_mut();
    let current = inner.stream_position()?;
    let end = inner.seek(std::io::SeekFrom::End(0))?;
    inner.seek(std::io::SeekFrom::Start(current))?;
    Ok(end)
}

/// Discard-parse chunks until the iterator has yielded `target_chunks`
/// chunks. Each parse still validates CRCs but the resulting [`Chunk`] is
/// dropped without applying.
fn fast_forward<R: std::io::Read>(
    reader: &mut chunk::ZiPatchReader<R>,
    target_chunks: u64,
    expected_bytes_read: u64,
) -> Result<()> {
    let mut consumed: u64 = 0;
    while consumed < target_chunks {
        match reader.next() {
            Some(Ok(_)) => consumed += 1,
            Some(Err(e)) => return Err(e),
            None => {
                return Err(ZiPatchError::TruncatedPatch);
            }
        }
    }
    if reader.bytes_read() != expected_bytes_read {
        // Drift is informational, not a hard error: the fast-forward is
        // positional (re-parse `target_chunks` chunks), and
        // `bytes_read` is metadata the recording driver carried for
        // diagnostics. A future reader-format tweak that adjusts chunk
        // framing could legitimately produce a different byte total
        // for the same chunk count; the resume contract is positional
        // chunk index, so we surface the discrepancy and continue.
        tracing::warn!(
            actual_bytes_read = reader.bytes_read(),
            expected_bytes_read,
            target_chunks,
            "resume_apply_to: bytes_read drift during fast-forward"
        );
    }
    tracing::debug!(
        skipped_chunks = target_chunks,
        bytes_read = reader.bytes_read(),
        "resume_apply_to: fast-forward complete"
    );
    Ok(())
}

/// Apply the in-flight chunk at `start_index`, starting from
/// `in_flight.block_idx`.
///
/// Parses the next chunk via the normal reader; on a target/path/offset
/// mismatch or a partial-file safety failure, falls back to applying the
/// chunk fresh from block 0 (with a `warn!`).
fn resume_in_flight_chunk<R: std::io::Read>(
    reader: &mut chunk::ZiPatchReader<R>,
    ctx: &mut apply::ApplyContext,
    chunk_index: u64,
    in_flight: &apply::InFlightAddFile,
) -> Result<()> {
    use apply::Apply;
    use std::ops::ControlFlow;

    let chunk = match reader.next() {
        Some(Ok(c)) => c,
        Some(Err(e)) => return Err(e),
        None => return Err(ZiPatchError::TruncatedPatch),
    };

    ctx.current_chunk_index = chunk_index;
    ctx.current_chunk_bytes_read = reader.bytes_read();

    let (start_block, start_bytes) = match resolve_in_flight_resume(&chunk, ctx, in_flight) {
        InFlightResume::Resume {
            start_block,
            start_bytes,
        } => (start_block, start_bytes),
        InFlightResume::Restart => (0, 0),
    };

    match &chunk {
        chunk::Chunk::Sqpk(chunk::SqpkCommand::File(file))
            if matches!(
                file.operation,
                crate::chunk::sqpk::SqpkFileOperation::AddFile
            ) =>
        {
            apply::sqpk::apply_file_add_from(file, ctx, start_block, start_bytes)?;
        }
        // The matching guard above already passed in the resolve step or
        // we're on the Restart branch — re-apply the chunk fresh.
        _ => chunk.apply(ctx)?,
    }

    let bytes_read = reader.bytes_read();
    let tag = reader
        .last_tag()
        .expect("last_tag is set whenever next() yielded Some(Ok(_))");
    let next_chunk_index = chunk_index + 1;
    let checkpoint = apply::Checkpoint::Sequential(apply::SequentialCheckpoint {
        schema_version: apply::SequentialCheckpoint::CURRENT_SCHEMA_VERSION,
        next_chunk_index,
        bytes_read,
        patch_name: ctx.patch_name.clone(),
        patch_size: ctx.patch_size,
        in_flight: None,
    });
    ctx.record_checkpoint(&checkpoint)?;
    let event = apply::ChunkEvent {
        index: chunk_index as usize,
        kind: tag,
        bytes_read,
    };
    if let ControlFlow::Break(()) = ctx.observer.on_chunk_applied(event) {
        return Err(ZiPatchError::Cancelled);
    }
    Ok(())
}

enum InFlightResume {
    Resume {
        start_block: usize,
        start_bytes: u64,
    },
    Restart,
}

fn resolve_in_flight_resume(
    chunk: &chunk::Chunk,
    ctx: &apply::ApplyContext,
    in_flight: &apply::InFlightAddFile,
) -> InFlightResume {
    let chunk::Chunk::Sqpk(chunk::SqpkCommand::File(file)) = chunk else {
        tracing::warn!(
            "resume_apply_to: in-flight chunk is not an SqpkFile; discarding in-flight state"
        );
        return InFlightResume::Restart;
    };
    if !matches!(
        file.operation,
        crate::chunk::sqpk::SqpkFileOperation::AddFile
    ) {
        tracing::warn!(
            "resume_apply_to: in-flight chunk is not an AddFile; discarding in-flight state"
        );
        return InFlightResume::Restart;
    }

    let expected_path = apply::path::generic_path(ctx, &file.path);
    if expected_path != in_flight.target_path {
        tracing::warn!(
            chunk_path = %expected_path.display(),
            in_flight_path = %in_flight.target_path.display(),
            "resume_apply_to: in-flight target path does not match chunk; discarding"
        );
        return InFlightResume::Restart;
    }
    let Ok(chunk_offset) = u64::try_from(file.file_offset) else {
        tracing::warn!(
            file_offset = file.file_offset,
            "resume_apply_to: negative file_offset on in-flight chunk; discarding"
        );
        return InFlightResume::Restart;
    };
    if chunk_offset != in_flight.file_offset {
        tracing::warn!(
            chunk_offset,
            in_flight_offset = in_flight.file_offset,
            "resume_apply_to: in-flight file_offset does not match chunk; discarding"
        );
        return InFlightResume::Restart;
    }
    if in_flight.block_idx as usize > file.blocks.len() {
        tracing::warn!(
            block_idx = in_flight.block_idx,
            block_count = file.blocks.len(),
            "resume_apply_to: in-flight block_idx out of range; discarding"
        );
        return InFlightResume::Restart;
    }
    // AddFile @ offset 0 safety: the target's current on-disk length must
    // cover the bytes the checkpoint says have already been written. A
    // shorter file (or a missing file) means the partial content was
    // truncated, deleted, or replaced between the crash and the resume, and
    // re-running the block loop from `block_idx` would leave a hole.
    if chunk_offset == 0 && in_flight.bytes_into_target > 0 {
        let on_disk_len = std::fs::metadata(&in_flight.target_path).map_or(0, |m| m.len());
        if on_disk_len < in_flight.bytes_into_target {
            tracing::warn!(
                target = %in_flight.target_path.display(),
                on_disk_len,
                bytes_into_target = in_flight.bytes_into_target,
                "resume_apply_to: target file truncated or missing since checkpoint; restarting AddFile"
            );
            return InFlightResume::Restart;
        }
    }

    InFlightResume::Resume {
        start_block: in_flight.block_idx as usize,
        start_bytes: in_flight.bytes_into_target,
    }
}

/// Target platform for `SqPack` file path resolution.
///
/// FFXIV's `SqPack` archive files live in platform-specific subdirectories
/// under the game install root. For example, a data file for the Windows
/// client lives at `sqpack/ffxiv/000000.win32.dat0`, while the PS4 equivalent
/// is `sqpack/ffxiv/000000.ps4.dat0`. The [`Platform`] value stored in an
/// [`ApplyContext`] selects which suffix is used when resolving chunk targets
/// to filesystem paths.
///
/// # Default
///
/// An [`ApplyContext`] defaults to [`Platform::Win32`]. Override this at
/// construction time with [`ApplyContext::with_platform`].
///
/// # Runtime override via `SqpkTargetInfo`
///
/// In practice, real FFXIV patch files begin with an `SQPK T` chunk
/// ([`chunk::SqpkTargetInfo`]) that declares the target platform. When
/// [`Apply::apply`] is called on that chunk (see `src/apply/sqpk.rs`,
/// `apply_target_info`), it overwrites [`ApplyContext::platform`] with the
/// decoded [`Platform`] value. This means the default is only relevant for
/// synthetic patches or when you know the target in advance and want to assert
/// it before the stream starts.
///
/// # Forward compatibility
///
/// The enum is `#[non_exhaustive]`. The [`Platform::Unknown`] variant
/// preserves unrecognised platform IDs so that newer patch files do not fail
/// parsing when a new platform is introduced. Path resolution for `SqPack`
/// `.dat`/`.index` files refuses to guess and returns
/// [`ZiPatchError::UnsupportedPlatform`] carrying the raw `platform_id` —
/// silently substituting a default layout would risk writing platform-specific
/// data to the wrong file.
///
/// # Display
///
/// Implements [`std::fmt::Display`]: `"Win32"`, `"PS3"`, `"PS4"`, or
/// `"Unknown(N)"` where `N` is the raw platform ID.
///
/// # Example
///
/// ```rust
/// use zipatch_rs::{ApplyContext, Platform};
///
/// let ctx = ApplyContext::new("/opt/ffxiv/game")
///     .with_platform(Platform::Win32);
///
/// assert_eq!(ctx.platform(), Platform::Win32);
/// assert_eq!(format!("{}", Platform::Unknown(99)), "Unknown(99)");
/// ```
///
/// [`chunk::SqpkTargetInfo`]: crate::chunk::SqpkTargetInfo
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Platform {
    /// Windows / PC client (`win32` path suffix).
    ///
    /// This is the platform used by all current PC releases of FFXIV and is
    /// the default for [`ApplyContext`].
    Win32,
    /// `PlayStation` 3 client (`ps3` path suffix).
    ///
    /// PS3 support was discontinued after FFXIV: A Realm Reborn. Patches
    /// targeting this platform are no longer issued by Square Enix, but the
    /// variant is retained for completeness.
    Ps3,
    /// `PlayStation` 4 client (`ps4` path suffix).
    ///
    /// Active platform alongside Windows. PS4 patches share the same chunk
    /// structure as Windows patches but target different file paths.
    Ps4,
    /// Unrecognised platform ID preserved from a `SqpkTargetInfo` chunk.
    ///
    /// When `apply_target_info` in `src/apply/sqpk.rs` encounters a
    /// `platform_id` it does not recognise, it stores the raw `u16` value
    /// here and emits a `warn!` tracing event. Subsequent `SqPack` path
    /// resolution returns [`ZiPatchError::UnsupportedPlatform`] carrying
    /// the same `u16` rather than silently routing writes to a default
    /// layout — quietly substituting `win32` paths for an unknown platform
    /// would corrupt the on-disk install with platform-specific data
    /// written to the wrong files. Non-SqPack chunks (e.g. `ADIR`, `DELD`,
    /// or `SqpkFile` operations resolved via `generic_path`) continue to
    /// apply, so an unknown platform only aborts at the first `.dat` or
    /// `.index` lookup.
    Unknown(u16),
}

impl std::fmt::Display for Platform {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Platform::Win32 => f.write_str("Win32"),
            Platform::Ps3 => f.write_str("PS3"),
            Platform::Ps4 => f.write_str("PS4"),
            Platform::Unknown(id) => write!(f, "Unknown({id})"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::{MAGIC, make_chunk};
    use std::io::Cursor;
    use std::ops::ControlFlow;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// One uncompressed block carrying 8 bytes of payload, framed as a
    /// `SqpkCompressedBlock` would appear inside an `SqpkFile` `AddFile` body.
    ///
    /// Block layout: 16-byte header + 8 data bytes + 104 alignment-pad bytes
    /// (rounded up to the 128-byte boundary via `(8 + 143) & !127 = 128`).
    fn make_sqpk_file_block(byte: u8) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&16i32.to_le_bytes()); // header_size
        out.extend_from_slice(&0u32.to_le_bytes()); // pad
        out.extend_from_slice(&0x7d00i32.to_le_bytes()); // compressed_size = uncompressed sentinel
        out.extend_from_slice(&8i32.to_le_bytes()); // decompressed_size
        out.extend_from_slice(&[byte; 8]); // data
        out.extend_from_slice(&[0u8; 104]); // 128-byte alignment padding
        out
    }

    /// Build an SQPK `F`(`AddFile`) chunk that targets `path` and contains
    /// `block_count` uncompressed blocks of 8 bytes each.
    fn make_sqpk_addfile_chunk(path: &str, block_count: usize) -> Vec<u8> {
        // SQPK `F` command body layout — see `chunk/sqpk/file.rs` docs.
        let path_bytes: Vec<u8> = {
            let mut p = path.as_bytes().to_vec();
            p.push(0); // NUL terminator
            p
        };

        let mut cmd_body = Vec::new();
        cmd_body.push(b'A'); // operation = AddFile
        cmd_body.extend_from_slice(&[0u8; 2]); // alignment
        cmd_body.extend_from_slice(&0u64.to_be_bytes()); // file_offset = 0
        cmd_body.extend_from_slice(&0u64.to_be_bytes()); // file_size
        cmd_body.extend_from_slice(&(path_bytes.len() as u32).to_be_bytes());
        cmd_body.extend_from_slice(&0u16.to_be_bytes()); // expansion_id
        cmd_body.extend_from_slice(&[0u8; 2]); // padding
        cmd_body.extend_from_slice(&path_bytes);
        for i in 0..block_count {
            cmd_body.extend_from_slice(&make_sqpk_file_block(0xA0 + (i as u8)));
        }

        // SQPK chunk body: i32 BE inner_size + 'F' command byte + cmd_body
        let inner_size = 5 + cmd_body.len();
        let mut sqpk_body = Vec::new();
        sqpk_body.extend_from_slice(&(inner_size as i32).to_be_bytes());
        sqpk_body.push(b'F');
        sqpk_body.extend_from_slice(&cmd_body);

        make_chunk(b"SQPK", &sqpk_body)
    }

    // --- Platform Display ---

    #[test]
    fn platform_display_all_variants() {
        assert_eq!(format!("{}", Platform::Win32), "Win32");
        assert_eq!(format!("{}", Platform::Ps3), "PS3");
        assert_eq!(format!("{}", Platform::Ps4), "PS4");
        assert_eq!(format!("{}", Platform::Unknown(42)), "Unknown(42)");
        // Zero unknown ID is distinct from Win32.
        assert_eq!(format!("{}", Platform::Unknown(0)), "Unknown(0)");
    }

    // --- apply_to: basic end-to-end ---

    #[test]
    fn apply_to_applies_adir_chunk_to_filesystem() {
        // Verify that a well-formed ADIR + EOF_ patch creates the directory.
        let mut adir_body = Vec::new();
        adir_body.extend_from_slice(&7u32.to_be_bytes());
        adir_body.extend_from_slice(b"created");

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_chunk(b"ADIR", &adir_body));
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path());
        ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap();

        assert!(
            tmp.path().join("created").is_dir(),
            "ADIR must have created the directory"
        );
    }

    #[test]
    fn apply_to_empty_patch_succeeds_without_side_effects() {
        // MAGIC + EOF_ only: apply_to must return Ok(()) with no filesystem changes.
        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path());
        ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap();
        // No new entries should appear in the temp dir.
        let entries: Vec<_> = std::fs::read_dir(tmp.path()).unwrap().collect();
        assert!(
            entries.is_empty(),
            "empty patch must not create any files/dirs"
        );
    }

    // --- apply_to: error propagation ---

    #[test]
    fn apply_to_propagates_parse_error_as_unknown_chunk_tag() {
        // ZZZZ is not a known tag; apply_to must surface UnknownChunkTag.
        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_chunk(b"ZZZZ", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path());
        let err = ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap_err();
        assert!(
            matches!(err, ZiPatchError::UnknownChunkTag(_)),
            "expected UnknownChunkTag, got {err:?}"
        );
    }

    #[test]
    fn apply_to_propagates_apply_error_from_delete_directory() {
        // DELD on a non-existent directory without ignore_missing must return Io.
        let mut deld_body = Vec::new();
        deld_body.extend_from_slice(&14u32.to_be_bytes());
        deld_body.extend_from_slice(b"does_not_exist");

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_chunk(b"DELD", &deld_body));
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path());
        let err = ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap_err();
        assert!(
            matches!(err, ZiPatchError::Io(_)),
            "expected ZiPatchError::Io for missing dir without ignore_missing, got {err:?}"
        );
    }

    // --- Progress / observer / cancellation tests ---

    /// Observer that returns `should_cancel() == true` after `cancel_after` calls.
    struct CancelAfter {
        calls: usize,
        cancel_after: usize,
    }

    impl ApplyObserver for CancelAfter {
        fn should_cancel(&mut self) -> bool {
            let now = self.calls;
            self.calls += 1;
            now >= self.cancel_after
        }
    }

    #[test]
    fn observer_fires_for_each_non_eof_chunk_with_correct_fields() {
        // Two ADIR chunks — observer must receive exactly two events, in order,
        // with 0-based index, correct tag, and a monotonically increasing
        // bytes_read that matches the exact wire-frame sizes.
        let log: Arc<std::sync::Mutex<Vec<ChunkEvent>>> =
            Arc::new(std::sync::Mutex::new(Vec::new()));
        let log_clone = log.clone();

        let mut a = Vec::new();
        a.extend_from_slice(&1u32.to_be_bytes());
        a.extend_from_slice(b"a");
        let mut b = Vec::new();
        b.extend_from_slice(&1u32.to_be_bytes());
        b.extend_from_slice(b"b");

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_chunk(b"ADIR", &a));
        patch.extend_from_slice(&make_chunk(b"ADIR", &b));
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path()).with_observer(move |ev| {
            log_clone.lock().unwrap().push(ev);
            ControlFlow::Continue(())
        });
        ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap();

        let events = log.lock().unwrap();
        assert_eq!(
            events.len(),
            2,
            "two non-EOF chunks must fire exactly two events"
        );
        // Index must be 0-based and monotonically increasing.
        assert_eq!(events[0].index, 0, "first event index must be 0");
        assert_eq!(events[1].index, 1, "second event index must be 1");
        // Tag must reflect the chunk wire tag.
        assert_eq!(events[0].kind, *b"ADIR");
        assert_eq!(events[1].kind, *b"ADIR");
        // ADIR body for name "a": 4 (name_len) + 1 (byte) = 5
        // Frame: 4(size) + 4(tag) + 5(body) + 4(crc) = 17
        assert_eq!(
            events[0].bytes_read,
            12 + 17,
            "bytes_read after first ADIR must be magic + one 17-byte frame"
        );
        assert_eq!(
            events[1].bytes_read,
            12 + 17 + 17,
            "bytes_read after second ADIR must be magic + two 17-byte frames"
        );
        // Strict monotonicity.
        assert!(
            events[0].bytes_read < events[1].bytes_read,
            "bytes_read must strictly increase between events"
        );
    }

    #[test]
    fn observer_break_on_first_chunk_aborts_immediately_leaving_first_applied() {
        // Observer that always breaks: only the first chunk's apply runs, then
        // apply_to returns Cancelled. Second and third chunks are never reached.
        let mut a = Vec::new();
        a.extend_from_slice(&1u32.to_be_bytes());
        a.extend_from_slice(b"a");
        let mut b_body = Vec::new();
        b_body.extend_from_slice(&1u32.to_be_bytes());
        b_body.extend_from_slice(b"b");
        let mut c = Vec::new();
        c.extend_from_slice(&1u32.to_be_bytes());
        c.extend_from_slice(b"c");

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_chunk(b"ADIR", &a));
        patch.extend_from_slice(&make_chunk(b"ADIR", &b_body));
        patch.extend_from_slice(&make_chunk(b"ADIR", &c));
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let count = Arc::new(AtomicUsize::new(0));
        let count_clone = count.clone();

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path()).with_observer(move |_| {
            count_clone.fetch_add(1, Ordering::Relaxed);
            ControlFlow::Break(())
        });
        let err = ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap_err();

        assert!(
            matches!(err, ZiPatchError::Cancelled),
            "observer Break must produce ZiPatchError::Cancelled, got {err:?}"
        );
        assert_eq!(
            count.load(Ordering::Relaxed),
            1,
            "exactly one on_chunk_applied call fires before the abort takes effect"
        );
        // The first ADIR's apply completed before the event fired.
        assert!(
            tmp.path().join("a").is_dir(),
            "first ADIR must have been applied before Cancelled was returned"
        );
        // Second and third ADIRs were never reached.
        assert!(
            !tmp.path().join("b").exists(),
            "second ADIR must NOT have been applied after Cancelled"
        );
        assert!(
            !tmp.path().join("c").exists(),
            "third ADIR must NOT have been applied after Cancelled"
        );
    }

    #[test]
    fn observer_break_on_last_chunk_before_eof_leaves_all_earlier_applied() {
        // Three ADIRs: observer continues for the first two, breaks on the third.
        // After Cancelled, a/ and b/ must exist; c/ was the breaker's chunk
        // (its apply ran before the event fired) and d/ (hypothetical fourth) never runs.
        let make_adir_chunk = |name: &[u8]| -> Vec<u8> {
            let mut body = Vec::new();
            body.extend_from_slice(&(name.len() as u32).to_be_bytes());
            body.extend_from_slice(name);
            make_chunk(b"ADIR", &body)
        };

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_adir_chunk(b"a"));
        patch.extend_from_slice(&make_adir_chunk(b"b"));
        patch.extend_from_slice(&make_adir_chunk(b"c"));
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let call_count = Arc::new(AtomicUsize::new(0));
        let cc = call_count.clone();
        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path()).with_observer(move |_| {
            let n = cc.fetch_add(1, Ordering::Relaxed) + 1;
            if n >= 3 {
                ControlFlow::Break(())
            } else {
                ControlFlow::Continue(())
            }
        });

        let err = ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap_err();

        assert!(
            matches!(err, ZiPatchError::Cancelled),
            "expected Cancelled, got {err:?}"
        );
        // First two ADIRs fully applied.
        assert!(tmp.path().join("a").is_dir(), "a/ must exist");
        assert!(tmp.path().join("b").is_dir(), "b/ must exist");
        // Third ADIR's apply ran before the event — c/ exists.
        assert!(
            tmp.path().join("c").is_dir(),
            "c/ must exist (apply ran before event fired)"
        );
    }

    #[test]
    fn sqpk_file_cancellation_mid_block_loop_returns_aborted() {
        // Three blocks of 8 bytes each. Observer cancels after 2 should_cancel
        // polls, so at most 2 blocks are written before abort.
        let chunk = make_sqpk_addfile_chunk("created/test.dat", 3);

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&chunk);
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path()).with_observer(CancelAfter {
            calls: 0,
            cancel_after: 2,
        });

        let err = ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap_err();

        assert!(
            matches!(err, ZiPatchError::Cancelled),
            "mid-block cancellation must return Cancelled, got {err:?}"
        );

        // File exists (create=true opened it) but the third block must not have
        // been written.  With `cancel_after = 2`, `should_cancel` returns true
        // on the third poll (the one that gates block 3), so exactly the first
        // two 8-byte blocks (= 16 bytes) reach disk.  Pin this exactly so an
        // off-by-one in where `should_cancel` is polled inside the block loop
        // would surface as a failing test rather than passing by inequality.
        let target = tmp.path().join("created").join("test.dat");
        assert!(
            target.is_file(),
            "target file must exist (was created before cancel)"
        );
        let len = std::fs::metadata(&target).unwrap().len();
        assert_eq!(
            len, 16,
            "partial write: exactly 2 of 3 blocks (= 16 bytes) must have \
             been written before cancellation"
        );
    }

    #[test]
    fn sqpk_file_single_block_no_mid_loop_cancel_opportunity() {
        // A single-block AddFile provides no between-block cancellation
        // opportunity. An observer that cancels only on the second call to
        // should_cancel must NOT abort — the loop executes exactly one block
        // and then the chunk completes normally. The chunk-boundary event fires
        // next, and a Continue there lets apply_to succeed.
        let chunk = make_sqpk_addfile_chunk("created/single.dat", 1);

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&chunk);
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path()).with_observer(CancelAfter {
            calls: 0,
            cancel_after: 2, // never reaches 2nd call within a single block
        });

        // should succeed: only 1 should_cancel call (call 0 < 2 = cancel_after)
        ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap();

        let target = tmp.path().join("created").join("single.dat");
        assert!(
            target.is_file(),
            "single-block AddFile must complete and create the file"
        );
        assert_eq!(
            std::fs::metadata(&target).unwrap().len(),
            8,
            "single block of 8 bytes must be fully written"
        );
    }

    #[test]
    fn sqpk_file_cancel_on_very_first_block_writes_zero_blocks() {
        // Observer cancels immediately (cancel_after = 0).  The first
        // should_cancel poll inside the block loop fires before any block data
        // is written, so the file must be empty (truncated by set_len(0) but
        // no block data written).
        let chunk = make_sqpk_addfile_chunk("created/zero.dat", 3);

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&chunk);
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path()).with_observer(CancelAfter {
            calls: 0,
            cancel_after: 0, // cancel on very first check
        });

        let err = ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap_err();

        assert!(
            matches!(err, ZiPatchError::Cancelled),
            "immediate cancel must return Cancelled, got {err:?}"
        );

        let target = tmp.path().join("created").join("zero.dat");
        let len = std::fs::metadata(&target).unwrap().len();
        assert_eq!(
            len, 0,
            "cancel before first block: file must be empty, got {len} bytes"
        );
    }

    #[test]
    fn closure_observer_composes_ergonomically_with_with_observer() {
        // Verify the intended ergonomic usage path: a closure recording state,
        // passed directly to with_observer via the blanket impl on FnMut.
        let events = Arc::new(std::sync::Mutex::new(Vec::<(usize, [u8; 4])>::new()));
        let ev_clone = events.clone();

        let make_adir = |name: &[u8]| -> Vec<u8> {
            let mut body = Vec::new();
            body.extend_from_slice(&(name.len() as u32).to_be_bytes());
            body.extend_from_slice(name);
            make_chunk(b"ADIR", &body)
        };

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_adir(b"d1"));
        patch.extend_from_slice(&make_adir(b"d2"));
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path()).with_observer(move |ev: ChunkEvent| {
            ev_clone.lock().unwrap().push((ev.index, ev.kind));
            ControlFlow::Continue(())
        });

        ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap();

        let recorded = events.lock().unwrap();
        assert_eq!(recorded.len(), 2);
        assert_eq!(recorded[0], (0, *b"ADIR"));
        assert_eq!(recorded[1], (1, *b"ADIR"));
    }

    #[test]
    fn default_no_observer_apply_succeeds_as_before() {
        // Regression: without with_observer the apply must succeed exactly as
        // it did before the observer API was introduced.
        let mut adir_body = Vec::new();
        adir_body.extend_from_slice(&7u32.to_be_bytes());
        adir_body.extend_from_slice(b"created");

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_chunk(b"ADIR", &adir_body));
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let mut ctx = ApplyContext::new(tmp.path()); // no with_observer call
        ZiPatchReader::new(Cursor::new(patch))
            .unwrap()
            .apply_to(&mut ctx)
            .unwrap();
        assert!(
            tmp.path().join("created").is_dir(),
            "ADIR must be applied when no observer is set"
        );
    }
}