zipatch-rs 1.1.0

Parser for FFXIV ZiPatch patch files
Documentation
use binrw::{BinRead, BinResult, Endian};
use std::io::Cursor;

use super::SqpackFile;

/// Sub-command byte of a SQPK `I` (Index) chunk.
///
/// Determines whether the index entry described by the containing [`SqpkIndex`]
/// should be added to or removed from the `SqPack` index file.
///
/// Encoded as a single ASCII byte: `b'A'` → `Add`, `b'D'` → `Delete`.
/// Any other byte is rejected with a [`binrw::Error::Custom`].
///
/// See `SqpkIndex.cs` in the `XIVLauncher` reference implementation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndexCommand {
    /// Add or update an index entry for the described asset.
    Add,
    /// Remove the index entry for the described asset.
    Delete,
}

fn read_index_command<R: std::io::Read + std::io::Seek>(
    reader: &mut R,
    _: Endian,
    (): (),
) -> BinResult<IndexCommand> {
    let byte = <u8 as BinRead>::read_options(reader, Endian::Big, ())?;
    match byte {
        b'A' => Ok(IndexCommand::Add),
        b'D' => Ok(IndexCommand::Delete),
        _ => Err(binrw::Error::Custom {
            pos: 0,
            err: Box::new(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "unknown IndexCommand",
            )),
        }),
    }
}

/// SQPK `I` command body: add or remove a single `SqPack` index entry.
///
/// Index entries map a 64-bit asset path hash to a block location inside a
/// `.dat` file. The `I` command is used by the indexed `ZiPatch` reader to
/// maintain the `.index` files without a full re-scan; it has **no direct
/// apply effect** (the apply arm returns `Ok(())` immediately).
///
/// ## Wire format (all big-endian)
///
/// ```text
/// ┌──────────────────────────────────────────────────────────────┐
/// │ command      : u8      b'A' = Add, b'D' = Delete             │  byte 0
/// │ is_synonym   : u8      0 = false, nonzero = true             │  byte 1
/// │ <padding>    : u8      (reserved)                            │  byte 2
/// │ main_id      : u16 BE  SqPack category ID                    │  bytes 3–4
/// │ sub_id       : u16 BE  SqPack sub-category ID                │  bytes 5–6
/// │ file_id      : u32 BE  dat/index file index                  │  bytes 7–10
/// │ file_hash    : u64 BE  64-bit hash of the asset path         │  bytes 11–18
/// │ block_offset : u32 BE  block offset within the .dat file     │  bytes 19–22
/// │ block_number : u32 BE  index lookup block number             │  bytes 23–26
/// └──────────────────────────────────────────────────────────────┘
/// ```
///
/// ## Reference
///
/// See `SqpkIndex.cs` in the `XIVLauncher` reference implementation.
///
/// # Errors
///
/// Parsing returns [`crate::ZiPatchError::BinrwError`] if:
/// - `command` is not `b'A'` or `b'D'`.
/// - The body is too short to contain all required fields.
#[derive(BinRead, Debug, Clone, PartialEq, Eq)]
#[br(big)]
pub struct SqpkIndex {
    /// Whether to add the entry to the index or delete it.
    ///
    /// Parsed from a single ASCII byte: `b'A'` → [`IndexCommand::Add`],
    /// `b'D'` → [`IndexCommand::Delete`].
    #[br(parse_with = read_index_command)]
    pub command: IndexCommand,
    /// `true` if this entry is a synonym (hash-collision) record in the index.
    ///
    /// Synonym entries exist when two asset paths hash to the same value;
    /// the index stores them in a secondary synonym table rather than the
    /// primary hash table.
    ///
    /// Parsed from a `u8`: `0` → `false`, any nonzero → `true`.
    #[br(map = |x: u8| x != 0)]
    pub is_synonym: bool,
    /// The `SqPack` file whose index is being modified.
    ///
    /// Preceded by 1 byte of alignment padding in the wire format.
    #[br(pad_before = 1)]
    pub target_file: SqpackFile,
    /// 64-bit hash of the indexed asset path.
    ///
    /// The hash algorithm is `SqPack`'s internal path hash (a combination of
    /// folder hash and filename hash). Encoded as a big-endian `u64`.
    pub file_hash: u64,
    /// Block offset of the asset data within the target `.dat` file.
    ///
    /// Encoded as a big-endian `u32`. Unlike the offsets in `AddData` /
    /// `ExpandData` / `DeleteData`, this value is stored and used directly
    /// by the index reader without the `<< 7` shift.
    pub block_offset: u32,
    /// Block number for the index lookup table entry.
    ///
    /// Encoded as a big-endian `u32`.
    pub block_number: u32,
}

/// SQPK `X` command body: patch install metadata.
///
/// Carries informational fields about the patch as a whole — install status,
/// format version, and the declared post-patch total install size. Like `I`,
/// this command has **no direct apply effect** and the apply arm returns
/// `Ok(())` immediately.
///
/// ## Wire format (all big-endian)
///
/// ```text
/// ┌────────────────────────────────────────────────────────┐
/// │ status       : u8      install status code             │  byte 0
/// │ version      : u8      patch info structure version    │  byte 1
/// │ <padding>    : u8      (reserved)                      │  byte 2
/// │ install_size : u64 BE  declared total size after patch │  bytes 3–10
/// └────────────────────────────────────────────────────────┘
/// ```
///
/// ## Reference
///
/// See `SqpkPatchInfo.cs` in the `XIVLauncher` reference implementation.
///
/// # Errors
///
/// Parsing returns [`crate::ZiPatchError::BinrwError`] if the body is too
/// short to contain all required fields.
#[derive(BinRead, Debug, Clone, PartialEq, Eq)]
#[br(big)]
pub struct SqpkPatchInfo {
    /// Install status code for this patch. The exact semantics are SE-internal;
    /// no known values are documented in the `XIVLauncher` reference.
    pub status: u8,
    /// Version of the `SqpkPatchInfo` wire structure.
    pub version: u8,
    /// Declared total install size (in bytes) of the game after this patch is
    /// applied. Informational only; not validated during apply.
    ///
    /// Preceded by 1 byte of alignment padding. Encoded as a big-endian `u64`.
    #[br(pad_before = 1)]
    pub install_size: u64,
}

pub(crate) fn parse_index(body: &[u8]) -> crate::Result<SqpkIndex> {
    Ok(SqpkIndex::read_be(&mut Cursor::new(body))?)
}

pub(crate) fn parse_patch_info(body: &[u8]) -> crate::Result<SqpkPatchInfo> {
    Ok(SqpkPatchInfo::read_be(&mut Cursor::new(body))?)
}

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

    #[test]
    fn parses_sqpk_index_add() {
        let mut body = Vec::new();
        body.push(b'A'); // command = Add
        body.push(1u8); // is_synonym = true
        body.push(0u8); // alignment
        body.extend_from_slice(&0x0102u16.to_be_bytes()); // main_id
        body.extend_from_slice(&0x0304u16.to_be_bytes()); // sub_id
        body.extend_from_slice(&0u32.to_be_bytes()); // file_id
        body.extend_from_slice(&0x0807060504030201u64.to_be_bytes()); // file_hash (would differ in LE)
        body.extend_from_slice(&5u32.to_be_bytes()); // block_offset
        body.extend_from_slice(&10u32.to_be_bytes()); // block_number

        let idx = parse_index(&body).unwrap();
        assert!(matches!(idx.command, IndexCommand::Add));
        assert!(idx.is_synonym);
        assert_eq!(idx.target_file.main_id, 0x0102);
        assert_eq!(idx.file_hash, 0x0807060504030201);
        assert_eq!(idx.block_offset, 5);
        assert_eq!(idx.block_number, 10);
    }

    #[test]
    fn rejects_unknown_index_command() {
        let mut body = Vec::new();
        body.push(b'Z'); // invalid
        body.extend_from_slice(&[0u8; 20]);
        assert!(parse_index(&body).is_err());
    }

    #[test]
    fn parses_sqpk_patch_info() {
        let mut body = Vec::new();
        body.push(3u8); // status
        body.push(1u8); // version
        body.push(0u8); // alignment
        body.extend_from_slice(&0x0102030405060708u64.to_be_bytes()); // install_size (BE, not LE)

        let info = parse_patch_info(&body).unwrap();
        assert_eq!(info.status, 3);
        assert_eq!(info.version, 1);
        assert_eq!(info.install_size, 0x0102030405060708);
    }
}