zipatch-rs 1.0.1

Parser for FFXIV ZiPatch patch files
Documentation
/// All failures returned by parsing or applying a `ZiPatch` stream.
///
/// Both the parsing layer ([`crate::chunk`]) and the apply layer
/// ([`crate::apply`]) surface errors through this single enum, so callers
/// need only one error type in their `match` arms.
///
/// # Mapping from standard errors
///
/// - [`std::io::Error`] converts automatically via `#[from]` into [`ZiPatchError::Io`].
/// - [`std::string::FromUtf8Error`] converts automatically into [`ZiPatchError::Utf8Error`].
/// - [`binrw::Error`] converts automatically into [`ZiPatchError::BinrwError`].
///
/// # Example
///
/// ```rust
/// use zipatch_rs::ZiPatchError;
///
/// fn describe(e: &ZiPatchError) -> &'static str {
///     match e {
///         ZiPatchError::Io(_)               => "I/O error",
///         ZiPatchError::InvalidMagic        => "not a ZiPatch file",
///         ZiPatchError::UnknownChunkTag(_)  => "unrecognised chunk",
///         ZiPatchError::ChecksumMismatch {..}=> "corrupt chunk",
///         ZiPatchError::TruncatedPatch      => "download incomplete",
///         _                                 => "other error",
///     }
/// }
/// ```
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ZiPatchError {
    /// Underlying I/O failure from the patch source or target filesystem.
    ///
    /// Raised by the parsing layer when reading from the patch stream fails
    /// (e.g. a network read error), and by the apply layer when any filesystem
    /// operation fails (open, seek, write, delete, create-dir).
    ///
    /// The wrapped [`std::io::Error`] carries the OS-level error code and kind.
    /// Use [`std::io::Error::kind`] to distinguish `NotFound`, `PermissionDenied`,
    /// and similar conditions.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// The 12-byte `ZiPatch` magic header was missing or did not match.
    ///
    /// Raised by [`ZiPatchReader::new`](crate::ZiPatchReader::new) and
    /// [`ZiPatchReader::from_path`](crate::ZiPatchReader::from_path) when
    /// the first 12 bytes of the source do not equal the expected magic
    /// sequence `\x91ZIPATCH\r\n\x1a\n`. Typically indicates the caller opened
    /// the wrong file, or the file is corrupted at the very start.
    #[error("invalid magic bytes")]
    InvalidMagic,

    /// A 4-byte chunk tag was not recognised by the parser.
    ///
    /// Raised by the chunk dispatcher in [`crate::chunk`] when a tag does not
    /// match any of `FHDR`, `APLY`, `APFS`, `ADIR`, `DELD`, `SQPK`, or
    /// `EOF_`. The raw tag bytes are preserved so callers can log them for
    /// diagnostic purposes.
    ///
    /// This can occur with genuinely new chunk types introduced by Square Enix
    /// in future patches. Upgrading the library or filing an issue is the
    /// appropriate response.
    #[error("unknown chunk tag: {0:?}")]
    UnknownChunkTag([u8; 4]),

    /// A SQPK sub-command byte was not recognised by the parser.
    ///
    /// Raised by the SQPK dispatcher in [`crate::chunk`] when the single-byte
    /// command code inside an `SQPK` chunk does not match any of the known
    /// values (`A`, `D`, `E`, `F`, `H`, `I`, `T`, `X`). The raw byte is
    /// preserved for diagnostics.
    #[error("unknown SQPK command: {0:#x}")]
    UnknownSqpkCommand(u8),

    /// A chunk's recorded CRC32 did not match the computed CRC32.
    ///
    /// Raised by the chunk framing code in [`crate::chunk`] when CRC32
    /// verification is enabled (the default) and the stored checksum in the
    /// patch stream does not match the checksum computed over `tag ++ body`.
    ///
    /// This indicates a corrupt or partially-written patch file. Disable
    /// verification with
    /// [`ZiPatchReader::skip_checksum_verification`](crate::ZiPatchReader::skip_checksum_verification)
    /// if the source has already been verified out-of-band.
    ///
    /// The `tag`, `expected`, and `actual` fields provide enough information
    /// to log a precise diagnostic message.
    #[error("CRC32 mismatch on chunk {tag:?}: expected {expected:#010x}, got {actual:#010x}")]
    ChecksumMismatch {
        /// Tag of the chunk whose checksum failed.
        tag: [u8; 4],
        /// CRC32 stored in the patch file.
        expected: u32,
        /// CRC32 computed over the actual chunk bytes.
        actual: u32,
    },

    /// DEFLATE decompression of a `SqpkFile` block failed.
    ///
    /// Raised by the `SqpkFile` apply logic when `flate2` cannot decompress
    /// a compressed block payload inside an `AddFile` operation. The wrapped
    /// [`std::io::Error`] is the decompressor's error, not a filesystem error;
    /// it is stored as a `#[source]` rather than `#[from]` to keep it distinct
    /// from [`ZiPatchError::Io`].
    #[error("decompression error")]
    Decompress(#[source] std::io::Error),

    /// A field value failed a parser invariant (e.g. negative size).
    ///
    /// Raised by chunk-specific parsers in [`crate::chunk`] when a field
    /// value is syntactically valid (i.e. could be parsed) but violates a
    /// semantic constraint required by the format — for example, a length
    /// field that is negative, or a size that overflows the expected range.
    ///
    /// The `context` string names the specific field that failed its check,
    /// giving enough information to locate the offending position in the
    /// binary format documentation.
    #[error("invalid field: {context}")]
    InvalidField {
        /// Human-readable description of which field was invalid and why.
        context: &'static str,
    },

    /// A chunk declared a size larger than the parser's maximum (512 MiB).
    ///
    /// Raised by the chunk framing code in [`crate::chunk`] when the
    /// `body_len` field of a chunk frame exceeds 512 MiB. This guard prevents
    /// allocating an arbitrarily large buffer from a malformed or malicious
    /// patch stream. The preserved size value can be logged for diagnostics.
    #[error("chunk size {0} exceeds maximum")]
    OversizedChunk(usize),

    /// A `SqpkFile` operation byte was not recognised.
    ///
    /// Raised by the `SqpkFile` parser when the single-byte `operation` field
    /// does not match any of `A` (`AddFile`), `R` (`RemoveAll`), `D` (`DeleteFile`),
    /// or `M` (`MakeDirTree`). The raw byte is preserved for diagnostics.
    #[error("unknown SqpkFile operation: {0:#02x}")]
    UnknownFileOperation(u8),

    /// A UTF-8 decode failed when reading a path or name field.
    ///
    /// Raised by the parsing layer when a length-prefixed byte string (e.g. a
    /// directory name in an `ADIR` chunk or a file path in a `SqpkFile` chunk)
    /// is not valid UTF-8. FFXIV patch paths are documented as ASCII, so this
    /// error indicates either a corrupt patch file or an undocumented encoding
    /// extension.
    #[error("UTF-8 decode error")]
    Utf8Error(#[from] std::string::FromUtf8Error),

    /// A `binrw` parser produced an error; wraps the underlying cause.
    ///
    /// Several chunk types (notably those using `#[derive(BinRead)]`) delegate
    /// their parsing to `binrw`. When `binrw` encounters an unexpected byte
    /// pattern or short read, it returns a [`binrw::Error`] which is wrapped
    /// here via `#[from]`.
    ///
    /// The inner error message usually identifies the field name and byte
    /// offset where parsing failed.
    #[error("binrw parse error: {0}")]
    BinrwError(#[from] binrw::Error),

    /// A `SqpkFile` carried a negative `file_offset` that cannot be applied.
    ///
    /// Raised by the `AddFile` arm of the `SqpkFile` apply logic when
    /// `cmd.file_offset` is negative and therefore cannot be converted to a
    /// [`u64`] seek position. The wire format stores this field as `i64`;
    /// a non-negative value is the invariant required for correct application.
    ///
    /// The preserved `i64` value can be logged to report the exact field content.
    #[error("negative file_offset in SqpkFile: {0}")]
    NegativeFileOffset(i64),

    /// Stream ended without an `EOF_` chunk; download or copy was truncated.
    ///
    /// Raised by the chunk framing code when attempting to read the 4-byte
    /// `body_len` field of the next chunk returns an unexpected EOF. This
    /// indicates the patch stream ended before the mandatory `EOF_` terminator
    /// chunk was encountered — the patch file was likely incompletely
    /// downloaded or written to disk.
    ///
    /// Use [`ZiPatchReader::is_complete`](crate::ZiPatchReader::is_complete)
    /// after iteration to distinguish this case from a clean end of stream.
    #[error("patch file ended without EOF_ chunk (truncated download?)")]
    TruncatedPatch,
}