zipatch-rs 1.1.1

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
//! `SqPack` on-disk path resolution.
//!
//! `SqPack` files live under
//! `<game_root>/sqpack/<expansion>/<category><sub>.<platform>.<kind>[<n>]`.
//! This module reconstructs those paths from the numeric identifiers carried
//! in SQPK chunk headers.
//!
//! # Path structure
//!
//! Every `SqPack` file path has four variable components:
//!
//! | Component | Source | Example |
//! |-----------|--------|---------|
//! | Expansion folder | high byte of `sub_id` | `ffxiv`, `ex1`, `ex2` |
//! | Filename prefix | `main_id` (2 hex digits) + `sub_id` (4 hex digits) | `040100` |
//! | Platform suffix | [`crate::Platform`] from [`crate::apply::ApplyContext`] | `win32`, `ps3`, `ps4` |
//! | Kind + index | `.dat0`, `.index`, `.index1` | |
//!
//! ## Expansion folder
//!
//! Derived from bits `[15:8]` of `sub_id` (i.e. `sub_id >> 8`):
//!
//! - `0` → `ffxiv` (base game data)
//! - `n > 0` → `ex<n>` (expansion packs: `ex1`, `ex2`, …)
//!
//! ## Platform suffix
//!
//! Derived from [`crate::Platform`] stored in [`crate::apply::ApplyContext`]:
//!
//! - [`crate::Platform::Win32`] → `win32`
//! - [`crate::Platform::Ps3`] → `ps3`
//! - [`crate::Platform::Ps4`] → `ps4`
//! - [`crate::Platform::Unknown`] → [`crate::ZiPatchError::UnsupportedPlatform`]
//!   (a silent fallback would risk writing platform-specific data to the wrong
//!   file — see [`platform_str`] for the full rationale)
//!
//! ## `.dat` files
//!
//! `<game_root>/sqpack/<expansion>/<main_id:02x><sub_id:04x>.<platform>.dat<file_id>`
//!
//! Example: `main_id=0x04`, `sub_id=0x0100`, `file_id=2`, `platform=Win32`
//! → `sqpack/ex1/040100.win32.dat2`
//!
//! ## `.index` files
//!
//! `<game_root>/sqpack/<expansion>/<main_id:02x><sub_id:04x>.<platform>.index[<file_id>]`
//!
//! `file_id=0` produces no suffix (`.index`); `file_id=1` produces `.index1`,
//! `file_id=2` produces `.index2`, and so on. This matches the on-disk layout
//! where the primary index has no numeric suffix and alternate indexes are
//! numbered from 1.
//!
//! ## Generic files
//!
//! Non-`SqPack` files (written by [`crate::chunk::sqpk::SqpkFile`]'s
//! `AddFile` and `DeleteFile` operations) are resolved as a simple join:
//! `<game_root>/<relative_path>`.

use super::{ApplyContext, PathCacheKey, PathKind};
use crate::{Platform, Result, ZiPatchError};
use std::path::PathBuf;

/// Map an expansion ID to its on-disk folder name.
///
/// - `0` → `"ffxiv"` (base game)
/// - `n > 0` → `"ex<n>"` (e.g. `1` → `"ex1"`, `2` → `"ex2"`)
///
/// This is the public form that accepts a pre-extracted expansion ID (i.e. the
/// high byte of `sub_id`). The `expansion_folder` private function calls this
/// after extracting the ID from a raw `sub_id` via `sub_id >> 8`.
pub(crate) fn expansion_folder_id(id: u16) -> String {
    if id == 0 {
        "ffxiv".to_string()
    } else {
        format!("ex{id}")
    }
}

/// Extract the expansion ID from a raw `sub_id` and return its folder name.
///
/// The expansion ID is the high byte of `sub_id` (`sub_id >> 8`).
fn expansion_folder(sub_id: u16) -> String {
    expansion_folder_id(sub_id >> 8)
}

/// Map a [`Platform`] to its path-component string.
///
/// The parsing layer tolerates unrecognised `platform_id` values in
/// [`SqpkTargetInfo`](crate::chunk::SqpkTargetInfo) by storing them as
/// [`Platform::Unknown`] rather than failing, so the iterator can still yield
/// non-SqPack chunks (e.g. `ADIR`, `DELD`, generic `SqpkFile` ops) from a
/// patch authored for a future platform. Path resolution, however, refuses to
/// guess: silently substituting the `win32` layout for an unknown platform
/// would write platform-specific data to the wrong `.dat`/`.index` file and
/// corrupt the on-disk install. This function therefore returns
/// [`ZiPatchError::UnsupportedPlatform`] carrying the raw `platform_id` so
/// callers can surface it to users.
///
/// # Errors
///
/// Returns [`ZiPatchError::UnsupportedPlatform`] when `platform` is
/// [`Platform::Unknown`].
fn platform_str(platform: Platform) -> Result<&'static str> {
    match platform {
        Platform::Win32 => Ok("win32"),
        Platform::Ps3 => Ok("ps3"),
        Platform::Ps4 => Ok("ps4"),
        Platform::Unknown(id) => Err(ZiPatchError::UnsupportedPlatform(id)),
    }
}

/// Compute (uncached) the path of a `SqPack` `.dat` file.
fn build_dat_path(ctx: &ApplyContext, main_id: u16, sub_id: u16, file_id: u32) -> Result<PathBuf> {
    let platform = platform_str(ctx.platform)?;
    Ok(ctx
        .game_path
        .join("sqpack")
        .join(expansion_folder(sub_id))
        .join(format!("{main_id:02x}{sub_id:04x}.{platform}.dat{file_id}")))
}

/// Resolve the path of a `SqPack` `.dat` file, consulting the per-context cache.
///
/// Produces:
/// `<game_root>/sqpack/<expansion>/<main_id:02x><sub_id:04x>.<platform>.dat<file_id>`
///
/// On cache hit the cached `PathBuf` is cloned (one allocation) and returned.
/// On miss the path is built from scratch — three `PathBuf::join` calls plus
/// two intermediate `String` allocations — and the result is inserted before
/// the clone is handed back. The cache is invalidated by
/// `apply_target_info` whenever the target platform changes, since the
/// resolved path embeds the platform string.
///
/// # Arguments
///
/// - `ctx` — provides the install root, current platform, and cache.
/// - `main_id` — the category/repository identifier (2 lower hex digits of
///   the filename prefix).
/// - `sub_id` — the sub-category identifier (4 hex digits). Its high byte
///   selects the expansion folder.
/// - `file_id` — the dat file index, appended as a decimal suffix after
///   `.dat` with no separator (e.g. `dat0`, `dat2`).
///
/// # Errors
///
/// Returns [`ZiPatchError::UnsupportedPlatform`] when [`ApplyContext::platform`]
/// is [`Platform::Unknown`]. The parser preserves unrecognised `platform_id`
/// values rather than failing the iterator, so this is the first point at
/// which an unknown platform aborts an apply that would otherwise misroute a
/// `.dat` write to the wrong on-disk layout. The error path does **not**
/// insert into the cache.
pub(crate) fn dat_path(
    ctx: &mut ApplyContext,
    main_id: u16,
    sub_id: u16,
    file_id: u32,
) -> Result<PathBuf> {
    let key = PathCacheKey {
        main_id,
        sub_id,
        file_id,
        kind: PathKind::Dat,
    };
    if let Some(cached) = ctx.path_cache.get(&key) {
        return Ok(cached.clone());
    }
    let path = build_dat_path(ctx, main_id, sub_id, file_id)?;
    ctx.path_cache.insert(key, path.clone());
    Ok(path)
}

/// Compute (uncached) the path of a `SqPack` `.index` file.
fn build_index_path(
    ctx: &ApplyContext,
    main_id: u16,
    sub_id: u16,
    file_id: u32,
) -> Result<PathBuf> {
    let platform = platform_str(ctx.platform)?;
    let suffix = if file_id == 0 {
        String::new()
    } else {
        file_id.to_string()
    };
    Ok(ctx
        .game_path
        .join("sqpack")
        .join(expansion_folder(sub_id))
        .join(format!(
            "{main_id:02x}{sub_id:04x}.{platform}.index{suffix}"
        )))
}

/// Resolve the path of a `SqPack` `.index` file, consulting the per-context cache.
///
/// Produces:
/// `<game_root>/sqpack/<expansion>/<main_id:02x><sub_id:04x>.<platform>.index[<file_id>]`
///
/// `file_id=0` appends no numeric suffix (primary index); `file_id > 0`
/// appends the decimal value directly, yielding `.index1`, `.index2`, etc.
/// See [`dat_path`] for the caching semantics — they apply identically here.
///
/// # Arguments
///
/// - `ctx` — provides the install root, current platform, and cache.
/// - `main_id` — the category/repository identifier.
/// - `sub_id` — the sub-category identifier; high byte selects the expansion.
/// - `file_id` — `0` for the primary index, `1` or higher for alternate indexes.
///
/// # Errors
///
/// Returns [`ZiPatchError::UnsupportedPlatform`] when [`ApplyContext::platform`]
/// is [`Platform::Unknown`]. The parser preserves unrecognised `platform_id`
/// values rather than failing the iterator, so this is the first point at
/// which an unknown platform aborts an apply that would otherwise misroute an
/// `.index` write to the wrong on-disk layout. The error path does **not**
/// insert into the cache.
pub(crate) fn index_path(
    ctx: &mut ApplyContext,
    main_id: u16,
    sub_id: u16,
    file_id: u32,
) -> Result<PathBuf> {
    let key = PathCacheKey {
        main_id,
        sub_id,
        file_id,
        kind: PathKind::Index,
    };
    if let Some(cached) = ctx.path_cache.get(&key) {
        return Ok(cached.clone());
    }
    let path = build_index_path(ctx, main_id, sub_id, file_id)?;
    ctx.path_cache.insert(key, path.clone());
    Ok(path)
}

/// Resolve a generic (non-`SqPack`) path relative to the game install root.
///
/// Simply joins `ctx.game_path` with `relative_path`. Used by
/// [`crate::chunk::sqpk::SqpkFile`] operations that target files outside the
/// `sqpack/` subtree (e.g. launcher executables or movie files written by
/// `AddFile`/`DeleteFile`).
///
/// No path components are validated or normalised; the caller is responsible
/// for ensuring `relative_path` does not escape the install root.
#[must_use]
pub(crate) fn generic_path(ctx: &ApplyContext, relative_path: &str) -> PathBuf {
    ctx.game_path.join(relative_path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::apply::ApplyContext;

    fn ctx(game: &str) -> ApplyContext {
        ApplyContext::new(game)
    }

    #[test]
    fn dat_expansion_0() {
        let mut c = ctx("/game");
        let result = dat_path(&mut c, 0x00, 0x0000, 0).unwrap();
        assert_eq!(
            result,
            PathBuf::from("/game/sqpack/ffxiv/000000.win32.dat0")
        );
    }

    #[test]
    fn dat_expansion_1() {
        let mut c = ctx("/game");
        let result = dat_path(&mut c, 0x04, 0x0100, 2).unwrap();
        assert_eq!(result, PathBuf::from("/game/sqpack/ex1/040100.win32.dat2"));
    }

    #[test]
    fn index_expansion_0_file_id_0() {
        let mut c = ctx("/game");
        let result = index_path(&mut c, 0x00, 0x0000, 0).unwrap();
        assert_eq!(
            result,
            PathBuf::from("/game/sqpack/ffxiv/000000.win32.index")
        );
    }

    #[test]
    fn index_expansion_0_file_id_1() {
        let mut c = ctx("/game");
        let result = index_path(&mut c, 0x00, 0x0000, 1).unwrap();
        assert_eq!(
            result,
            PathBuf::from("/game/sqpack/ffxiv/000000.win32.index1")
        );
    }

    #[test]
    fn index_expansion_1_file_id_0() {
        let mut c = ctx("/game");
        let result = index_path(&mut c, 0x04, 0x0100, 0).unwrap();
        assert_eq!(result, PathBuf::from("/game/sqpack/ex1/040100.win32.index"));
    }

    #[test]
    fn index_expansion_1_file_id_1() {
        let mut c = ctx("/game");
        let result = index_path(&mut c, 0x04, 0x0100, 1).unwrap();
        assert_eq!(
            result,
            PathBuf::from("/game/sqpack/ex1/040100.win32.index1")
        );
    }

    #[test]
    fn dat_ps3_platform() {
        let mut ctx = ApplyContext::new("/game");
        ctx.platform = Platform::Ps3;
        assert_eq!(
            dat_path(&mut ctx, 0x00, 0x0000, 0).unwrap(),
            PathBuf::from("/game/sqpack/ffxiv/000000.ps3.dat0")
        );
    }

    #[test]
    fn dat_ps4_platform() {
        let mut ctx = ApplyContext::new("/game");
        ctx.platform = Platform::Ps4;
        assert_eq!(
            dat_path(&mut ctx, 0x00, 0x0000, 0).unwrap(),
            PathBuf::from("/game/sqpack/ffxiv/000000.ps4.dat0")
        );
    }

    #[test]
    fn dat_expansion_2() {
        // sub_id >> 8 == 2 → "ex2"
        let mut c = ctx("/game");
        let result = dat_path(&mut c, 0x08, 0x0200, 0).unwrap();
        assert_eq!(result, PathBuf::from("/game/sqpack/ex2/080200.win32.dat0"));
    }

    // --- Unknown-platform refusal ---

    #[test]
    fn dat_path_returns_unsupported_platform_for_unknown() {
        // Confirms the fix: an unknown platform_id no longer silently routes
        // to a win32 path. The error carries the raw u16 so callers can
        // surface it to users.
        let mut c = ApplyContext::new("/game");
        c.platform = Platform::Unknown(99);
        let err = dat_path(&mut c, 0x00, 0x0000, 0)
            .expect_err("unknown platform must abort dat_path resolution");
        match err {
            ZiPatchError::UnsupportedPlatform(id) => assert_eq!(
                id, 99,
                "error must carry the raw platform_id for diagnostics"
            ),
            other => panic!("expected UnsupportedPlatform(99), got {other:?}"),
        }
    }

    #[test]
    fn index_path_returns_unsupported_platform_for_unknown() {
        let mut c = ApplyContext::new("/game");
        c.platform = Platform::Unknown(7);
        let err = index_path(&mut c, 0x00, 0x0000, 1)
            .expect_err("unknown platform must abort index_path resolution");
        match err {
            ZiPatchError::UnsupportedPlatform(id) => assert_eq!(id, 7),
            other => panic!("expected UnsupportedPlatform(7), got {other:?}"),
        }
    }

    // --- Path cache ---

    #[test]
    fn dat_path_populates_and_serves_from_cache() {
        // First call resolves and inserts into the cache; second call for the
        // same key must hit the cache (population is observable as a non-zero
        // map length) and return an equal path.
        let mut c = ctx("/game");
        assert!(
            c.path_cache.is_empty(),
            "fresh ApplyContext starts with an empty path cache"
        );
        let p1 = dat_path(&mut c, 0x04, 0x0100, 2).unwrap();
        assert_eq!(c.path_cache.len(), 1, "first call must populate the cache");
        let p2 = dat_path(&mut c, 0x04, 0x0100, 2).unwrap();
        assert_eq!(p1, p2, "cache hit must produce an equal PathBuf");
        assert_eq!(
            c.path_cache.len(),
            1,
            "second call for the same key must not grow the cache"
        );
    }

    #[test]
    fn dat_and_index_paths_share_cache_under_different_kinds() {
        // Same numeric key but different `PathKind` discriminants must hash to
        // distinct cache entries.
        let mut c = ctx("/game");
        let d = dat_path(&mut c, 0x00, 0x0000, 0).unwrap();
        let i = index_path(&mut c, 0x00, 0x0000, 0).unwrap();
        assert_ne!(d, i, "dat and index paths must differ");
        assert_eq!(
            c.path_cache.len(),
            2,
            "PathKind discriminates: dat and index must occupy separate cache slots"
        );
    }

    #[test]
    fn path_cache_unsupported_platform_does_not_insert() {
        // Errors must not pollute the cache — a later platform change must be
        // able to serve a fresh resolution on the next call.
        let mut c = ApplyContext::new("/game");
        c.platform = Platform::Unknown(42);
        assert!(dat_path(&mut c, 0x00, 0x0000, 0).is_err());
        assert!(
            c.path_cache.is_empty(),
            "unsupported-platform error must not insert into the path cache"
        );
    }

    #[test]
    fn invalidate_path_cache_drops_every_entry() {
        let mut c = ctx("/game");
        let _ = dat_path(&mut c, 0x04, 0x0100, 2).unwrap();
        let _ = index_path(&mut c, 0x04, 0x0100, 0).unwrap();
        assert_eq!(c.path_cache.len(), 2);
        c.invalidate_path_cache();
        assert!(
            c.path_cache.is_empty(),
            "invalidate_path_cache must empty the entire map"
        );
    }

    #[test]
    fn index_path_populates_and_serves_from_cache() {
        // First call resolves and inserts; second call for the same key must
        // return the cached clone without growing the map.  This exercises the
        // `return Ok(cached.clone())` early-return in `index_path` (the
        // counterpart of the identical cache-hit arm in `dat_path`).
        let mut c = ctx("/game");
        assert!(
            c.path_cache.is_empty(),
            "fresh ApplyContext starts with an empty path cache"
        );
        let p1 = index_path(&mut c, 0x04, 0x0100, 0).unwrap();
        assert_eq!(c.path_cache.len(), 1, "first call must populate the cache");
        let p2 = index_path(&mut c, 0x04, 0x0100, 0).unwrap();
        assert_eq!(p1, p2, "cache hit must return an equal PathBuf");
        assert_eq!(
            c.path_cache.len(),
            1,
            "second call for the same key must not grow the cache"
        );
    }
}