Skip to main content

wacore_binary/
zlib_pool.rs

1use std::cell::RefCell;
2use std::io;
3use std::sync::atomic::{AtomicUsize, Ordering};
4use zlib_rs::{Inflate, InflateError, InflateFlush, Status};
5
6/// zlib inflate wants a zlib header and the 32 KB LZ77 window.
7const ZLIB_HEADER: bool = true;
8const WINDOW_BITS: u8 = 15;
9
10thread_local! {
11    // Free-list of inflate state, shared by every inflate on this thread: the
12    // one-shot [`decompress_zlib_pooled`] and the streaming [`InflateReader`].
13    // zlib-rs allocates the state and its 32 KB window as one block of roughly
14    // 47.5 KB, so a thread that ran both paths used to retain two of them for
15    // the life of the process; one list means one.
16    //
17    // The output window is deliberately not part of the entry. It is the larger
18    // allocation of the two and costs one malloc to recreate, where zlib state
19    // costs an order of magnitude more, so retaining it bought little and left
20    // 64 KB alive per thread for the process's lifetime after a single sync.
21    static INFLATE_POOL: RefCell<Vec<Inflate>> = const { RefCell::new(Vec::new()) };
22}
23
24/// How many inflate states a thread parks between uses; see [`set_pool_retention`].
25static POOL_RETENTION: AtomicUsize = AtomicUsize::new(DEFAULT_POOL_RETENTION);
26
27/// One parked state per thread. Sequential inflates are the norm (a bootstrap
28/// history sync inflates its blobs one after another, a connection its
29/// compressed frames one at a time) and one parked entry is all that case ever
30/// checks out, so a deeper pool only retains another ~47.5 KB per slot, per
31/// thread that ever inflated anything, for the life of the process. Nested
32/// readers still work; they just build their state instead of finding it parked.
33const DEFAULT_POOL_RETENTION: usize = 1;
34
35/// Set how many inflate states each thread keeps parked between uses.
36///
37/// Every inflate on a thread first checks its pool and, finding it empty,
38/// builds a fresh state: one allocation of roughly 47.5 KB (zlib-rs allocates
39/// the state and its 32 KB window together). The default of one keeps that
40/// allocation resident on every thread that ever inflated anything, which is
41/// what a host with memory to spare wants. A client whose whole heap is a few
42/// hundred KB may prefer `0`: every inflate then pays the allocation and
43/// releases it, so the ~47.5 KB is only ever held while something is actually
44/// being inflated, at the cost of one large malloc per compressed frame.
45///
46/// Process-wide; takes effect on the next park. Lowering it does not evict
47/// states already parked, see [`drain_pool`].
48pub fn set_pool_retention(states_per_thread: usize) {
49    POOL_RETENTION.store(states_per_thread, Ordering::Relaxed);
50}
51
52/// Build this thread's inflate state ahead of its first compressed payload.
53///
54/// The state is one ~47.5 KB allocation, and a heap that fragments as a
55/// connection comes up may no longer have a hole that size by the time the
56/// first large compressed frame is already sitting in it. Calling this on the
57/// thread that will run the read loop, while the heap is still fresh, moves
58/// that allocation to a moment it is known to succeed; the pool then hands the
59/// same state to every inflate on this thread. A no-op when a state is already
60/// parked, or when [`set_pool_retention`] is zero, since nothing would keep it.
61pub fn warm_pool() {
62    if POOL_RETENTION.load(Ordering::Relaxed) == 0 {
63        return;
64    }
65    let parked = INFLATE_POOL.with(|p| !p.borrow().is_empty());
66    if !parked {
67        park(Inflate::new(ZLIB_HEADER, WINDOW_BITS));
68    }
69}
70
71/// Release the inflate states this thread has parked, returning their memory.
72///
73/// The pool refills on the next inflate; this only matters on a target that
74/// needs the ~47.5 KB back between connections.
75pub fn drain_pool() {
76    INFLATE_POOL.with(|p| p.borrow_mut().clear());
77}
78
79/// Number of inflate states this thread currently keeps parked.
80pub fn parked_states() -> usize {
81    INFLATE_POOL.with(|p| p.borrow().len())
82}
83
84/// A reset inflate state: the thread's parked one when there is one, built
85/// otherwise. `reset` on checkout makes any prior stream state (including an
86/// error the last user hit) moot.
87fn checkout() -> Inflate {
88    INFLATE_POOL.with(|p| p.borrow_mut().pop()).map_or_else(
89        || Inflate::new(ZLIB_HEADER, WINDOW_BITS),
90        |mut decomp| {
91            decomp.reset(ZLIB_HEADER);
92            decomp
93        },
94    )
95}
96
97/// Return a state to this thread's pool, or drop it once the pool is full.
98fn park(decomp: Inflate) {
99    INFLATE_POOL.with(|p| {
100        let mut pool = p.borrow_mut();
101        if pool.len() < POOL_RETENTION.load(Ordering::Relaxed) {
102            pool.push(decomp);
103        }
104    });
105}
106
107/// Inflate straight into the vector's spare capacity, then extend its length by
108/// the produced count. Unlike `flate2::Decompress::decompress_vec`, this never
109/// zero-initializes the spare region first: flate2's zlib-rs backend doesn't
110/// override `decompress_uninit`, so it memsets the whole output window before
111/// every call — pure waste, since inflate overwrites exactly those bytes.
112fn inflate_into_spare(
113    inflate: &mut Inflate,
114    input: &[u8],
115    out: &mut Vec<u8>,
116    flush: InflateFlush,
117) -> Result<Status, InflateError> {
118    let before = inflate.total_out();
119    let status = inflate.decompress_uninit(input, out.spare_capacity_mut(), flush)?;
120    let produced = (inflate.total_out() - before) as usize;
121    // SAFETY: `decompress_uninit` wrote exactly `produced` bytes (per total_out)
122    // into the spare capacity, so that prefix is now initialized and in-bounds.
123    unsafe { out.set_len(out.len() + produced) };
124    Ok(status)
125}
126
127/// Streaming zlib reader: decompresses `input` incrementally into a small
128/// accumulation buffer, so a caller can parse length-delimited records as they
129/// become available and discard consumed bytes — peak memory stays ~the largest
130/// single record being buffered, not the whole decompressed blob.
131///
132/// Usage: `ensure(n)` to make ≥ n bytes available, read from `available()`, then
133/// `consume(k)`. The buffer is compacted (consumed prefix dropped) as it grows.
134pub struct InflateReader<'a> {
135    input: &'a [u8],
136    in_pos: usize,
137    // `Option` so `Drop` can move the state back into the pool (Inflate has no
138    // cheap throwaway value to swap in). Always `Some` until dropped.
139    decomp: Option<Inflate>,
140    buf: Vec<u8>,
141    cursor: usize,
142    chunk: usize,
143    total_out: u64,
144    max: u64,
145    eof: bool,
146    stream_end: bool,
147}
148
149impl<'a> InflateReader<'a> {
150    /// Output decompress window per pump; also the compaction threshold. One
151    /// window is the steady state: the pump compacts a consumed prefix before
152    /// inflating, so the buffer only grows past the chunk when one individual
153    /// record genuinely exceeds it. Allocated per reader, never retained.
154    ///
155    /// 64 KB suits the multi-megabyte history-sync blobs this reader was built
156    /// for, where each pump's fixed cost is worth amortizing; a reader over a
157    /// protocol frame on a small heap picks its own with [`Self::with_chunk`].
158    pub const CHUNK: usize = 64 * 1024;
159
160    pub fn new(input: &'a [u8], max: u64) -> Self {
161        Self::with_chunk(input, max, Self::CHUNK)
162    }
163
164    /// A reader whose output window is `chunk` bytes instead of [`Self::CHUNK`].
165    ///
166    /// The window is the reader's one allocation of its own, so it is the
167    /// reader's whole footprint beyond the pooled zlib state: a 4 KB chunk
168    /// keeps a stream of small records inside 4 KB however long the stream
169    /// is. A record larger than the chunk still grows the window to fit it.
170    pub fn with_chunk(input: &'a [u8], max: u64, chunk: usize) -> Self {
171        let chunk = chunk.max(1);
172        Self {
173            input,
174            in_pos: 0,
175            decomp: Some(checkout()),
176            buf: Vec::with_capacity(chunk),
177            cursor: 0,
178            chunk,
179            total_out: 0,
180            max,
181            eof: false,
182            stream_end: false,
183        }
184    }
185
186    /// Unparsed decompressed bytes currently buffered.
187    #[inline]
188    pub fn available(&self) -> &[u8] {
189        &self.buf[self.cursor..]
190    }
191
192    /// Mark `n` already-read bytes as consumed.
193    #[inline]
194    pub fn consume(&mut self, n: usize) {
195        self.cursor = (self.cursor + n).min(self.buf.len());
196    }
197
198    /// Ensure at least `need` unparsed bytes are buffered, decompressing more as
199    /// required. Returns `Ok(false)` if the stream ends before reaching `need`.
200    pub fn ensure(&mut self, need: usize) -> io::Result<bool> {
201        while self.buf.len() - self.cursor < need {
202            if self.eof {
203                return Ok(false);
204            }
205            self.pump()?;
206        }
207        Ok(true)
208    }
209
210    /// True once the stream is fully decompressed and all bytes consumed.
211    pub fn is_done(&self) -> bool {
212        self.eof && self.cursor >= self.buf.len()
213    }
214
215    /// Total decompressed bytes produced so far. After the stream ends this is
216    /// the blob's exact inflated size.
217    pub fn total_out(&self) -> u64 {
218        self.total_out
219    }
220
221    /// Compressed input consumed so far plus the input's full length. The
222    /// ratio lets callers extrapolate totals (e.g. record counts) from a
223    /// prefix without a second pass over the blob.
224    #[inline]
225    pub fn compressed_progress(&self) -> (usize, usize) {
226        (self.in_pos, self.input.len())
227    }
228
229    /// Whether zlib reported a proper stream end (terminator + adler32
230    /// checksum). An EOF (`ensure` returning false) without this means the
231    /// input was truncated, not finished.
232    pub fn stream_ended(&self) -> bool {
233        self.stream_end
234    }
235
236    fn pump(&mut self) -> io::Result<()> {
237        // Reclaim the consumed prefix before inflating. Reserving a full output
238        // window on top of a small read-ahead suffix made ordinary framed
239        // streams jump from 64 to 128 KiB even though no record needed it.
240        // Compacting here keeps those streams in one window; a record larger
241        // than the window still grows normally below.
242        if self.cursor != 0 {
243            let remaining = self.buf.len() - self.cursor;
244            self.buf.copy_within(self.cursor.., 0);
245            self.buf.truncate(remaining);
246            self.cursor = 0;
247        }
248
249        // `decomp` is `Some` for the reader's whole lifetime (only `Drop` takes it),
250        // so this is unreachable in practice; surface it as an error rather than panic.
251        let decomp = self
252            .decomp
253            .as_mut()
254            .ok_or_else(|| io::Error::other("InflateReader used after pool return"))?;
255        // Inflate straight into the window's spare capacity: a stack chunk +
256        // extend_from_slice would copy every decompressed byte a second time
257        // (~10% of a history-sync extraction).
258        if self.buf.len() == self.buf.capacity() {
259            self.buf.reserve(self.chunk);
260        }
261        let prev_in = decomp.total_in();
262        let prev_out = decomp.total_out();
263        let status = inflate_into_spare(
264            decomp,
265            &self.input[self.in_pos..],
266            &mut self.buf,
267            InflateFlush::NoFlush,
268        )
269        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.as_str()))?;
270        let new_in = decomp.total_in();
271        let produced = (decomp.total_out() - prev_out) as usize;
272        self.in_pos += (new_in - prev_in) as usize;
273        self.total_out += produced as u64;
274        if self.total_out > self.max {
275            return Err(io::Error::new(
276                io::ErrorKind::InvalidData,
277                format!("decompressed payload exceeds {} bytes", self.max),
278            ));
279        }
280
281        match status {
282            Status::StreamEnd => {
283                self.eof = true;
284                self.stream_end = true;
285            }
286            // No output produced and not at stream end: distinguish a truncated
287            // tail (no input left → treat as end, with `stream_end` left false
288            // so callers can tell it apart from a real terminator) from a
289            // stalled/corrupt stream (input remains but the decompressor
290            // consumed none → error, instead of spinning forever since 64 KB of
291            // output is always available).
292            // Mirrors the no-progress guard in `decompress_zlib_pooled`.
293            _ if produced == 0 => {
294                if self.in_pos >= self.input.len() {
295                    self.eof = true;
296                } else if new_in == prev_in {
297                    return Err(io::Error::new(
298                        io::ErrorKind::InvalidData,
299                        "zlib stream stalled (no progress)",
300                    ));
301                }
302            }
303            _ => {}
304        }
305        Ok(())
306    }
307}
308
309impl InflateReader<'_> {
310    /// Inflate the rest of the stream into the window without consuming any of
311    /// it, then hand the window over: every decompressed byte from the first
312    /// one not yet consumed to the end of the stream, in one `Vec`.
313    ///
314    /// This is the one-shot [`decompress_zlib_pooled`] result reached from a
315    /// reader that has already looked at the head of the stream. The window is
316    /// grown by the expansion ratio observed so far rather than by doubling, as
317    /// the one-shot path does, so the prefix already inflated is what sizes the
318    /// rest. A stream that ends without its terminator is an error here, as it
319    /// is there: a caller draining to the end wants the whole payload or none.
320    pub fn read_to_end(mut self) -> io::Result<Vec<u8>> {
321        while !self.eof {
322            if self.buf.len() == self.buf.capacity() {
323                let cap = (self.max as usize).saturating_add(1);
324                if self.buf.len() >= cap {
325                    return Err(io::Error::new(
326                        io::ErrorKind::InvalidData,
327                        format!("decompressed payload exceeds {} bytes", self.max),
328                    ));
329                }
330                let decomp = self
331                    .decomp
332                    .as_ref()
333                    .ok_or_else(|| io::Error::other("InflateReader used after pool return"))?;
334                grow_by_observed_ratio(&mut self.buf, decomp, self.input.len(), cap);
335            }
336            self.pump()?;
337        }
338        if !self.stream_end {
339            return Err(io::Error::new(
340                io::ErrorKind::InvalidData,
341                "zlib stream truncated (no terminator)",
342            ));
343        }
344        let mut buf = std::mem::take(&mut self.buf);
345        if self.cursor != 0 {
346            buf.drain(..self.cursor);
347        }
348        Ok(buf)
349    }
350}
351
352impl Drop for InflateReader<'_> {
353    fn drop(&mut self) {
354        // Return the decompressor to the per-thread free-list for reuse; the
355        // window goes back to the allocator with the rest of the reader.
356        if let Some(decomp) = self.decomp.take() {
357            park(decomp);
358        }
359    }
360}
361
362/// Grow the output buffer by projecting the decompressed size from the
363/// expansion ratio observed so far, instead of blind capacity doubling. A
364/// high-ratio stream (the up-front `2x compressed` guess undershot) then
365/// converges in one or two reallocations sized near the real total, rather
366/// than a doubling chain whose copies and final overshoot dominate both the
367/// allocated-bytes count and the peak.
368fn grow_by_observed_ratio(
369    scratch: &mut Vec<u8>,
370    decompressor: &Inflate,
371    compressed_len: usize,
372    cap: usize,
373) {
374    let consumed = decompressor.total_in() as usize;
375    let produced = decompressor.total_out() as usize;
376    let remaining_in = compressed_len.saturating_sub(consumed) as u64;
377    let projected = if consumed > 0 && produced > 0 {
378        // 9/8 margin: early bytes compress worse than the warmed-up tail, so
379        // the observed ratio slightly underestimates the remainder.
380        ((produced as u64).saturating_mul(remaining_in) / consumed as u64).saturating_mul(9) / 8
381    } else {
382        0
383    };
384    // Floor at the doubling step: small payloads (protocol nodes) keep their
385    // old growth exactly; the projection only ever grows MORE, for the
386    // high-ratio multi-MB streams it exists for.
387    let min_grow = scratch.capacity().max(4096);
388    let want = (projected.min(usize::MAX as u64) as usize)
389        .max(min_grow)
390        .min(cap - scratch.len());
391    scratch.reserve(want);
392}
393
394/// Decompress zlib data using a pooled decompressor.
395///
396/// Reuses the per-thread `zlib_rs::Inflate` state (~47.5 KB) across calls; see
397/// [`set_pool_retention`]. The output buffer is returned to the caller
398/// (zero-copy), so it is sized up-front from the compressed length to avoid
399/// repeated doubling reallocations while it grows to the decompressed size.
400pub fn decompress_zlib_pooled(compressed: &[u8], max_size: u64) -> io::Result<Vec<u8>> {
401    let mut decompressor = checkout();
402    let result = decompress_with(&mut decompressor, compressed, max_size);
403    park(decompressor);
404    result
405}
406
407fn decompress_with(
408    decompressor: &mut Inflate,
409    compressed: &[u8],
410    max_size: u64,
411) -> io::Result<Vec<u8>> {
412    // Cap output growth to max_size + 1 so we detect oversized payloads
413    // without allocating unbounded memory from a compressed bomb.
414    let cap = (max_size as usize).saturating_add(1);
415
416    // Pre-size the output near the likely decompressed size to avoid the
417    // repeated doubling reallocations the old 64 KB upper clamp forced for
418    // every multi-MB history-sync chunk. 2x the compressed length is a
419    // conservative first guess (zlib here compresses ~2-5x): it rarely
420    // overshoots the real size, so it cuts reallocations without inflating
421    // peak memory. Bounded by `cap` so a bad guess can't exceed the limit;
422    // the floor also bows to `cap` because callers now pass exact (possibly
423    // tiny) decompressed sizes as the limit, where a fixed 4096 floor would
424    // invert the clamp and panic.
425    let floor = 4096.min(cap);
426    let estimated = compressed.len().saturating_mul(2).clamp(floor, cap);
427    let mut scratch = Vec::with_capacity(estimated);
428
429    let mut input_offset = 0;
430    loop {
431        // Enforce cap before we grow the buffer for the next inflate call
432        if scratch.len() >= cap {
433            return Err(io::Error::new(
434                io::ErrorKind::InvalidData,
435                format!("decompressed payload exceeds {max_size} bytes"),
436            ));
437        }
438
439        let prev_in = decompressor.total_in();
440        let prev_out = decompressor.total_out();
441
442        let status = inflate_into_spare(
443            decompressor,
444            &compressed[input_offset..],
445            &mut scratch,
446            InflateFlush::Finish,
447        )
448        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.as_str()))?;
449
450        input_offset = decompressor.total_in() as usize;
451
452        if scratch.len() as u64 > max_size {
453            return Err(io::Error::new(
454                io::ErrorKind::InvalidData,
455                format!("decompressed payload exceeds {max_size} bytes"),
456            ));
457        }
458
459        match status {
460            Status::StreamEnd => break,
461            Status::Ok => {
462                grow_by_observed_ratio(&mut scratch, decompressor, compressed.len(), cap);
463            }
464            Status::BufError => {
465                if decompressor.total_in() == prev_in && decompressor.total_out() == prev_out {
466                    return Err(io::Error::new(
467                        io::ErrorKind::InvalidData,
468                        "zlib stream truncated (no progress)",
469                    ));
470                }
471                grow_by_observed_ratio(&mut scratch, decompressor, compressed.len(), cap);
472            }
473        }
474    }
475
476    Ok(scratch)
477}
478
479/// Fixture support shared by this crate's test modules.
480#[cfg(test)]
481pub(crate) mod test_support {
482    /// A zlib stream carrying `data` verbatim in stored (uncompressed) deflate
483    /// blocks, hand-built so the fixture costs no compressor.
484    ///
485    /// A real compressor cannot be used under Miri: zlib-rs's *deflate* state
486    /// frees its buffers from `deflate::end` while a `&mut` into them is still
487    /// protected, which Miri rejects. That is the compression half, which this
488    /// crate never runs (inflate is the whole production path), so the fixture
489    /// side steps around it rather than the tests being dropped from the
490    /// Miri gate. Blocks are 64 KB at most, so longer data spans several.
491    pub(crate) fn stored_zlib(data: &[u8]) -> Vec<u8> {
492        // 0x78 0x01: deflate, 32 KB window, and (0x78 << 8 | 0x01) % 31 == 0 as
493        // the header check requires.
494        let mut out = vec![0x78, 0x01];
495        let mut blocks = data.chunks(u16::MAX as usize).peekable();
496        if blocks.peek().is_none() {
497            out.extend_from_slice(&[0x01, 0, 0, 0xff, 0xff]);
498        }
499        while let Some(block) = blocks.next() {
500            let len = block.len() as u16;
501            // BFINAL on the last block, BTYPE=00 (stored), then the
502            // byte-aligned LEN/!LEN pair.
503            out.push(u8::from(blocks.peek().is_none()));
504            out.extend_from_slice(&len.to_le_bytes());
505            out.extend_from_slice(&(!len).to_le_bytes());
506            out.extend_from_slice(block);
507        }
508
509        let (mut a, mut b) = (1u32, 0u32);
510        for &byte in data {
511            a = (a + byte as u32) % 65521;
512            b = (b + a) % 65521;
513        }
514        out.extend_from_slice(&(((b << 16) | a).to_be_bytes()));
515        out
516    }
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522    use flate2::Compression;
523    use flate2::write::ZlibEncoder;
524    use std::io::Write;
525
526    fn zlib(data: &[u8]) -> Vec<u8> {
527        let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
528        e.write_all(data).unwrap();
529        e.finish().unwrap()
530    }
531
532    fn varied(n: usize) -> Vec<u8> {
533        let mut s: u64 = 0x9e37_79b9_7f4a_7c15;
534        (0..n)
535            .map(|_| {
536                s ^= s << 13;
537                s ^= s >> 7;
538                s ^= s << 17;
539                (s >> 24) as u8
540            })
541            .collect()
542    }
543
544    use super::test_support::stored_zlib;
545
546    // Tests sized in hundreds of KB to MB reach window refill and the growth
547    // projection, which puts a full inflate cycle hours out of reach of Miri's
548    // interpreter, so those are `#[cfg_attr(miri, ignore)]`. This one and the
549    // truncated/corrupt pair keep the `set_len` in `inflate_into_spare` under
550    // Miri on fixtures it can finish.
551    #[test]
552    fn pooled_roundtrip_small_input() {
553        let original = varied(1024);
554        let compressed = stored_zlib(&original);
555        assert_eq!(
556            decompress_zlib_pooled(&compressed, 64 * 1024).unwrap(),
557            original
558        );
559        assert_eq!(drain_reader(&compressed, original.len()), original);
560    }
561
562    #[test]
563    #[cfg_attr(miri, ignore)]
564    fn inflate_reader_roundtrip_across_chunks() {
565        // >128 KB so the stream spans multiple 64 KB decompress windows, and read
566        // it back in tiny odd steps to exercise refill + compaction.
567        let original = varied(200 * 1024);
568        let compressed = zlib(&original);
569        let mut r = InflateReader::new(&compressed, 64 * 1024 * 1024);
570        let mut out = Vec::with_capacity(original.len());
571        while r.ensure(1).unwrap() {
572            let n = r.available().len().min(7);
573            out.extend_from_slice(&r.available()[..n]);
574            r.consume(n);
575        }
576        assert!(r.is_done());
577        assert_eq!(out, original);
578    }
579
580    #[test]
581    #[cfg_attr(miri, ignore)]
582    fn inflate_reader_ensure_larger_than_chunk() {
583        // A single record bigger than the 64 KB window must be fully buffered.
584        let original: Vec<u8> = (0..150 * 1024).map(|i| (i % 256) as u8).collect();
585        let compressed = zlib(&original);
586        let mut r = InflateReader::new(&compressed, 64 * 1024 * 1024);
587        assert!(r.ensure(150 * 1024).unwrap());
588        assert_eq!(&r.available()[..150 * 1024], &original[..]);
589    }
590
591    #[test]
592    #[cfg_attr(miri, ignore)]
593    fn inflate_reader_keeps_one_window_for_smaller_records() {
594        const RECORD: usize = 30 * 1024;
595        let original = varied(RECORD * 8);
596        let compressed = zlib(&original);
597        let mut r = InflateReader::new(&compressed, 64 * 1024 * 1024);
598
599        for expected in original.chunks(RECORD) {
600            assert!(r.ensure(expected.len()).unwrap());
601            assert_eq!(&r.available()[..expected.len()], expected);
602            r.consume(expected.len());
603            assert!(
604                r.buf.capacity() <= InflateReader::CHUNK,
605                "sub-window records grew the inflate buffer to {} bytes",
606                r.buf.capacity()
607            );
608        }
609        assert!(!r.ensure(1).unwrap());
610        assert!(r.is_done());
611    }
612
613    #[test]
614    #[cfg_attr(miri, ignore)]
615    fn inflate_reader_enforces_max() {
616        let original = vec![0u8; 1024 * 1024];
617        let compressed = zlib(&original);
618        let mut r = InflateReader::new(&compressed, 4096);
619        assert!(r.ensure(1024 * 1024).is_err());
620    }
621
622    #[test]
623    #[cfg_attr(miri, ignore)]
624    fn pooled_high_ratio_stream_roundtrips() {
625        // ~50x expansion: the 2x up-front guess undershoots badly, so this
626        // exercises the ratio-projected growth path end to end.
627        let original: Vec<u8> = (0..4_000_000u32).map(|i| ((i / 1024) % 7) as u8).collect();
628        let compressed = zlib(&original);
629        assert!(
630            compressed.len() < original.len() / 20,
631            "fixture not high-ratio"
632        );
633        let out = decompress_zlib_pooled(&compressed, 64 * 1024 * 1024).unwrap();
634        assert_eq!(out, original);
635        // The projection should land near the real size, not at a doubling
636        // overshoot far past it.
637        assert!(
638            out.capacity() < original.len() * 2,
639            "capacity {} vs data {}",
640            out.capacity(),
641            original.len()
642        );
643    }
644
645    #[test]
646    #[cfg_attr(miri, ignore)]
647    fn pooled_oneshot_matches_streaming() {
648        let original = varied(100_000);
649        let compressed = zlib(&original);
650        let one_shot = decompress_zlib_pooled(&compressed, 64 * 1024 * 1024).unwrap();
651        assert_eq!(one_shot, original);
652    }
653
654    fn drain_reader(compressed: &[u8], n: usize) -> Vec<u8> {
655        let mut r = InflateReader::new(compressed, 64 * 1024 * 1024);
656        let mut out = Vec::with_capacity(n);
657        while r.ensure(1).unwrap() {
658            let take = r.available().len();
659            out.extend_from_slice(r.available());
660            r.consume(take);
661        }
662        assert!(r.is_done());
663        out
664    }
665
666    #[test]
667    #[cfg_attr(miri, ignore)]
668    fn inflate_reader_reuses_pool_state_correctly() {
669        // Back-to-back readers each checkout the pooled Decompress and reset it, so
670        // no state may carry over between streams. Verify several sizes in sequence.
671        for n in [10_000usize, 250_000, 1, 80_000] {
672            let original = varied(n);
673            assert_eq!(drain_reader(&zlib(&original), n), original, "size {n}");
674        }
675    }
676
677    #[test]
678    #[cfg_attr(miri, ignore)]
679    fn inflate_reader_reuse_after_error() {
680        // A reader aborted mid-stream (max exceeded) returns partial zlib state to
681        // the pool; the next checkout must reset it and decompress a full stream.
682        {
683            let compressed = zlib(&varied(500_000));
684            let mut r = InflateReader::new(&compressed, 4096);
685            assert!(r.ensure(500_000).is_err());
686        }
687        let original = varied(120_000);
688        assert_eq!(drain_reader(&zlib(&original), 120_000), original);
689    }
690
691    #[test]
692    #[cfg_attr(miri, ignore)]
693    fn oversized_window_is_not_retained_for_the_thread() {
694        // Buffering a large record grows `buf` to many MB. The window is not part
695        // of a pool entry, so the next reader starts back at one window instead of
696        // inheriting the grown allocation.
697        let big = varied(2 * 1024 * 1024);
698        let compressed = zlib(&big);
699        {
700            let mut r = InflateReader::new(&compressed, 64 * 1024 * 1024);
701            assert!(r.ensure(big.len()).unwrap());
702            assert!(r.buf.capacity() >= big.len(), "buf should grow while alive");
703        }
704        let next = InflateReader::new(&compressed, 64 * 1024 * 1024);
705        assert!(
706            next.buf.capacity() <= InflateReader::CHUNK,
707            "fresh reader inherited a {} byte window",
708            next.buf.capacity()
709        );
710    }
711
712    /// Truncation is reported as EOF without a terminator, not as an error, and
713    /// the reader that picks the pooled state up next still decodes a full stream.
714    #[test]
715    fn truncated_stream_reports_missing_terminator() {
716        let original = varied(1024);
717        let compressed = stored_zlib(&original);
718        let truncated = &compressed[..compressed.len() - 300];
719
720        let mut r = InflateReader::new(truncated, 64 * 1024);
721        while r.ensure(1).unwrap() {
722            let n = r.available().len();
723            r.consume(n);
724        }
725        assert!(!r.stream_ended(), "truncated input reported a terminator");
726        assert!(r.is_done());
727        drop(r);
728
729        assert_eq!(drain_reader(&compressed, original.len()), original);
730    }
731
732    /// A corrupt stream fails with `InvalidData` and returns its half-used state
733    /// to the pool; the next checkout must reset it rather than inherit the fault.
734    #[test]
735    fn corrupt_stream_errors_without_poisoning_the_pool() {
736        let original = varied(1024);
737        let mut compressed = stored_zlib(&original);
738        // Break the stored block's LEN/!LEN complement pair, which inflate
739        // rejects outright rather than mis-decoding.
740        compressed[5] ^= 0xff;
741
742        let mut r = InflateReader::new(&compressed, 64 * 1024);
743        let err = r.ensure(1).unwrap_err();
744        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
745        drop(r);
746
747        let good = stored_zlib(&original);
748        assert_eq!(drain_reader(&good, original.len()), original);
749    }
750
751    /// The pool is thread-local but its retention is process-wide, so the tests
752    /// that observe either take this lock: `cargo test` runs them on threads.
753    static POOL_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
754
755    /// One parked state serves both inflate paths on a thread. A thread that
756    /// ran both used to hold two ~47.5 KB states for the life of the process.
757    #[test]
758    #[cfg_attr(miri, ignore)]
759    fn one_shot_and_streaming_inflate_share_one_parked_state() {
760        let _guard = POOL_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
761        drain_pool();
762        let original = varied(50_000);
763        let compressed = zlib(&original);
764
765        assert_eq!(
766            decompress_zlib_pooled(&compressed, 1 << 20).unwrap(),
767            original
768        );
769        assert_eq!(parked_states(), 1);
770        assert_eq!(drain_reader(&compressed, original.len()), original);
771        assert_eq!(parked_states(), 1);
772        assert_eq!(
773            decompress_zlib_pooled(&compressed, 1 << 20).unwrap(),
774            original
775        );
776        assert_eq!(
777            parked_states(),
778            1,
779            "a second path must not park a second state"
780        );
781    }
782
783    /// Retention zero: nothing is parked, `warm_pool` has nothing to do, and
784    /// both paths still inflate correctly on a fresh state each time.
785    ///
786    /// Not under Miri: this is the one test that drops an `Inflate`, and
787    /// zlib-rs 0.6.7's `inflate::end` frees the state from behind a `&mut`
788    /// into it, the same shape as the deflate half `stored_zlib` exists to
789    /// avoid. Every other test parks its state instead.
790    #[test]
791    #[cfg_attr(miri, ignore)]
792    fn retention_zero_parks_nothing() {
793        let _guard = POOL_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
794        drain_pool();
795        set_pool_retention(0);
796        let original = varied(1024);
797        let compressed = stored_zlib(&original);
798
799        warm_pool();
800        assert_eq!(parked_states(), 0);
801        assert_eq!(
802            decompress_zlib_pooled(&compressed, 64 * 1024).unwrap(),
803            original
804        );
805        assert_eq!(parked_states(), 0);
806        assert_eq!(drain_reader(&compressed, original.len()), original);
807        assert_eq!(parked_states(), 0);
808
809        set_pool_retention(DEFAULT_POOL_RETENTION);
810        warm_pool();
811        assert_eq!(parked_states(), 1);
812        warm_pool();
813        assert_eq!(parked_states(), 1, "warming twice must not park twice");
814        drain_pool();
815        assert_eq!(parked_states(), 0);
816    }
817
818    /// A reader that looked at the head of a stream can still hand over the
819    /// whole payload, and it is the same payload the one-shot path produces.
820    #[test]
821    #[cfg_attr(miri, ignore)]
822    fn read_to_end_after_a_peek_matches_the_one_shot_result() {
823        let original = varied(300_000);
824        let compressed = zlib(&original);
825
826        let mut r = InflateReader::with_chunk(&compressed, 1 << 24, 4096);
827        assert!(r.ensure(100).unwrap());
828        assert_eq!(&r.available()[..100], &original[..100]);
829        let whole = r.read_to_end().unwrap();
830        assert_eq!(whole, original);
831        assert_eq!(whole, decompress_zlib_pooled(&compressed, 1 << 24).unwrap());
832        assert!(
833            whole.capacity() < original.len() * 2,
834            "drain grew by doubling ({}) instead of by the observed ratio",
835            whole.capacity()
836        );
837
838        // A consumed prefix is not part of what comes back.
839        let mut r = InflateReader::with_chunk(&compressed, 1 << 24, 4096);
840        assert!(r.ensure(100).unwrap());
841        r.consume(100);
842        assert_eq!(r.read_to_end().unwrap(), &original[100..]);
843    }
844
845    #[test]
846    fn read_to_end_rejects_a_truncated_stream_and_the_max() {
847        let original = varied(1024);
848        let compressed = stored_zlib(&original);
849        let truncated = &compressed[..compressed.len() - 300];
850        let err = InflateReader::with_chunk(truncated, 64 * 1024, 256)
851            .read_to_end()
852            .unwrap_err();
853        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
854
855        let err = InflateReader::with_chunk(&compressed, 512, 256)
856            .read_to_end()
857            .unwrap_err();
858        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
859
860        assert_eq!(
861            InflateReader::with_chunk(&compressed, 64 * 1024, 256)
862                .read_to_end()
863                .unwrap(),
864            original
865        );
866    }
867
868    /// A small chunk bounds the window for a stream of small records: the
869    /// footprint of streaming a frame on a small heap is the chunk, not the
870    /// decompressed size.
871    #[test]
872    #[cfg_attr(miri, ignore)]
873    fn a_small_chunk_keeps_small_records_within_the_chunk() {
874        const RECORD: usize = 100;
875        const CHUNK: usize = 4096;
876        let original = varied(RECORD * 2000);
877        let compressed = zlib(&original);
878        let mut r = InflateReader::with_chunk(&compressed, 1 << 24, CHUNK);
879        for expected in original.chunks(RECORD) {
880            assert!(r.ensure(expected.len()).unwrap());
881            assert_eq!(&r.available()[..expected.len()], expected);
882            r.consume(expected.len());
883            assert!(
884                r.buf.capacity() <= CHUNK,
885                "window grew to {}",
886                r.buf.capacity()
887            );
888        }
889        assert!(!r.ensure(1).unwrap());
890    }
891}