pub struct Decoder { /* private fields */ }
Expand description
A low-level decoder implementation
This decoder does no IO by itself, instead enough data has to be written to it in order for it to be able to decode the next block. After that the decompressed content for the block can be read until all of the data from the block has been exhausted. Repeating this process for every block in sequence will result into the entire file being decompressed.
use bzip2_rs::decoder::{Decoder, ReadState, WriteState};
let mut compressed_file: &[u8] = include_bytes!("../../tests/samplefiles/sample1.bz2").as_ref();
let mut output = Vec::new();
let mut decoder = Decoder::new();
assert!(
!compressed_file.is_empty(),
"empty files will cause the following loop to spin forever"
);
let mut buf = [0; 1024];
loop {
match decoder.read(&mut buf)? {
ReadState::NeedsWrite(space) => {
// `Decoder` needs more data to be written to it before it
// can decode the next block.
// If we reached the end of the file `compressed_file.len()` will be 0,
// signaling to the `Decoder` that the last block is smaller and it can
// proceed with reading.
match decoder.write(&compressed_file)? {
WriteState::NeedsRead => unreachable!(),
WriteState::Written(written) => compressed_file = &compressed_file[written..],
};
}
ReadState::Read(n) => {
// `n` uncompressed bytes have been read into `buf`
output.extend_from_slice(&buf[..n]);
}
ReadState::Eof => {
// we reached the end of the file
break;
}
}
}
// `output` contains the decompressed file
let decompressed_file: &[u8] = include_bytes!("../../tests/samplefiles/sample1.ref").as_ref();
assert_eq!(output, decompressed_file);
Implementations§
Source§impl Decoder
impl Decoder
Sourcepub fn write(&mut self, buf: &[u8]) -> Result<WriteState, DecoderError>
pub fn write(&mut self, buf: &[u8]) -> Result<WriteState, DecoderError>
Write more compressed data into this Decoder
See the documentation for WriteState
to decide
what to do next.
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Decoder
impl RefUnwindSafe for Decoder
impl Send for Decoder
impl Sync for Decoder
impl Unpin for Decoder
impl UnwindSafe for Decoder
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more