zipatch-rs 1.1.0

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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Wire-format chunk types and the [`ZiPatchReader`] iterator.
//!
//! This module is the parsing layer: it decodes the raw `ZiPatch` byte
//! stream into a stream of typed [`Chunk`] values. Each top-level
//! variant corresponds to one 4-byte ASCII wire tag (`FHDR`, `APLY`,
//! `SQPK`, …); the per-variant submodules below own the binary layout for
//! their body. Nothing in this module touches the filesystem — apply-time
//! effects live in [`crate::apply`].
//!
//! The [`ZiPatchReader`] iterator validates the 12-byte file magic on
//! construction, then yields one [`Chunk`] per [`Iterator::next`] call
//! until the internal `EOF_` terminator is consumed or a parse error
//! surfaces.

pub(crate) mod adir;
pub(crate) mod afsp;
pub(crate) mod aply;
pub(crate) mod ddir;
pub(crate) mod fhdr;
pub(crate) mod sqpk;
pub(crate) mod util;

pub use adir::AddDirectory;
pub use afsp::ApplyFreeSpace;
pub use aply::{ApplyOption, ApplyOptionKind};
pub use ddir::DeleteDirectory;
pub use fhdr::{FileHeader, FileHeaderV2, FileHeaderV3};
pub use sqpk::{SqpackFile, SqpkCommand};
// Re-export SqpkCommand sub-types so callers can match on them
pub use sqpk::{
    IndexCommand, SqpkAddData, SqpkCompressedBlock, SqpkDeleteData, SqpkExpandData, SqpkFile,
    SqpkFileOperation, SqpkHeader, SqpkHeaderTarget, SqpkIndex, SqpkPatchInfo, SqpkTargetInfo,
    TargetFileKind, TargetHeaderKind,
};

use crate::reader::ReadExt;
use crate::{Result, ZiPatchError};
use tracing::trace;

const MAGIC: [u8; 12] = [
    0x91, 0x5A, 0x49, 0x50, 0x41, 0x54, 0x43, 0x48, 0x0D, 0x0A, 0x1A, 0x0A,
];

const MAX_CHUNK_SIZE: usize = 512 * 1024 * 1024;

/// One top-level chunk parsed from a `ZiPatch` stream.
///
/// Each variant corresponds to a 4-byte ASCII wire tag. The tag dispatch table
/// mirrors the C# reference in
/// `lib/FFXIVQuickLauncher/.../Patching/ZiPatch/Chunk/ZiPatchChunk.cs`.
///
/// # Observed frequency
///
/// SE's XIVARR+ patch files almost exclusively contain `FHDR`, `APLY`, and
/// `SQPK` chunks. `ADIR`/`DELD` can theoretically appear and are implemented,
/// but are rarely emitted in practice. `APFS` has never been observed in modern
/// patches (the reference implementation treats it as a no-op). `EOF_` is
/// consumed by [`ZiPatchReader`] and is never yielded to the caller.
///
/// # Exhaustiveness
///
/// The enum is `#[non_exhaustive]`. Match arms should include a wildcard to
/// remain forward-compatible as new chunk types are added.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Chunk {
    /// `FHDR` — the first chunk in every patch file; carries version and
    /// per-version patch metadata. See [`FileHeader`] for the versioned body.
    FileHeader(FileHeader),
    /// `APLY` — sets or clears a boolean apply-time flag on the
    /// [`crate::ApplyContext`] (e.g. "ignore missing files"). See [`ApplyOption`].
    ApplyOption(ApplyOption),
    /// `APFS` — free-space book-keeping emitted by old patcher tooling; treated
    /// as a no-op at apply time. See [`ApplyFreeSpace`].
    ApplyFreeSpace(ApplyFreeSpace),
    /// `ADIR` — instructs the patcher to create a directory under the game
    /// install root. See [`AddDirectory`].
    AddDirectory(AddDirectory),
    /// `DELD` — instructs the patcher to remove a directory under the game
    /// install root. See [`DeleteDirectory`].
    DeleteDirectory(DeleteDirectory),
    /// `SQPK` — the workhorse chunk; wraps one of eight sub-commands that
    /// add, delete, expand, or replace `SqPack` data. See [`SqpkCommand`].
    Sqpk(SqpkCommand),
    /// `EOF_` — marks the clean end of the patch stream. [`ZiPatchReader`]
    /// consumes this chunk internally; it is never yielded to the caller.
    EndOfFile,
}

/// One parsed chunk plus its 4-byte ASCII tag and the byte count consumed
/// from the input stream by its frame.
///
/// Returned by [`parse_chunk`]. The `consumed` count is exactly the size of
/// the chunk's on-wire frame: `4 (body_len) + 4 (tag) + body_len + 4 (crc32)`
/// = `body_len + 12`. This is what
/// [`ZiPatchReader`](crate::ZiPatchReader) accumulates into its running
/// byte counter for progress reporting.
pub(crate) struct ParsedChunk {
    pub(crate) chunk: Chunk,
    pub(crate) tag: [u8; 4],
    pub(crate) consumed: u64,
}

/// Parse one chunk frame from `r`.
///
/// # Wire framing
///
/// Each chunk is laid out as:
///
/// ```text
/// [body_len: u32 BE] [tag: 4 bytes] [body: body_len bytes] [crc32: u32 BE]
/// ```
///
/// The CRC32 is computed over `tag ++ body` (not over `body_len`), matching
/// the C# `ChecksumBinaryReader` in the `XIVLauncher` reference. When
/// `verify_checksums` is `true` and the stored CRC does not match the computed
/// one, [`ZiPatchError::ChecksumMismatch`] is returned.
///
/// # Errors
///
/// - [`ZiPatchError::TruncatedPatch`] — the reader returns EOF while reading
///   the `body_len` field (i.e. no more chunks are present but `EOF_` was
///   never seen).
/// - [`ZiPatchError::OversizedChunk`] — `body_len` exceeds 512 MiB.
/// - [`ZiPatchError::ChecksumMismatch`] — CRC32 mismatch (only when
///   `verify_checksums` is `true`).
/// - [`ZiPatchError::UnknownChunkTag`] — tag is not recognised.
/// - [`ZiPatchError::Io`] — any other I/O failure reading from `r`.
pub(crate) fn parse_chunk<R: std::io::Read>(
    r: &mut R,
    verify_checksums: bool,
) -> Result<ParsedChunk> {
    let size = match r.read_u32_be() {
        Ok(s) => s as usize,
        Err(ZiPatchError::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
            return Err(ZiPatchError::TruncatedPatch);
        }
        Err(e) => return Err(e),
    };
    if size > MAX_CHUNK_SIZE {
        return Err(ZiPatchError::OversizedChunk(size));
    }
    // buf layout: [tag: 4] [body: size] [crc32: 4]
    let buf = r.read_exact_vec(size + 8)?;

    let tag: [u8; 4] = buf[..4].try_into().unwrap();

    let actual_crc = crc32fast::hash(&buf[..size + 4]);
    let expected_crc = u32::from_be_bytes(buf[size + 4..].try_into().unwrap());
    if verify_checksums && actual_crc != expected_crc {
        return Err(ZiPatchError::ChecksumMismatch {
            tag,
            expected: expected_crc,
            actual: actual_crc,
        });
    }

    let body = &buf[4..size + 4];

    trace!(tag = %String::from_utf8_lossy(&tag), "chunk");

    // 4 (body_len) + 4 (tag) + size (body) + 4 (crc32)
    let consumed = (size as u64) + 12;

    let chunk = match &tag {
        b"EOF_" => Chunk::EndOfFile,
        b"FHDR" => Chunk::FileHeader(fhdr::parse(body)?),
        b"APLY" => Chunk::ApplyOption(aply::parse(body)?),
        b"APFS" => Chunk::ApplyFreeSpace(afsp::parse(body)?),
        b"ADIR" => Chunk::AddDirectory(adir::parse(body)?),
        b"DELD" => Chunk::DeleteDirectory(ddir::parse(body)?),
        b"SQPK" => Chunk::Sqpk(sqpk::parse_sqpk(body)?),
        _ => return Err(ZiPatchError::UnknownChunkTag(tag)),
    };

    Ok(ParsedChunk {
        chunk,
        tag,
        consumed,
    })
}

/// Iterator over the [`Chunk`]s in a `ZiPatch` stream.
///
/// `ZiPatchReader` wraps any [`std::io::Read`] source and yields one
/// [`Chunk`] per call to [`Iterator::next`]. It validates the 12-byte file
/// magic on construction, then reads chunks sequentially until the `EOF_`
/// terminator is encountered or an error occurs.
///
/// # Stream contract
///
/// - **Magic** — the first 12 bytes must be `\x91ZIPATCH\r\n\x1a\n`. Any
///   mismatch returns [`ZiPatchError::InvalidMagic`] from [`ZiPatchReader::new`].
/// - **Framing** — every chunk is a length-prefixed frame:
///   `[body_len: u32 BE] [tag: 4 B] [body: body_len B] [crc32: u32 BE]`.
/// - **CRC32** — computed over `tag ++ body`. Verification is enabled by
///   default; use [`ZiPatchReader::skip_checksum_verification`] to disable it.
/// - **Termination** — the `EOF_` chunk is consumed internally and causes
///   the iterator to return `None`. Call [`ZiPatchReader::is_complete`] after
///   iteration to distinguish a clean end from a truncated stream.
/// - **Fused** — once `None` is returned (either from `EOF_` or an error),
///   subsequent calls to `next` also return `None`. The iterator implements
///   [`std::iter::FusedIterator`].
///
/// # Errors
///
/// Each call to [`Iterator::next`] returns `Some(Err(e))` on parse failure,
/// then `None` on all future calls. Possible errors include:
/// - [`ZiPatchError::TruncatedPatch`] — stream ended before `EOF_`.
/// - [`ZiPatchError::OversizedChunk`] — a declared chunk body exceeds 512 MiB.
/// - [`ZiPatchError::ChecksumMismatch`] — CRC32 verification failed.
/// - [`ZiPatchError::UnknownChunkTag`] — unrecognised 4-byte tag.
/// - [`ZiPatchError::Io`] — underlying I/O failure.
///
/// # Example
///
/// Build a minimal in-memory patch (magic + `ADIR` + `EOF_`) and iterate it:
///
/// ```rust
/// use std::io::Cursor;
/// use zipatch_rs::{Chunk, ZiPatchReader};
///
/// // Helper: wrap tag + body into a correctly framed chunk with CRC32.
/// fn make_chunk(tag: &[u8; 4], body: &[u8]) -> Vec<u8> {
///     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());
///     out.extend_from_slice(tag);
///     out.extend_from_slice(body);
///     out.extend_from_slice(&crc.to_be_bytes());
///     out
/// }
///
/// // 12-byte ZiPatch magic.
/// let magic: [u8; 12] = [0x91, 0x5A, 0x49, 0x50, 0x41, 0x54, 0x43, 0x48, 0x0D, 0x0A, 0x1A, 0x0A];
///
/// // ADIR body: u32 BE name_len (7) + b"created".
/// let mut adir_body = Vec::new();
/// adir_body.extend_from_slice(&7u32.to_be_bytes());
/// adir_body.extend_from_slice(b"created");
///
/// 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_", &[]));
///
/// let chunks: Vec<_> = ZiPatchReader::new(Cursor::new(patch))
///     .unwrap()
///     .collect::<Result<_, _>>()
///     .unwrap();
///
/// assert_eq!(chunks.len(), 1);
/// assert!(matches!(chunks[0], Chunk::AddDirectory(_)));
/// ```
#[derive(Debug)]
pub struct ZiPatchReader<R> {
    inner: R,
    done: bool,
    verify_checksums: bool,
    eof_seen: bool,
    // Running total of bytes consumed from `inner`, including the 12-byte
    // magic header. Updated after each successful `parse_chunk` call.
    // Exposed via `bytes_read()` so the apply driver can fire monotonic
    // progress events without instrumenting the underlying `Read` source.
    bytes_read: u64,
    // 4-byte ASCII tag of the most recently yielded chunk. `None` before the
    // first successful `next()` and after iteration completes. Used by
    // `apply_to` to attach the tag to per-chunk progress events without
    // re-matching on the `Chunk` enum.
    last_tag: Option<[u8; 4]>,
}

impl<R: std::io::Read> ZiPatchReader<R> {
    /// Wrap `reader` and validate the leading 12-byte `ZiPatch` magic.
    ///
    /// Consumes exactly 12 bytes from `reader`. The magic is the byte sequence
    /// `0x91 0x5A 0x49 0x50 0x41 0x54 0x43 0x48 0x0D 0x0A 0x1A 0x0A`
    /// (i.e. `\x91ZIPATCH\r\n\x1a\n`).
    ///
    /// CRC32 verification is **enabled** by default. Call
    /// [`ZiPatchReader::skip_checksum_verification`] before iterating to
    /// disable it.
    ///
    /// # Errors
    ///
    /// - [`ZiPatchError::InvalidMagic`] — the first 12 bytes do not match the
    ///   expected magic.
    /// - [`ZiPatchError::Io`] — an I/O error occurred while reading the magic.
    pub fn new(mut reader: R) -> Result<Self> {
        let magic = reader.read_exact_vec(12)?;
        if magic.as_slice() != MAGIC {
            return Err(ZiPatchError::InvalidMagic);
        }
        Ok(Self {
            inner: reader,
            done: false,
            verify_checksums: true,
            eof_seen: false,
            // The 12-byte magic header has already been consumed.
            bytes_read: 12,
            last_tag: None,
        })
    }

    /// Enable per-chunk CRC32 verification (the default).
    ///
    /// This is the default state after [`ZiPatchReader::new`]. Calling this
    /// method after construction is only necessary if
    /// [`ZiPatchReader::skip_checksum_verification`] was previously called.
    #[must_use]
    pub fn verify_checksums(mut self) -> Self {
        self.verify_checksums = true;
        self
    }

    /// Disable per-chunk CRC32 verification.
    ///
    /// Useful when the source has already been verified out-of-band (e.g. a
    /// download hash was checked before the file was opened), or when
    /// processing known-good test data where the overhead is unnecessary.
    #[must_use]
    pub fn skip_checksum_verification(mut self) -> Self {
        self.verify_checksums = false;
        self
    }

    /// Returns `true` if iteration reached the `EOF_` terminator cleanly.
    ///
    /// A `false` return after `next()` yields `None` indicates the stream was
    /// truncated — the download or file copy was incomplete. In that case the
    /// iterator stopped because of a [`ZiPatchError::TruncatedPatch`] error,
    /// not because the patch finished normally.
    pub fn is_complete(&self) -> bool {
        self.eof_seen
    }

    /// Returns the running total of bytes consumed from the patch stream.
    ///
    /// Starts at `12` after [`ZiPatchReader::new`] (the magic header has been
    /// read) and increases monotonically by the size of each chunk's wire
    /// frame after each successful [`Iterator::next`] call. Includes the
    /// `EOF_` terminator's frame.
    ///
    /// On parse error, the counter is **not** advanced past the failing
    /// chunk — it reflects the byte offset at the start of that chunk's
    /// length prefix, not the broken position somewhere inside its frame.
    /// Use this offset together with the surfaced error to point a user at
    /// where the patch became unreadable.
    ///
    /// This is the same counter that the
    /// [`apply_to`](crate::ZiPatchReader::apply_to) driver attaches to
    /// [`ChunkEvent::bytes_read`](crate::ChunkEvent::bytes_read) when firing
    /// progress events. Useful for the `bytes_applied / total_patch_size`
    /// ratio in a progress bar.
    #[must_use]
    pub fn bytes_read(&self) -> u64 {
        self.bytes_read
    }

    /// Returns the 4-byte ASCII tag of the most recently yielded chunk.
    ///
    /// `None` before the first successful [`Iterator::next`] call and after
    /// the `EOF_` terminator has been consumed (or an error has been
    /// surfaced). Used by [`apply_to`](crate::ZiPatchReader::apply_to) to
    /// populate [`ChunkEvent::kind`](crate::ChunkEvent::kind).
    #[must_use]
    pub fn last_tag(&self) -> Option<[u8; 4]> {
        self.last_tag
    }
}

impl ZiPatchReader<std::io::BufReader<std::fs::File>> {
    /// Open the file at `path`, wrap it in a [`std::io::BufReader`], and
    /// validate the `ZiPatch` magic.
    ///
    /// This is a convenience constructor equivalent to:
    ///
    /// ```rust,no_run
    /// # use std::io::BufReader;
    /// # use std::fs::File;
    /// # use zipatch_rs::ZiPatchReader;
    /// let reader = ZiPatchReader::new(BufReader::new(File::open("patch.patch").unwrap())).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// - [`ZiPatchError::Io`] — the file could not be opened.
    /// - [`ZiPatchError::InvalidMagic`] — the file does not start with the
    ///   `ZiPatch` magic bytes.
    pub fn from_path(path: impl AsRef<std::path::Path>) -> crate::Result<Self> {
        let file = std::fs::File::open(path)?;
        Self::new(std::io::BufReader::new(file))
    }
}

impl<R: std::io::Read> Iterator for ZiPatchReader<R> {
    type Item = Result<Chunk>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        match parse_chunk(&mut self.inner, self.verify_checksums) {
            Ok(ParsedChunk {
                chunk: Chunk::EndOfFile,
                tag,
                consumed,
            }) => {
                self.bytes_read += consumed;
                self.last_tag = Some(tag);
                self.done = true;
                self.eof_seen = true;
                None
            }
            Ok(ParsedChunk {
                chunk,
                tag,
                consumed,
            }) => {
                self.bytes_read += consumed;
                self.last_tag = Some(tag);
                Some(Ok(chunk))
            }
            Err(e) => {
                self.done = true;
                Some(Err(e))
            }
        }
    }
}

impl<R: std::io::Read> std::iter::FusedIterator for ZiPatchReader<R> {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::make_chunk;
    use std::io::Cursor;

    // --- parse_chunk error paths ---

    #[test]
    fn truncated_at_chunk_boundary_yields_truncated_patch() {
        // Magic + no chunks: parse_chunk must see EOF on the body_len read and
        // convert it to TruncatedPatch.  This exercises the
        // `Err(ZiPatchError::Io(e)) if e.kind() == UnexpectedEof` arm at
        // chunk/mod.rs line 121.
        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        let mut reader = ZiPatchReader::new(Cursor::new(patch)).unwrap();
        match reader
            .next()
            .expect("iterator must yield an error, not None")
        {
            Err(ZiPatchError::TruncatedPatch) => {}
            other => panic!("expected TruncatedPatch, got {other:?}"),
        }
        assert!(!reader.is_complete(), "stream is not clean-ended");
    }

    #[test]
    fn non_eof_io_error_on_body_len_read_propagates_as_io() {
        // Exercises the `Err(e) => return Err(e)` arm at line 124: an I/O
        // error that is NOT UnexpectedEof must propagate verbatim.
        // We trigger this by passing a reader that errors immediately.
        struct BrokenReader;
        impl std::io::Read for BrokenReader {
            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
                Err(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "simulated broken pipe",
                ))
            }
        }
        let result = parse_chunk(&mut BrokenReader, false);
        match result {
            Err(ZiPatchError::Io(e)) => {
                assert_eq!(
                    e.kind(),
                    std::io::ErrorKind::BrokenPipe,
                    "non-EOF I/O error must propagate unchanged, got kind {:?}",
                    e.kind()
                );
            }
            Err(other) => panic!("expected ZiPatchError::Io(BrokenPipe), got {other:?}"),
            Ok(_) => panic!("expected an error, got Ok"),
        }
    }

    #[test]
    fn truncated_after_one_chunk_yields_truncated_patch() {
        // Magic + one well-formed ADIR + no more bytes: the second call to
        // next() must surface TruncatedPatch, not None.
        let mut adir_body = Vec::new();
        adir_body.extend_from_slice(&4u32.to_be_bytes());
        adir_body.extend_from_slice(b"test");
        let chunk = make_chunk(b"ADIR", &adir_body);

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&chunk);

        let mut reader = ZiPatchReader::new(Cursor::new(patch)).unwrap();
        let first = reader.next().expect("first chunk must be present");
        assert!(
            first.is_ok(),
            "first ADIR chunk should parse cleanly: {first:?}"
        );
        match reader.next().expect("second call must yield an error") {
            Err(ZiPatchError::TruncatedPatch) => {}
            other => panic!("expected TruncatedPatch on truncated stream, got {other:?}"),
        }
        assert!(
            !reader.is_complete(),
            "is_complete must be false after truncation"
        );
    }

    #[test]
    fn checksum_mismatch_returns_checksum_mismatch_error() {
        // Corrupt the CRC32 field of an otherwise valid ADIR chunk and verify
        // that parse_chunk returns ChecksumMismatch (not a panic or a wrong error).
        let mut adir_body = Vec::new();
        adir_body.extend_from_slice(&4u32.to_be_bytes());
        adir_body.extend_from_slice(b"test");
        let mut chunk = make_chunk(b"ADIR", &adir_body);
        // Flip the last byte of the CRC32 field.
        let last = chunk.len() - 1;
        chunk[last] ^= 0xFF;

        let mut cur = Cursor::new(chunk);
        let result = parse_chunk(&mut cur, true);
        assert!(
            matches!(result, Err(ZiPatchError::ChecksumMismatch { .. })),
            "corrupted CRC must yield ChecksumMismatch"
        );
    }

    #[test]
    fn unknown_chunk_tag_returns_unknown_chunk_tag_error() {
        // A tag of all-Z bytes is not recognised; parse_chunk must return
        // UnknownChunkTag carrying the raw 4-byte tag.
        let chunk = make_chunk(b"ZZZZ", &[]);
        let mut cur = Cursor::new(chunk);
        match parse_chunk(&mut cur, false) {
            Err(ZiPatchError::UnknownChunkTag(tag)) => {
                assert_eq!(tag, *b"ZZZZ", "tag bytes must be preserved in error");
            }
            Err(other) => panic!("expected UnknownChunkTag, got {other:?}"),
            Ok(_) => panic!("expected UnknownChunkTag, got Ok"),
        }
    }

    #[test]
    fn oversized_chunk_body_len_returns_oversized_chunk_error() {
        // body_len == u32::MAX (> 512 MiB) must be rejected before any allocation.
        let bytes = [0xFFu8, 0xFF, 0xFF, 0xFF];
        let mut cur = Cursor::new(&bytes[..]);
        let Err(ZiPatchError::OversizedChunk(size)) = parse_chunk(&mut cur, false) else {
            panic!("expected OversizedChunk for u32::MAX body_len")
        };
        assert!(
            size > MAX_CHUNK_SIZE,
            "reported size {size} must exceed MAX_CHUNK_SIZE {MAX_CHUNK_SIZE}"
        );
    }

    // --- ZiPatchReader byte-counter and tag accessors ---

    #[test]
    fn bytes_read_starts_at_12_before_first_chunk() {
        // The magic header is 12 bytes; bytes_read must reflect that immediately
        // after construction, before any chunk is read.
        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));
        let reader = ZiPatchReader::new(Cursor::new(patch)).unwrap();
        assert_eq!(
            reader.bytes_read(),
            12,
            "bytes_read must be 12 (magic only) before iteration starts"
        );
    }

    #[test]
    fn last_tag_is_none_before_first_chunk() {
        // Before calling next(), last_tag must be None.
        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));
        let reader = ZiPatchReader::new(Cursor::new(patch)).unwrap();
        assert_eq!(
            reader.last_tag(),
            None,
            "last_tag must be None before any chunk is read"
        );
    }

    #[test]
    fn bytes_read_and_last_tag_track_each_chunk_frame() {
        // MAGIC + ADIR("a") + EOF_ — verify bytes_read grows by the exact frame
        // size after each chunk and that last_tag follows the stream.
        let mut adir_body = Vec::new();
        adir_body.extend_from_slice(&1u32.to_be_bytes());
        adir_body.extend_from_slice(b"a");
        // ADIR frame: 4(size) + 4(tag) + 5(body) + 4(crc) = 17 bytes
        // EOF_  frame: 4 + 4 + 0 + 4 = 12 bytes

        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_", &[]));

        let mut reader = ZiPatchReader::new(Cursor::new(patch)).unwrap();
        assert_eq!(reader.bytes_read(), 12, "pre-read: magic only");
        assert_eq!(reader.last_tag(), None, "pre-read: no tag yet");

        let chunk = reader.next().unwrap().unwrap();
        assert!(
            matches!(chunk, Chunk::AddDirectory(_)),
            "first chunk must be ADIR"
        );
        assert_eq!(
            reader.bytes_read(),
            12 + 17,
            "after ADIR: magic + ADIR frame"
        );
        assert_eq!(
            reader.last_tag(),
            Some(*b"ADIR"),
            "last_tag must be ADIR after first next()"
        );

        assert!(reader.next().is_none(), "EOF_ must terminate iteration");
        assert_eq!(
            reader.bytes_read(),
            12 + 17 + 12,
            "after EOF_: magic + ADIR + EOF_ frames"
        );
        assert_eq!(
            reader.last_tag(),
            Some(*b"EOF_"),
            "last_tag must be EOF_ after stream ends"
        );
        assert!(reader.is_complete(), "is_complete must be true after EOF_");
    }

    #[test]
    fn bytes_read_is_monotonically_non_decreasing() {
        // Stream with two ADIR chunks + EOF_ — verify bytes_read only ever
        // increases between calls to next() and that consuming the EOF_
        // chunk (whose body is empty but whose frame is 12 bytes) still
        // advances the counter past the last non-EOF position.
        let make_adir = |name: &[u8]| -> Vec<u8> {
            let mut body = Vec::new();
            body.extend_from_slice(&(name.len() as u32).to_be_bytes());
            body.extend_from_slice(name);
            make_chunk(b"ADIR", &body)
        };

        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_adir(b"a"));
        patch.extend_from_slice(&make_adir(b"bb"));
        patch.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let mut reader = ZiPatchReader::new(Cursor::new(patch)).unwrap();
        let mut prev = reader.bytes_read();
        while let Some(result) = reader.next() {
            result.unwrap();
            let current = reader.bytes_read();
            assert!(
                current >= prev,
                "bytes_read must be monotonically non-decreasing: {prev} -> {current}"
            );
            // For ADIR chunks with non-empty bodies, the increment must be
            // strictly positive — a body of N bytes adds N + 12 frame bytes.
            assert!(
                current > prev,
                "non-empty ADIR frame must strictly advance bytes_read: \
                 {prev} -> {current}"
            );
            prev = current;
        }
        // EOF_ has been consumed: its 12-byte empty-body frame must have
        // pushed the counter past the previous position.
        assert!(
            reader.bytes_read() > prev,
            "consuming EOF_ must advance bytes_read by its 12-byte frame: \
             {prev} -> {}",
            reader.bytes_read()
        );
    }

    // --- from_path constructor ---

    #[test]
    fn from_path_opens_minimal_patch_and_reaches_eof() {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&MAGIC);
        bytes.extend_from_slice(&make_chunk(b"EOF_", &[]));

        let tmp = tempfile::tempdir().unwrap();
        let file_path = tmp.path().join("test.patch");
        std::fs::write(&file_path, &bytes).unwrap();

        let mut reader =
            ZiPatchReader::from_path(&file_path).expect("from_path must open valid patch");
        assert!(
            reader.next().is_none(),
            "EOF_ must terminate iteration immediately"
        );
        assert!(reader.is_complete(), "is_complete must be true after EOF_");
    }

    #[test]
    fn from_path_returns_io_error_when_file_is_missing() {
        let tmp = tempfile::tempdir().unwrap();
        let file_path = tmp.path().join("nonexistent.patch");
        assert!(
            matches!(
                ZiPatchReader::from_path(&file_path),
                Err(ZiPatchError::Io(_))
            ),
            "from_path on a missing file must return ZiPatchError::Io"
        );
    }

    // --- Iterator fused-ness and is_complete ---

    #[test]
    fn iterator_is_fused_after_error() {
        // Once next() yields Some(Err(_)), all subsequent calls must yield None.
        let mut patch = Vec::new();
        patch.extend_from_slice(&MAGIC);
        patch.extend_from_slice(&make_chunk(b"ZZZZ", &[])); // unknown tag → error

        let mut reader = ZiPatchReader::new(Cursor::new(patch)).unwrap();
        let first = reader.next();
        assert!(
            matches!(first, Some(Err(ZiPatchError::UnknownChunkTag(_)))),
            "first call must yield the error: {first:?}"
        );
        // All subsequent calls must return None.
        assert!(
            reader.next().is_none(),
            "fused: must return None after error"
        );
        assert!(reader.next().is_none(), "fused: still None on third call");
    }

    #[test]
    fn is_complete_false_until_eof_seen() {
        let mut adir_body = Vec::new();
        adir_body.extend_from_slice(&1u32.to_be_bytes());
        adir_body.extend_from_slice(b"x");

        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_", &[]));

        let mut reader = ZiPatchReader::new(Cursor::new(patch)).unwrap();
        assert!(
            !reader.is_complete(),
            "not complete before reading anything"
        );
        reader.next().unwrap().unwrap(); // consume ADIR
        assert!(
            !reader.is_complete(),
            "not complete after ADIR, before EOF_"
        );
        assert!(reader.next().is_none(), "EOF_ consumed");
        assert!(reader.is_complete(), "complete after EOF_ consumed");
    }
}