primase-foundations 0.3.6

Checked byte readers, game-file hashes, vertex decoding, texture sampling and the compression codecs (LZ4, deflate, zstd, LZMA, Brotli, LZO2A, Oodle) game files use
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
//! The compression codecs games store their data in, behind two traits: [`Decompressor`] and [`Compressor`].
//!
//! | codec | type | decode | encode |
//! | --- | --- | --- | --- |
//! | LZ4 raw block | [`Lz4`] | yes | yes |
//! | raw deflate (RFC 1951) | [`Deflate`] | yes | yes |
//! | zlib (RFC 1950) | [`Zlib`] | yes | yes |
//! | zlib with a missing end marker or checksum | [`ZlibUnterminated`] | yes | no |
//! | zlib or raw deflate, fed piece by piece | [`Inflater`] | yes | no |
//! | Zstandard frame (RFC 8878) | [`Zstd`] | yes | no |
//! | LZMA (the property bytes and the raw stream) | [`Lzma`] | yes | no |
//! | Brotli stream (RFC 7932) | [`Brotli`] | yes | no |
//! | LZO1X (miniLZO's format) | [`Lzo1x`] | yes | no |
//! | LZO2A | [`Lzo2a`] | yes | no |
//! | LZX (XNA's content), frame by frame | [`LzxDecoder`] | yes | no |
//! | Oodle (Kraken, Mermaid, Selkie, Leviathan) | [`oodle::Oodle`] | yes | Kraken, with the game's library only |
//!
//! The adapters are strict. A decode takes the exact output size the container states and refuses a stream that
//! produces more or fewer bytes, has input left over, ends early, or (where the format carries one) fails its
//! checksum; the error names the codec and the input offset. There is no format autodetection: the caller says which
//! codec a stream is. A size claimed by a container is untrusted, so what a decode allocates for it is bounded by the
//! input: LZ4, deflate, zlib, LZO1X and LZO2A refuse, before allocating anything, a claim above their format's ratio
//! ([`LZ4_MAX_RATIO`], [`DEFLATE_MAX_RATIO`], [`LZO1X_MAX_RATIO`], [`LZO2A_MAX_RATIO`]) times the input's length, and
//! zstd, LZMA and Brotli grow their output as the stream produces it. Oodle's ratio is not bounded here: its decode
//! allocates the claimed size up front (fallibly, as [`Error::Limit`]), so bound the size before asking. The tighter
//! bound a container knows is the caller's to apply.
//!
//! [`Inflater`] is the exception to whole-payload decoding: a container whose reader interleaves decompression with
//! other work, feeding input in the pieces the game reads it in, decodes through it one call at a time and checks
//! the stream's size and end itself.
//!
//! # Oodle
//!
//! Oodle is a commercial codec and its library is not part of this crate. [`oodle::Oodle::load`] loads the game's own
//! copy of the library from a path the caller gives (an `unsafe` call, because loading a native library runs its
//! initialization). Off Windows, [`oodle::Oodle::open`] with no path decodes with the pure-Rust oozextract crate
//! instead, which cannot compress. On Windows there is no built-in decoder, so a path is required.
//!
//! The library and oozextract decode a stream without saying whether bytes were left after its last block, so
//! [`oodle::Oodle`]'s decode does not check that. [`oodle_framing::walk`] does, by reading the stream's block and
//! quantum headers without decoding it: a container that knows its payload's exact extent calls it first.
#![deny(clippy::disallowed_methods, clippy::disallowed_types)]

use std::io::Write;

mod lzo1x;
mod lzo2a;
mod lzx;
pub use lzo1x::Lzo1x;
pub use lzo2a::Lzo2a;
pub use lzx::{LZX_FRAME, LzxDecoder};
#[allow(unsafe_code)]
pub mod oodle;
pub mod oodle_framing;
#[cfg(any(feature = "reference-decoder", not(windows)))]
pub mod reference;

/// Why a stream was refused or a codec could not be used.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The stream is malformed or not what the adapter accepts.
    #[error("{codec} at input offset {offset}: {detail}")]
    Invalid {
        /// The codec that refused it.
        codec: &'static str,
        /// Where in the input the problem was found.
        offset: usize,
        /// What was wrong.
        detail: String,
    },
    /// The stream decoded to a different number of bytes than expected (`actual` is the amount reached when the
    /// decoder stopped, which for an overrun can be just past `expected`).
    #[error("output size {actual}, expected {expected}")]
    Size {
        /// The size the caller stated.
        expected: usize,
        /// The size the stream produced.
        actual: usize,
    },
    /// The output buffer could not be allocated, or a size does not fit the platform's integers.
    #[error("allocation/size limit exceeded")]
    Limit,
    /// An I/O error from an encoder, or from resolving a library path.
    #[error("I/O: {0}")]
    Io(#[from] std::io::Error),
    /// The Oodle library could not be loaded or lacks an export.
    #[error("Oodle library: {0}")]
    Library(#[from] libloading::Error),
}
/// A result with this module's [`Error`].
pub type Result<T> = std::result::Result<T, Error>;
pub(crate) fn invalid(codec: &'static str, offset: usize, detail: impl ToString) -> Error {
    Error::Invalid {
        codec,
        offset,
        detail: detail.to_string(),
    }
}
/// Refuses, before anything is allocated for it, a claimed output of `expected` bytes from `input_len` bytes of a format
/// that cannot expand more than `max_ratio` to 1.
pub(crate) fn check_claim(
    codec: &'static str,
    input_len: usize,
    expected: usize,
    max_ratio: usize,
) -> Result<()> {
    let most = input_len.saturating_mul(max_ratio);
    if expected > most {
        return Err(invalid(
            codec,
            0,
            format!(
                "the container claims {expected} output bytes, but {input_len} input bytes make at most {most} ({max_ratio}:1)"
            ),
        ));
    }
    Ok(())
}
/// How many input bytes the decompressor has consumed (a count past `usize` is beyond any input).
fn total_in(d: &zlib_rs::Inflate) -> usize {
    usize::try_from(d.total_in()).unwrap_or(usize::MAX)
}
/// What the inflater says of a stream it refused, in the words this module has always used for it.
fn inflate_error(e: zlib_rs::InflateError) -> &'static str {
    match e {
        zlib_rs::InflateError::NeedDict { .. } => "requires a dictionary",
        zlib_rs::InflateError::StreamError
        | zlib_rs::InflateError::DataError
        | zlib_rs::InflateError::MemError => "deflate decompression error",
    }
}
/// The window an inflater is made with: the largest deflate has, which every stream fits.
const WINDOW_BITS: u8 = 15;
/// What a raw DEFLATE stream's window holds before its first byte: zeros. Some streams copy from before their start
/// (GTA V Enhanced stores one: `x64a.rpf\textures\parachute_decals.ytd`, whose matches reach back past byte 0), which
/// a strict inflater refuses as "invalid distance too far back"; read against a zero-filled window that stream decodes
/// to exactly what flate2's miniz_oxide made of it, and to what zlib 1.3.1 makes of it with this window as its
/// dictionary. A stream that copies only from its own output decodes the same with or without the window.
static ZERO_WINDOW: [u8; 1 << WINDOW_BITS] = [0; 1 << WINDOW_BITS];
/// An inflater for a raw DEFLATE stream (`zlib` false: its window starts as [`ZERO_WINDOW`]) or a zlib one (`zlib`
/// true: a zlib stream names any dictionary it needs in its header, so its window starts empty, as RFC 1950 has it).
fn inflater(zlib: bool) -> Result<zlib_rs::Inflate> {
    let mut d = zlib_rs::Inflate::new(zlib, WINDOW_BITS);
    if !zlib {
        d.set_dictionary(&ZERO_WINDOW)
            .map_err(|e| invalid("deflate", 0, inflate_error(e)))?;
    }
    Ok(d)
}
/// The input offset a decoder reached when `left` bytes remained.
fn consumed(input: &[u8], left: usize) -> usize {
    input.len().saturating_sub(left)
}
pub(crate) fn buffer(size: usize) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    out.try_reserve_exact(size).map_err(|_| Error::Limit)?;
    out.resize(size, 0);
    Ok(out)
}
pub(crate) fn check_size(actual: usize, expected: usize) -> Result<()> {
    if actual == expected {
        Ok(())
    } else {
        Err(Error::Size { expected, actual })
    }
}
/// Decodes one exactly framed payload to an output size the caller states.
/// Implementations reject output overrun; the caller must bound untrusted sizes.
pub trait Decompressor {
    /// The `expected` bytes `input` decodes to; any other outcome is an error.
    fn decompress(&self, input: &[u8], expected: usize) -> Result<Vec<u8>>;
}
/// Encodes one payload; framing belongs to the selected codec.
pub trait Compressor {
    /// `input` compressed.
    fn compress(&self, input: &[u8]) -> Result<Vec<u8>>;
}

/// The most bytes an LZ4 block can produce for one byte of input (a match length is extended by bytes of 255, each
/// adding 255 to it), rounded up: a claimed output size above this times the input is false.
pub const LZ4_MAX_RATIO: usize = 255;

/// Raw LZ4 block, no size prefix and no frame. All input bytes belong to the block; a final literal sequence terminates
/// it. The output size comes from the enclosing archive.
#[derive(Debug, Clone, Copy)]
pub struct Lz4;
impl Decompressor for Lz4 {
    fn decompress(&self, input: &[u8], expected: usize) -> Result<Vec<u8>> {
        if input.is_empty() {
            return Err(invalid("lz4", 0, "missing token: expected at least one byte"));
        }
        check_claim("lz4", input.len(), expected, LZ4_MAX_RATIO)?;
        let mut out = buffer(expected)?;
        let n = lz4_flex::block::decompress_into(input, &mut out).map_err(|e| invalid("lz4", 0, e))?;
        check_size(n, expected)?;
        Ok(out)
    }
}
impl Compressor for Lz4 {
    fn compress(&self, input: &[u8]) -> Result<Vec<u8>> {
        Ok(lz4_flex::block::compress(input))
    }
}

/// An LZMA stream as Unity's asset bundles and 7-Zip's archives store one: five property bytes (`lc`/`lp`/`pb` as one
/// byte, then the dictionary size, a u32) and the raw range-coded stream, without the `.lzma` file's 8-byte size; the
/// size comes from the container. The stream decodes to exactly the expected size and every input byte is consumed: a
/// stream that ends with the optional end-of-payload marker after the expected bytes is read to the marker's end, and
/// anything else after the payload is refused. The output grows with what the stream produces, never past the
/// expected size.
#[derive(Debug, Clone, Copy)]
pub struct Lzma;
impl Lzma {
    /// Decodes `input` with the unpacked size `size` (`None`: up to the end-of-payload marker) into at most `limit`
    /// bytes; returns the output and the input bytes the decoder took, or `None` for output past `limit`.
    fn run(input: &[u8], size: Option<usize>, limit: usize) -> Result<Option<(Vec<u8>, usize)>> {
        /// The output, refusing a write past the limit.
        struct Bounded {
            out: Vec<u8>,
            limit: usize,
            overflowed: bool,
        }
        impl Write for Bounded {
            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
                if buf.len() > self.limit.saturating_sub(self.out.len()) {
                    self.overflowed = true;
                    return Err(std::io::Error::other("past the expected size"));
                }
                self.out.try_reserve(buf.len()).map_err(std::io::Error::other)?;
                self.out.extend_from_slice(buf);
                Ok(buf.len())
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }
        let options = lzma_rs::decompress::Options {
            unpacked_size: lzma_rs::decompress::UnpackedSize::UseProvided(
                size.map(|s| u64::try_from(s).unwrap_or(u64::MAX)),
            ),
            memlimit: None,
            allow_incomplete: false,
        };
        let mut src = std::io::Cursor::new(input);
        let mut out = Bounded {
            out: Vec::new(),
            limit,
            overflowed: false,
        };
        match lzma_rs::lzma_decompress_with_options(&mut src, &mut out, &options) {
            Ok(()) => Ok(Some((
                out.out,
                usize::try_from(src.position()).unwrap_or(usize::MAX),
            ))),
            Err(_) if out.overflowed => Ok(None),
            Err(e) => Err(invalid("lzma", usize::try_from(src.position()).unwrap_or(0), e)),
        }
    }
}
impl Decompressor for Lzma {
    fn decompress(&self, input: &[u8], expected: usize) -> Result<Vec<u8>> {
        if input.len() < 5 {
            return Err(invalid("lzma", 0, "the five property bytes are missing"));
        }
        let Some((out, used)) = Lzma::run(input, Some(expected), expected)? else {
            return Err(Error::Size {
                expected,
                actual: expected.saturating_add(1),
            });
        };
        check_size(out.len(), expected)?;
        if used == input.len() {
            return Ok(out);
        }
        // bytes after the payload: only the end-of-payload marker may be there
        match Lzma::run(input, None, expected) {
            Ok(Some((marked, all))) if all == input.len() && marked.len() == expected => Ok(out),
            _ => Err(invalid(
                "lzma",
                used,
                format!(
                    "{} bytes after the payload that are no end-of-payload marker",
                    input.len().saturating_sub(used)
                ),
            )),
        }
    }
}

/// A Brotli stream (RFC 7932), as AssetRipper's type tree packages store theirs. The stream must end exactly at the
/// end of the input and produce exactly the expected size; the output grows as the stream produces it.
#[derive(Debug, Clone, Copy)]
pub struct Brotli;
impl Decompressor for Brotli {
    fn decompress(&self, input: &[u8], expected: usize) -> Result<Vec<u8>> {
        use brotli_decompressor::{BrotliDecompressStream, BrotliResult, BrotliState, StandardAlloc};
        let mut state = BrotliState::new(
            StandardAlloc::default(),
            StandardAlloc::default(),
            StandardAlloc::default(),
        );
        // one byte past `expected` is room enough to see an overrun
        let mut chunk = vec![0; expected.saturating_add(1).min(1 << 16)];
        let mut out = Vec::new();
        let (mut available_in, mut input_offset, mut total_out) = (input.len(), 0, 0);
        loop {
            let (mut available_out, mut output_offset) = (chunk.len(), 0);
            let result = BrotliDecompressStream(
                &mut available_in,
                &mut input_offset,
                input,
                &mut available_out,
                &mut output_offset,
                &mut chunk,
                &mut total_out,
                &mut state,
            );
            let made = chunk.get(..output_offset).unwrap_or_default();
            let total = out.len().checked_add(made.len()).ok_or(Error::Limit)?;
            if total > expected {
                return Err(Error::Size {
                    expected,
                    actual: total,
                });
            }
            out.try_reserve(made.len()).map_err(|_| Error::Limit)?;
            out.extend_from_slice(made);
            match result {
                BrotliResult::ResultSuccess => break,
                BrotliResult::NeedsMoreOutput => {}
                BrotliResult::NeedsMoreInput => {
                    return Err(invalid("brotli", input_offset, "the stream ends early"));
                }
                BrotliResult::ResultFailure => {
                    return Err(invalid("brotli", input_offset, "malformed stream"));
                }
            }
        }
        if input_offset != input.len() {
            return Err(invalid(
                "brotli",
                input_offset,
                format!(
                    "{} bytes after the stream",
                    input.len().saturating_sub(input_offset)
                ),
            ));
        }
        check_size(out.len(), expected)?;
        Ok(out)
    }
}

/// One zstd frame (RFC 8878), decoded exactly: no skippable frame, no dictionary, a stated content size (where the
/// frame states one) equal to the expected size, every input byte consumed, a stated content checksum verified, and
/// never more than the expected output (decoded a block at a time, refused as soon as it would exceed it).
#[derive(Debug, Clone, Copy)]
pub struct Zstd;
impl Decompressor for Zstd {
    fn decompress(&self, input: &[u8], expected: usize) -> Result<Vec<u8>> {
        use ruzstd::{BlockDecodingStrategy, FrameDecoder};
        use std::io::Read;
        let (frame, _) = ruzstd::frame::read_frame_header(input).map_err(|e| invalid("zstd", 0, e))?;
        if let Some(id) = frame.header.dictionary_id() {
            return Err(invalid("zstd", 0, format!("frame needs dictionary {id}")));
        }
        let descriptor = &frame.header.descriptor;
        let states_size = descriptor.single_segment_flag()
            || descriptor
                .frame_content_size_bytes()
                .map_err(|e| invalid("zstd", 0, e))?
                > 0;
        if states_size {
            let stated = usize::try_from(frame.header.frame_content_size()).map_err(|_| Error::Limit)?;
            check_size(stated, expected)?;
        }
        let mut d = FrameDecoder::new();
        let mut src = input;
        d.init(&mut src).map_err(|e| invalid("zstd", 0, e))?;
        // grown with what the stream produces, which the check below keeps within `expected`
        let mut out = Vec::new();
        loop {
            let before = src.len();
            d.decode_blocks(&mut src, BlockDecodingStrategy::UptoBlocks(1))
                .map_err(|e| invalid("zstd", consumed(input, before), e))?;
            let ready = d.can_collect();
            let total = out.len().checked_add(ready).ok_or(Error::Limit)?;
            if total > expected {
                return Err(Error::Size {
                    expected,
                    actual: total,
                });
            }
            let at = out.len();
            out.try_reserve(ready).map_err(|_| Error::Limit)?;
            out.resize(total, 0);
            let fresh = out.get_mut(at..).ok_or_else(|| {
                invalid(
                    "zstd",
                    consumed(input, src.len()),
                    "output shorter than collected",
                )
            })?;
            d.read_exact(fresh)?;
            if d.is_finished() && d.can_collect() == 0 {
                break;
            }
            if src.len() == before && ready == 0 {
                return Err(invalid(
                    "zstd",
                    consumed(input, src.len()),
                    "frame ends before its last block: expected another block",
                ));
            }
        }
        if !src.is_empty() {
            return Err(invalid(
                "zstd",
                consumed(input, src.len()),
                "trailing input after the frame: expected the frame to end here",
            ));
        }
        if let (Some(stored), Some(computed)) = (d.get_checksum_from_data(), d.get_calculated_checksum())
            && stored != computed
        {
            return Err(invalid(
                "zstd",
                input.len(),
                format!("content checksum {stored:08x}, computed {computed:08x}"),
            ));
        }
        check_size(out.len(), expected)?;
        Ok(out)
    }
}

/// RFC1951 raw DEFLATE. Requires the final block marker and exact input consumption.
#[derive(Debug, Clone, Copy)]
pub struct Deflate;
/// RFC1950 zlib: header, DEFLATE, Adler32 trailer. Requires StreamEnd and exact consumption.
#[derive(Debug, Clone, Copy)]
pub struct Zlib;
/// zlib as some archives' tables of contents store it: with a missing final block marker or Adler-32 checksum. Such a
/// stream is accepted only if all input is consumed, the decoder reports no error, and exactly the expected bytes are
/// produced. An incomplete stream cannot be checked against its Adler-32, so this is a size check, not an integrity
/// check. Complete streams are accepted too.
#[derive(Debug, Clone, Copy)]
pub struct ZlibUnterminated;
fn inflate(input: &[u8], expected: usize, zlib: bool, incomplete: bool) -> Result<Vec<u8>> {
    check_claim("deflate/zlib", input.len(), expected, DEFLATE_MAX_RATIO)?;
    let mut d = inflater(zlib)?;
    let mut out = buffer(expected.checked_add(1).ok_or(Error::Limit)?)?;
    let status = d
        .decompress(input, &mut out, zlib_rs::InflateFlush::NoFlush)
        .map_err(|e| invalid("deflate/zlib", total_in(&d), inflate_error(e)))?;
    check_size(usize::try_from(d.total_out()).unwrap_or(usize::MAX), expected)?;
    if total_in(&d) != input.len() {
        return Err(invalid(
            "deflate/zlib",
            total_in(&d),
            "trailing input: expected the stream to end here",
        ));
    }
    if status != zlib_rs::Status::StreamEnd && !incomplete {
        return Err(invalid("deflate/zlib", input.len(), "missing stream end"));
    }
    // Even incomplete empty zlib needs a valid two-byte header.
    if zlib && input.len() < 2 {
        return Err(invalid("zlib", input.len(), "short header"));
    }
    out.truncate(expected);
    Ok(out)
}
impl Decompressor for Deflate {
    fn decompress(&self, input: &[u8], expected: usize) -> Result<Vec<u8>> {
        inflate(input, expected, false, false)
    }
}
/// The most bytes a DEFLATE stream can produce for one byte of input (RFC 1951: a match of 258 bytes takes about two
/// bits), rounded up: a claimed output size above this times the input is false.
pub const DEFLATE_MAX_RATIO: usize = 1032;

/// The most bytes an LZO1X stream can produce for one byte of input, rounded up: its longest instructions (an M3 or M4
/// match, `33 + 255 z + n` or `9 + 255 z + n` bytes) take the instruction byte, `z` zero bytes, the byte `n` and two
/// distance bytes, so their output stays under 255 times their input; a literal run is one byte out per byte in, and an
/// M1 or M2 match at most 8 bytes for 2.
pub const LZO1X_MAX_RATIO: usize = 255;

/// The most bytes an LZO2A stream can produce for one byte of input, rounded up: a long match of length `9 + 255 z + n`
/// takes the two bytes of its distance, `z` zero bytes and the byte `n`, so its output stays under 255 times its input.
pub const LZO2A_MAX_RATIO: usize = 255;

impl Deflate {
    /// A complete raw DEFLATE stream whose output size is not stated, at most `max` bytes. The output grows with what
    /// the stream produces (at most [`DEFLATE_MAX_RATIO`] times its input), never with `max`, so a caller's bound
    /// taken from an untrusted header costs no memory by itself. Requires the final block marker and exact input
    /// consumption; more than `max` bytes of output is [`Error::Size`] (`actual` is then `max + 1`).
    pub fn decompress_up_to(&self, input: &[u8], max: usize) -> Result<Vec<u8>> {
        let mut d = inflater(false)?;
        let mut out: Vec<u8> = Vec::new();
        loop {
            if out.len() == out.capacity() {
                // double, but never past one byte more than `max`, which is what shows the stream overran it
                let want = out
                    .capacity()
                    .max(4096)
                    .saturating_mul(2)
                    .min(max.saturating_add(1));
                let more = want.saturating_sub(out.len());
                if more == 0 {
                    return Err(Error::Size {
                        expected: max,
                        actual: out.len(),
                    });
                }
                out.try_reserve_exact(more).map_err(|_| Error::Limit)?;
            }
            let taken = total_in(&d);
            let rest = input.get(taken..).unwrap_or_default();
            let before = (d.total_in(), d.total_out());
            // the inflater writes into initialised bytes: the room is zero-filled, and cut back to what it produced
            let at = out.len();
            out.resize(out.capacity(), 0);
            let result = match out.get_mut(at..) {
                Some(room) => d.decompress(rest, room, zlib_rs::InflateFlush::NoFlush),
                None => Ok(zlib_rs::Status::BufError),
            };
            let produced = usize::try_from(d.total_out().saturating_sub(before.1)).unwrap_or(usize::MAX);
            out.truncate(at.saturating_add(produced));
            let status = result.map_err(|e| invalid("deflate", taken, inflate_error(e)))?;
            if out.len() > max {
                return Err(Error::Size {
                    expected: max,
                    actual: out.len(),
                });
            }
            if status == zlib_rs::Status::StreamEnd {
                break;
            }
            if (d.total_in(), d.total_out()) == before && out.len() < out.capacity() {
                return Err(invalid("deflate", input.len(), "missing stream end"));
            }
        }
        if total_in(&d) != input.len() {
            return Err(invalid(
                "deflate",
                total_in(&d),
                "trailing input: expected the stream to end here",
            ));
        }
        Ok(out)
    }
}
impl Decompressor for Zlib {
    fn decompress(&self, input: &[u8], expected: usize) -> Result<Vec<u8>> {
        inflate(input, expected, true, false)
    }
}
impl Decompressor for ZlibUnterminated {
    fn decompress(&self, input: &[u8], expected: usize) -> Result<Vec<u8>> {
        inflate(input, expected, true, true)
    }
}
/// A zlib (RFC 1950) or raw DEFLATE stream decoded one call at a time, for a container that has to feed its input in
/// the pieces the game reads it in and learn when each is used up: [`Inflater::inflate`] behaves as zlib's `inflate`
/// with `Z_SYNC_FLUSH`, taking input only as the output it writes needs it.
pub struct Inflater {
    d: zlib_rs::Inflate,
    codec: &'static str,
    ended: bool,
}

/// What one [`Inflater::inflate`] call did.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Inflated {
    /// Input bytes it consumed, from the start of the slice it was given.
    pub consumed: usize,
    /// Output bytes it wrote, from the start of the slice it was given.
    pub produced: usize,
    /// The stream reached its end (for zlib, with its Adler-32 checked); nothing more is consumed or produced.
    pub ended: bool,
}

impl std::fmt::Debug for Inflater {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Inflater")
            .field("codec", &self.codec)
            .field("total_in", &self.d.total_in())
            .field("total_out", &self.d.total_out())
            .field("ended", &self.ended)
            .finish()
    }
}

impl Inflater {
    /// An inflater for a zlib stream.
    pub fn zlib() -> Result<Self> {
        Ok(Self {
            d: inflater(true)?,
            codec: "zlib",
            ended: false,
        })
    }
    /// An inflater for a raw DEFLATE stream (its window starts zero-filled, as [`Deflate`]'s does).
    pub fn deflate() -> Result<Self> {
        Ok(Self {
            d: inflater(false)?,
            codec: "deflate",
            ended: false,
        })
    }
    /// Decodes from `input` into `output` until the output is full, the input is used up, or the stream ends. A call
    /// that can make no progress (no input left, or no room) consumes and produces nothing. A malformed stream is an
    /// error naming the offset in the whole stream's input where it was found.
    pub fn inflate(&mut self, input: &[u8], output: &mut [u8]) -> Result<Inflated> {
        if self.ended {
            return Ok(Inflated {
                consumed: 0,
                produced: 0,
                ended: true,
            });
        }
        let (before_in, before_out) = (self.d.total_in(), self.d.total_out());
        let status = self
            .d
            .decompress(input, output, zlib_rs::InflateFlush::SyncFlush)
            .map_err(|e| invalid(self.codec, total_in(&self.d), inflate_error(e)))?;
        self.ended = status == zlib_rs::Status::StreamEnd;
        // each call moves the totals by at most its slices' lengths
        let moved =
            |after: u64, before: u64| usize::try_from(after.saturating_sub(before)).unwrap_or(usize::MAX);
        Ok(Inflated {
            consumed: moved(self.d.total_in(), before_in),
            produced: moved(self.d.total_out(), before_out),
            ended: self.ended,
        })
    }
    /// Input bytes consumed since the start of the stream.
    pub fn total_in(&self) -> usize {
        total_in(&self.d)
    }
    /// Output bytes written since the start of the stream.
    pub fn total_out(&self) -> usize {
        usize::try_from(self.d.total_out()).unwrap_or(usize::MAX)
    }
}
impl Compressor for Deflate {
    fn compress(&self, input: &[u8]) -> Result<Vec<u8>> {
        let mut e = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
        e.write_all(input)?;
        Ok(e.finish()?)
    }
}
impl Compressor for Zlib {
    fn compress(&self, input: &[u8]) -> Result<Vec<u8>> {
        let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
        e.write_all(input)?;
        Ok(e.finish()?)
    }
}