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
//! 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.
//!
//! # Quick start
//!
//! The most common usage — apply a single patch file to an install root
//! with all defaults — is a single call:
//!
//! ```no_run
//! zipatch_rs::apply_patch_file(
//! "H2017.07.11.0000.0000a.patch",
//! "/opt/ffxiv/game",
//! ).unwrap();
//! ```
//!
//! For consumers that need progress observers, custom checkpoint sinks, a
//! non-default platform, or multi-patch session reuse, use the two-step
//! form directly:
//!
//! ```no_run
//! use zipatch_rs::{ApplyConfig, open_patch};
//!
//! let reader = open_patch("H2017.07.11.0000.0000a.patch").unwrap();
//! let ctx = ApplyConfig::new("/opt/ffxiv/game");
//! ctx.apply_patch(reader).unwrap();
//! ```
//!
//! # Choosing an apply pipeline
//!
//! `zipatch-rs` ships two apply pipelines. They are not alternatives in the
//! sense of "one is better" — they answer different questions.
//!
//! - **Sequential** ([`ApplyConfig::apply_patch`]) walks a single patch in
//! chunk order and writes each chunk to disk as it is parsed. One pass,
//! one patch, bounded memory, minimum latency from "start" to "first byte
//! on disk". This is the default; reach for it unless you specifically need
//! what the indexed pipeline offers.
//! - **Indexed** ([`PlanBuilder`] → [`Plan`] →
//! [`IndexApplier::execute`](crate::IndexApplier::execute)) folds one or
//! many patches into a deduplicated, target-major [`Plan`] in memory, then
//! replays it against the install. The plan is pure data: it can be
//! inspected, persisted (with the `serde` feature), CRC-populated via
//! [`Plan::with_crc32`](crate::index::Plan::with_crc32), verified against
//! the current install via [`PlanVerifier`](crate::index::PlanVerifier),
//! and used to drive a repair via
//! [`IndexApplier::execute_with_manifest`](crate::index::IndexApplier::execute_with_manifest)
//! with a [`RepairManifest`](crate::index::RepairManifest).
//!
//! Pick by what the consumer needs:
//!
//! | Need | Pipeline |
//! |---------------------------------------------------------------------|------------|
//! | Apply one patch to an install, in order, now | Sequential |
//! | Apply a chain of N patches and dedupe writes superseded mid-chain | Indexed |
//! | Pre-validate the chain against the install before touching a byte | Indexed |
//! | Pre-compute expected CRC32s and verify the install against them | Indexed |
//! | Produce a [`RepairManifest`](crate::index::RepairManifest) of drifted regions | Indexed |
//! | Persist a structured description of pending work for later replay | Indexed |
//! | Minimum latency to first write; bounded streaming memory | Sequential |
//! | Patch source is forward-only (no seeks) | Sequential |
//!
//! Costs to weigh: the indexed pipeline does two passes over the patch
//! source (plan-build, then apply) and holds the plan in memory; the source
//! must support random access, which is why the indexed entry points take a
//! [`PatchSource`](crate::index::PatchSource) (typically
//! [`FilePatchSource`](crate::index::FilePatchSource)) rather than a plain
//! [`Read`](std::io::Read). The sequential pipeline does a single forward
//! pass and never holds more than one chunk in flight.
//!
//! Starting sequential and growing to indexed later is a supported path —
//! the [`ApplyConfig`] knobs (`with_observer`, `with_cancel_token`,
//! `with_checkpoint_sink`, `with_platform`, `with_vfs`) all carry across to
//! [`IndexApplier`] with the same names and semantics.
//!
//! ```no_run
//! // Sequential: one patch, one pass.
//! zipatch_rs::apply_patch_file("patch.patch", "/opt/ffxiv/game").unwrap();
//! ```
//!
//! ```no_run
//! // Indexed: build a plan over a chain, then apply it.
//! use zipatch_rs::{IndexApplier, PlanBuilder, open_patch};
//! use zipatch_rs::index::FilePatchSource;
//!
//! let mut builder = PlanBuilder::new();
//! builder.add_patch("p1.patch", open_patch("p1.patch").unwrap()).unwrap();
//! builder.add_patch("p2.patch", open_patch("p2.patch").unwrap()).unwrap();
//! let plan = builder.finish();
//!
//! let source = FilePatchSource::open_chain(["p1.patch", "p2.patch"]).unwrap();
//! IndexApplier::new(source, "/opt/ffxiv/game").execute(&plan).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 mut reader = ZiPatchReader::new(File::open("patch.patch").unwrap()).unwrap();
//! while let Some(rec) = reader.next_chunk().unwrap() {
//! match rec.chunk {
//! 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::{ApplyConfig, 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 = ApplyConfig::new(tmp.path());
//! let reader = ZiPatchReader::new(Cursor::new(patch)).unwrap();
//! ctx.apply_patch(reader).unwrap();
//!
//! assert!(tmp.path().join("created").is_dir());
//! ```
//!
//! # Error handling
//!
//! Each layer returns its own domain-specific error type ([`ParseError`],
//! [`ApplyError`], [`IndexError`], [`VerifyError`]); the corresponding
//! [`ParseResult`], [`ApplyResult`], [`IndexResult`], and [`VerifyResult`]
//! aliases at the crate root cover the common signatures.
//!
//! Callers that want a single `?`-friendly type at the edges of their code
//! can use the umbrella [`Error`] enum (and the matching [`Result`] alias) —
//! every domain error `From`-converts into it, so a one-line `?` collapses
//! the four domains into one match arm.
//!
//! ```no_run
//! use zipatch_rs::{apply_patch_file, Error, Result};
//!
//! fn install(patch: &str, root: &str) -> Result<()> {
//! apply_patch_file(patch, root)?; // ApplyError -> Error via From
//! Ok(())
//! }
//! # let _ = install;
//! ```
//!
//! # Progress and cancellation
//!
//! [`ApplyConfig::with_observer`] installs an [`ApplyObserver`] that is
//! called after each chunk applies (with the chunk index, tag, and running
//! byte count from [`chunk::ChunkRecord::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
//! [`ApplyError::Cancelled`]. Parsing-only consumers and existing
//! [`apply_patch`](ApplyConfig::apply_patch) callers that never install an
//! observer pay nothing — the default is a no-op.
//!
//! For cancellation alone, prefer [`CancelToken`]: a cheap cloneable
//! [`AtomicBool`](std::sync::atomic::AtomicBool) wrapper installed via
//! [`ApplyConfig::with_cancel_token`] (or
//! [`IndexApplier::with_cancel_token`](crate::IndexApplier::with_cancel_token)).
//! Hold a clone on whichever thread initiates cancellation, call
//! [`CancelToken::cancel`] on a user gesture, and the apply driver picks
//! up the flip at the next chunk boundary or inner-loop poll point. The
//! token composes with an installed observer — both are polled, either can
//! abort.
//!
//! # 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 listed below 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 emit at `debug`. Recoverable anomalies — stale
//! manifest entries, unknown platform IDs, missing-but-ignored files — fire
//! `warn!`; errors are returned via the domain error types rather than
//! logged. No subscriber is configured here — that is the consumer's
//! responsibility.
//!
//! [`tracing`]: https://docs.rs/tracing
//!
//! ## Stability contract
//!
//! `tracing` names are a public API for any consumer wiring up
//! `tracing-subscriber` filters, OpenTelemetry exporters, log scrapers, or
//! dashboards that key off span/event/field names. This crate treats them
//! as such, with the following tiers:
//!
//! - **Stable (SemVer-tracked)** — the span names and field names listed in
//! the catalog below at the **info** and **debug** levels, plus the
//! per-operation completion-event messages explicitly called out.
//! Renaming or removing one of these is a minor-version bump while the
//! crate is on `0.x`/`1.x`; a major-version bump after `2.0`. New spans,
//! new events, and new fields on existing spans are additive and ship in
//! patch releases.
//! - **Best-effort (not contracted)** — `trace!` events and any field they
//! carry, all event messages not explicitly listed, and the precise
//! wording of `warn!` messages. These exist for operator forensics and
//! may change in any release; depend on them only inside a development
//! environment.
//!
//! The canonical strings live in a crate-internal `tracing_schema` module
//! so a rename lands in a single file. Field names are kept as
//! literals at the emission sites (their `tracing` macro syntax for
//! const-named fields would clutter the call site without a corresponding
//! rename-cost benefit), but they appear in the stable catalog below and
//! follow the same contract.
//!
//! ## Span catalog
//!
//! All spans are tagged with the entry point they bracket and the fields
//! they carry on creation. Sub-spans inherit the parent's field set via
//! the standard `tracing` span hierarchy.
//!
//! ### Info-level (top-level operations)
//!
//! | Span | Entry point | Fields |
//! |---|---|---|
//! | `apply_patch` | [`ApplyConfig::apply_patch`] | *(none on creation)* |
//! | `resume_apply_patch` | [`ApplyConfig::resume_apply_patch`] | *(none on creation)* |
//! | `apply_plan` | [`IndexApplier::execute_with_manifest`](crate::index::IndexApplier::execute_with_manifest) | `mode`, `targets`, `regions` |
//! | `resume_execute` | [`IndexApplier::execute`](crate::index::IndexApplier::execute) / [`IndexApplier::resume_execute`](crate::index::IndexApplier::resume_execute) | `plan_crc32`, `targets`, `regions`, `fs_ops` |
//! | `build_plan_patch` | [`PlanBuilder::add_patch`](crate::index::PlanBuilder::add_patch) | `patch` |
//! | `with_crc32` | [`Plan::with_crc32`](crate::index::Plan::with_crc32) | `targets` |
//! | `verify_plan` | [`PlanVerifier::execute`](crate::index::PlanVerifier::execute) | `targets` |
//! | `verify_hashes` | [`HashVerifier::execute`](crate::verify::HashVerifier::execute) | `files` |
//!
//! ### Debug-level (per-target / per-file sub-spans)
//!
//! | Span | Parent | Fields |
//! |---|---|---|
//! | `apply_target` | `apply_plan` / `resume_execute` | `target_idx`, `path`, `regions` |
//! | `verify_target` | `verify_plan` | `target` |
//! | `verify_file` | `verify_hashes` | `path` |
//!
//! ## Event catalog (info-level, per-operation completion)
//!
//! These messages are emitted exactly once per call to their owning entry
//! point on the success path, and are part of the stable contract:
//!
//! | Span | Message | Fields |
//! |---|---|---|
//! | `apply_patch` | `apply_patch: patch applied` | `chunks`, `bytes_read`, `resumed_from_chunk`, `elapsed_ms` |
//! | `resume_apply_patch` | `resume_apply_patch: patch applied` | `chunks`, `bytes_read`, `resumed_from_chunk`, `skipped_bytes` (resumed only), `elapsed_ms` |
//! | `resume_apply_patch` | `resume_apply_patch: resuming patch` | `patch_name`, `skipped_chunks`, `skipped_bytes`, `has_in_flight` |
//! | `resume_execute` | `apply_plan: indexed apply complete` | `bytes_written`, `targets`, `resumed_from`, `elapsed_ms` |
//! | `resume_execute` | `resume_execute: resuming indexed apply` | `plan_crc32`, `skipped_targets`, `skipped_regions`, `fs_ops_skipped` |
//! | `apply_plan` | `apply_plan: manifest replay complete` | `bytes_written`, `targets`, `regions`, `elapsed_ms` |
//! | `build_plan_patch` | `plan: patch consumed` | `chunks`, `targets`, `fs_ops` |
//! | *(none — fires from `PlanBuilder::finish`)* | `plan: built` | `patches`, `targets`, `regions`, `fs_ops` |
//! | `with_crc32` | `with_crc32: populated CRC32 for regions` | `populated`, `skipped` |
//! | `verify_plan` | `verify_plan: scan complete` | `targets`, `missing_targets`, `size_mismatched`, `damaged_targets`, `damaged_regions`, `elapsed_ms` |
//! | `verify_hashes` | `verify_hashes: run complete` | `files`, `failures`, `bytes_hashed`, `elapsed_ms` |
//!
//! ## Stable field-name vocabulary
//!
//! Field names attached to the spans and events above are stable. Across
//! the library they're used consistently:
//!
//! - `patch`, `patch_name`, `patches`, `chunks`, `bytes_read`, `elapsed_ms`
//! - `resumed_from_chunk`, `resumed_from`, `skipped_chunks`, `skipped_bytes`,
//! `skipped_targets`, `skipped_regions`, `has_in_flight`, `fs_ops_skipped`
//! - `targets`, `regions`, `fs_ops`, `target_idx`, `region_idx`,
//! `target`, `path`, `mode`
//! - `plan_crc32`, `populated`, `skipped`, `bytes_written`
//! - `files`, `failures`, `bytes_hashed`, `missing_targets`,
//! `size_mismatched`, `damaged_targets`, `damaged_regions`
//!
//! Field names emitted only at `debug!` / `trace!` levels (e.g.
//! `next_chunk_index`, `bytes_into_target`, `block_idx`, `chunk_bytes`,
//! `delete_zeros`, `decoded_skip`, per-fs-op `folder`/`kind`) are
//! best-effort and may change without a version bump.
//!
//! # API conventions
//!
//! All constructors follow consistent naming:
//!
//! - **`new(…)`** — canonical constructor; fails only on structurally invalid input
//! ([`ZiPatchReader::new`] validates the file magic).
//! - **`open(path)`** — opens a filesystem resource and returns a `Result`
//! ([`index::FilePatchSource::open`], [`index::FilePatchSource::open_chain`]).
//! - **`with_X(self, value) -> Self`** — builder-style setter; chains on
//! [`ApplyConfig`] and [`IndexApplier`].
//! - **`into_X(self)`** — type transition consuming `self`
//! ([`ApplyConfig::into_session`]).
//! - **`execute(self, …) -> Result<T>`** — runs a pipeline to completion
//! ([`IndexApplier::execute`](crate::IndexApplier::execute),
//! [`index::PlanVerifier::execute`],
//! [`verify::HashVerifier::execute`]).
//! - **`finish(self) -> T`** — builder finaliser with no I/O
//! ([`index::PlanBuilder::finish`]).
//!
//! The crate root re-exports the happy-path symbols. Secondary types live in
//! their owning modules:
//!
//! - [`chunk`] — [`chunk::ChunkRecord`], [`chunk::SqpkCommand`],
//! [`chunk::SqpackFileId`], [`chunk::SqpkCompressedBlock`]
//! - [`apply`] — [`apply::CheckpointSink`], [`apply::Checkpoint`],
//! [`apply::CheckpointPolicy`], [`apply::SequentialCheckpoint`],
//! [`apply::IndexedCheckpoint`], [`apply::NoopCheckpointSink`],
//! [`apply::NoopObserver`], [`apply::Vfs`], [`apply::StdFs`],
//! [`apply::InMemoryFs`]
//! - [`index`] — [`index::PlanVerifier`], [`index::PatchSource`],
//! [`index::FilePatchSource`], [`index::RepairManifest`]
//! - [`newtypes`] — [`newtypes::PatchIndex`], [`newtypes::ChunkTag`],
//! [`newtypes::SchemaVersion`]
//!
//! # Async usage
//!
//! `zipatch-rs` is a **synchronous** crate. Every public trait
//! ([`index::PatchSource`], [`apply::CheckpointSink`],
//! [`ApplyObserver`], [`apply::Vfs`]) and every driver entry point
//! ([`ApplyConfig::apply_patch`], [`IndexApplier::execute`](crate::index::IndexApplier::execute),
//! [`ZiPatchReader::next_chunk`]) is blocking. The crate has no
//! runtime dependency.
//!
//! This is a deliberate design choice. The apply-side hot path is
//! dominated by DEFLATE decompression (CPU-bound) and filesystem
//! syscalls (blocking by their nature on every mainstream OS); neither
//! benefits from an `async` signature. Staying sync also keeps the crate
//! trivially embeddable in a CLI binary, a Tauri command, or an
//! async-runtime worker without forcing a runtime choice or pulling
//! `tokio` into the dependency graph.
//!
//! ## Driving the crate from an async runtime
//!
//! Async consumers (e.g. a tokio-based launcher) park the whole apply
//! call on a blocking-pool thread:
//!
//! ```ignore
//! // pseudo-code; the crate has no tokio dependency
//! let install_path = install_path.clone();
//! let patch_path = patch_path.clone();
//! let cancel = zipatch_rs::CancelToken::new();
//! let cancel_bg = cancel.clone();
//!
//! // ... wire `cancel.cancel()` to a tokio::select! arm or UI handler ...
//!
//! let result = tokio::task::spawn_blocking(move || {
//! let reader = zipatch_rs::open_patch(&patch_path)?;
//! let ctx = zipatch_rs::ApplyConfig::new(install_path)
//! .with_cancel_token(cancel_bg);
//! ctx.apply_patch(reader)
//! }).await??;
//! ```
//!
//! Per-chunk progress reaches the async UI through an
//! [`mpsc`](std::sync::mpsc) (or tokio-mpsc-equivalent) channel whose
//! `Sender` lives inside an [`ApplyObserver`] impl and whose `Receiver`
//! is polled from an async task. Consumers that need both progress and
//! cancellation pair an observer (for progress) with a [`CancelToken`]
//! (for cancellation) — they compose without a wrapper observer.
//!
//! ## Async-backed sources
//!
//! Implementors whose backing storage is itself async (e.g. an
//! in-progress download, an async KV store for checkpoints, a remote
//! object-store [`apply::Vfs`]) satisfy the sync traits by bridging through a
//! channel against a separate async task: the sync method blocks on a
//! response from the async side. Because the trait methods run from
//! inside the `spawn_blocking` thread, blocking on the channel does
//! not stall the runtime's reactor.
compile_error!;
/// Filesystem application of parsed chunks ([`ApplyConfig`]).
/// Wire-format chunk types and the [`ZiPatchReader`] iterator.
/// Domain-split error types ([`ParseError`], [`ApplyError`], [`IndexError`], [`VerifyError`]).
/// Indexed-apply plan model and single-patch builder
/// ([`Plan`], [`PlanBuilder`]).
/// Strongly-typed wrappers around primitive identifiers in the public API
/// ([`newtypes::PatchIndex`], [`newtypes::ChunkTag`], [`newtypes::SchemaVersion`]).
pub
/// Post-apply integrity verification against caller-supplied file hashes.
/// Test fixtures quarantined behind the `test-utils` Cargo feature.
///
/// `#[doc(hidden)]` so this module — and everything it re-exports — stays
/// out of the user-facing rustdoc landing page. See the module rustdoc for
/// the no-stability stance.
// =============================================================================
// Public API — curated crate-root surface
//
// Only the happy-path symbols are re-exported here. Everything else stays
// addressable via its module path (`zipatch_rs::chunk::ChunkRecord`,
// `zipatch_rs::apply::CheckpointSink`, `zipatch_rs::newtypes::PatchIndex`,
// `zipatch_rs::index::PlanVerifier`, …) but does not crowd the landing page.
// =============================================================================
// --- One-shot drivers — the 90% case ---
pub use open_patch;
// `apply_patch_file` is defined below.
// --- Parsing primary types ---
pub use ;
// --- Apply primary types ---
pub use ;
// --- Indexed-pipeline primary types ---
pub use ;
// --- Central domain types ---
// `Platform` is defined at the crate root (below) since it has no natural home
// in a sub-module — every layer references it.
// --- Error umbrella + per-domain errors and result aliases ---
pub use ;
/// One-shot: open `patch_path` and apply every chunk to `install_root` with
/// all defaults.
///
/// Equivalent to:
///
/// ```ignore
/// let reader = zipatch_rs::open_patch(patch_path)?;
/// zipatch_rs::ApplyConfig::new(install_root).apply_patch(reader)?;
/// ```
///
/// The returned [`ApplyResult`] surfaces parsing failures as
/// [`ApplyError::Parse`] and apply-side failures as their respective
/// [`ApplyError`] variants, so a single match arm covers both layers.
///
/// Use the two-step form ([`open_patch`] + [`ApplyConfig::apply_patch`])
/// when you need to install an [`ApplyObserver`], a [`apply::CheckpointSink`],
/// a custom [`apply::Vfs`], a non-default [`Platform`], or to reuse one
/// [`ApplySession`] across multiple patches.
///
/// # Errors
///
/// Returns the first failure surfaced by either layer:
///
/// - [`ApplyError::Parse`] wrapping a [`ParseError`] for header, chunk, or
/// stream-shape problems (including the initial file open).
/// - [`ApplyError::Io`] for filesystem failures against `install_root`.
/// - [`ApplyError::UnsupportedPlatform`] if the patch declares a platform
/// this build does not know how to resolve `SqPack` paths for.
///
/// # Example
///
/// ```no_run
/// zipatch_rs::apply_patch_file(
/// "H2017.07.11.0000.0000a.patch",
/// "/opt/ffxiv/game",
/// ).unwrap();
/// ```
/// 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
/// [`ApplyConfig`] selects which suffix is used when resolving chunk targets
/// to filesystem paths.
///
/// # Default
///
/// An [`ApplyConfig`] defaults to [`Platform::Win32`]. Override this at
/// construction time with [`ApplyConfig::with_platform`].
///
/// # Runtime override via `SqpkTargetInfo`
///
/// In practice, real FFXIV patch files begin with an `SQPK T` chunk
/// (`SqpkTargetInfo`) that declares the target platform. When
/// [`Chunk::apply`] is called on that chunk, it overwrites
/// [`ApplyConfig::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]` because Square Enix has shipped console
/// targets on a sliding schedule (Win32, PS3, PS4) and a future PS5 / Switch
/// build would land here as a new named variant. 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
/// [`ApplyError::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::{ApplyConfig, Platform};
///
/// let ctx = ApplyConfig::new("/opt/ffxiv/game")
/// .with_platform(Platform::Win32);
///
/// assert_eq!(ctx.platform(), Platform::Win32);
/// assert_eq!(format!("{}", Platform::Unknown(99)), "Unknown(99)");
/// ```
///