Skip to main content

ostrya_core/
deflate.rs

1//! The raw-DEFLATE encoders of archive-mode content objects.
2//!
3//! `DeflateSink` and `DeflateReader` use the same compressor setup and the
4//! same `compress` step. Both give the same bytes for the same input at the
5//! same level. The golden hashes of the tests hold this output fixed.
6
7use std::io;
8use std::pin::Pin;
9use std::task::{Context, Poll};
10
11use futures_io::{AsyncBufRead, AsyncRead, AsyncWrite};
12use miniz_oxide::deflate::core::CompressorOxide;
13use miniz_oxide::deflate::stream::deflate;
14use miniz_oxide::{DataFormat, MZError, MZFlush, MZStatus};
15
16/// The size of the output buffer of [`DeflateSink`], and of the input buffer
17/// and the output buffer of [`DeflateReader`].
18const DEFLATE_CHUNK: usize = 64 * 1024;
19
20/// A streaming raw-DEFLATE encoder over an async writer.
21///
22/// The sink is the encoder of archive-mode content objects. The stored
23/// `.filez` payload is its output.
24///
25/// Each `poll_write` compresses the chunk of the caller into an output buffer
26/// of 64 KiB. The sink writes this buffer to the inner writer, so a payload of
27/// any size goes through in pieces of a fixed size.
28///
29/// `poll_flush` ends the current DEFLATE block with a sync flush, so a flush
30/// changes the compressed bytes. `poll_close` ends the stream, flushes the
31/// inner writer, and leaves it open. A caller can then still write to the
32/// inner writer, for example to patch a header in front of the stream.
33///
34/// [`reset`](DeflateSink::reset) starts a new stream in the same compressor
35/// and output buffer, so one sink can encode many objects in turn.
36pub struct DeflateSink<W> {
37    inner: W,
38    compressor: Box<CompressorOxide>,
39    /// The output buffer that the compressor fills.
40    out: Vec<u8>,
41    /// The number of bytes of `out` that `inner` took.
42    sent: usize,
43    /// The number of bytes of `out` that the compressor filled.
44    filled: usize,
45    /// `true` while a sync flush is under way. A resumed `poll_flush` then
46    /// runs only the steps that take the remaining output, with no second
47    /// sync step.
48    syncing: bool,
49    /// `true` if the current DEFLATE block is closed and no input arrived
50    /// after the close.
51    flushed: bool,
52    /// `true` if the compressor reached the end of the stream.
53    done: bool,
54}
55
56impl<W> DeflateSink<W> {
57    /// Creates a raw-DEFLATE encoder that writes to `inner` at `level`.
58    ///
59    /// An archive-mode repository uses a level from 1 through 9. The sink
60    /// passes `level` to the encoder with no check, and no level causes a
61    /// panic.
62    pub fn new(inner: W, level: u8) -> DeflateSink<W> {
63        DeflateSink {
64            inner,
65            compressor: compressor(level),
66            out: vec![0u8; DEFLATE_CHUNK],
67            sent: 0,
68            filled: 0,
69            syncing: false,
70            flushed: true,
71            done: false,
72        }
73    }
74
75    /// Starts a new stream into `inner` at `level` and returns the previous
76    /// writer.
77    ///
78    /// The sink resets the compressor in place with `level` and keeps the
79    /// output buffer. A caller that compresses many objects can keep one sink
80    /// with no new allocation.
81    ///
82    /// The sink discards the compressed bytes that it holds and did not write
83    /// to the previous writer. A caller that needs the whole previous stream
84    /// closes the sink before the reset.
85    pub fn reset(&mut self, inner: W, level: u8) -> W {
86        restart(&mut self.compressor, level);
87        self.sent = 0;
88        self.filled = 0;
89        self.syncing = false;
90        self.flushed = true;
91        self.done = false;
92        std::mem::replace(&mut self.inner, inner)
93    }
94
95    /// Returns the inner writer.
96    ///
97    /// The sink discards the compressed bytes that it holds and did not write.
98    pub fn into_inner(self) -> W {
99        self.inner
100    }
101}
102
103impl<W: AsyncWrite + Unpin> DeflateSink<W> {
104    /// Writes the compressed bytes in `out` to `inner`.
105    fn poll_drain(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
106        while self.sent < self.filled {
107            let n = std::task::ready!(
108                Pin::new(&mut self.inner).poll_write(cx, &self.out[self.sent..self.filled])
109            )?;
110            if n == 0 {
111                return Poll::Ready(Err(io::Error::new(
112                    io::ErrorKind::WriteZero,
113                    "write returned zero",
114                )));
115            }
116            self.sent += n;
117        }
118        self.sent = 0;
119        self.filled = 0;
120        Poll::Ready(Ok(()))
121    }
122
123    /// Runs the compressor once over `input` with `flush`, into an empty
124    /// output buffer.
125    ///
126    /// The step drains the buffer first, so a `Pending` return leaves the
127    /// compressor untouched. The caller then repeats the same step.
128    ///
129    /// Returns three values:
130    ///
131    /// - the number of bytes of `input` that the compressor took
132    /// - the number of bytes that it produced
133    /// - `true` if it reached the end of the stream
134    ///
135    /// A `Buf` result reports that the compressor made no progress. The flush
136    /// and close sequences read this result as the end of the output that
137    /// they wait for.
138    fn poll_step(
139        &mut self,
140        cx: &mut Context<'_>,
141        input: &[u8],
142        flush: MZFlush,
143    ) -> Poll<io::Result<(usize, usize, bool)>> {
144        std::task::ready!(self.poll_drain(cx))?;
145        let step = compress(&mut self.compressor, input, &mut self.out, flush)?;
146        self.filled = step.1;
147        Poll::Ready(Ok(step))
148    }
149}
150
151/// Creates a raw-DEFLATE compressor at `level`.
152fn compressor(level: u8) -> Box<CompressorOxide> {
153    let mut compressor = Box::<CompressorOxide>::default();
154    compressor.set_format_and_level(DataFormat::Raw, level);
155    compressor
156}
157
158/// Starts a new stream in `compressor` at `level`.
159fn restart(compressor: &mut CompressorOxide, level: u8) {
160    compressor.reset();
161    compressor.set_format_and_level(DataFormat::Raw, level);
162}
163
164/// Runs `compressor` once over `input` with `flush` into `out`.
165///
166/// Returns three values:
167///
168/// - the number of bytes of `input` that the compressor took
169/// - the number of bytes that it wrote to `out`
170/// - `true` if it reached the end of the stream
171///
172/// A `Buf` result reports that the compressor made no progress.
173fn compress(
174    compressor: &mut CompressorOxide,
175    input: &[u8],
176    out: &mut [u8],
177    flush: MZFlush,
178) -> io::Result<(usize, usize, bool)> {
179    let res = deflate(compressor, input, out, flush);
180    let end = match res.status {
181        Ok(MZStatus::StreamEnd) => true,
182        Ok(_) | Err(MZError::Buf) => false,
183        Err(e) => {
184            return Err(io::Error::other(format!(
185                "the DEFLATE encoder failed: {e:?}"
186            )));
187        }
188    };
189    Ok((res.bytes_consumed, res.bytes_written, end))
190}
191
192impl<W: AsyncWrite + Unpin> AsyncWrite for DeflateSink<W> {
193    fn poll_write(
194        self: Pin<&mut Self>,
195        cx: &mut Context<'_>,
196        buf: &[u8],
197    ) -> Poll<io::Result<usize>> {
198        if buf.is_empty() {
199            return Poll::Ready(Ok(0));
200        }
201        let me = self.get_mut();
202        loop {
203            let (taken, produced, _) = std::task::ready!(me.poll_step(cx, buf, MZFlush::None))?;
204            // The compressor ran over the chunk of the caller, so the block is
205            // open, and the sink abandons a flush that was under way. A
206            // `Pending` return from the step leaves both flags unchanged.
207            me.flushed = false;
208            me.syncing = false;
209            if taken > 0 {
210                return Poll::Ready(Ok(taken));
211            }
212            if produced == 0 {
213                return Poll::Ready(Err(io::Error::other(
214                    "the DEFLATE encoder took no input and produced no output",
215                )));
216            }
217        }
218    }
219
220    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
221        let me = self.get_mut();
222        // A sync step ends the block. The next steps take the remaining
223        // output of the compressor, until a step produces nothing.
224        while !me.flushed {
225            let flush = if me.syncing {
226                MZFlush::None
227            } else {
228                MZFlush::Sync
229            };
230            let (_, produced, _) = std::task::ready!(me.poll_step(cx, &[], flush))?;
231            me.syncing = true;
232            if produced == 0 {
233                me.flushed = true;
234                me.syncing = false;
235            }
236        }
237        std::task::ready!(me.poll_drain(cx))?;
238        Pin::new(&mut me.inner).poll_flush(cx)
239    }
240
241    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
242        let me = self.get_mut();
243        while !me.done {
244            let (_, _, end) = std::task::ready!(me.poll_step(cx, &[], MZFlush::Finish))?;
245            me.done = end;
246        }
247        std::task::ready!(me.poll_drain(cx))?;
248        // The stream ends here. The inner writer stays open, so a caller can
249        // still patch a header in front of the stream.
250        Pin::new(&mut me.inner).poll_flush(cx)
251    }
252}
253
254fn stalled() -> io::Error {
255    io::Error::other("the DEFLATE encoder stalled with no output")
256}
257
258/// A raw-DEFLATE encoder that reads uncompressed bytes from a source.
259///
260/// A read returns the compressed form of the source bytes. End of file comes
261/// after the end of the stream.
262///
263/// If the caller of a [`DeflateSink`] does not flush, the sink and the reader
264/// give the same bytes for one input and level. The reader
265/// runs the compressor in the same sequence of steps, each into an empty
266/// output buffer. The reader does not flush the stream before its end,
267/// because a flush changes the bytes.
268///
269/// The reader holds one compressor, an input buffer of 64 KiB, and an output
270/// buffer of 64 KiB. Its memory does not grow with the size of the source.
271/// The reader returns the compressed bytes that it holds before it reads the
272/// source again. [`reset`](DeflateReader::reset) starts a new stream in the
273/// same compressor and buffers, so one reader can encode many objects in turn.
274///
275/// The reader implements `AsyncBufRead`. A caller that reads through
276/// `poll_fill_buf` and `consume` takes the compressed bytes from the output
277/// buffer with no copy.
278pub struct DeflateReader<R> {
279    source: R,
280    compressor: Box<CompressorOxide>,
281    /// The source bytes that the reader read and did not compress yet:
282    /// `input[pos..len]`.
283    input: Box<[u8]>,
284    pos: usize,
285    len: usize,
286    /// The compressed bytes that the caller did not read yet:
287    /// `out[out_pos..out_len]`.
288    out: Box<[u8]>,
289    out_pos: usize,
290    out_len: usize,
291    /// `true` if the source reached end of file.
292    eof: bool,
293    /// `true` if the compressor reached the end of the stream.
294    done: bool,
295}
296
297impl<R> DeflateReader<R> {
298    /// Creates a raw-DEFLATE encoder that reads from `source` at `level`.
299    ///
300    /// `level` has the meaning that [`DeflateSink::new`] states.
301    pub fn new(source: R, level: u8) -> DeflateReader<R> {
302        DeflateReader {
303            source,
304            compressor: compressor(level),
305            input: vec![0u8; DEFLATE_CHUNK].into_boxed_slice(),
306            pos: 0,
307            len: 0,
308            out: vec![0u8; DEFLATE_CHUNK].into_boxed_slice(),
309            out_pos: 0,
310            out_len: 0,
311            eof: false,
312            done: false,
313        }
314    }
315
316    /// Starts a new stream over `source` at `level` and returns the previous
317    /// source.
318    ///
319    /// The reader resets the compressor in place with `level` and keeps the
320    /// buffers. The reader discards the source bytes and the compressed bytes
321    /// of the previous stream that it holds.
322    pub fn reset(&mut self, source: R, level: u8) -> R {
323        restart(&mut self.compressor, level);
324        self.pos = 0;
325        self.len = 0;
326        self.out_pos = 0;
327        self.out_len = 0;
328        self.eof = false;
329        self.done = false;
330        std::mem::replace(&mut self.source, source)
331    }
332
333    /// Returns a shared reference to the source.
334    pub fn get_ref(&self) -> &R {
335        &self.source
336    }
337
338    /// Returns a mutable reference to the source.
339    ///
340    /// Bytes that a caller reads from the source through this reference do
341    /// not reach the stream.
342    pub fn get_mut(&mut self) -> &mut R {
343        &mut self.source
344    }
345
346    /// Returns the source.
347    ///
348    /// The reader discards the source bytes and the compressed bytes that it
349    /// holds.
350    pub fn into_inner(self) -> R {
351        self.source
352    }
353}
354
355impl<R: AsyncRead + Unpin> DeflateReader<R> {
356    /// Runs the encoder until the output buffer holds unread bytes or the
357    /// stream ends.
358    fn poll_fill(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
359        loop {
360            if self.out_pos < self.out_len || self.done {
361                return Poll::Ready(Ok(()));
362            }
363            self.out_pos = 0;
364            self.out_len = 0;
365            if self.pos < self.len {
366                let (taken, written, _) = compress(
367                    &mut self.compressor,
368                    &self.input[self.pos..self.len],
369                    &mut self.out,
370                    MZFlush::None,
371                )?;
372                if taken == 0 && written == 0 {
373                    return Poll::Ready(Err(stalled()));
374                }
375                self.pos += taken;
376                self.out_len = written;
377                continue;
378            }
379            if !self.eof {
380                let n =
381                    std::task::ready!(Pin::new(&mut self.source).poll_read(cx, &mut self.input))?;
382                if n == 0 {
383                    self.eof = true;
384                } else {
385                    self.pos = 0;
386                    self.len = n;
387                }
388                continue;
389            }
390            let (_, written, end) =
391                compress(&mut self.compressor, &[], &mut self.out, MZFlush::Finish)?;
392            if !end && written == 0 {
393                return Poll::Ready(Err(stalled()));
394            }
395            self.out_len = written;
396            self.done = end;
397        }
398    }
399}
400
401impl<R: AsyncRead + Unpin> AsyncBufRead for DeflateReader<R> {
402    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
403        let me = self.get_mut();
404        std::task::ready!(me.poll_fill(cx))?;
405        Poll::Ready(Ok(&me.out[me.out_pos..me.out_len]))
406    }
407
408    fn consume(self: Pin<&mut Self>, amt: usize) {
409        let me = self.get_mut();
410        me.out_pos = (me.out_pos + amt).min(me.out_len);
411    }
412}
413
414impl<R: AsyncRead + Unpin> AsyncRead for DeflateReader<R> {
415    fn poll_read(
416        self: Pin<&mut Self>,
417        cx: &mut Context<'_>,
418        buf: &mut [u8],
419    ) -> Poll<io::Result<usize>> {
420        if buf.is_empty() {
421            return Poll::Ready(Ok(0));
422        }
423        let me = self.get_mut();
424        std::task::ready!(me.poll_fill(cx))?;
425        let n = buf.len().min(me.out_len - me.out_pos);
426        buf[..n].copy_from_slice(&me.out[me.out_pos..me.out_pos + n]);
427        me.out_pos += n;
428        Poll::Ready(Ok(n))
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use std::collections::BTreeSet;
435    use std::io;
436    use std::pin::Pin;
437    use std::task::{Context, Poll};
438
439    use futures_lite::future::block_on;
440    use futures_lite::io::AsyncWriteExt;
441    use sha2::{Digest, Sha256};
442
443    use super::{DEFLATE_CHUNK, DeflateReader, DeflateSink};
444    use crate::Checksum;
445
446    /// The SHA-256 of the encoder output over [`golden_payload`], one entry
447    /// per `[archive] zlib-level`: index 0 holds level 1, index 8 holds level
448    /// 9. The nine entries differ, because `miniz_oxide` gives each level its
449    /// own match-search depth and its own choice of greedy or lazy parsing.
450    ///
451    /// A mismatch states that the encoder output changed, which changes the
452    /// bytes stored in every archive-mode content object at that level. Find
453    /// the cause -- a `miniz_oxide` release, or an edit to [`DeflateSink`].
454    /// Then check the stored bytes against the bytes of the `ostree` command
455    /// with `archive_objects_are_byte_identical_to_the_fixture` in
456    /// `crates/ostrya/tests/write.rs` before you record a constant here again.
457    const GOLDEN: [&str; 9] = [
458        "a1fd96479b110a51c3b9c333da0ff6879cd295fc27a98b48c88b70a0ea558bb4",
459        "7964fd5c5e4ffb18bf953852b31704681eaf7a4590d488a01be5f213978c0876",
460        "e5ff230c2f7715f8883cbd5c19ee1255f165c7e25fc886516c290b0d246954a0",
461        "7ae743a6aa5027a1ef08604f6c0a4e6062d39f73879dd0789780aca2e8027932",
462        "95b7d927a18b71b941598bf6411029653910307881528355a5b18cccfd3dea0a",
463        "b9b31232e8e4458ff831e1de64ba695c0c07b630215e2ce01d372fa2fd8bbcc3",
464        "8436585ce3c3eea757ab9d5020de4b41c3f32ac29fdd8b5c02ec8ec51df9067d",
465        "c1bc0d4abcb002a3e15241b86c7f200ddc4c71ff30752a7ce933755433ceb88c",
466        "b6ddd39fc7e629dfcc81b42ba9706eb6e4e46cd4f90527d3e1ccda0d072faca7",
467    ];
468
469    /// The SHA-256 of the encoder output over [`golden_payload`] at the
470    /// default level 6 when the caller flushes once, at the halfway point of
471    /// the payload. The content writer of `ostrya` passes a flush on to the
472    /// encoder, and the encoder ends the DEFLATE block with a sync flush. A
473    /// caller that flushes then stores different bytes for the same content.
474    ///
475    /// The identity of the object is over the uncompressed bytes, so both
476    /// forms carry the same checksum and the `ostree` command reads both. The
477    /// ingest paths of `ostrya` write straight through and reach [`GOLDEN`].
478    const GOLDEN_FLUSHED: &str = "009e2fd466deb6af8f1828281fccd0a7be5fef1356215f1eaa10708a86caa4b3";
479
480    /// One xorshift32 step.
481    fn xorshift(state: &mut u32) -> u32 {
482        *state ^= *state << 13;
483        *state ^= *state >> 17;
484        *state ^= *state << 5;
485        *state
486    }
487
488    /// A payload of one and a half [`DEFLATE_CHUNK`] in three half-chunk
489    /// blocks. The first block uses a four-symbol alphabet. Its long match
490    /// chains let the search depth of a level change the output. The other
491    /// two blocks hold an xorshift32 stream that the encoder cannot compress.
492    ///
493    /// The output holds literal and match coding, spans more than one
494    /// [`DEFLATE_CHUNK`], and takes nine distinct forms over the nine levels.
495    fn golden_payload() -> Vec<u8> {
496        const BLOCK: usize = DEFLATE_CHUNK / 2;
497        let mut out = Vec::with_capacity(3 * BLOCK);
498        let mut state: u32 = 0x1234_5678;
499        // Two bits per byte, sixteen bytes per step, over `A` to `D`.
500        for _ in 0..BLOCK / 16 {
501            let word = xorshift(&mut state);
502            for k in 0..16 {
503                out.push(b'A' + ((word >> (2 * k)) & 3) as u8);
504            }
505        }
506        for _ in 0..2 * BLOCK {
507            out.push((xorshift(&mut state) >> 24) as u8);
508        }
509        out
510    }
511
512    /// The encoder output over `data` at `level`, driven in `chunk`-byte
513    /// writes and ended with a close, the way the content writer of `ostrya`
514    /// ends it.
515    fn encode(data: &[u8], level: u8, chunk: usize) -> Vec<u8> {
516        block_on(async {
517            let mut sink = DeflateSink::new(Vec::new(), level);
518            for part in data.chunks(chunk) {
519                sink.write_all(part).await.unwrap();
520            }
521            sink.close().await.unwrap();
522            sink.into_inner()
523        })
524    }
525
526    /// A sink that encoded a first stream at a different level and was then
527    /// reset to `level`. The first stream is closed, or it is abandoned
528    /// mid-stream when `abandon` is set. Returns the old writer and the output
529    /// of the second stream over `data`, in 4093-byte writes.
530    fn encode_after_reset(data: &[u8], level: u8, abandon: bool) -> (Vec<u8>, Vec<u8>) {
531        block_on(async {
532            let mut sink = DeflateSink::new(Vec::new(), level % 9 + 1);
533            sink.write_all(&data[..data.len() / 3]).await.unwrap();
534            if !abandon {
535                sink.close().await.unwrap();
536            }
537            let old = sink.reset(Vec::new(), level);
538            for part in data.chunks(4093) {
539                sink.write_all(part).await.unwrap();
540            }
541            sink.close().await.unwrap();
542            (old, sink.into_inner())
543        })
544    }
545
546    /// A writer that takes `budget` bytes and then stays `Pending`.
547    struct Stall {
548        taken: Vec<u8>,
549        budget: usize,
550    }
551
552    impl futures_io::AsyncWrite for Stall {
553        fn poll_write(
554            self: Pin<&mut Self>,
555            _cx: &mut Context<'_>,
556            buf: &[u8],
557        ) -> Poll<io::Result<usize>> {
558            let me = self.get_mut();
559            let n = buf.len().min(me.budget - me.taken.len());
560            if n == 0 {
561                return Poll::Pending;
562            }
563            me.taken.extend_from_slice(&buf[..n]);
564            Poll::Ready(Ok(n))
565        }
566
567        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
568            Poll::Ready(Ok(()))
569        }
570
571        fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
572            Poll::Ready(Ok(()))
573        }
574    }
575
576    /// A sink whose first stream, at a different level, stalls on a writer
577    /// that stops taking bytes, and which is then reset to `level`. The reset
578    /// comes while the output buffer holds compressed bytes that did not reach
579    /// the stalled writer. Returns the output of the second stream over
580    /// `data`, in 4093-byte writes.
581    fn encode_after_a_stalled_reset(data: &[u8], level: u8) -> Vec<u8> {
582        block_on(async {
583            let mut sink = DeflateSink::new(
584                Stall {
585                    taken: Vec::new(),
586                    budget: 1000,
587                },
588                level % 9 + 1,
589            );
590            // The compressor holds its output back until its own buffer is
591            // full. The first stream takes the payload twice, so that it
592            // produces bytes before its input ends.
593            let first = data.repeat(2);
594            assert!(
595                futures_lite::future::poll_once(sink.write_all(&first))
596                    .await
597                    .is_none(),
598                "level {level}: the first stream stalls"
599            );
600            assert!(
601                sink.sent < sink.filled,
602                "level {level}: the output buffer holds unsent bytes at the reset"
603            );
604            let old = sink.reset(
605                Stall {
606                    taken: Vec::new(),
607                    budget: usize::MAX,
608                },
609                level,
610            );
611            assert_eq!(old.taken.len(), 1000);
612            for part in data.chunks(4093) {
613                sink.write_all(part).await.unwrap();
614            }
615            sink.close().await.unwrap();
616            sink.into_inner().taken
617        })
618    }
619
620    /// The encoder output over `data` at the default level when the caller
621    /// flushes once, at the halfway point of the payload. With `reset` set,
622    /// the sink first encodes and closes a stream at level 1 and is then
623    /// reset to level 6.
624    fn encode_with_a_flush(data: &[u8], reset: bool) -> Vec<u8> {
625        block_on(async {
626            let mut sink = if reset {
627                let mut sink = DeflateSink::new(Vec::new(), 1);
628                sink.write_all(data).await.unwrap();
629                sink.close().await.unwrap();
630                sink.reset(Vec::new(), 6);
631                sink
632            } else {
633                DeflateSink::new(Vec::new(), 6)
634            };
635            let (head, tail) = data.split_at(data.len() / 2);
636            sink.write_all(head).await.unwrap();
637            sink.flush().await.unwrap();
638            sink.write_all(tail).await.unwrap();
639            sink.close().await.unwrap();
640            sink.into_inner()
641        })
642    }
643
644    fn hash(bytes: &[u8]) -> String {
645        Checksum::from_bytes(Sha256::digest(bytes).into()).to_hex()
646    }
647
648    #[test]
649    fn deflate_output_matches_the_golden_hashes() {
650        let data = golden_payload();
651        assert!(
652            data.len() > DEFLATE_CHUNK,
653            "the payload spans more than one chunk"
654        );
655        assert_eq!(
656            GOLDEN.iter().collect::<BTreeSet<_>>().len(),
657            GOLDEN.len(),
658            "each level reaches its own bytes"
659        );
660        for (i, &want) in GOLDEN.iter().enumerate() {
661            let level = i as u8 + 1;
662            let out = encode(&data, level, 1);
663            assert!(
664                out.len() > DEFLATE_CHUNK,
665                "level {level}: output spans more than one chunk"
666            );
667            // The write sizes of the ingest path do not change the output of
668            // the encoder. These sizes all give the same bytes:
669            // - one byte at a time
670            // - an odd size that divides neither the payload nor the chunk
671            // - the whole payload in one write
672            for chunk in [4093, data.len()] {
673                assert_eq!(
674                    encode(&data, level, chunk),
675                    out,
676                    "level {level}, {chunk}-byte writes"
677                );
678            }
679            // A sink reset after an earlier stream, closed or abandoned,
680            // gives the bytes of a new sink.
681            let (old, after_close) = encode_after_reset(&data, level, false);
682            assert!(
683                !old.is_empty(),
684                "level {level}: reset returns the old writer"
685            );
686            assert_eq!(after_close, out, "level {level}, reset after a close");
687            let (_, after_abandon) = encode_after_reset(&data, level, true);
688            assert_eq!(after_abandon, out, "level {level}, reset mid-stream");
689            assert_eq!(
690                encode_after_a_stalled_reset(&data, level),
691                out,
692                "level {level}, reset with unsent bytes"
693            );
694            assert_eq!(hash(&out), want, "DEFLATE level {level} output hash");
695        }
696
697        let flushed = hash(&encode_with_a_flush(&data, false));
698        assert_eq!(
699            flushed, GOLDEN_FLUSHED,
700            "DEFLATE level 6 output hash after a flush"
701        );
702        assert_ne!(
703            flushed, GOLDEN[5],
704            "a flush ends the DEFLATE block, so it reaches the output"
705        );
706        assert_eq!(
707            hash(&encode_with_a_flush(&data, true)),
708            GOLDEN_FLUSHED,
709            "DEFLATE level 6 output hash after a reset and a flush"
710        );
711    }
712
713    /// A source that gives one byte for each read and is `Pending` before
714    /// each byte.
715    struct Trickle<'a> {
716        data: &'a [u8],
717        ready: bool,
718    }
719
720    impl futures_io::AsyncRead for Trickle<'_> {
721        fn poll_read(
722            self: Pin<&mut Self>,
723            cx: &mut Context<'_>,
724            buf: &mut [u8],
725        ) -> Poll<io::Result<usize>> {
726            let me = self.get_mut();
727            if !me.ready {
728                me.ready = true;
729                cx.waker().wake_by_ref();
730                return Poll::Pending;
731            }
732            me.ready = false;
733            let n = buf.len().min(me.data.len()).min(1);
734            buf[..n].copy_from_slice(&me.data[..n]);
735            me.data = &me.data[n..];
736            Poll::Ready(Ok(n))
737        }
738    }
739
740    /// The rest of the stream of `reader`, in reads of `size` bytes.
741    fn read_all<R: futures_io::AsyncRead + Unpin>(
742        reader: &mut DeflateReader<R>,
743        size: usize,
744    ) -> Vec<u8> {
745        block_on(async {
746            use futures_lite::io::AsyncReadExt;
747            let mut out = Vec::new();
748            let mut buf = vec![0u8; size];
749            loop {
750                let n = reader.read(&mut buf).await.unwrap();
751                if n == 0 {
752                    return out;
753                }
754                out.extend_from_slice(&buf[..n]);
755            }
756        })
757    }
758
759    /// The rest of the stream of `reader`, through `fill_buf` and `consume`.
760    fn read_buffered<R: futures_io::AsyncRead + Unpin>(reader: &mut DeflateReader<R>) -> Vec<u8> {
761        block_on(async {
762            use futures_lite::io::AsyncBufReadExt;
763            let mut out = Vec::new();
764            loop {
765                let chunk = reader.fill_buf().await.unwrap();
766                if chunk.is_empty() {
767                    return out;
768                }
769                assert!(chunk.len() <= DEFLATE_CHUNK, "a chunk fits one buffer");
770                let n = chunk.len();
771                out.extend_from_slice(chunk);
772                reader.consume(n);
773            }
774        })
775    }
776
777    #[test]
778    fn deflate_reader_output_matches_the_golden_hashes() {
779        let data = golden_payload();
780        for (i, &want) in GOLDEN.iter().enumerate() {
781            let level = i as u8 + 1;
782            let out = read_all(&mut DeflateReader::new(&data[..], level), 4093);
783            assert_eq!(hash(&out), want, "level {level}: reader output hash");
784            assert_eq!(out, encode(&data, level, 4093), "level {level}: sink bytes");
785            for size in [1, DEFLATE_CHUNK + 7, 4 * data.len()] {
786                assert_eq!(
787                    read_all(&mut DeflateReader::new(&data[..], level), size),
788                    out,
789                    "level {level}, {size}-byte reads"
790                );
791            }
792            assert_eq!(
793                read_buffered(&mut DeflateReader::new(&data[..], level)),
794                out,
795                "level {level}, buffered reads"
796            );
797            let trickle = Trickle {
798                data: &data,
799                ready: false,
800            };
801            assert_eq!(
802                read_all(&mut DeflateReader::new(trickle, level), 4093),
803                out,
804                "level {level}, a source of one byte after each Pending"
805            );
806
807            // A reset after a complete stream, and after a stream read
808            // halfway, gives the bytes of a new reader.
809            let mut reader = DeflateReader::new(&data[..data.len() / 3], level % 9 + 1);
810            assert!(!read_all(&mut reader, 4093).is_empty());
811            let old = reader.reset(&data[..], level);
812            assert!(
813                old.is_empty(),
814                "reset returns the old source, read to its end"
815            );
816            assert_eq!(
817                read_all(&mut reader, 4093),
818                out,
819                "level {level}, reset after the end"
820            );
821
822            let mut reader = DeflateReader::new(&data[..], level % 9 + 1);
823            block_on(async {
824                use futures_lite::io::AsyncReadExt;
825                let mut buf = vec![0u8; 1000];
826                reader.read_exact(&mut buf).await.unwrap();
827            });
828            reader.reset(&data[..], level);
829            assert_eq!(
830                read_buffered(&mut reader),
831                out,
832                "level {level}, reset mid-stream"
833            );
834
835            // An empty source gives the empty stream of the sink.
836            let empty = read_all(&mut DeflateReader::new(&[][..], level), 4093);
837            assert_eq!(empty, encode(&[], level, 1), "level {level}, empty input");
838            assert!(!empty.is_empty(), "the empty stream still ends");
839            assert_eq!(
840                read_all(&mut reader, 4093),
841                Vec::<u8>::new(),
842                "end of file after the end of the stream"
843            );
844        }
845    }
846
847    /// A source that gives its data, then is `Pending` with no wake until
848    /// `open` is set, and then reaches end of file.
849    struct Held<'a> {
850        data: &'a [u8],
851        open: bool,
852    }
853
854    impl futures_io::AsyncRead for Held<'_> {
855        fn poll_read(
856            self: Pin<&mut Self>,
857            _cx: &mut Context<'_>,
858            buf: &mut [u8],
859        ) -> Poll<io::Result<usize>> {
860            let me = self.get_mut();
861            if me.data.is_empty() && !me.open {
862                return Poll::Pending;
863            }
864            let n = buf.len().min(me.data.len());
865            buf[..n].copy_from_slice(&me.data[..n]);
866            me.data = &me.data[n..];
867            Poll::Ready(Ok(n))
868        }
869    }
870
871    #[test]
872    fn deflate_reader_gives_its_output_before_it_waits_on_the_source() {
873        use futures_io::AsyncBufRead;
874        use miniz_oxide::deflate::core::CompressorOxide;
875        use miniz_oxide::deflate::stream::deflate;
876        use miniz_oxide::{DataFormat, MZFlush};
877
878        let mut state = 7;
879        let data: Vec<u8> = (0..4 * DEFLATE_CHUNK)
880            .map(|_| xorshift(&mut state) as u8)
881            .collect();
882        // The bytes the compressor gives for the whole input with no flush,
883        // run over the input in pieces of the reader's input buffer.
884        let mut compressor = Box::<CompressorOxide>::default();
885        compressor.set_format_and_level(DataFormat::Raw, 1);
886        let mut out = vec![0u8; DEFLATE_CHUNK];
887        let mut ready = 0;
888        for piece in data.chunks(DEFLATE_CHUNK) {
889            let mut pos = 0;
890            while pos < piece.len() {
891                let res = deflate(&mut compressor, &piece[pos..], &mut out, MZFlush::None);
892                pos += res.bytes_consumed;
893                ready += res.bytes_written;
894            }
895        }
896        assert!(ready > 0);
897
898        let mut reader = DeflateReader::new(
899            Held {
900                data: &data,
901                open: false,
902            },
903            1,
904        );
905        let mut got = Vec::new();
906        let waker = std::task::Waker::noop();
907        let mut cx = Context::from_waker(waker);
908        while let Poll::Ready(chunk) = Pin::new(&mut reader).poll_fill_buf(&mut cx) {
909            let chunk = chunk.unwrap();
910            assert!(!chunk.is_empty(), "no end of file while the source waits");
911            let n = chunk.len();
912            got.extend_from_slice(chunk);
913            Pin::new(&mut reader).consume(n);
914        }
915        assert_eq!(got.len(), ready, "every compressed byte before the wait");
916        reader.get_mut().open = true;
917        got.extend(read_all(&mut reader, 4093));
918        assert_eq!(got, encode(&data, 1, 4093));
919    }
920
921    #[test]
922    fn deflate_reader_is_send_and_sync() {
923        fn assert_send_sync<T: Send + Sync>() {}
924        assert_send_sync::<DeflateReader<&[u8]>>();
925    }
926}