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::io::{self, Read, Write};
13
14use crate::ffi;
15use crate::{Algorithm, Error, Status};
16
17/// Size of the fixed scratch buffer each stream drains through. The protocol
18/// works with any size; 64 KiB keeps the FFI call count low without holding
19/// much memory. Matches the Go binding.
20const SCRATCH: usize = 64 * 1024;
21
22impl From<Error> for io::Error {
23    fn from(e: Error) -> io::Error {
24        io::Error::new(io::ErrorKind::Other, e)
25    }
26}
27
28/// A `BUF_TOO_SMALL` status always accompanies a fully-written output buffer;
29/// if the codec reports it with zero bytes produced it is stuck (malformed
30/// input, or a decoder that can neither consume nor emit) and looping would
31/// spin forever / grow memory unbounded. Turn that into a hard error.
32fn stuck_error() -> io::Error {
33    Error {
34        code: Status::Decompression,
35        message: "compress-utils: decoder made no progress (malformed or truncated input)"
36            .to_string(),
37    }
38    .into()
39}
40
41/// Recover a library [`Error`] from an [`io::Error`] produced by the streaming
42/// adapters (used by the top-level [`crate::decompress`] fallback).
43pub(crate) fn io_to_error(e: io::Error) -> Error {
44    let fallback = e.to_string();
45    match e.into_inner() {
46        Some(b) => match b.downcast::<Error>() {
47            Ok(err) => *err,
48            Err(b) => Error {
49                code: Status::Internal,
50                message: b.to_string(),
51            },
52        },
53        None => Error {
54            code: Status::Internal,
55            message: fallback,
56        },
57    }
58}
59
60/// A [`Write`] that compresses into an inner sink.
61///
62/// You **must** call [`Compressor::finish`] to flush the final frame and get a
63/// clean, decodable stream. As a safety net the frame is also finalized on drop
64/// (best-effort, errors ignored), but relying on that discards any I/O error —
65/// prefer `finish`.
66pub struct Compressor<W: Write> {
67    sink: Option<W>,
68    stream: *mut ffi::cu_compress_stream,
69    scratch: Vec<u8>,
70    finished: bool,
71}
72
73impl<W: Write> Compressor<W> {
74    /// Create a compressor writing to `sink` with `algo` at `level`
75    /// (1 fastest ..= 10 smallest).
76    pub fn new(sink: W, algo: Algorithm, level: i32) -> Result<Self, Error> {
77        let mut stream: *mut ffi::cu_compress_stream = std::ptr::null_mut();
78        // SAFETY: out_stream points at a local; on CU_OK it is set to a valid
79        // handle we own until destroy.
80        let st = unsafe { ffi::cu_compress_stream_create(algo.to_raw(), level, &mut stream) };
81        crate::check_status(st)?;
82        Ok(Compressor {
83            sink: Some(sink),
84            stream,
85            scratch: vec![0u8; SCRATCH],
86            finished: false,
87        })
88    }
89
90    /// Flush the final frame, release the C stream, and return the inner sink.
91    pub fn finish(mut self) -> io::Result<W> {
92        self.do_finish()?;
93        self.destroy();
94        // SAFETY: sink is always Some until finish/drop takes it exactly once.
95        Ok(self.sink.take().expect("sink present"))
96    }
97
98    /// Drain the finalize phase to the sink. Idempotent.
99    fn do_finish(&mut self) -> io::Result<()> {
100        if self.finished {
101            return Ok(());
102        }
103        loop {
104            let mut out_len = self.scratch.len();
105            // SAFETY: valid handle + scratch buffer; out_len is in/out.
106            let st = unsafe {
107                ffi::cu_compress_stream_finish(self.stream, self.scratch.as_mut_ptr(), &mut out_len)
108            };
109            if out_len > 0 {
110                self.sink
111                    .as_mut()
112                    .expect("sink present")
113                    .write_all(&self.scratch[..out_len])?;
114            }
115            if st == ffi::CU_OK {
116                self.finished = true;
117                return Ok(());
118            }
119            if st != ffi::CU_ERR_BUF_TOO_SMALL {
120                return Err(crate::make_error(st).into());
121            }
122            if out_len == 0 {
123                return Err(stuck_error());
124            }
125        }
126    }
127
128    fn destroy(&mut self) {
129        if !self.stream.is_null() {
130            // SAFETY: handle created by create() and not yet destroyed.
131            unsafe { ffi::cu_compress_stream_destroy(self.stream) };
132            self.stream = std::ptr::null_mut();
133        }
134    }
135}
136
137impl<W: Write> Write for Compressor<W> {
138    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
139        if self.finished {
140            return Err(io::Error::new(
141                io::ErrorKind::Other,
142                "compress-utils: stream is finished",
143            ));
144        }
145        if buf.is_empty() {
146            return Ok(0);
147        }
148        let sink = self.sink.as_mut().expect("sink present");
149        let mut first = true;
150        loop {
151            let mut out_len = self.scratch.len();
152            // First call feeds the input; the stream retains any unconsumed
153            // tail internally, so subsequent drain calls feed (NULL, 0).
154            let (in_ptr, in_len) = if first {
155                (buf.as_ptr(), buf.len())
156            } else {
157                (std::ptr::null(), 0usize)
158            };
159            first = false;
160            // SAFETY: in/out pointers valid for their lengths; out_len in/out.
161            let st = unsafe {
162                ffi::cu_compress_stream_write(
163                    self.stream,
164                    in_ptr,
165                    in_len,
166                    self.scratch.as_mut_ptr(),
167                    &mut out_len,
168                )
169            };
170            if out_len > 0 {
171                sink.write_all(&self.scratch[..out_len])?;
172            }
173            if st == ffi::CU_OK {
174                return Ok(buf.len());
175            }
176            if st != ffi::CU_ERR_BUF_TOO_SMALL {
177                return Err(crate::make_error(st).into());
178            }
179            if out_len == 0 {
180                return Err(stuck_error());
181            }
182        }
183    }
184
185    fn flush(&mut self) -> io::Result<()> {
186        // Data is forwarded to the sink on every write; the C compress stream
187        // has no mid-stream flush that keeps the frame open, so we only flush
188        // the sink. Call finish() to finalize the frame.
189        if let Some(sink) = self.sink.as_mut() {
190            sink.flush()
191        } else {
192            Ok(())
193        }
194    }
195}
196
197impl<W: Write> Drop for Compressor<W> {
198    fn drop(&mut self) {
199        // Best-effort finalize so a forgotten finish() still yields a decodable
200        // stream; errors are unreportable here, hence finish() is preferred.
201        if self.sink.is_some() && !self.finished {
202            let _ = self.do_finish();
203        }
204        self.destroy();
205    }
206}
207
208/// A [`Read`] that decompresses from an inner source.
209pub struct Decompressor<R: Read> {
210    src: R,
211    stream: *mut ffi::cu_decompress_stream,
212    in_buf: Vec<u8>,
213    scratch: Vec<u8>,
214    out: Vec<u8>,
215    out_pos: usize,
216
217    input_done: bool,
218    draining: bool,
219    finished: bool,
220}
221
222impl<R: Read> Decompressor<R> {
223    /// Create a decompressor reading a stream produced by `algo` from `src`.
224    pub fn new(src: R, algo: Algorithm) -> Result<Self, Error> {
225        let mut stream: *mut ffi::cu_decompress_stream = std::ptr::null_mut();
226        // SAFETY: out_stream points at a local; set to a valid handle on CU_OK.
227        let st = unsafe { ffi::cu_decompress_stream_create(algo.to_raw(), &mut stream) };
228        crate::check_status(st)?;
229        Ok(Decompressor {
230            src,
231            stream,
232            in_buf: vec![0u8; SCRATCH],
233            scratch: vec![0u8; SCRATCH],
234            out: Vec::new(),
235            out_pos: 0,
236            input_done: false,
237            draining: false,
238            finished: false,
239        })
240    }
241
242    /// Append decompressed bytes to `out` by advancing the C stream one step.
243    /// Mirrors the Go reader's feed/drain/finish state machine.
244    fn pump(&mut self) -> io::Result<()> {
245        // Finish phase: input exhausted, flush trailing output.
246        if self.input_done && !self.draining {
247            let mut out_len = self.scratch.len();
248            // SAFETY: valid handle + scratch; out_len in/out.
249            let st = unsafe {
250                ffi::cu_decompress_stream_finish(
251                    self.stream,
252                    self.scratch.as_mut_ptr(),
253                    &mut out_len,
254                )
255            };
256            if out_len > 0 {
257                self.out.extend_from_slice(&self.scratch[..out_len]);
258            }
259            if st == ffi::CU_OK {
260                self.finished = true;
261                return Ok(());
262            }
263            if st == ffi::CU_ERR_BUF_TOO_SMALL {
264                if out_len == 0 {
265                    return Err(stuck_error());
266                }
267                return Ok(()); // more finish output next pump
268            }
269            return Err(crate::make_error(st).into());
270        }
271
272        // Decide what to feed: nothing while draining retained input, else a
273        // fresh chunk from src.
274        let mut fed = 0usize;
275        if !self.draining {
276            let n = self.src.read(&mut self.in_buf)?;
277            if n == 0 {
278                self.input_done = true;
279                return Ok(()); // re-enter in the finish phase
280            }
281            fed = n;
282        }
283
284        let mut out_len = self.scratch.len();
285        let (in_ptr, in_len) = if self.draining {
286            (std::ptr::null(), 0usize)
287        } else {
288            (self.in_buf.as_ptr(), fed)
289        };
290        // SAFETY: in/out pointers valid for their lengths; out_len in/out.
291        let st = unsafe {
292            ffi::cu_decompress_stream_write(
293                self.stream,
294                in_ptr,
295                in_len,
296                self.scratch.as_mut_ptr(),
297                &mut out_len,
298            )
299        };
300        if out_len > 0 {
301            self.out.extend_from_slice(&self.scratch[..out_len]);
302        }
303        match st {
304            ffi::CU_OK => {
305                self.draining = false;
306                Ok(())
307            }
308            ffi::CU_ERR_BUF_TOO_SMALL => {
309                if out_len == 0 {
310                    return Err(stuck_error());
311                }
312                self.draining = true; // unconsumed input remains; drain next
313                Ok(())
314            }
315            other => Err(crate::make_error(other).into()),
316        }
317    }
318}
319
320impl<R: Read> Read for Decompressor<R> {
321    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
322        while self.out_pos == self.out.len() {
323            if self.finished {
324                return Ok(0);
325            }
326            // Reset the output accumulator between refills to bound memory.
327            self.out.clear();
328            self.out_pos = 0;
329            self.pump()?;
330        }
331        let n = std::cmp::min(buf.len(), self.out.len() - self.out_pos);
332        buf[..n].copy_from_slice(&self.out[self.out_pos..self.out_pos + n]);
333        self.out_pos += n;
334        Ok(n)
335    }
336}
337
338impl<R: Read> Drop for Decompressor<R> {
339    fn drop(&mut self) {
340        if !self.stream.is_null() {
341            // SAFETY: handle created by create() and not yet destroyed.
342            unsafe { ffi::cu_decompress_stream_destroy(self.stream) };
343            self.stream = std::ptr::null_mut();
344        }
345    }
346}