Skip to main content

compress_utils/
stream.rs

1//! Streaming compression and decompression as standard [`std::io`] adapters.
2//!
3//! [`Compressor`] is a [`Write`] that compresses everything written to it and
4//! forwards the result to an inner sink. [`Decompressor`] is a [`Read`] that
5//! decompresses from an inner source on demand. Both drive the C ABI's
6//! fill-buffer / `BUF_TOO_SMALL` / drain protocol internally, so callers never
7//! see it.
8//!
9//! Neither type is safe for concurrent use (each owns a non-thread-safe C
10//! stream handle).
11
12use std::fmt;
13use std::io::{self, Read, Write};
14
15use crate::ffi;
16use crate::{Algorithm, Error, Status};
17
18/// Size of the fixed scratch buffer each stream drains through. The protocol
19/// works with any size; 64 KiB keeps the FFI call count low without holding
20/// much memory. Matches the Go binding.
21const SCRATCH: usize = 64 * 1024;
22
23impl From<Error> for io::Error {
24    fn from(e: Error) -> io::Error {
25        io::Error::new(io::ErrorKind::Other, e)
26    }
27}
28
29/// A `BUF_TOO_SMALL` status always accompanies a fully-written output buffer;
30/// if the codec reports it with zero bytes produced it is stuck (malformed
31/// input, or a decoder that can neither consume nor emit) and looping would
32/// spin forever / grow memory unbounded. Turn that into a hard error.
33fn stuck_error() -> io::Error {
34    Error {
35        code: Status::Decompression,
36        message: "compress-utils: decoder made no progress (malformed or truncated input)"
37            .to_string(),
38    }
39    .into()
40}
41
42/// Recover a library [`Error`] from an [`io::Error`] produced by the streaming
43/// adapters (used by the top-level [`crate::decompress`] fallback).
44pub(crate) fn io_to_error(e: io::Error) -> Error {
45    let fallback = e.to_string();
46    match e.into_inner() {
47        Some(b) => match b.downcast::<Error>() {
48            Ok(err) => *err,
49            Err(b) => Error {
50                code: Status::Internal,
51                message: b.to_string(),
52            },
53        },
54        None => Error {
55            code: Status::Internal,
56            message: fallback,
57        },
58    }
59}
60
61/// A [`Write`] that compresses into an inner sink.
62///
63/// You **must** call [`Compressor::finish`] to flush the final frame and get a
64/// clean, decodable stream. As a safety net the frame is also finalized on drop
65/// (best-effort, errors ignored), but relying on that discards any I/O error —
66/// prefer `finish`.
67pub struct Compressor<W: Write> {
68    sink: Option<W>,
69    stream: *mut ffi::cu_compress_stream,
70    scratch: Vec<u8>,
71    finished: bool,
72}
73
74impl<W: Write> Compressor<W> {
75    /// Create a compressor writing to `sink` with `algo` at `level`
76    /// (1 fastest ..= 10 smallest).
77    pub fn new(sink: W, algo: Algorithm, level: i32) -> Result<Self, Error> {
78        let mut stream: *mut ffi::cu_compress_stream = std::ptr::null_mut();
79        // SAFETY: out_stream points at a local; on CU_OK it is set to a valid
80        // handle we own until destroy.
81        let st = unsafe { ffi::cu_compress_stream_create(algo.to_raw(), level, &mut stream) };
82        crate::check_status(st)?;
83        Ok(Compressor {
84            sink: Some(sink),
85            stream,
86            scratch: vec![0u8; SCRATCH],
87            finished: false,
88        })
89    }
90
91    /// Flush the final frame, release the C stream, and return the inner sink.
92    pub fn finish(mut self) -> io::Result<W> {
93        self.do_finish()?;
94        self.destroy();
95        // SAFETY: sink is always Some until finish/drop takes it exactly once.
96        Ok(self.sink.take().expect("sink present"))
97    }
98
99    /// Drain the finalize phase to the sink. Idempotent.
100    fn do_finish(&mut self) -> io::Result<()> {
101        if self.finished {
102            return Ok(());
103        }
104        loop {
105            let mut out_len = self.scratch.len();
106            // SAFETY: valid handle + scratch buffer; out_len is in/out.
107            let st = unsafe {
108                ffi::cu_compress_stream_finish(self.stream, self.scratch.as_mut_ptr(), &mut out_len)
109            };
110            if out_len > 0 {
111                self.sink
112                    .as_mut()
113                    .expect("sink present")
114                    .write_all(&self.scratch[..out_len])?;
115            }
116            if st == ffi::CU_OK {
117                self.finished = true;
118                return Ok(());
119            }
120            if st != ffi::CU_ERR_BUF_TOO_SMALL {
121                return Err(crate::make_error(st).into());
122            }
123            if out_len == 0 {
124                return Err(stuck_error());
125            }
126        }
127    }
128
129    fn destroy(&mut self) {
130        if !self.stream.is_null() {
131            // SAFETY: handle created by create() and not yet destroyed.
132            unsafe { ffi::cu_compress_stream_destroy(self.stream) };
133            self.stream = std::ptr::null_mut();
134        }
135    }
136}
137
138impl<W: Write> Write for Compressor<W> {
139    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
140        if self.finished {
141            return Err(io::Error::new(
142                io::ErrorKind::Other,
143                "compress-utils: stream is finished",
144            ));
145        }
146        if buf.is_empty() {
147            return Ok(0);
148        }
149        let sink = self.sink.as_mut().expect("sink present");
150        let mut first = true;
151        loop {
152            let mut out_len = self.scratch.len();
153            // First call feeds the input; the stream retains any unconsumed
154            // tail internally, so subsequent drain calls feed (NULL, 0).
155            let (in_ptr, in_len) = if first {
156                (buf.as_ptr(), buf.len())
157            } else {
158                (std::ptr::null(), 0usize)
159            };
160            first = false;
161            // SAFETY: in/out pointers valid for their lengths; out_len in/out.
162            let st = unsafe {
163                ffi::cu_compress_stream_write(
164                    self.stream,
165                    in_ptr,
166                    in_len,
167                    self.scratch.as_mut_ptr(),
168                    &mut out_len,
169                )
170            };
171            if out_len > 0 {
172                sink.write_all(&self.scratch[..out_len])?;
173            }
174            if st == ffi::CU_OK {
175                return Ok(buf.len());
176            }
177            if st != ffi::CU_ERR_BUF_TOO_SMALL {
178                return Err(crate::make_error(st).into());
179            }
180            if out_len == 0 {
181                return Err(stuck_error());
182            }
183        }
184    }
185
186    /// Flushes the codec, then the sink: everything written so far reaches
187    /// the sink in decodable form, and the frame stays open for more writes
188    /// (as flate2's `flush` does). Each flush costs a few bytes of output.
189    ///
190    /// Returns an [`io::ErrorKind::Unsupported`] error for Snappy and Bz2,
191    /// which can't flush mid-stream.
192    fn flush(&mut self) -> io::Result<()> {
193        let Some(sink) = self.sink.as_mut() else {
194            return Ok(());
195        };
196        while !self.finished {
197            let mut out_len = self.scratch.len();
198            // SAFETY: valid handle + scratch buffer; out_len is in/out.
199            let st = unsafe {
200                ffi::cu_compress_stream_flush(self.stream, self.scratch.as_mut_ptr(), &mut out_len)
201            };
202            if out_len > 0 {
203                sink.write_all(&self.scratch[..out_len])?;
204            }
205            match st {
206                ffi::CU_OK => break,
207                ffi::CU_ERR_BUF_TOO_SMALL if out_len == 0 => return Err(stuck_error()),
208                ffi::CU_ERR_BUF_TOO_SMALL => {}
209                ffi::CU_ERR_UNSUPPORTED_ALGO => {
210                    return Err(io::Error::new(
211                        io::ErrorKind::Unsupported,
212                        crate::make_error(st),
213                    ))
214                }
215                other => return Err(crate::make_error(other).into()),
216            }
217        }
218        sink.flush()
219    }
220}
221
222impl<W: Write> Drop for Compressor<W> {
223    fn drop(&mut self) {
224        // Best-effort finalize so a forgotten finish() still yields a decodable
225        // stream; errors are unreportable here, hence finish() is preferred.
226        if self.sink.is_some() && !self.finished {
227            let _ = self.do_finish();
228        }
229        self.destroy();
230    }
231}
232
233/// A [`Read`] that decompresses from an inner source.
234///
235/// By default concatenated zstd/LZ4 frames, gzip members and xz streams decode
236/// as one stream, and the source must end on a frame boundary. A decompressor
237/// made with [`Decompressor::single_stream`] instead stops at the end of the
238/// first frame and hands back the bytes after it.
239pub struct Decompressor<R: Read> {
240    /// `None` only once [`Decompressor::into_parts`] has taken it.
241    src: Option<R>,
242    stream: *mut ffi::cu_decompress_stream,
243    in_buf: Vec<u8>,
244    scratch: Vec<u8>,
245    out: Vec<u8>,
246    out_pos: usize,
247
248    input_done: bool,
249    draining: bool,
250    finished: bool,
251
252    single: bool,
253    eof: bool,
254    /// Single mode: the bytes read from `src` after the end of the stream.
255    unused: Vec<u8>,
256}
257
258impl<R: Read> Decompressor<R> {
259    /// Create a decompressor reading a stream produced by `algo` from `src`.
260    pub fn new(src: R, algo: Algorithm) -> Result<Self, Error> {
261        Self::create(src, algo, 0)
262    }
263
264    /// Create a decompressor that stops at the end of the first frame (zstd or
265    /// LZ4 frame, gzip member, zlib/DEFLATE/xz/brotli/bzip2 stream, or Snappy
266    /// block) instead of continuing into whatever follows it, such as another
267    /// message on the same connection.
268    ///
269    /// `read` returns `Ok(0)` once that frame is fully decoded. It reads `src`
270    /// in chunks, so it usually reads past the end: those bytes come back from
271    /// [`unused`](Self::unused) or [`into_parts`](Self::into_parts), so the
272    /// caller can carry on reading the source:
273    ///
274    /// ```
275    /// use std::io::{Cursor, Read};
276    /// use compress_utils::{compress, Algorithm, Decompressor};
277    ///
278    /// let mut wire = compress(Algorithm::Zstd, b"first", 5).unwrap();
279    /// wire.extend_from_slice(b"rest of the source");
280    ///
281    /// let mut d = Decompressor::single_stream(Cursor::new(wire), Algorithm::Zstd).unwrap();
282    /// let mut first = Vec::new();
283    /// d.read_to_end(&mut first).unwrap();
284    /// assert_eq!(first, b"first");
285    ///
286    /// let (src, unused) = d.into_parts().unwrap();
287    /// let mut rest = Vec::new();
288    /// Cursor::new(unused).chain(src).read_to_end(&mut rest).unwrap();
289    /// assert_eq!(rest, b"rest of the source");
290    /// ```
291    ///
292    /// Raw LZ4 and LZO have no end marker to stop at and return
293    /// [`Status::UnsupportedAlgo`]. Single-mode Snappy produces no output until
294    /// its whole block has arrived, and rejects a block declaring more than
295    /// [`crate::set_max_decompressed_size`] (as set when the decompressor is
296    /// created) with [`Status::SizeLimit`].
297    pub fn single_stream(src: R, algo: Algorithm) -> Result<Self, Error> {
298        Self::create(src, algo, ffi::CU_DSTREAM_SINGLE)
299    }
300
301    fn create(src: R, algo: Algorithm, flags: u32) -> Result<Self, Error> {
302        let mut stream: *mut ffi::cu_decompress_stream = std::ptr::null_mut();
303        // SAFETY: out_stream points at a local; set to a valid handle on CU_OK.
304        let st = unsafe {
305            if flags == 0 {
306                ffi::cu_decompress_stream_create(algo.to_raw(), &mut stream)
307            } else {
308                ffi::cu_decompress_stream_create_ex(algo.to_raw(), flags, &mut stream)
309            }
310        };
311        crate::check_status(st)?;
312        Ok(Decompressor {
313            src: Some(src),
314            stream,
315            in_buf: vec![0u8; SCRATCH],
316            scratch: vec![0u8; SCRATCH],
317            out: Vec::new(),
318            out_pos: 0,
319            input_done: false,
320            draining: false,
321            finished: false,
322            single: flags & ffi::CU_DSTREAM_SINGLE != 0,
323            eof: false,
324            unused: Vec::new(),
325        })
326    }
327
328    /// Single-stream mode: whether the end of the stream has been decoded.
329    /// Output decoded before it may still be waiting to be read; `read`
330    /// returns `Ok(0)` once it has been. Always `false` for decompressors made
331    /// with [`Decompressor::new`].
332    pub fn is_eof(&self) -> bool {
333        self.eof
334    }
335
336    /// Single-stream mode: the bytes read from the source after the end of the
337    /// stream, in order. Empty until [`is_eof`](Self::is_eof), and always for
338    /// decompressors made with [`Decompressor::new`].
339    pub fn unused(&self) -> &[u8] {
340        &self.unused
341    }
342
343    /// Returns the source and the bytes already read from it after the end of
344    /// the stream ([`unused`](Self::unused)). Reading the unused bytes, then
345    /// the source, continues exactly where the compressed stream ended.
346    ///
347    /// Only once the stream has ended and all of its output has been read
348    /// (`read` has returned `Ok(0)`): before that, part of the stream and the
349    /// bytes after it may still be held inside the decompressor, and taking
350    /// the source would lose them. Otherwise this returns an
351    /// [`IntoPartsError`] that hands the decompressor back, so you can keep
352    /// reading. A caller that stops at the end of its own data (as `pickle`
353    /// stops at its STOP opcode) should read to `Ok(0)` first.
354    pub fn into_parts(mut self) -> Result<(R, Vec<u8>), IntoPartsError<R>> {
355        if !self.finished || self.out_pos < self.out.len() {
356            return Err(IntoPartsError(self));
357        }
358        let unused = std::mem::take(&mut self.unused);
359        let src = self.src.take().expect("source present until into_parts");
360        Ok((src, unused))
361    }
362
363    /// Single mode: after a call that returned CU_OK, latch eof once the C
364    /// stream reports it and keep the input it didn't use. Every byte read from
365    /// `src` is passed to the C stream in the same call, so its unused bytes
366    /// are all the read-ahead there is.
367    fn settle_single(&mut self) {
368        if !self.single || self.eof {
369            return;
370        }
371        // SAFETY: valid handle.
372        if unsafe { ffi::cu_decompress_stream_eof(self.stream) } == 0 {
373            return;
374        }
375        let mut data: *const u8 = std::ptr::null();
376        let mut len = 0usize;
377        // SAFETY: valid handle; data/len point at locals. The C buffer stays
378        // valid until the next call on the stream, and is copied before then.
379        let st = unsafe { ffi::cu_decompress_stream_unused(self.stream, &mut data, &mut len) };
380        if st == ffi::CU_OK && len > 0 && !data.is_null() {
381            // SAFETY: C guarantees `data` points at `len` readable bytes.
382            self.unused
383                .extend_from_slice(unsafe { std::slice::from_raw_parts(data, len) });
384        }
385        self.eof = true;
386        self.finished = true;
387    }
388
389    /// Append decompressed bytes to `out` by advancing the C stream one step.
390    /// Mirrors the Go reader's feed/drain/finish state machine.
391    fn pump(&mut self) -> io::Result<()> {
392        // Finish phase: input exhausted, flush trailing output.
393        if self.input_done && !self.draining {
394            let mut out_len = self.scratch.len();
395            // SAFETY: valid handle + scratch; out_len in/out.
396            let st = unsafe {
397                ffi::cu_decompress_stream_finish(
398                    self.stream,
399                    self.scratch.as_mut_ptr(),
400                    &mut out_len,
401                )
402            };
403            if out_len > 0 {
404                self.out.extend_from_slice(&self.scratch[..out_len]);
405            }
406            if st == ffi::CU_OK {
407                self.finished = true;
408                self.settle_single();
409                return Ok(());
410            }
411            if st == ffi::CU_ERR_BUF_TOO_SMALL {
412                if out_len == 0 {
413                    return Err(stuck_error());
414                }
415                return Ok(()); // more finish output next pump
416            }
417            return Err(crate::make_error(st).into());
418        }
419
420        // Decide what to feed: nothing while draining retained input, else a
421        // fresh chunk from src.
422        let mut fed = 0usize;
423        if !self.draining {
424            let src = self.src.as_mut().expect("source present until into_parts");
425            let n = src.read(&mut self.in_buf)?;
426            if n == 0 {
427                self.input_done = true;
428                return Ok(()); // re-enter in the finish phase
429            }
430            fed = n;
431        }
432
433        let mut out_len = self.scratch.len();
434        let (in_ptr, in_len) = if self.draining {
435            (std::ptr::null(), 0usize)
436        } else {
437            (self.in_buf.as_ptr(), fed)
438        };
439        // SAFETY: in/out pointers valid for their lengths; out_len in/out.
440        let st = unsafe {
441            ffi::cu_decompress_stream_write(
442                self.stream,
443                in_ptr,
444                in_len,
445                self.scratch.as_mut_ptr(),
446                &mut out_len,
447            )
448        };
449        if out_len > 0 {
450            self.out.extend_from_slice(&self.scratch[..out_len]);
451        }
452        match st {
453            ffi::CU_OK => {
454                self.draining = false;
455                self.settle_single();
456                Ok(())
457            }
458            ffi::CU_ERR_BUF_TOO_SMALL => {
459                if out_len == 0 {
460                    return Err(stuck_error());
461                }
462                self.draining = true; // unconsumed input remains; drain next
463                Ok(())
464            }
465            other => Err(crate::make_error(other).into()),
466        }
467    }
468}
469
470/// [`Decompressor::into_parts`] before the stream ended and all of its output
471/// was read. [`into_inner`](Self::into_inner) returns the decompressor, which
472/// keeps reading where it left off.
473pub struct IntoPartsError<R: Read>(Decompressor<R>);
474
475impl<R: Read> IntoPartsError<R> {
476    /// The decompressor, unchanged.
477    pub fn into_inner(self) -> Decompressor<R> {
478        self.0
479    }
480}
481
482impl<R: Read> fmt::Debug for IntoPartsError<R> {
483    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484        f.write_str("IntoPartsError")
485    }
486}
487
488impl<R: Read> fmt::Display for IntoPartsError<R> {
489    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
490        f.write_str("compress-utils: into_parts before the stream ended and its output was read")
491    }
492}
493
494impl<R: Read> std::error::Error for IntoPartsError<R> {}
495
496impl<R: Read> From<IntoPartsError<R>> for io::Error {
497    fn from(e: IntoPartsError<R>) -> io::Error {
498        io::Error::new(io::ErrorKind::Other, e.to_string())
499    }
500}
501
502impl<R: Read> Read for Decompressor<R> {
503    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
504        while self.out_pos == self.out.len() {
505            if self.finished {
506                return Ok(0);
507            }
508            // Reset the output accumulator between refills to bound memory.
509            self.out.clear();
510            self.out_pos = 0;
511            self.pump()?;
512        }
513        let n = std::cmp::min(buf.len(), self.out.len() - self.out_pos);
514        buf[..n].copy_from_slice(&self.out[self.out_pos..self.out_pos + n]);
515        self.out_pos += n;
516        Ok(n)
517    }
518}
519
520impl<R: Read> Drop for Decompressor<R> {
521    fn drop(&mut self) {
522        if !self.stream.is_null() {
523            // SAFETY: handle created by create() and not yet destroyed.
524            unsafe { ffi::cu_decompress_stream_destroy(self.stream) };
525            self.stream = std::ptr::null_mut();
526        }
527    }
528}