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
//! 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.
//!
//! # Tracing
//!
//! The library emits structured [`tracing`] events at `trace!`, `debug!`, and
//! `warn!` levels. No subscriber is configured here — configure output in your
//! application binary (or in `gaveloc`'s launcher binary).
//!
//! [`tracing`]: https://docs.rs/tracing
/// Filesystem application of parsed chunks ([`Apply`], [`ApplyContext`]).
/// Wire-format chunk types and the [`ZiPatchReader`] iterator.
/// Error type returned by parsing and applying ([`ZiPatchError`]).
pub
pub use ;
pub use ;
pub use ZiPatchError;
/// Crate-wide `Result` alias parameterised over [`ZiPatchError`].
pub type Result<T> = Result;
/// 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 falls back to
/// the `win32` layout for unknown variants.
///
/// # 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