Skip to main content

ntex/http/encoding/
decoder.rs

1use std::sync::atomic::{AtomicUsize, Ordering};
2use std::{collections::VecDeque, future::Future, io, pin::Pin, task::Context, task::Poll};
3
4use flate2::{Crc, Decompress, FlushDecompress, Status};
5use zstd::zstd_safe::{DCtx, DParameter, InBuffer, OutBuffer};
6
7use super::{Spare, offload, zstd_error};
8use crate::http::error::PayloadError;
9use crate::http::header::{CONTENT_ENCODING, ContentEncoding, HeaderMap};
10use crate::rt::BlockingResult;
11use crate::util::{BufMut, BytePageSize, Bytes, BytesMut, Stream};
12
13/// Decoders write into pages of this size, so decoded chunks are never larger.
14#[cfg(test)]
15const MAX_CHUNK_SIZE: usize = 32 * 1024;
16
17/// A blocking task stops decoding once its output reaches this size.
18///
19/// The output is kept in chunks of at most 32KiB, a single page.
20const MAX_TASK_OUTPUT: usize = 256 * 1024;
21
22/// The largest `zstd` window a decoder accepts, 8MiB as required by RFC 9659.
23const ZSTD_WINDOW_LOG_MAX: u32 = 23;
24
25/// Memory all `zstd` decoders of the process may use beyond `ZSTD_FREE_MEMORY` each.
26///
27/// RFC 9659 requires 8MiB windows, so a request can make its decoder allocate
28/// about 9MiB. A frame that would take the total over this limit is rejected.
29const ZSTD_MEMORY_LIMIT: usize = 512 * 1024 * 1024;
30
31/// Memory a `zstd` decoder uses without being counted, enough for a 512KiB window.
32const ZSTD_FREE_MEMORY: usize = 1024 * 1024;
33
34static ZSTD_MEMORY: ZstdMemory = ZstdMemory::new(ZSTD_MEMORY_LIMIT);
35
36/// Payload stream decoder.
37///
38/// Decompresses a stream of payload chunks. `gzip`, `deflate` and `zstd` are
39/// decoded; other encodings pass the stream through unchanged.
40#[derive(derive_more::Debug)]
41pub struct Decoder<S> {
42    #[debug(skip)]
43    inner: Option<ContentDecoder>,
44    stream: S,
45    eof: bool,
46    /// The stream is decoded
47    decode: bool,
48    /// Input that is not decoded yet
49    #[debug(skip)]
50    pending: Option<Bytes>,
51    /// Output of a blocking task that is not returned yet
52    #[debug(skip)]
53    ready: VecDeque<Bytes>,
54    #[debug(skip)]
55    fut: Option<BlockingResult<DecodeResult>>,
56}
57
58type DecodeResult = Result<(VecDeque<Bytes>, ContentDecoder, Bytes), io::Error>;
59
60impl<S> Decoder<S>
61where
62    S: Stream<Item = Result<Bytes, PayloadError>>,
63{
64    /// Construct a decoder for the given content encoding.
65    #[inline]
66    pub fn new(stream: S, encoding: ContentEncoding) -> Decoder<S> {
67        let inner = match encoding {
68            ContentEncoding::Deflate => {
69                Some(ContentDecoder::Flate(Box::new(FlateDecoder::new(false))))
70            }
71            ContentEncoding::Gzip => Some(ContentDecoder::Flate(Box::new(FlateDecoder::new(true)))),
72            ContentEncoding::Zstd => ZstdDecoder::new()
73                .inspect_err(|err| log::error!("Cannot create zstd decoder: {err}"))
74                .ok()
75                .map(|d| ContentDecoder::Zstd(Box::new(d))),
76            _ => None,
77        };
78        Decoder {
79            decode: inner.is_some(),
80            inner,
81            stream,
82            fut: None,
83            eof: false,
84            pending: None,
85            ready: VecDeque::new(),
86        }
87    }
88
89    /// Returns `true` if the stream is decoded.
90    pub(crate) fn is_decoding(&self) -> bool {
91        self.decode
92    }
93
94    /// Construct decoder based on the `Content-Encoding` header.
95    ///
96    /// A missing, invalid or unsupported header selects the `Identity`
97    /// encoding, the payload is passed through undecoded.
98    #[inline]
99    pub fn from_headers(stream: S, headers: &HeaderMap) -> Decoder<S> {
100        let encoding = headers
101            .get(&CONTENT_ENCODING)
102            .and_then(|enc| enc.to_str().ok()?.parse().ok())
103            .unwrap_or(ContentEncoding::Identity);
104        Self::new(stream, encoding)
105    }
106}
107
108impl<S> Stream for Decoder<S>
109where
110    S: Stream<Item = Result<Bytes, PayloadError>> + Unpin,
111{
112    type Item = Result<Bytes, PayloadError>;
113
114    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
115        let result = self.poll_decoded(cx);
116        if let Poll::Ready(Some(Err(_))) = result
117            && self.decode
118            && self.inner.is_none()
119        {
120            // the decoder state is lost, the stream must not continue with raw data
121            self.eof = true;
122            self.fut = None;
123            self.pending = None;
124        }
125        result
126    }
127}
128
129impl<S> Decoder<S>
130where
131    S: Stream<Item = Result<Bytes, PayloadError>> + Unpin,
132{
133    /// Puts the decoder back after a feed, with the input it left.
134    fn restore(&mut self, decoder: ContentDecoder, rest: Bytes) {
135        if !rest.is_empty() || decoder.has_more() {
136            self.pending = Some(rest);
137        }
138        self.inner = Some(decoder);
139    }
140
141    fn poll_decoded(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, PayloadError>>> {
142        loop {
143            if let Some(chunk) = self.ready.pop_front() {
144                return Poll::Ready(Some(Ok(chunk)));
145            }
146
147            if let Some(ref mut fut) = self.fut {
148                let (chunks, decoder, rest) = match Pin::new(fut).poll(cx) {
149                    Poll::Ready(Ok(Ok(item))) => item,
150                    Poll::Ready(Ok(Err(e))) => return Poll::Ready(Some(Err(e.into()))),
151                    Poll::Ready(Err(e)) => return Poll::Ready(Some(Err(e.into()))),
152                    Poll::Pending => return Poll::Pending,
153                };
154                self.fut = None;
155                self.restore(decoder, rest);
156                self.ready = chunks;
157                continue;
158            }
159
160            if let Some(mut data) = self.pending.take() {
161                let mut decoder = self.inner.take().unwrap();
162                if data.len() < decoder.limit() {
163                    let chunk = decoder.feed_data(&mut data)?;
164                    self.restore(decoder, data);
165                    if let Some(chunk) = chunk {
166                        return Poll::Ready(Some(Ok(chunk)));
167                    }
168                } else {
169                    self.fut = Some(offload(move || {
170                        let chunks = decoder.feed_task(&mut data)?;
171                        Ok((chunks, decoder, data))
172                    }));
173                }
174                continue;
175            }
176
177            if self.eof {
178                return Poll::Ready(None);
179            }
180
181            match Pin::new(&mut self.stream).poll_next(cx) {
182                Poll::Ready(Some(Err(err))) => return Poll::Ready(Some(Err(err))),
183                Poll::Ready(Some(Ok(chunk))) => {
184                    if self.inner.is_some() {
185                        if !chunk.is_empty() {
186                            self.pending = Some(chunk);
187                        }
188                        continue;
189                    }
190                    return Poll::Ready(Some(Ok(chunk)));
191                }
192                Poll::Ready(None) => {
193                    self.eof = true;
194                    if let Some(decoder) = self.inner.take() {
195                        decoder.finish()?;
196                    }
197                    return Poll::Ready(None);
198                }
199                Poll::Pending => return Poll::Pending,
200            }
201        }
202    }
203}
204
205enum ContentDecoder {
206    Flate(Box<FlateDecoder>),
207    Zstd(Box<ZstdDecoder>),
208}
209
210impl ContentDecoder {
211    /// Input of this size and larger is decoded on the blocking thread pool.
212    ///
213    /// A feed on the current thread decodes a single page of output, a task
214    /// on the pool decodes several pages, up to `MAX_TASK_OUTPUT`.
215    const fn limit(&self) -> usize {
216        match self {
217            ContentDecoder::Flate(_) => 128 * 1024,
218            ContentDecoder::Zstd(_) => 512 * 1024,
219        }
220    }
221
222    /// Returns `true` if decoded output is left without new input.
223    fn has_more(&self) -> bool {
224        match self {
225            ContentDecoder::Flate(decoder) => decoder.more,
226            ContentDecoder::Zstd(decoder) => decoder.more,
227        }
228    }
229
230    /// Checks that the compressed stream is complete.
231    fn finish(&self) -> io::Result<()> {
232        match self {
233            ContentDecoder::Flate(decoder) => decoder.finish(),
234            ContentDecoder::Zstd(decoder) => decoder.finish(),
235        }
236    }
237
238    /// Decodes `data` on a blocking task until the output reaches `MAX_TASK_OUTPUT`.
239    fn feed_task(&mut self, data: &mut Bytes) -> io::Result<VecDeque<Bytes>> {
240        let mut chunks = VecDeque::new();
241        let mut size = 0;
242        while size < MAX_TASK_OUTPUT && !data.is_empty() {
243            let Some(chunk) = self.feed_data(data)? else {
244                break;
245            };
246            size += chunk.len();
247            chunks.push_back(chunk);
248        }
249        Ok(chunks)
250    }
251
252    /// Decodes `data` until a page of output is full.
253    ///
254    /// Decoded input is removed from `data`.
255    fn feed_data(&mut self, data: &mut Bytes) -> io::Result<Option<Bytes>> {
256        match self {
257            ContentDecoder::Flate(decoder) => decoder.feed(data),
258            ContentDecoder::Zstd(decoder) => decoder.feed(data),
259        }
260    }
261}
262
263/// `deflate` (zlib) or `gzip` decoder.
264struct FlateDecoder {
265    inner: Decompress,
266    buf: BytesMut,
267    /// The `gzip` header and trailer, `None` for `deflate`
268    gzip: Option<Gzip>,
269    /// The compressed data is complete
270    done: bool,
271    /// The output buffer was filled, the decoder may hold more output
272    more: bool,
273}
274
275impl FlateDecoder {
276    fn new(gzip: bool) -> Self {
277        FlateDecoder {
278            inner: Decompress::new(!gzip),
279            buf: BytesMut::with_page_size(BytePageSize::Size32),
280            gzip: gzip.then(Gzip::new),
281            done: false,
282            more: false,
283        }
284    }
285
286    /// Decodes `data` until the output buffer is full.
287    fn feed(&mut self, data: &mut Bytes) -> io::Result<Option<Bytes>> {
288        if let Some(gzip) = &mut self.gzip
289            && !gzip.header(data)?
290        {
291            return Ok(None);
292        }
293
294        self.buf.reserve_more();
295        let start = self.buf.len();
296        while !self.done && self.buf.remaining_mut() > 0 && (!data.is_empty() || self.more) {
297            let (total_in, total_out) = (self.inner.total_in(), self.inner.total_out());
298            // SAFETY: the decoder only writes to the slice, and `advance_mut`
299            // covers just the bytes it has written
300            let status = unsafe {
301                let spare = self.buf.chunk_mut().as_uninit_slice_mut();
302                self.inner
303                    .decompress_uninit(data, spare, FlushDecompress::None)
304                    .map_err(invalid_data)?
305            };
306            let read = usize::try_from(self.inner.total_in() - total_in).unwrap();
307            let written = usize::try_from(self.inner.total_out() - total_out).unwrap();
308            // SAFETY: The decoder initialized `written` bytes in the spare chunk without reallocating it.
309            unsafe { self.buf.advance_mut(written) };
310            data.advance_to(read);
311
312            self.done = status == Status::StreamEnd;
313            self.more = !self.done && self.buf.remaining_mut() == 0;
314            if read == 0 && written == 0 {
315                break;
316            }
317        }
318
319        if let Some(gzip) = &mut self.gzip {
320            gzip.crc.update(&self.buf[start..]);
321            if self.done {
322                gzip.trailer(data)?;
323            }
324        }
325        if self.done && !data.is_empty() {
326            return Err(invalid_data("data after the end of the stream"));
327        }
328
329        Ok((!self.buf.is_empty()).then(|| self.buf.take()))
330    }
331
332    fn finish(&self) -> io::Result<()> {
333        if self.done
334            && self
335                .gzip
336                .as_ref()
337                .is_none_or(|gzip| gzip.state == GzState::Done)
338        {
339            Ok(())
340        } else {
341            Err(io::Error::new(
342                io::ErrorKind::UnexpectedEof,
343                "compressed stream is incomplete",
344            ))
345        }
346    }
347}
348
349const FHCRC: u8 = 0x02;
350const FEXTRA: u8 = 0x04;
351const FNAME: u8 = 0x08;
352const FCOMMENT: u8 = 0x10;
353const FRESERVED: u8 = 0xe0;
354
355#[derive(Copy, Clone, Debug, PartialEq, Eq)]
356enum GzState {
357    Header,
358    ExtraLen,
359    Extra(usize),
360    Name,
361    Comment,
362    HeaderCrc,
363    Body,
364    Trailer,
365    Done,
366}
367
368/// Parser of the `gzip` member header and trailer, RFC 1952.
369///
370/// The optional header fields are skipped. Like most decoders, only a single
371/// member is accepted.
372struct Gzip {
373    state: GzState,
374    flags: u8,
375    /// Checksum of the header
376    header_crc: Crc,
377    /// Checksum and size of the decoded data
378    crc: Crc,
379    buf: [u8; 10],
380    len: usize,
381}
382
383impl Gzip {
384    fn new() -> Self {
385        Gzip {
386            state: GzState::Header,
387            flags: 0,
388            header_crc: Crc::new(),
389            crc: Crc::new(),
390            buf: [0; 10],
391            len: 0,
392        }
393    }
394
395    /// Moves up to `n` bytes of `data` to `buf`, returns `true` once it holds `n` bytes.
396    fn fill(&mut self, data: &mut Bytes, n: usize) -> bool {
397        let size = (n - self.len).min(data.len());
398        self.buf[self.len..self.len + size].copy_from_slice(&data[..size]);
399        self.len += size;
400        data.advance_to(size);
401        self.len == n
402    }
403
404    /// Moves to `state`, the bytes of the previous field are dropped.
405    fn next(&mut self, state: GzState) {
406        self.state = state;
407        self.len = 0;
408    }
409
410    /// Parses the header, returns `true` once it is complete.
411    fn header(&mut self, data: &mut Bytes) -> io::Result<bool> {
412        loop {
413            match self.state {
414                GzState::Header => {
415                    if !self.fill(data, 10) {
416                        return Ok(false);
417                    }
418                    let [id1, id2, method, flags, ..] = self.buf;
419                    if id1 != 0x1f || id2 != 0x8b {
420                        return Err(invalid_data("invalid gzip header"));
421                    }
422                    if method != 8 || flags & FRESERVED != 0 {
423                        return Err(invalid_data("unsupported gzip header"));
424                    }
425                    self.flags = flags;
426                    self.header_crc.update(&self.buf);
427                    self.next(GzState::ExtraLen);
428                }
429                GzState::ExtraLen if self.flags & FEXTRA == 0 => self.next(GzState::Name),
430                GzState::ExtraLen => {
431                    if !self.fill(data, 2) {
432                        return Ok(false);
433                    }
434                    let len = [self.buf[0], self.buf[1]];
435                    self.header_crc.update(&len);
436                    self.next(GzState::Extra(u16::from_le_bytes(len).into()));
437                }
438                GzState::Extra(len) => {
439                    let size = len.min(data.len());
440                    self.header_crc.update(&data[..size]);
441                    data.advance_to(size);
442                    if size < len {
443                        self.state = GzState::Extra(len - size);
444                        return Ok(false);
445                    }
446                    self.next(GzState::Name);
447                }
448                GzState::Name if self.flags & FNAME == 0 => self.next(GzState::Comment),
449                GzState::Comment if self.flags & FCOMMENT == 0 => self.next(GzState::HeaderCrc),
450                GzState::Name | GzState::Comment => {
451                    // a zero-terminated string
452                    let Some(end) = data.iter().position(|b| *b == 0) else {
453                        self.header_crc.update(data);
454                        data.advance_to(data.len());
455                        return Ok(false);
456                    };
457                    self.header_crc.update(&data[..=end]);
458                    data.advance_to(end + 1);
459                    self.next(if self.state == GzState::Name {
460                        GzState::Comment
461                    } else {
462                        GzState::HeaderCrc
463                    });
464                }
465                GzState::HeaderCrc if self.flags & FHCRC == 0 => self.next(GzState::Body),
466                GzState::HeaderCrc => {
467                    if !self.fill(data, 2) {
468                        return Ok(false);
469                    }
470                    // the low 16 bits of the crc32
471                    let crc = u16::from_le_bytes([self.buf[0], self.buf[1]]);
472                    if u32::from(crc) != self.header_crc.sum() & 0xffff {
473                        return Err(invalid_data("gzip header checksum mismatch"));
474                    }
475                    self.next(GzState::Body);
476                }
477                GzState::Body | GzState::Trailer | GzState::Done => return Ok(true),
478            }
479        }
480    }
481
482    /// Checks the trailer after the compressed data, the crc32 and size of the output.
483    fn trailer(&mut self, data: &mut Bytes) -> io::Result<()> {
484        if self.state == GzState::Body {
485            self.next(GzState::Trailer);
486        }
487        if self.state == GzState::Trailer && self.fill(data, 8) {
488            let [c0, c1, c2, c3, s0, s1, s2, s3, ..] = self.buf;
489            if u32::from_le_bytes([c0, c1, c2, c3]) != self.crc.sum() {
490                return Err(invalid_data("gzip checksum mismatch"));
491            }
492            // the size modulo 2^32
493            if u32::from_le_bytes([s0, s1, s2, s3]) != self.crc.amount() {
494                return Err(invalid_data("gzip size mismatch"));
495            }
496            self.next(GzState::Done);
497        }
498        Ok(())
499    }
500}
501
502fn invalid_data<E>(err: E) -> io::Error
503where
504    E: Into<Box<dyn std::error::Error + Send + Sync>>,
505{
506    io::Error::new(io::ErrorKind::InvalidData, err)
507}
508
509/// Memory used by `zstd` decoders.
510struct ZstdMemory {
511    used: AtomicUsize,
512    limit: usize,
513}
514
515impl ZstdMemory {
516    const fn new(limit: usize) -> Self {
517        ZstdMemory {
518            used: AtomicUsize::new(0),
519            limit,
520        }
521    }
522
523    fn acquire(&self, size: usize) -> io::Result<()> {
524        self.used
525            .try_update(Ordering::AcqRel, Ordering::Acquire, |used| {
526                used.checked_add(size).filter(|total| *total <= self.limit)
527            })
528            .map(|_| ())
529            .map_err(|_| {
530                io::Error::new(
531                    io::ErrorKind::OutOfMemory,
532                    "zstd decoders memory limit is reached",
533                )
534            })
535    }
536
537    fn release(&self, size: usize) {
538        self.used.fetch_sub(size, Ordering::AcqRel);
539    }
540}
541
542struct ZstdDecoder {
543    ctx: DCtx<'static>,
544    buf: BytesMut,
545    memory: &'static ZstdMemory,
546    /// Memory counted in `memory`
547    charged: usize,
548    /// The last frame is complete
549    done: bool,
550    /// The output buffer was filled, the decoder may hold more output
551    more: bool,
552}
553
554impl ZstdDecoder {
555    fn new() -> io::Result<Self> {
556        Self::with_memory(&ZSTD_MEMORY)
557    }
558
559    fn with_memory(memory: &'static ZstdMemory) -> io::Result<Self> {
560        let mut ctx = DCtx::try_create().ok_or(io::ErrorKind::OutOfMemory)?;
561        ctx.set_parameter(DParameter::WindowLogMax(ZSTD_WINDOW_LOG_MAX))
562            .map_err(zstd_error)?;
563        Ok(ZstdDecoder {
564            ctx,
565            memory,
566            charged: 0,
567            buf: BytesMut::with_page_size(BytePageSize::Size32),
568            done: false,
569            more: false,
570        })
571    }
572
573    /// Decodes `data` until the output buffer is full.
574    fn feed(&mut self, data: &mut Bytes) -> io::Result<Option<Bytes>> {
575        self.buf.reserve_more();
576        while self.buf.remaining_mut() > 0 && (!data.is_empty() || self.more) {
577            let mut src = InBuffer::around(data);
578            let mut spare = Spare::new(&mut self.buf);
579            let mut dst = OutBuffer::around(&mut spare);
580            // a new frame starts automatically after the previous one is complete
581            let hint = self
582                .ctx
583                .decompress_stream(&mut dst, &mut src)
584                .map_err(zstd_error)?;
585            let (read, written) = (src.pos(), dst.pos());
586            self.charge()?;
587            self.more = self.buf.remaining_mut() == 0;
588            if read == 0 && written == 0 {
589                break;
590            }
591            self.done = hint == 0;
592            data.advance_to(read);
593        }
594        Ok((!self.buf.is_empty()).then(|| self.buf.take()))
595    }
596
597    /// Counts the memory of the context, it grows with the window of a frame.
598    fn charge(&mut self) -> io::Result<()> {
599        let size = self.ctx.sizeof().saturating_sub(ZSTD_FREE_MEMORY);
600        if size > self.charged {
601            self.memory.acquire(size - self.charged)?;
602        } else {
603            self.memory.release(self.charged - size);
604        }
605        self.charged = size;
606        Ok(())
607    }
608
609    fn finish(&self) -> io::Result<()> {
610        if self.done {
611            Ok(())
612        } else {
613            Err(io::Error::new(
614                io::ErrorKind::UnexpectedEof,
615                "zstd stream is incomplete",
616            ))
617        }
618    }
619}
620
621impl Drop for ZstdDecoder {
622    fn drop(&mut self) {
623        self.memory.release(self.charged);
624    }
625}
626
627#[cfg(test)]
628mod tests {
629    use std::io::Write;
630
631    use flate2::{Compression, write::GzEncoder, write::ZlibEncoder};
632    use futures_util::stream::{self, StreamExt};
633
634    use super::*;
635
636    const BOMB_SIZE: usize = 4 * 1024 * 1024;
637
638    fn bomb(encoding: ContentEncoding) -> Vec<u8> {
639        let data = vec![0u8; BOMB_SIZE];
640        if encoding == ContentEncoding::Gzip {
641            let mut e = GzEncoder::new(Vec::new(), Compression::best());
642            e.write_all(&data).unwrap();
643            e.finish().unwrap()
644        } else {
645            let mut e = ZlibEncoder::new(Vec::new(), Compression::best());
646            e.write_all(&data).unwrap();
647            e.finish().unwrap()
648        }
649    }
650
651    /// STATEMENT: Gzip and deflate expansion produces bounded chunks even from highly compressible input.
652    ///
653    /// HOW:
654    /// - Decode a multi-megabyte zero payload using whole and split compressed inputs.
655    /// - Verify every output byte, total decoded length, and maximum emitted chunk size.
656    #[crate::rt_test]
657    async fn decoded_chunks_are_bounded() {
658        for encoding in [ContentEncoding::Gzip, ContentEncoding::Deflate] {
659            let compressed = bomb(encoding);
660            assert!(compressed.len() < 32 * 1024);
661
662            for size in [compressed.len(), 2048] {
663                let chunks: Vec<_> = compressed
664                    .chunks(size)
665                    .map(|c| Ok::<_, PayloadError>(Bytes::copy_from_slice(c)))
666                    .collect();
667                let mut decoder = Decoder::new(stream::iter(chunks), encoding);
668
669                let mut total = 0;
670                let mut max = 0;
671                while let Some(chunk) = decoder.next().await {
672                    let chunk = chunk.unwrap();
673                    assert!(chunk.iter().all(|b| *b == 0));
674                    max = max.max(chunk.len());
675                    total += chunk.len();
676                }
677                assert_eq!(total, BOMB_SIZE);
678                assert!(max <= MAX_CHUNK_SIZE, "{encoding:?} chunk of {max} bytes");
679            }
680        }
681    }
682
683    /// STATEMENT: A failed content decoder ends instead of passing through later input.
684    ///
685    /// HOW:
686    /// - Feed invalid gzip followed by raw bytes and check one error followed by EOF.
687    #[crate::rt_test]
688    async fn decoder_is_fused_after_error() {
689        let chunks = vec![
690            Ok::<_, PayloadError>(Bytes::from_static(b"not gzip data")),
691            Ok(Bytes::from_static(b"raw")),
692        ];
693        let mut decoder = Decoder::new(stream::iter(chunks), ContentEncoding::Gzip);
694        assert!(matches!(decoder.next().await, Some(Err(_))));
695        assert!(decoder.next().await.is_none());
696    }
697
698    /// STATEMENT: An unparseable or unsupported content-encoding header leaves input undecoded.
699    ///
700    /// HOW:
701    /// - Construct decoders from non-text, misspelled, unsupported and combined
702    ///   encoding headers and verify raw bytes, disabled decoding, and EOF.
703    /// - Construct a decoder from a supported `GZip` header and verify decoding is enabled.
704    #[crate::rt_test]
705    async fn decoder_from_headers() {
706        use crate::http::header::HeaderValue;
707
708        for value in [&b"gzip\xff"[..], b"gizp", b"compress", b"gzip, br", b""] {
709            let mut headers = HeaderMap::new();
710            headers.insert(CONTENT_ENCODING, HeaderValue::from_bytes(value).unwrap());
711            let chunks = vec![Ok::<_, PayloadError>(Bytes::from_static(b"raw"))];
712            let mut decoder = Decoder::from_headers(stream::iter(chunks), &headers);
713            assert!(!decoder.is_decoding(), "{value:?}");
714            assert_eq!(decoder.next().await.unwrap().unwrap(), "raw");
715            assert!(decoder.next().await.is_none());
716        }
717
718        let mut headers = HeaderMap::new();
719        headers.insert(CONTENT_ENCODING, HeaderValue::from_static("GZip"));
720        let decoder = Decoder::from_headers(stream::iter(Vec::new()), &headers);
721        assert!(decoder.is_decoding());
722    }
723
724    /// STATEMENT: Large invalid input fails through the blocking decoder and then ends the stream.
725    ///
726    /// HOW:
727    /// - Decode a large invalid deflate chunk and check the error, fused EOF, and exactly one offloaded task.
728    #[crate::rt_test]
729    async fn decoder_error_on_blocking_pool() {
730        let before = super::super::offloaded();
731        let chunks = vec![Ok::<_, PayloadError>(Bytes::from(vec![b'x'; 256 * 1024]))];
732        let mut decoder = Decoder::new(stream::iter(chunks), ContentEncoding::Deflate);
733        assert!(matches!(decoder.next().await, Some(Err(_))));
734        assert!(decoder.next().await.is_none());
735        assert_eq!(super::super::offloaded(), before + 1);
736    }
737
738    /// STATEMENT: A canceled blocking decoder reports an error and cannot expose pending or subsequent raw input.
739    ///
740    /// HOW:
741    /// - Inject a panicking decode task with pending bytes and another unread source chunk.
742    /// - Verify one I/O error, cleared pending work, and repeated EOF.
743    #[crate::rt_test]
744    async fn decoder_blocking_task_canceled() {
745        let chunks = vec![Ok::<_, PayloadError>(Bytes::from_static(b"raw source"))];
746        let mut decoder = Decoder::new(stream::iter(chunks), ContentEncoding::Gzip);
747        decoder.inner = None;
748        decoder.pending = Some(Bytes::from_static(b"pending input"));
749        decoder.fut = Some(crate::rt::spawn_blocking(|| panic!("decoder panic")));
750
751        assert!(matches!(
752            decoder.next().await,
753            Some(Err(PayloadError::Io(_)))
754        ));
755        assert!(decoder.pending.is_none());
756        assert!(decoder.fut.is_none());
757        assert!(decoder.next().await.is_none());
758        assert!(decoder.next().await.is_none());
759    }
760
761    fn compress(encoding: ContentEncoding, data: &[u8]) -> Vec<u8> {
762        match encoding {
763            ContentEncoding::Gzip => {
764                let mut e = GzEncoder::new(Vec::new(), Compression::fast());
765                e.write_all(data).unwrap();
766                e.finish().unwrap()
767            }
768            ContentEncoding::Deflate => {
769                let mut e = ZlibEncoder::new(Vec::new(), Compression::fast());
770                e.write_all(data).unwrap();
771                e.finish().unwrap()
772            }
773            ContentEncoding::Zstd => zstd::encode_all(data, 0).unwrap(),
774            _ => unreachable!(),
775        }
776    }
777
778    async fn decode(
779        encoding: ContentEncoding,
780        chunks: Vec<Bytes>,
781    ) -> Result<Vec<u8>, PayloadError> {
782        let chunks = chunks.into_iter().map(Ok::<_, PayloadError>);
783        let mut decoder = Decoder::new(stream::iter(chunks), encoding);
784        let mut out = Vec::new();
785        while let Some(chunk) = decoder.next().await {
786            let chunk = chunk?;
787            assert!(!chunk.is_empty());
788            assert!(chunk.len() <= MAX_CHUNK_SIZE);
789            out.extend_from_slice(&chunk);
790        }
791        Ok(out)
792    }
793
794    /// Incompressible data, so the compressed size is close to `len`.
795    fn random(len: usize) -> Vec<u8> {
796        let mut x = 0x2545_f491_4f6c_dd1d_u64;
797        (0..len)
798            .map(|_| {
799                x ^= x << 13;
800                x ^= x >> 7;
801                x ^= x << 17;
802                x as u8
803            })
804            .collect()
805    }
806
807    /// STATEMENT: Decoder offloading begins at each encoding's input threshold while smaller chunks stay inline.
808    ///
809    /// HOW:
810    /// - Decode incompressible data in below-threshold and threshold-sized chunks for each encoding.
811    /// - Compare round-trip bytes and exact changes in offloaded-task counts.
812    #[crate::rt_test]
813    async fn decoder_offloads_large_input() {
814        for (encoding, limit) in [
815            (ContentEncoding::Gzip, 128 * 1024),
816            (ContentEncoding::Deflate, 128 * 1024),
817            (ContentEncoding::Zstd, 512 * 1024),
818        ] {
819            let data = random(limit + 1024);
820            let compressed = compress(encoding, &data);
821            assert!(compressed.len() > limit);
822
823            // input below the limit is decoded in place
824            let before = super::super::offloaded();
825            let chunks = compressed
826                .chunks(limit - 1)
827                .map(Bytes::copy_from_slice)
828                .collect();
829            assert_eq!(decode(encoding, chunks).await.unwrap(), data);
830            assert_eq!(super::super::offloaded(), before, "{encoding:?}");
831
832            // the first feed of a larger chunk is offloaded
833            let chunks = compressed[..limit]
834                .chunks(limit)
835                .chain(compressed[limit..].chunks(limit))
836                .map(Bytes::copy_from_slice)
837                .collect();
838            assert_eq!(decode(encoding, chunks).await.unwrap(), data);
839            assert_eq!(super::super::offloaded(), before + 1, "{encoding:?}");
840        }
841    }
842
843    /// STATEMENT: Zstd decoding supports varied input fragmentation and concatenated frames.
844    ///
845    /// HOW:
846    /// - Decode a large payload with bytewise through whole-frame chunks, then decode two concatenated frames.
847    /// - Compare reconstructed bytes with the original payloads.
848    #[crate::rt_test]
849    async fn zstd_decoder() {
850        let data = random(300 * 1024);
851        let compressed = zstd::encode_all(&data[..], 0).unwrap();
852        for size in [1, 100, 64 * 1024, compressed.len()] {
853            let chunks = compressed
854                .chunks(size)
855                .map(Bytes::copy_from_slice)
856                .collect();
857            assert_eq!(decode(ContentEncoding::Zstd, chunks).await.unwrap(), data);
858        }
859
860        // concatenated frames
861        let mut frames = zstd::encode_all(&b"hello "[..], 0).unwrap();
862        frames.extend(zstd::encode_all(&b"world"[..], 0).unwrap());
863        let out = decode(ContentEncoding::Zstd, vec![Bytes::from(frames)]).await;
864        assert_eq!(out.unwrap(), b"hello world");
865    }
866
867    /// STATEMENT: Zstd releases already-decoded block output without waiting for more compressed input.
868    ///
869    /// HOW:
870    /// - Find a complete-block boundary, provide only that prefix, and leave the input stream pending.
871    /// - Read bounded output under a timeout and compare all bytes available from the completed block.
872    #[crate::rt_test]
873    async fn zstd_decoder_drains_output_without_input() {
874        use zstd::stream::raw::Operation;
875
876        let data = b"hello world ".repeat(50_000);
877        let compressed = zstd::encode_all(&data[..], 0).unwrap();
878
879        // find the input byte that completes the first block
880        let mut raw = zstd::stream::raw::Decoder::new().unwrap();
881        let mut out = vec![0; data.len()];
882        let mut pos = 0;
883        let mut split = 0;
884        for (i, b) in compressed.iter().enumerate() {
885            let mut src = InBuffer::around(std::slice::from_ref(b));
886            let mut dst = OutBuffer::around_pos(&mut out[..], pos);
887            raw.run(&mut src, &mut dst).unwrap();
888            if dst.pos() - pos > MAX_CHUNK_SIZE {
889                pos = dst.pos();
890                split = i + 1;
891                break;
892            }
893            pos = dst.pos();
894        }
895        assert!(split > 0 && split < compressed.len());
896
897        // the stream stalls after the block, its output must not wait for more input
898        let chunks = compressed[..split]
899            .chunks(1)
900            .map(|c| Ok::<_, PayloadError>(Bytes::copy_from_slice(c)))
901            .collect::<Vec<_>>();
902        let stream = stream::iter(chunks).chain(stream::pending());
903        let mut decoder = Decoder::new(stream, ContentEncoding::Zstd);
904
905        let mut decoded = Vec::new();
906        while decoded.len() < pos {
907            let chunk = crate::time::timeout(crate::time::Millis(5_000), decoder.next())
908                .await
909                .expect("decoder is stuck")
910                .unwrap()
911                .unwrap();
912            assert!(chunk.len() <= MAX_CHUNK_SIZE);
913            decoded.extend_from_slice(&chunk);
914        }
915        assert_eq!(decoded, data[..pos]);
916    }
917
918    /// STATEMENT: Highly compressed Zstd input cannot produce unbounded output chunks.
919    ///
920    /// HOW:
921    /// - Decode a multi-megabyte zero payload from bytewise and whole-frame input.
922    /// - Check chunk bounds, contents, and total output length.
923    #[crate::rt_test]
924    async fn zstd_decoded_chunks_are_bounded() {
925        let compressed = zstd::encode_all(&vec![0u8; BOMB_SIZE][..], 19).unwrap();
926        assert!(compressed.len() < 1024);
927
928        for size in [1, compressed.len()] {
929            let chunks: Vec<_> = compressed
930                .chunks(size)
931                .map(|c| Ok::<_, PayloadError>(Bytes::copy_from_slice(c)))
932                .collect();
933            let mut decoder = Decoder::new(stream::iter(chunks), ContentEncoding::Zstd);
934            let mut total = 0;
935            while let Some(chunk) = decoder.next().await {
936                let chunk = chunk.unwrap();
937                assert!(chunk.iter().all(|b| *b == 0));
938                assert!(chunk.len() <= BytePageSize::Size32.capacity());
939                total += chunk.len();
940            }
941            assert_eq!(total, BOMB_SIZE);
942        }
943    }
944
945    /// STATEMENT: Zstd rejects incomplete, corrupt, and over-window-limit frames while accepting the maximum permitted window.
946    ///
947    /// HOW:
948    /// - Decode truncated, empty, corrupt, 16 MiB-window, and 8 MiB-window inputs.
949    /// - Verify errors for the invalid cases and correct data at the accepted limit.
950    #[crate::rt_test]
951    async fn zstd_decoder_errors() {
952        let compressed = zstd::encode_all(&random(1024)[..], 0).unwrap();
953
954        // truncated
955        let chunks = vec![Bytes::copy_from_slice(&compressed[..compressed.len() - 4])];
956        assert!(decode(ContentEncoding::Zstd, chunks).await.is_err());
957
958        // empty body
959        assert!(decode(ContentEncoding::Zstd, vec![]).await.is_err());
960
961        // corrupted
962        let out = decode(ContentEncoding::Zstd, vec![Bytes::from_static(b"not zstd")]).await;
963        assert!(out.is_err());
964
965        // a window above 8MiB
966        let mut e = zstd::stream::write::Encoder::new(Vec::new(), 0).unwrap();
967        e.set_parameter(zstd::stream::raw::CParameter::WindowLog(24))
968            .unwrap();
969        e.write_all(b"hello").unwrap();
970        let large = e.finish().unwrap();
971        let out = decode(ContentEncoding::Zstd, vec![Bytes::from(large)]).await;
972        assert!(out.is_err());
973
974        // the same window size is accepted at 8MiB
975        let mut e = zstd::stream::write::Encoder::new(Vec::new(), 0).unwrap();
976        e.set_parameter(zstd::stream::raw::CParameter::WindowLog(23))
977            .unwrap();
978        e.write_all(b"hello").unwrap();
979        let ok = e.finish().unwrap();
980        let out = decode(ContentEncoding::Zstd, vec![Bytes::from(ok)]).await;
981        assert_eq!(out.unwrap(), b"hello");
982    }
983
984    /// A frame with an unknown content size, its decoder allocates the whole window.
985    fn zstd_frame(window_log: u32, data: &[u8]) -> Vec<u8> {
986        let mut e = zstd::stream::write::Encoder::new(Vec::new(), 0).unwrap();
987        e.set_parameter(zstd::stream::raw::CParameter::WindowLog(window_log))
988            .unwrap();
989        e.write_all(data).unwrap();
990        e.finish().unwrap()
991    }
992
993    fn zstd_feed(decoder: &mut ZstdDecoder, frame: &[u8]) -> io::Result<Vec<u8>> {
994        let mut data = Bytes::copy_from_slice(frame);
995        let mut out = Vec::new();
996        while !data.is_empty() || decoder.more {
997            if let Some(chunk) = decoder.feed(&mut data)? {
998                out.extend_from_slice(&chunk);
999            }
1000        }
1001        Ok(out)
1002    }
1003
1004    /// STATEMENT: Shared Zstd memory accounting limits large windows and makes released capacity reusable.
1005    ///
1006    /// HOW:
1007    /// - Allocate two large decoders, reject a third, and verify small windows are uncharged.
1008    /// - Drop a large decoder, retry allocation, and check all charges clear after final drops.
1009    #[test]
1010    fn zstd_decoder_memory_is_limited() {
1011        static MEMORY: ZstdMemory = ZstdMemory::new(20 * 1024 * 1024);
1012
1013        let large = zstd_frame(23, b"hello");
1014        let mut first = ZstdDecoder::with_memory(&MEMORY).unwrap();
1015        assert_eq!(zstd_feed(&mut first, &large).unwrap(), b"hello");
1016        let charged = first.charged;
1017        assert!(charged > 7 * 1024 * 1024, "{charged}");
1018        assert_eq!(MEMORY.used.load(Ordering::Acquire), charged);
1019
1020        let mut second = ZstdDecoder::with_memory(&MEMORY).unwrap();
1021        assert_eq!(zstd_feed(&mut second, &large).unwrap(), b"hello");
1022        assert_eq!(MEMORY.used.load(Ordering::Acquire), 2 * charged);
1023
1024        // the third decoder is over the limit
1025        let mut third = ZstdDecoder::with_memory(&MEMORY).unwrap();
1026        let err = zstd_feed(&mut third, &large).unwrap_err();
1027        assert_eq!(err.kind(), io::ErrorKind::OutOfMemory);
1028        drop(third);
1029        assert_eq!(MEMORY.used.load(Ordering::Acquire), 2 * charged);
1030
1031        // small windows are not counted
1032        let mut small = ZstdDecoder::with_memory(&MEMORY).unwrap();
1033        assert_eq!(
1034            zstd_feed(&mut small, &zstd_frame(19, b"hi")).unwrap(),
1035            b"hi"
1036        );
1037        assert_eq!(small.charged, 0);
1038
1039        // memory of a dropped decoder is available again
1040        drop(first);
1041        assert_eq!(MEMORY.used.load(Ordering::Acquire), charged);
1042        let mut third = ZstdDecoder::with_memory(&MEMORY).unwrap();
1043        assert_eq!(zstd_feed(&mut third, &large).unwrap(), b"hello");
1044        drop((second, third));
1045        assert_eq!(MEMORY.used.load(Ordering::Acquire), 0);
1046    }
1047
1048    /// STATEMENT: Zstd releases the accounting charge when repeated small frames shrink an oversized window.
1049    ///
1050    /// HOW:
1051    /// - Decode one large-window frame followed by many small-window frames and check both decoder and shared charges clear.
1052    #[test]
1053    fn zstd_decoder_memory_shrinks() {
1054        static MEMORY: ZstdMemory = ZstdMemory::new(20 * 1024 * 1024);
1055
1056        // zstd frees an oversized window after it was unused for a number of frames
1057        let mut decoder = ZstdDecoder::with_memory(&MEMORY).unwrap();
1058        zstd_feed(&mut decoder, &zstd_frame(23, b"hello")).unwrap();
1059        assert!(decoder.charged > 0);
1060        let small = zstd_frame(10, b"hi");
1061        for _ in 0..256 {
1062            zstd_feed(&mut decoder, &small).unwrap();
1063        }
1064        assert_eq!(decoder.charged, 0);
1065        assert_eq!(MEMORY.used.load(Ordering::Acquire), 0);
1066    }
1067
1068    /// STATEMENT: A Zstd memory-budget failure ends decoding and releases its accounting charge.
1069    ///
1070    /// HOW:
1071    /// - Decode a large-window frame with an insufficient shared budget.
1072    /// - Verify one stream error, subsequent EOF, and zero remaining memory usage.
1073    #[crate::rt_test]
1074    async fn zstd_decoder_memory_error() {
1075        static MEMORY: ZstdMemory = ZstdMemory::new(1024 * 1024);
1076
1077        let chunks = vec![Ok::<_, PayloadError>(Bytes::from(zstd_frame(23, b"hello")))];
1078        let mut decoder = Decoder {
1079            inner: Some(ContentDecoder::Zstd(Box::new(
1080                ZstdDecoder::with_memory(&MEMORY).unwrap(),
1081            ))),
1082            stream: stream::iter(chunks),
1083            eof: false,
1084            decode: true,
1085            pending: None,
1086            ready: VecDeque::new(),
1087            fut: None,
1088        };
1089        assert!(matches!(decoder.next().await, Some(Err(_))));
1090        assert!(decoder.next().await.is_none());
1091        assert_eq!(MEMORY.used.load(Ordering::Acquire), 0);
1092    }
1093
1094    /// STATEMENT: Blocking decode work is split according to its output budget.
1095    ///
1096    /// HOW:
1097    /// - Decode large incompressible gzip and Zstd inputs and compare reconstructed bytes.
1098    /// - Check offloaded-task counts fall within the expected output-budget range.
1099    #[crate::rt_test]
1100    async fn decoder_task_output() {
1101        for (encoding, limit) in [
1102            (ContentEncoding::Gzip, 128 * 1024),
1103            (ContentEncoding::Zstd, 512 * 1024),
1104        ] {
1105            let data = random(2 * 1024 * 1024);
1106            let compressed = compress(encoding, &data);
1107            let before = super::super::offloaded();
1108            let chunks = vec![Bytes::from(compressed)];
1109            assert_eq!(decode(encoding, chunks).await.unwrap(), data);
1110
1111            // each task decodes MAX_TASK_OUTPUT, the rest below the limit in place
1112            let tasks = super::super::offloaded() - before;
1113            let expected = (data.len() - limit).div_ceil(MAX_TASK_OUTPUT);
1114            assert!(
1115                (expected - 1..=expected).contains(&tasks),
1116                "{encoding:?} {tasks}"
1117            );
1118        }
1119    }
1120
1121    /// STATEMENT: A gzip stream missing its trailer reports an error rather than clean completion.
1122    ///
1123    /// HOW:
1124    /// - Remove the last four compressed bytes, consume the decoder, and verify an error was emitted.
1125    #[crate::rt_test]
1126    async fn decoder_truncated_stream() {
1127        let mut e = GzEncoder::new(Vec::new(), Compression::fast());
1128        e.write_all(b"hello world").unwrap();
1129        let data = e.finish().unwrap();
1130
1131        let chunks = vec![Ok::<_, PayloadError>(Bytes::copy_from_slice(
1132            &data[..data.len() - 4],
1133        ))];
1134        let mut decoder = Decoder::new(stream::iter(chunks), ContentEncoding::Gzip);
1135        let mut result = Ok(());
1136        while let Some(chunk) = decoder.next().await {
1137            if let Err(e) = chunk {
1138                result = Err(e);
1139            }
1140        }
1141        assert!(result.is_err());
1142    }
1143
1144    fn bytewise(data: &[u8]) -> Vec<Bytes> {
1145        data.chunks(1).map(Bytes::copy_from_slice).collect()
1146    }
1147
1148    /// A gzip member with all optional header fields, the header crc is at `len - 2`.
1149    fn gzip_header(flags: u8) -> Vec<u8> {
1150        let mut header = vec![0x1f, 0x8b, 8, flags, 1, 2, 3, 4, 0, 255];
1151        header.extend([3, 0, b'a', b'b', b'c']);
1152        header.extend(b"name\0comment\0");
1153        let mut crc = flate2::Crc::new();
1154        crc.update(&header);
1155        header.extend((crc.sum() as u16).to_le_bytes());
1156        header
1157    }
1158
1159    /// STATEMENT: Gzip optional headers support fragmented input while validating CRC, magic, method, and reserved flags.
1160    ///
1161    /// HOW:
1162    /// - Decode a member with all optional fields as a whole and bytewise.
1163    /// - Corrupt each checked header component and verify decoding fails.
1164    #[crate::rt_test]
1165    async fn gzip_decoder_header() {
1166        let data = random(4096);
1167        let body = &compress(ContentEncoding::Gzip, &data)[10..];
1168        let mut full = gzip_header(0x1e);
1169        full.extend(body);
1170        for chunks in [vec![Bytes::from(full.clone())], bytewise(&full)] {
1171            assert_eq!(decode(ContentEncoding::Gzip, chunks).await.unwrap(), data);
1172        }
1173
1174        // header crc, magic, method and reserved flags
1175        let crc = gzip_header(0x1e).len() - 2;
1176        for (pos, flip) in [(crc, 1), (0, 1), (1, 1), (2, 1), (3, 0x20), (3, 0x80)] {
1177            let mut bad = full.clone();
1178            bad[pos] ^= flip;
1179            let out = decode(ContentEncoding::Gzip, vec![Bytes::from(bad)]).await;
1180            assert!(out.is_err(), "{pos} {flip}");
1181        }
1182    }
1183
1184    /// STATEMENT: Gzip and deflate reject trailing data, checksum corruption, and truncated streams.
1185    ///
1186    /// HOW:
1187    /// - Verify bytewise round trips, then mutate checksums, append bytes, and truncate at several boundaries.
1188    /// - Check each malformed input reports an error.
1189    #[crate::rt_test]
1190    async fn flate_decoder_errors() {
1191        let data = random(4096);
1192        for encoding in [ContentEncoding::Gzip, ContentEncoding::Deflate] {
1193            let compressed = compress(encoding, &data);
1194            let len = compressed.len();
1195            assert_eq!(decode(encoding, bytewise(&compressed)).await.unwrap(), data);
1196
1197            let mut trailing = compressed.clone();
1198            trailing.push(0);
1199            let out = decode(encoding, vec![Bytes::from(trailing)]).await;
1200            assert!(out.is_err(), "{encoding:?} trailing data");
1201
1202            // checksums
1203            for pos in [len - 1, len - 5] {
1204                let mut bad = compressed.clone();
1205                bad[pos] ^= 1;
1206                let out = decode(encoding, vec![Bytes::from(bad)]).await;
1207                assert!(out.is_err(), "{encoding:?} {pos}");
1208            }
1209
1210            for n in [0, 1, 11, len - 1] {
1211                let chunks = vec![Bytes::copy_from_slice(&compressed[..n])];
1212                let out = decode(encoding, chunks).await;
1213                assert!(out.is_err(), "{encoding:?} truncated to {n}");
1214            }
1215        }
1216    }
1217
1218    /// STATEMENT: Gzip and deflate decode correctly when completion coincides with a full output page.
1219    ///
1220    /// HOW:
1221    /// - Decode payload sizes around the page boundary and compare full reconstructed data.
1222    /// - Verify the sweep actually reaches a completed decoder with no remaining output capacity.
1223    #[test]
1224    fn flate_decoder_output_fills_pages() {
1225        // some sizes end the stream exactly at the end of a page, which holds
1226        // a little less than `MAX_CHUNK_SIZE`
1227        let mut full = 0;
1228        for gzip in [false, true] {
1229            let encoding = if gzip {
1230                ContentEncoding::Gzip
1231            } else {
1232                ContentEncoding::Deflate
1233            };
1234            for len in MAX_CHUNK_SIZE - 64..=MAX_CHUNK_SIZE {
1235                let data = b"abc".repeat(len)[..len].to_vec();
1236                let mut input = Bytes::from(compress(encoding, &data));
1237                let mut decoder = FlateDecoder::new(gzip);
1238                let mut out = Vec::new();
1239                while !input.is_empty() || decoder.more {
1240                    if let Some(chunk) = decoder.feed(&mut input).unwrap() {
1241                        out.extend_from_slice(&chunk);
1242                    }
1243                    full += usize::from(decoder.done && decoder.buf.remaining_mut() == 0);
1244                }
1245                decoder.finish().unwrap();
1246                assert_eq!(out, data);
1247            }
1248        }
1249        assert!(full > 0);
1250    }
1251}