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 /// An error held back until the output decoded before it has been read.
257 pending: Option<io::Error>,
258}
259
260impl<R: Read> Decompressor<R> {
261 /// Create a decompressor reading a stream produced by `algo` from `src`.
262 pub fn new(src: R, algo: Algorithm) -> Result<Self, Error> {
263 Self::create(src, algo, 0)
264 }
265
266 /// Create a decompressor that stops at the end of the first frame (zstd or
267 /// LZ4 frame, gzip member, zlib/DEFLATE/xz/brotli/bzip2 stream, or Snappy
268 /// block) instead of continuing into whatever follows it, such as another
269 /// message on the same connection.
270 ///
271 /// `read` returns `Ok(0)` once that frame is fully decoded. It reads `src`
272 /// in chunks, so it usually reads past the end: those bytes come back from
273 /// [`unused`](Self::unused) or [`into_parts`](Self::into_parts), so the
274 /// caller can carry on reading the source:
275 ///
276 /// ```
277 /// use std::io::{Cursor, Read};
278 /// use compress_utils::{compress, Algorithm, Decompressor};
279 ///
280 /// let mut wire = compress(Algorithm::Zstd, b"first", 5).unwrap();
281 /// wire.extend_from_slice(b"rest of the source");
282 ///
283 /// let mut d = Decompressor::single_stream(Cursor::new(wire), Algorithm::Zstd).unwrap();
284 /// let mut first = Vec::new();
285 /// d.read_to_end(&mut first).unwrap();
286 /// assert_eq!(first, b"first");
287 ///
288 /// let (src, unused) = d.into_parts().unwrap();
289 /// let mut rest = Vec::new();
290 /// Cursor::new(unused).chain(src).read_to_end(&mut rest).unwrap();
291 /// assert_eq!(rest, b"rest of the source");
292 /// ```
293 ///
294 /// Raw LZ4 and LZO have no end marker to stop at and return
295 /// [`Status::UnsupportedAlgo`]. Single-mode Snappy produces no output until
296 /// its whole block has arrived, and rejects a block declaring more than
297 /// [`crate::set_max_decompressed_size`] (as set when the decompressor is
298 /// created) with [`Status::SizeLimit`].
299 pub fn single_stream(src: R, algo: Algorithm) -> Result<Self, Error> {
300 Self::create(src, algo, ffi::CU_DSTREAM_SINGLE)
301 }
302
303 fn create(src: R, algo: Algorithm, flags: u32) -> Result<Self, Error> {
304 let mut stream: *mut ffi::cu_decompress_stream = std::ptr::null_mut();
305 // SAFETY: out_stream points at a local; set to a valid handle on CU_OK.
306 let st = unsafe {
307 if flags == 0 {
308 ffi::cu_decompress_stream_create(algo.to_raw(), &mut stream)
309 } else {
310 ffi::cu_decompress_stream_create_ex(algo.to_raw(), flags, &mut stream)
311 }
312 };
313 crate::check_status(st)?;
314 Ok(Decompressor {
315 src: Some(src),
316 stream,
317 in_buf: vec![0u8; SCRATCH],
318 scratch: vec![0u8; SCRATCH],
319 out: Vec::new(),
320 out_pos: 0,
321 input_done: false,
322 draining: false,
323 finished: false,
324 single: flags & ffi::CU_DSTREAM_SINGLE != 0,
325 eof: false,
326 unused: Vec::new(),
327 pending: None,
328 })
329 }
330
331 /// Limit the total decompressed output to `bytes` (`0`, the default, means
332 /// no limit). The `read` that would go past it returns the bytes up to the
333 /// limit, then an error with [`Status::SizeLimit`]; the decompressor is
334 /// done after that. Use it when decompressing untrusted input, which can
335 /// expand to far more than its own size.
336 pub fn set_max_output(&mut self, bytes: usize) {
337 // SAFETY: `stream` is a live handle owned by `self`; the call only
338 // stores the limit.
339 unsafe { ffi::cu_decompress_stream_set_max_output(self.stream, bytes) };
340 }
341
342 /// Single-stream mode: whether the end of the stream has been decoded.
343 /// Output decoded before it may still be waiting to be read; `read`
344 /// returns `Ok(0)` once it has been. Always `false` for decompressors made
345 /// with [`Decompressor::new`].
346 pub fn is_eof(&self) -> bool {
347 self.eof
348 }
349
350 /// Single-stream mode: the bytes read from the source after the end of the
351 /// stream, in order. Empty until [`is_eof`](Self::is_eof), and always for
352 /// decompressors made with [`Decompressor::new`].
353 pub fn unused(&self) -> &[u8] {
354 &self.unused
355 }
356
357 /// Returns the source and the bytes already read from it after the end of
358 /// the stream ([`unused`](Self::unused)). Reading the unused bytes, then
359 /// the source, continues exactly where the compressed stream ended.
360 ///
361 /// Only once the stream has ended and all of its output has been read
362 /// (`read` has returned `Ok(0)`): before that, part of the stream and the
363 /// bytes after it may still be held inside the decompressor, and taking
364 /// the source would lose them. Otherwise this returns an
365 /// [`IntoPartsError`] that hands the decompressor back, so you can keep
366 /// reading. A caller that stops at the end of its own data (as `pickle`
367 /// stops at its STOP opcode) should read to `Ok(0)` first.
368 pub fn into_parts(mut self) -> Result<(R, Vec<u8>), IntoPartsError<R>> {
369 if !self.finished || self.out_pos < self.out.len() {
370 return Err(IntoPartsError(self));
371 }
372 let unused = std::mem::take(&mut self.unused);
373 let src = self.src.take().expect("source present until into_parts");
374 Ok((src, unused))
375 }
376
377 /// Single mode: after a call that returned CU_OK, latch eof once the C
378 /// stream reports it and keep the input it didn't use. Every byte read from
379 /// `src` is passed to the C stream in the same call, so its unused bytes
380 /// are all the read-ahead there is.
381 fn settle_single(&mut self) {
382 if !self.single || self.eof {
383 return;
384 }
385 // SAFETY: valid handle.
386 if unsafe { ffi::cu_decompress_stream_eof(self.stream) } == 0 {
387 return;
388 }
389 let mut data: *const u8 = std::ptr::null();
390 let mut len = 0usize;
391 // SAFETY: valid handle; data/len point at locals. The C buffer stays
392 // valid until the next call on the stream, and is copied before then.
393 let st = unsafe { ffi::cu_decompress_stream_unused(self.stream, &mut data, &mut len) };
394 if st == ffi::CU_OK && len > 0 && !data.is_null() {
395 // SAFETY: C guarantees `data` points at `len` readable bytes.
396 self.unused
397 .extend_from_slice(unsafe { std::slice::from_raw_parts(data, len) });
398 }
399 self.eof = true;
400 self.finished = true;
401 }
402
403 /// Append decompressed bytes to `out` by advancing the C stream one step.
404 /// Mirrors the Go reader's feed/drain/finish state machine.
405 fn pump(&mut self) -> io::Result<()> {
406 // Finish phase: input exhausted, flush trailing output.
407 if self.input_done && !self.draining {
408 let mut out_len = self.scratch.len();
409 // SAFETY: valid handle + scratch; out_len in/out.
410 let st = unsafe {
411 ffi::cu_decompress_stream_finish(
412 self.stream,
413 self.scratch.as_mut_ptr(),
414 &mut out_len,
415 )
416 };
417 if out_len > 0 {
418 self.out.extend_from_slice(&self.scratch[..out_len]);
419 }
420 if st == ffi::CU_OK {
421 self.finished = true;
422 self.settle_single();
423 return Ok(());
424 }
425 if st == ffi::CU_ERR_BUF_TOO_SMALL {
426 if out_len == 0 {
427 return Err(stuck_error());
428 }
429 return Ok(()); // more finish output next pump
430 }
431 return Err(crate::make_error(st).into());
432 }
433
434 // Decide what to feed: nothing while draining retained input, else a
435 // fresh chunk from src.
436 let mut fed = 0usize;
437 if !self.draining {
438 let src = self.src.as_mut().expect("source present until into_parts");
439 let n = src.read(&mut self.in_buf)?;
440 if n == 0 {
441 self.input_done = true;
442 return Ok(()); // re-enter in the finish phase
443 }
444 fed = n;
445 }
446
447 let mut out_len = self.scratch.len();
448 let (in_ptr, in_len) = if self.draining {
449 (std::ptr::null(), 0usize)
450 } else {
451 (self.in_buf.as_ptr(), fed)
452 };
453 // SAFETY: in/out pointers valid for their lengths; out_len in/out.
454 let st = unsafe {
455 ffi::cu_decompress_stream_write(
456 self.stream,
457 in_ptr,
458 in_len,
459 self.scratch.as_mut_ptr(),
460 &mut out_len,
461 )
462 };
463 if out_len > 0 {
464 self.out.extend_from_slice(&self.scratch[..out_len]);
465 }
466 match st {
467 ffi::CU_OK => {
468 self.draining = false;
469 self.settle_single();
470 Ok(())
471 }
472 ffi::CU_ERR_BUF_TOO_SMALL => {
473 if out_len == 0 {
474 return Err(stuck_error());
475 }
476 self.draining = true; // unconsumed input remains; drain next
477 Ok(())
478 }
479 other => Err(crate::make_error(other).into()),
480 }
481 }
482}
483
484/// [`Decompressor::into_parts`] before the stream ended and all of its output
485/// was read. [`into_inner`](Self::into_inner) returns the decompressor, which
486/// keeps reading where it left off.
487pub struct IntoPartsError<R: Read>(Decompressor<R>);
488
489impl<R: Read> IntoPartsError<R> {
490 /// The decompressor, unchanged.
491 pub fn into_inner(self) -> Decompressor<R> {
492 self.0
493 }
494}
495
496impl<R: Read> fmt::Debug for IntoPartsError<R> {
497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498 f.write_str("IntoPartsError")
499 }
500}
501
502impl<R: Read> fmt::Display for IntoPartsError<R> {
503 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 f.write_str("compress-utils: into_parts before the stream ended and its output was read")
505 }
506}
507
508impl<R: Read> std::error::Error for IntoPartsError<R> {}
509
510impl<R: Read> From<IntoPartsError<R>> for io::Error {
511 fn from(e: IntoPartsError<R>) -> io::Error {
512 io::Error::new(io::ErrorKind::Other, e.to_string())
513 }
514}
515
516impl<R: Read> Read for Decompressor<R> {
517 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
518 while self.out_pos == self.out.len() {
519 if let Some(e) = self.pending.take() {
520 return Err(e);
521 }
522 if self.finished {
523 return Ok(0);
524 }
525 // Reset the output accumulator between refills to bound memory.
526 self.out.clear();
527 self.out_pos = 0;
528 if let Err(e) = self.pump() {
529 if self.out.is_empty() {
530 return Err(e);
531 }
532 // Hand back the output decoded before the error first (e.g.
533 // the bytes up to a set_max_output limit); the error follows
534 // on the next call.
535 self.pending = Some(e);
536 }
537 }
538 let n = std::cmp::min(buf.len(), self.out.len() - self.out_pos);
539 buf[..n].copy_from_slice(&self.out[self.out_pos..self.out_pos + n]);
540 self.out_pos += n;
541 Ok(n)
542 }
543}
544
545impl<R: Read> Drop for Decompressor<R> {
546 fn drop(&mut self) {
547 if !self.stream.is_null() {
548 // SAFETY: handle created by create() and not yet destroyed.
549 unsafe { ffi::cu_decompress_stream_destroy(self.stream) };
550 self.stream = std::ptr::null_mut();
551 }
552 }
553}