Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure buffers are flushed to avoid decompression stream underread #251

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added assets/zeros64.zst
Binary file not shown.
4 changes: 3 additions & 1 deletion src/stream/read/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,9 @@ impl<'a, R: BufRead> Decoder<'a, R> {
///
/// Calling `finish()` is not *required* after reading a stream -
/// just use it if you need to get the `Read` back.
pub fn finish(self) -> R {
pub fn finish(mut self) -> R {
// Ensure the input buffers have been flushed by reading to a zero-length buffer.
let _ = self.reader.read(&mut [0; 0]);
self.reader.into_inner()
}

Expand Down
38 changes: 38 additions & 0 deletions tests/issue_251.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use std::io::Read;

#[test]
fn test_issue_251() {
// This is 64 compressed zero bytes.
let compressed_data = include_bytes!("../assets/zeros64.zst");
let decompressed_size = 64;

// Construct a decompressor using `with_buffer`. This should be ok as
// `Cursor` is `BufRead`.
let reader = std::io::Cursor::new(compressed_data);
let mut decomp = zstd::Decoder::with_buffer(reader).unwrap();

// Count how many bytes we decompress.
let mut total = 0;

// Decompress four bytes at a time (this is necessary to trigger underrun
// behaviour).
for _ in 0..(decompressed_size / 4) {
let mut buf = [0u8; 4];
let count = decomp.read(&mut buf).unwrap();
total += count;
}

// Finish reading and get the buffer back.
let reader = decomp.finish();

// The cursor should now be at the end of the compressed data.
println!("We read {total}/{decompressed_size} decompressed bytes");
println!(
"The underlying cursor is at position {} of {} compressed bytes",
reader.position(),
compressed_data.len()
);

assert_eq!(total, decompressed_size);
assert_eq!(reader.position() as usize, compressed_data.len());
}