wacore-binary 0.8.0

Binary data and constants for WhatsApp protocol
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
use std::cell::RefCell;
use std::io;
use std::sync::atomic::{AtomicUsize, Ordering};
use zlib_rs::{Inflate, InflateError, InflateFlush, Status};

/// zlib inflate wants a zlib header and the 32 KB LZ77 window.
const ZLIB_HEADER: bool = true;
const WINDOW_BITS: u8 = 15;

thread_local! {
    // Free-list of inflate state, shared by every inflate on this thread: the
    // one-shot [`decompress_zlib_pooled`] and the streaming [`InflateReader`].
    // zlib-rs allocates the state and its 32 KB window as one block of roughly
    // 47.5 KB, so a thread that ran both paths used to retain two of them for
    // the life of the process; one list means one.
    //
    // The output window is deliberately not part of the entry. It is the larger
    // allocation of the two and costs one malloc to recreate, where zlib state
    // costs an order of magnitude more, so retaining it bought little and left
    // 64 KB alive per thread for the process's lifetime after a single sync.
    static INFLATE_POOL: RefCell<Vec<Inflate>> = const { RefCell::new(Vec::new()) };
}

/// How many inflate states a thread parks between uses; see [`set_pool_retention`].
static POOL_RETENTION: AtomicUsize = AtomicUsize::new(DEFAULT_POOL_RETENTION);

/// One parked state per thread. Sequential inflates are the norm (a bootstrap
/// history sync inflates its blobs one after another, a connection its
/// compressed frames one at a time) and one parked entry is all that case ever
/// checks out, so a deeper pool only retains another ~47.5 KB per slot, per
/// thread that ever inflated anything, for the life of the process. Nested
/// readers still work; they just build their state instead of finding it parked.
const DEFAULT_POOL_RETENTION: usize = 1;

/// Set how many inflate states each thread keeps parked between uses.
///
/// Every inflate on a thread first checks its pool and, finding it empty,
/// builds a fresh state: one allocation of roughly 47.5 KB (zlib-rs allocates
/// the state and its 32 KB window together). The default of one keeps that
/// allocation resident on every thread that ever inflated anything, which is
/// what a host with memory to spare wants. A client whose whole heap is a few
/// hundred KB may prefer `0`: every inflate then pays the allocation and
/// releases it, so the ~47.5 KB is only ever held while something is actually
/// being inflated, at the cost of one large malloc per compressed frame.
///
/// Process-wide; takes effect on the next park. Lowering it does not evict
/// states already parked, see [`drain_pool`].
pub fn set_pool_retention(states_per_thread: usize) {
    POOL_RETENTION.store(states_per_thread, Ordering::Relaxed);
}

/// Build this thread's inflate state ahead of its first compressed payload.
///
/// The state is one ~47.5 KB allocation, and a heap that fragments as a
/// connection comes up may no longer have a hole that size by the time the
/// first large compressed frame is already sitting in it. Calling this on the
/// thread that will run the read loop, while the heap is still fresh, moves
/// that allocation to a moment it is known to succeed; the pool then hands the
/// same state to every inflate on this thread. A no-op when a state is already
/// parked, or when [`set_pool_retention`] is zero, since nothing would keep it.
pub fn warm_pool() {
    if POOL_RETENTION.load(Ordering::Relaxed) == 0 {
        return;
    }
    let parked = INFLATE_POOL.with(|p| !p.borrow().is_empty());
    if !parked {
        park(Inflate::new(ZLIB_HEADER, WINDOW_BITS));
    }
}

/// Release the inflate states this thread has parked, returning their memory.
///
/// The pool refills on the next inflate; this only matters on a target that
/// needs the ~47.5 KB back between connections.
pub fn drain_pool() {
    INFLATE_POOL.with(|p| p.borrow_mut().clear());
}

/// Number of inflate states this thread currently keeps parked.
pub fn parked_states() -> usize {
    INFLATE_POOL.with(|p| p.borrow().len())
}

/// A reset inflate state: the thread's parked one when there is one, built
/// otherwise. `reset` on checkout makes any prior stream state (including an
/// error the last user hit) moot.
fn checkout() -> Inflate {
    INFLATE_POOL.with(|p| p.borrow_mut().pop()).map_or_else(
        || Inflate::new(ZLIB_HEADER, WINDOW_BITS),
        |mut decomp| {
            decomp.reset(ZLIB_HEADER);
            decomp
        },
    )
}

/// Return a state to this thread's pool, or drop it once the pool is full.
fn park(decomp: Inflate) {
    INFLATE_POOL.with(|p| {
        let mut pool = p.borrow_mut();
        if pool.len() < POOL_RETENTION.load(Ordering::Relaxed) {
            pool.push(decomp);
        }
    });
}

/// Inflate straight into the vector's spare capacity, then extend its length by
/// the produced count. Unlike `flate2::Decompress::decompress_vec`, this never
/// zero-initializes the spare region first: flate2's zlib-rs backend doesn't
/// override `decompress_uninit`, so it memsets the whole output window before
/// every call — pure waste, since inflate overwrites exactly those bytes.
fn inflate_into_spare(
    inflate: &mut Inflate,
    input: &[u8],
    out: &mut Vec<u8>,
    flush: InflateFlush,
) -> Result<Status, InflateError> {
    let before = inflate.total_out();
    let status = inflate.decompress_uninit(input, out.spare_capacity_mut(), flush)?;
    let produced = (inflate.total_out() - before) as usize;
    // SAFETY: `decompress_uninit` wrote exactly `produced` bytes (per total_out)
    // into the spare capacity, so that prefix is now initialized and in-bounds.
    unsafe { out.set_len(out.len() + produced) };
    Ok(status)
}

/// Streaming zlib reader: decompresses `input` incrementally into a small
/// accumulation buffer, so a caller can parse length-delimited records as they
/// become available and discard consumed bytes — peak memory stays ~the largest
/// single record being buffered, not the whole decompressed blob.
///
/// Usage: `ensure(n)` to make ≥ n bytes available, read from `available()`, then
/// `consume(k)`. The buffer is compacted (consumed prefix dropped) as it grows.
pub struct InflateReader<'a> {
    input: &'a [u8],
    in_pos: usize,
    // `Option` so `Drop` can move the state back into the pool (Inflate has no
    // cheap throwaway value to swap in). Always `Some` until dropped.
    decomp: Option<Inflate>,
    buf: Vec<u8>,
    cursor: usize,
    chunk: usize,
    total_out: u64,
    max: u64,
    eof: bool,
    stream_end: bool,
}

impl<'a> InflateReader<'a> {
    /// Output decompress window per pump; also the compaction threshold. One
    /// window is the steady state: the pump compacts a consumed prefix before
    /// inflating, so the buffer only grows past the chunk when one individual
    /// record genuinely exceeds it. Allocated per reader, never retained.
    ///
    /// 64 KB suits the multi-megabyte history-sync blobs this reader was built
    /// for, where each pump's fixed cost is worth amortizing; a reader over a
    /// protocol frame on a small heap picks its own with [`Self::with_chunk`].
    pub const CHUNK: usize = 64 * 1024;

    pub fn new(input: &'a [u8], max: u64) -> Self {
        Self::with_chunk(input, max, Self::CHUNK)
    }

    /// A reader whose output window is `chunk` bytes instead of [`Self::CHUNK`].
    ///
    /// The window is the reader's one allocation of its own, so it is the
    /// reader's whole footprint beyond the pooled zlib state: a 4 KB chunk
    /// keeps a stream of small records inside 4 KB however long the stream
    /// is. A record larger than the chunk still grows the window to fit it.
    pub fn with_chunk(input: &'a [u8], max: u64, chunk: usize) -> Self {
        let chunk = chunk.max(1);
        Self {
            input,
            in_pos: 0,
            decomp: Some(checkout()),
            buf: Vec::with_capacity(chunk),
            cursor: 0,
            chunk,
            total_out: 0,
            max,
            eof: false,
            stream_end: false,
        }
    }

    /// Unparsed decompressed bytes currently buffered.
    #[inline]
    pub fn available(&self) -> &[u8] {
        &self.buf[self.cursor..]
    }

    /// Mark `n` already-read bytes as consumed.
    #[inline]
    pub fn consume(&mut self, n: usize) {
        self.cursor = (self.cursor + n).min(self.buf.len());
    }

    /// Ensure at least `need` unparsed bytes are buffered, decompressing more as
    /// required. Returns `Ok(false)` if the stream ends before reaching `need`.
    pub fn ensure(&mut self, need: usize) -> io::Result<bool> {
        while self.buf.len() - self.cursor < need {
            if self.eof {
                return Ok(false);
            }
            self.pump()?;
        }
        Ok(true)
    }

    /// True once the stream is fully decompressed and all bytes consumed.
    pub fn is_done(&self) -> bool {
        self.eof && self.cursor >= self.buf.len()
    }

    /// Total decompressed bytes produced so far. After the stream ends this is
    /// the blob's exact inflated size.
    pub fn total_out(&self) -> u64 {
        self.total_out
    }

    /// Compressed input consumed so far plus the input's full length. The
    /// ratio lets callers extrapolate totals (e.g. record counts) from a
    /// prefix without a second pass over the blob.
    #[inline]
    pub fn compressed_progress(&self) -> (usize, usize) {
        (self.in_pos, self.input.len())
    }

    /// Whether zlib reported a proper stream end (terminator + adler32
    /// checksum). An EOF (`ensure` returning false) without this means the
    /// input was truncated, not finished.
    pub fn stream_ended(&self) -> bool {
        self.stream_end
    }

    fn pump(&mut self) -> io::Result<()> {
        // Reclaim the consumed prefix before inflating. Reserving a full output
        // window on top of a small read-ahead suffix made ordinary framed
        // streams jump from 64 to 128 KiB even though no record needed it.
        // Compacting here keeps those streams in one window; a record larger
        // than the window still grows normally below.
        if self.cursor != 0 {
            let remaining = self.buf.len() - self.cursor;
            self.buf.copy_within(self.cursor.., 0);
            self.buf.truncate(remaining);
            self.cursor = 0;
        }

        // `decomp` is `Some` for the reader's whole lifetime (only `Drop` takes it),
        // so this is unreachable in practice; surface it as an error rather than panic.
        let decomp = self
            .decomp
            .as_mut()
            .ok_or_else(|| io::Error::other("InflateReader used after pool return"))?;
        // Inflate straight into the window's spare capacity: a stack chunk +
        // extend_from_slice would copy every decompressed byte a second time
        // (~10% of a history-sync extraction).
        if self.buf.len() == self.buf.capacity() {
            self.buf.reserve(self.chunk);
        }
        let prev_in = decomp.total_in();
        let prev_out = decomp.total_out();
        let status = inflate_into_spare(
            decomp,
            &self.input[self.in_pos..],
            &mut self.buf,
            InflateFlush::NoFlush,
        )
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.as_str()))?;
        let new_in = decomp.total_in();
        let produced = (decomp.total_out() - prev_out) as usize;
        self.in_pos += (new_in - prev_in) as usize;
        self.total_out += produced as u64;
        if self.total_out > self.max {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("decompressed payload exceeds {} bytes", self.max),
            ));
        }

        match status {
            Status::StreamEnd => {
                self.eof = true;
                self.stream_end = true;
            }
            // No output produced and not at stream end: distinguish a truncated
            // tail (no input left → treat as end, with `stream_end` left false
            // so callers can tell it apart from a real terminator) from a
            // stalled/corrupt stream (input remains but the decompressor
            // consumed none → error, instead of spinning forever since 64 KB of
            // output is always available).
            // Mirrors the no-progress guard in `decompress_zlib_pooled`.
            _ if produced == 0 => {
                if self.in_pos >= self.input.len() {
                    self.eof = true;
                } else if new_in == prev_in {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "zlib stream stalled (no progress)",
                    ));
                }
            }
            _ => {}
        }
        Ok(())
    }
}

impl InflateReader<'_> {
    /// Inflate the rest of the stream into the window without consuming any of
    /// it, then hand the window over: every decompressed byte from the first
    /// one not yet consumed to the end of the stream, in one `Vec`.
    ///
    /// This is the one-shot [`decompress_zlib_pooled`] result reached from a
    /// reader that has already looked at the head of the stream. The window is
    /// grown by the expansion ratio observed so far rather than by doubling, as
    /// the one-shot path does, so the prefix already inflated is what sizes the
    /// rest. A stream that ends without its terminator is an error here, as it
    /// is there: a caller draining to the end wants the whole payload or none.
    pub fn read_to_end(mut self) -> io::Result<Vec<u8>> {
        while !self.eof {
            if self.buf.len() == self.buf.capacity() {
                let cap = (self.max as usize).saturating_add(1);
                if self.buf.len() >= cap {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!("decompressed payload exceeds {} bytes", self.max),
                    ));
                }
                let decomp = self
                    .decomp
                    .as_ref()
                    .ok_or_else(|| io::Error::other("InflateReader used after pool return"))?;
                grow_by_observed_ratio(&mut self.buf, decomp, self.input.len(), cap);
            }
            self.pump()?;
        }
        if !self.stream_end {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "zlib stream truncated (no terminator)",
            ));
        }
        let mut buf = std::mem::take(&mut self.buf);
        if self.cursor != 0 {
            buf.drain(..self.cursor);
        }
        Ok(buf)
    }
}

impl Drop for InflateReader<'_> {
    fn drop(&mut self) {
        // Return the decompressor to the per-thread free-list for reuse; the
        // window goes back to the allocator with the rest of the reader.
        if let Some(decomp) = self.decomp.take() {
            park(decomp);
        }
    }
}

/// Grow the output buffer by projecting the decompressed size from the
/// expansion ratio observed so far, instead of blind capacity doubling. A
/// high-ratio stream (the up-front `2x compressed` guess undershot) then
/// converges in one or two reallocations sized near the real total, rather
/// than a doubling chain whose copies and final overshoot dominate both the
/// allocated-bytes count and the peak.
fn grow_by_observed_ratio(
    scratch: &mut Vec<u8>,
    decompressor: &Inflate,
    compressed_len: usize,
    cap: usize,
) {
    let consumed = decompressor.total_in() as usize;
    let produced = decompressor.total_out() as usize;
    let remaining_in = compressed_len.saturating_sub(consumed) as u64;
    let projected = if consumed > 0 && produced > 0 {
        // 9/8 margin: early bytes compress worse than the warmed-up tail, so
        // the observed ratio slightly underestimates the remainder.
        ((produced as u64).saturating_mul(remaining_in) / consumed as u64).saturating_mul(9) / 8
    } else {
        0
    };
    // Floor at the doubling step: small payloads (protocol nodes) keep their
    // old growth exactly; the projection only ever grows MORE, for the
    // high-ratio multi-MB streams it exists for.
    let min_grow = scratch.capacity().max(4096);
    let want = (projected.min(usize::MAX as u64) as usize)
        .max(min_grow)
        .min(cap - scratch.len());
    scratch.reserve(want);
}

/// Decompress zlib data using a pooled decompressor.
///
/// Reuses the per-thread `zlib_rs::Inflate` state (~47.5 KB) across calls; see
/// [`set_pool_retention`]. The output buffer is returned to the caller
/// (zero-copy), so it is sized up-front from the compressed length to avoid
/// repeated doubling reallocations while it grows to the decompressed size.
pub fn decompress_zlib_pooled(compressed: &[u8], max_size: u64) -> io::Result<Vec<u8>> {
    let mut decompressor = checkout();
    let result = decompress_with(&mut decompressor, compressed, max_size);
    park(decompressor);
    result
}

fn decompress_with(
    decompressor: &mut Inflate,
    compressed: &[u8],
    max_size: u64,
) -> io::Result<Vec<u8>> {
    // Cap output growth to max_size + 1 so we detect oversized payloads
    // without allocating unbounded memory from a compressed bomb.
    let cap = (max_size as usize).saturating_add(1);

    // Pre-size the output near the likely decompressed size to avoid the
    // repeated doubling reallocations the old 64 KB upper clamp forced for
    // every multi-MB history-sync chunk. 2x the compressed length is a
    // conservative first guess (zlib here compresses ~2-5x): it rarely
    // overshoots the real size, so it cuts reallocations without inflating
    // peak memory. Bounded by `cap` so a bad guess can't exceed the limit;
    // the floor also bows to `cap` because callers now pass exact (possibly
    // tiny) decompressed sizes as the limit, where a fixed 4096 floor would
    // invert the clamp and panic.
    let floor = 4096.min(cap);
    let estimated = compressed.len().saturating_mul(2).clamp(floor, cap);
    let mut scratch = Vec::with_capacity(estimated);

    let mut input_offset = 0;
    loop {
        // Enforce cap before we grow the buffer for the next inflate call
        if scratch.len() >= cap {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("decompressed payload exceeds {max_size} bytes"),
            ));
        }

        let prev_in = decompressor.total_in();
        let prev_out = decompressor.total_out();

        let status = inflate_into_spare(
            decompressor,
            &compressed[input_offset..],
            &mut scratch,
            InflateFlush::Finish,
        )
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.as_str()))?;

        input_offset = decompressor.total_in() as usize;

        if scratch.len() as u64 > max_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("decompressed payload exceeds {max_size} bytes"),
            ));
        }

        match status {
            Status::StreamEnd => break,
            Status::Ok => {
                grow_by_observed_ratio(&mut scratch, decompressor, compressed.len(), cap);
            }
            Status::BufError => {
                if decompressor.total_in() == prev_in && decompressor.total_out() == prev_out {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "zlib stream truncated (no progress)",
                    ));
                }
                grow_by_observed_ratio(&mut scratch, decompressor, compressed.len(), cap);
            }
        }
    }

    Ok(scratch)
}

/// Fixture support shared by this crate's test modules.
#[cfg(test)]
pub(crate) mod test_support {
    /// A zlib stream carrying `data` verbatim in stored (uncompressed) deflate
    /// blocks, hand-built so the fixture costs no compressor.
    ///
    /// A real compressor cannot be used under Miri: zlib-rs's *deflate* state
    /// frees its buffers from `deflate::end` while a `&mut` into them is still
    /// protected, which Miri rejects. That is the compression half, which this
    /// crate never runs (inflate is the whole production path), so the fixture
    /// side steps around it rather than the tests being dropped from the
    /// Miri gate. Blocks are 64 KB at most, so longer data spans several.
    pub(crate) fn stored_zlib(data: &[u8]) -> Vec<u8> {
        // 0x78 0x01: deflate, 32 KB window, and (0x78 << 8 | 0x01) % 31 == 0 as
        // the header check requires.
        let mut out = vec![0x78, 0x01];
        let mut blocks = data.chunks(u16::MAX as usize).peekable();
        if blocks.peek().is_none() {
            out.extend_from_slice(&[0x01, 0, 0, 0xff, 0xff]);
        }
        while let Some(block) = blocks.next() {
            let len = block.len() as u16;
            // BFINAL on the last block, BTYPE=00 (stored), then the
            // byte-aligned LEN/!LEN pair.
            out.push(u8::from(blocks.peek().is_none()));
            out.extend_from_slice(&len.to_le_bytes());
            out.extend_from_slice(&(!len).to_le_bytes());
            out.extend_from_slice(block);
        }

        let (mut a, mut b) = (1u32, 0u32);
        for &byte in data {
            a = (a + byte as u32) % 65521;
            b = (b + a) % 65521;
        }
        out.extend_from_slice(&(((b << 16) | a).to_be_bytes()));
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use flate2::Compression;
    use flate2::write::ZlibEncoder;
    use std::io::Write;

    fn zlib(data: &[u8]) -> Vec<u8> {
        let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
        e.write_all(data).unwrap();
        e.finish().unwrap()
    }

    fn varied(n: usize) -> Vec<u8> {
        let mut s: u64 = 0x9e37_79b9_7f4a_7c15;
        (0..n)
            .map(|_| {
                s ^= s << 13;
                s ^= s >> 7;
                s ^= s << 17;
                (s >> 24) as u8
            })
            .collect()
    }

    use super::test_support::stored_zlib;

    // Tests sized in hundreds of KB to MB reach window refill and the growth
    // projection, which puts a full inflate cycle hours out of reach of Miri's
    // interpreter, so those are `#[cfg_attr(miri, ignore)]`. This one and the
    // truncated/corrupt pair keep the `set_len` in `inflate_into_spare` under
    // Miri on fixtures it can finish.
    #[test]
    fn pooled_roundtrip_small_input() {
        let original = varied(1024);
        let compressed = stored_zlib(&original);
        assert_eq!(
            decompress_zlib_pooled(&compressed, 64 * 1024).unwrap(),
            original
        );
        assert_eq!(drain_reader(&compressed, original.len()), original);
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn inflate_reader_roundtrip_across_chunks() {
        // >128 KB so the stream spans multiple 64 KB decompress windows, and read
        // it back in tiny odd steps to exercise refill + compaction.
        let original = varied(200 * 1024);
        let compressed = zlib(&original);
        let mut r = InflateReader::new(&compressed, 64 * 1024 * 1024);
        let mut out = Vec::with_capacity(original.len());
        while r.ensure(1).unwrap() {
            let n = r.available().len().min(7);
            out.extend_from_slice(&r.available()[..n]);
            r.consume(n);
        }
        assert!(r.is_done());
        assert_eq!(out, original);
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn inflate_reader_ensure_larger_than_chunk() {
        // A single record bigger than the 64 KB window must be fully buffered.
        let original: Vec<u8> = (0..150 * 1024).map(|i| (i % 256) as u8).collect();
        let compressed = zlib(&original);
        let mut r = InflateReader::new(&compressed, 64 * 1024 * 1024);
        assert!(r.ensure(150 * 1024).unwrap());
        assert_eq!(&r.available()[..150 * 1024], &original[..]);
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn inflate_reader_keeps_one_window_for_smaller_records() {
        const RECORD: usize = 30 * 1024;
        let original = varied(RECORD * 8);
        let compressed = zlib(&original);
        let mut r = InflateReader::new(&compressed, 64 * 1024 * 1024);

        for expected in original.chunks(RECORD) {
            assert!(r.ensure(expected.len()).unwrap());
            assert_eq!(&r.available()[..expected.len()], expected);
            r.consume(expected.len());
            assert!(
                r.buf.capacity() <= InflateReader::CHUNK,
                "sub-window records grew the inflate buffer to {} bytes",
                r.buf.capacity()
            );
        }
        assert!(!r.ensure(1).unwrap());
        assert!(r.is_done());
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn inflate_reader_enforces_max() {
        let original = vec![0u8; 1024 * 1024];
        let compressed = zlib(&original);
        let mut r = InflateReader::new(&compressed, 4096);
        assert!(r.ensure(1024 * 1024).is_err());
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn pooled_high_ratio_stream_roundtrips() {
        // ~50x expansion: the 2x up-front guess undershoots badly, so this
        // exercises the ratio-projected growth path end to end.
        let original: Vec<u8> = (0..4_000_000u32).map(|i| ((i / 1024) % 7) as u8).collect();
        let compressed = zlib(&original);
        assert!(
            compressed.len() < original.len() / 20,
            "fixture not high-ratio"
        );
        let out = decompress_zlib_pooled(&compressed, 64 * 1024 * 1024).unwrap();
        assert_eq!(out, original);
        // The projection should land near the real size, not at a doubling
        // overshoot far past it.
        assert!(
            out.capacity() < original.len() * 2,
            "capacity {} vs data {}",
            out.capacity(),
            original.len()
        );
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn pooled_oneshot_matches_streaming() {
        let original = varied(100_000);
        let compressed = zlib(&original);
        let one_shot = decompress_zlib_pooled(&compressed, 64 * 1024 * 1024).unwrap();
        assert_eq!(one_shot, original);
    }

    fn drain_reader(compressed: &[u8], n: usize) -> Vec<u8> {
        let mut r = InflateReader::new(compressed, 64 * 1024 * 1024);
        let mut out = Vec::with_capacity(n);
        while r.ensure(1).unwrap() {
            let take = r.available().len();
            out.extend_from_slice(r.available());
            r.consume(take);
        }
        assert!(r.is_done());
        out
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn inflate_reader_reuses_pool_state_correctly() {
        // Back-to-back readers each checkout the pooled Decompress and reset it, so
        // no state may carry over between streams. Verify several sizes in sequence.
        for n in [10_000usize, 250_000, 1, 80_000] {
            let original = varied(n);
            assert_eq!(drain_reader(&zlib(&original), n), original, "size {n}");
        }
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn inflate_reader_reuse_after_error() {
        // A reader aborted mid-stream (max exceeded) returns partial zlib state to
        // the pool; the next checkout must reset it and decompress a full stream.
        {
            let compressed = zlib(&varied(500_000));
            let mut r = InflateReader::new(&compressed, 4096);
            assert!(r.ensure(500_000).is_err());
        }
        let original = varied(120_000);
        assert_eq!(drain_reader(&zlib(&original), 120_000), original);
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn oversized_window_is_not_retained_for_the_thread() {
        // Buffering a large record grows `buf` to many MB. The window is not part
        // of a pool entry, so the next reader starts back at one window instead of
        // inheriting the grown allocation.
        let big = varied(2 * 1024 * 1024);
        let compressed = zlib(&big);
        {
            let mut r = InflateReader::new(&compressed, 64 * 1024 * 1024);
            assert!(r.ensure(big.len()).unwrap());
            assert!(r.buf.capacity() >= big.len(), "buf should grow while alive");
        }
        let next = InflateReader::new(&compressed, 64 * 1024 * 1024);
        assert!(
            next.buf.capacity() <= InflateReader::CHUNK,
            "fresh reader inherited a {} byte window",
            next.buf.capacity()
        );
    }

    /// Truncation is reported as EOF without a terminator, not as an error, and
    /// the reader that picks the pooled state up next still decodes a full stream.
    #[test]
    fn truncated_stream_reports_missing_terminator() {
        let original = varied(1024);
        let compressed = stored_zlib(&original);
        let truncated = &compressed[..compressed.len() - 300];

        let mut r = InflateReader::new(truncated, 64 * 1024);
        while r.ensure(1).unwrap() {
            let n = r.available().len();
            r.consume(n);
        }
        assert!(!r.stream_ended(), "truncated input reported a terminator");
        assert!(r.is_done());
        drop(r);

        assert_eq!(drain_reader(&compressed, original.len()), original);
    }

    /// A corrupt stream fails with `InvalidData` and returns its half-used state
    /// to the pool; the next checkout must reset it rather than inherit the fault.
    #[test]
    fn corrupt_stream_errors_without_poisoning_the_pool() {
        let original = varied(1024);
        let mut compressed = stored_zlib(&original);
        // Break the stored block's LEN/!LEN complement pair, which inflate
        // rejects outright rather than mis-decoding.
        compressed[5] ^= 0xff;

        let mut r = InflateReader::new(&compressed, 64 * 1024);
        let err = r.ensure(1).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        drop(r);

        let good = stored_zlib(&original);
        assert_eq!(drain_reader(&good, original.len()), original);
    }

    /// The pool is thread-local but its retention is process-wide, so the tests
    /// that observe either take this lock: `cargo test` runs them on threads.
    static POOL_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// One parked state serves both inflate paths on a thread. A thread that
    /// ran both used to hold two ~47.5 KB states for the life of the process.
    #[test]
    #[cfg_attr(miri, ignore)]
    fn one_shot_and_streaming_inflate_share_one_parked_state() {
        let _guard = POOL_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        drain_pool();
        let original = varied(50_000);
        let compressed = zlib(&original);

        assert_eq!(
            decompress_zlib_pooled(&compressed, 1 << 20).unwrap(),
            original
        );
        assert_eq!(parked_states(), 1);
        assert_eq!(drain_reader(&compressed, original.len()), original);
        assert_eq!(parked_states(), 1);
        assert_eq!(
            decompress_zlib_pooled(&compressed, 1 << 20).unwrap(),
            original
        );
        assert_eq!(
            parked_states(),
            1,
            "a second path must not park a second state"
        );
    }

    /// Retention zero: nothing is parked, `warm_pool` has nothing to do, and
    /// both paths still inflate correctly on a fresh state each time.
    ///
    /// Not under Miri: this is the one test that drops an `Inflate`, and
    /// zlib-rs 0.6.7's `inflate::end` frees the state from behind a `&mut`
    /// into it, the same shape as the deflate half `stored_zlib` exists to
    /// avoid. Every other test parks its state instead.
    #[test]
    #[cfg_attr(miri, ignore)]
    fn retention_zero_parks_nothing() {
        let _guard = POOL_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        drain_pool();
        set_pool_retention(0);
        let original = varied(1024);
        let compressed = stored_zlib(&original);

        warm_pool();
        assert_eq!(parked_states(), 0);
        assert_eq!(
            decompress_zlib_pooled(&compressed, 64 * 1024).unwrap(),
            original
        );
        assert_eq!(parked_states(), 0);
        assert_eq!(drain_reader(&compressed, original.len()), original);
        assert_eq!(parked_states(), 0);

        set_pool_retention(DEFAULT_POOL_RETENTION);
        warm_pool();
        assert_eq!(parked_states(), 1);
        warm_pool();
        assert_eq!(parked_states(), 1, "warming twice must not park twice");
        drain_pool();
        assert_eq!(parked_states(), 0);
    }

    /// A reader that looked at the head of a stream can still hand over the
    /// whole payload, and it is the same payload the one-shot path produces.
    #[test]
    #[cfg_attr(miri, ignore)]
    fn read_to_end_after_a_peek_matches_the_one_shot_result() {
        let original = varied(300_000);
        let compressed = zlib(&original);

        let mut r = InflateReader::with_chunk(&compressed, 1 << 24, 4096);
        assert!(r.ensure(100).unwrap());
        assert_eq!(&r.available()[..100], &original[..100]);
        let whole = r.read_to_end().unwrap();
        assert_eq!(whole, original);
        assert_eq!(whole, decompress_zlib_pooled(&compressed, 1 << 24).unwrap());
        assert!(
            whole.capacity() < original.len() * 2,
            "drain grew by doubling ({}) instead of by the observed ratio",
            whole.capacity()
        );

        // A consumed prefix is not part of what comes back.
        let mut r = InflateReader::with_chunk(&compressed, 1 << 24, 4096);
        assert!(r.ensure(100).unwrap());
        r.consume(100);
        assert_eq!(r.read_to_end().unwrap(), &original[100..]);
    }

    #[test]
    fn read_to_end_rejects_a_truncated_stream_and_the_max() {
        let original = varied(1024);
        let compressed = stored_zlib(&original);
        let truncated = &compressed[..compressed.len() - 300];
        let err = InflateReader::with_chunk(truncated, 64 * 1024, 256)
            .read_to_end()
            .unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);

        let err = InflateReader::with_chunk(&compressed, 512, 256)
            .read_to_end()
            .unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);

        assert_eq!(
            InflateReader::with_chunk(&compressed, 64 * 1024, 256)
                .read_to_end()
                .unwrap(),
            original
        );
    }

    /// A small chunk bounds the window for a stream of small records: the
    /// footprint of streaming a frame on a small heap is the chunk, not the
    /// decompressed size.
    #[test]
    #[cfg_attr(miri, ignore)]
    fn a_small_chunk_keeps_small_records_within_the_chunk() {
        const RECORD: usize = 100;
        const CHUNK: usize = 4096;
        let original = varied(RECORD * 2000);
        let compressed = zlib(&original);
        let mut r = InflateReader::with_chunk(&compressed, 1 << 24, CHUNK);
        for expected in original.chunks(RECORD) {
            assert!(r.ensure(expected.len()).unwrap());
            assert_eq!(&r.available()[..expected.len()], expected);
            r.consume(expected.len());
            assert!(
                r.buf.capacity() <= CHUNK,
                "window grew to {}",
                r.buf.capacity()
            );
        }
        assert!(!r.ensure(1).unwrap());
    }
}