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