M1 primary view: wx-rs patched+extended (Linux/GTK3 build, widget bridge), vendored wx 3.3.3 + asic-rs in thirdparty/, UI-SPEC table+KPIs+dialogs, build scripts

This commit is contained in:
2026-09-15 13:59:55 -06:00
parent 165d899fd8
commit b264cdd6d1
16316 changed files with 4932188 additions and 58 deletions
+336
View File
@@ -0,0 +1,336 @@
//! I/O streams for wrapping `BufRead` types as encoders/decoders
use std::io;
use std::io::prelude::*;
#[cfg(feature = "tokio")]
use futures::Poll;
#[cfg(feature = "tokio")]
use tokio_io::{AsyncRead, AsyncWrite};
use {Action, Compress, Compression, Decompress, Status};
/// A bz2 encoder, or compressor.
///
/// This structure implements a `BufRead` interface and will read uncompressed
/// data from an underlying stream and emit a stream of compressed data.
pub struct BzEncoder<R> {
obj: R,
data: Compress,
done: bool,
}
/// A bz2 decoder, or decompressor.
///
/// This structure implements a `BufRead` interface and takes a stream of
/// compressed data as input, providing the decompressed data when read from.
pub struct BzDecoder<R> {
obj: R,
data: Decompress,
done: bool,
multi: bool,
}
impl<R: BufRead> BzEncoder<R> {
/// Creates a new encoder which will read uncompressed data from the given
/// stream and emit the compressed stream.
pub fn new(r: R, level: Compression) -> BzEncoder<R> {
BzEncoder {
obj: r,
data: Compress::new(level, 30),
done: false,
}
}
}
impl<R> BzEncoder<R> {
/// Acquires a reference to the underlying stream
pub fn get_ref(&self) -> &R {
&self.obj
}
/// Acquires a mutable reference to the underlying stream
///
/// Note that mutation of the stream may result in surprising results if
/// this encoder is continued to be used.
pub fn get_mut(&mut self) -> &mut R {
&mut self.obj
}
/// Consumes this encoder, returning the underlying reader.
pub fn into_inner(self) -> R {
self.obj
}
/// Returns the number of bytes produced by the compressor
/// (e.g. the number of bytes read from this stream)
///
/// Note that, due to buffering, this only bears any relation to
/// total_in() when the compressor chooses to flush its data
/// (unfortunately, this won't happen in general
/// at the end of the stream, because the compressor doesn't know
/// if there's more data to come). At that point,
/// `total_out() / total_in()` would be the compression ratio.
pub fn total_out(&self) -> u64 {
self.data.total_out()
}
/// Returns the number of bytes consumed by the compressor
/// (e.g. the number of bytes read from the underlying stream)
pub fn total_in(&self) -> u64 {
self.data.total_in()
}
}
impl<R: BufRead> Read for BzEncoder<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.done {
return Ok(0);
}
loop {
let (read, consumed, eof, ret);
{
let input = self.obj.fill_buf()?;
eof = input.is_empty();
let before_out = self.data.total_out();
let before_in = self.data.total_in();
let action = if eof { Action::Finish } else { Action::Run };
ret = self.data.compress(input, buf, action);
read = (self.data.total_out() - before_out) as usize;
consumed = (self.data.total_in() - before_in) as usize;
}
self.obj.consume(consumed);
// we should never get the sequence error that's possible to be
// returned from compression
let ret = ret.unwrap();
// If we haven't ready any data and we haven't hit EOF yet, then we
// need to keep asking for more data because if we return that 0
// bytes of data have been read then it will be interpreted as EOF.
if read == 0 && !eof && buf.len() > 0 {
continue;
}
if ret == Status::StreamEnd {
self.done = true;
}
return Ok(read);
}
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncRead + BufRead> AsyncRead for BzEncoder<R> {}
impl<W: Write> Write for BzEncoder<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.get_mut().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.get_mut().flush()
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncWrite> AsyncWrite for BzEncoder<R> {
fn shutdown(&mut self) -> Poll<(), io::Error> {
self.get_mut().shutdown()
}
}
impl<R: BufRead> BzDecoder<R> {
/// Creates a new decoder which will decompress data read from the given
/// stream.
pub fn new(r: R) -> BzDecoder<R> {
BzDecoder {
obj: r,
data: Decompress::new(false),
done: false,
multi: false,
}
}
fn multi(mut self, flag: bool) -> BzDecoder<R> {
self.multi = flag;
self
}
}
impl<R> BzDecoder<R> {
/// Acquires a reference to the underlying stream
pub fn get_ref(&self) -> &R {
&self.obj
}
/// Acquires a mutable reference to the underlying stream
///
/// Note that mutation of the stream may result in surprising results if
/// this encoder is continued to be used.
pub fn get_mut(&mut self) -> &mut R {
&mut self.obj
}
/// Consumes this decoder, returning the underlying reader.
pub fn into_inner(self) -> R {
self.obj
}
/// Returns the number of bytes that the decompressor has consumed.
///
/// Note that this will likely be smaller than what the decompressor
/// actually read from the underlying stream due to buffering.
pub fn total_in(&self) -> u64 {
self.data.total_in()
}
/// Returns the number of bytes that the decompressor has produced.
pub fn total_out(&self) -> u64 {
self.data.total_out()
}
}
impl<R: BufRead> Read for BzDecoder<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
loop {
if self.done && !self.multi {
return Ok(0);
}
let (read, consumed, remaining, ret);
{
let input = self.obj.fill_buf()?;
if self.done {
assert!(self.multi);
if input.is_empty() {
// beyond last stream in multi-stream case
return Ok(0);
} else {
// previous stream ended, more data follows => create new decompressor
self.data = Decompress::new(false);
self.done = false;
}
}
let before_out = self.data.total_out();
let before_in = self.data.total_in();
ret = self.data.decompress(input, buf);
read = (self.data.total_out() - before_out) as usize;
consumed = (self.data.total_in() - before_in) as usize;
remaining = input.len() - consumed;
}
self.obj.consume(consumed);
let ret = ret.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
if ret == Status::StreamEnd {
self.done = true;
} else if consumed == 0 && remaining == 0 && read == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"decompression not finished but EOF reached",
));
}
if read > 0 || buf.len() == 0 {
return Ok(read);
}
}
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncRead + BufRead> AsyncRead for BzDecoder<R> {}
impl<W: Write> Write for BzDecoder<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.get_mut().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.get_mut().flush()
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncWrite> AsyncWrite for BzDecoder<R> {
fn shutdown(&mut self) -> Poll<(), io::Error> {
self.get_mut().shutdown()
}
}
/// A bzip2 streaming decoder that decodes all members of a multistream.
///
/// Wikipedia, particularly, uses bzip2 multistream for their dumps, and the
/// `pbzip2` tool creates such data as well;
pub struct MultiBzDecoder<R>(BzDecoder<R>);
impl<R: BufRead> MultiBzDecoder<R> {
/// Creates a new decoder from the given reader. If the bzip2 stream contains multiple members
/// all will be decoded.
pub fn new(r: R) -> MultiBzDecoder<R> {
MultiBzDecoder(BzDecoder::new(r).multi(true))
}
}
impl<R> MultiBzDecoder<R> {
/// Acquires a reference to the underlying reader.
pub fn get_ref(&self) -> &R {
self.0.get_ref()
}
/// Acquires a mutable reference to the underlying stream.
///
/// Note that mutation of the stream may result in surprising results if
/// this encoder is continued to be used.
pub fn get_mut(&mut self) -> &mut R {
self.0.get_mut()
}
/// Consumes this decoder, returning the underlying reader.
pub fn into_inner(self) -> R {
self.0.into_inner()
}
}
impl<R: BufRead> Read for MultiBzDecoder<R> {
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
self.0.read(into)
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncRead + BufRead> AsyncRead for MultiBzDecoder<R> {}
impl<R: BufRead + Write> Write for MultiBzDecoder<R> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.get_mut().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.get_mut().flush()
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncWrite + BufRead> AsyncWrite for MultiBzDecoder<R> {
fn shutdown(&mut self) -> Poll<(), io::Error> {
self.get_mut().shutdown()
}
}
#[cfg(test)]
mod tests {
use super::MultiBzDecoder;
use std::io::{BufReader, Read};
#[test]
fn bug_61() {
let compressed_bytes = include_bytes!("../tests/bug_61.bz2");
let uncompressed_bytes = include_bytes!("../tests/bug_61.raw");
let reader = BufReader::with_capacity(8192, compressed_bytes.as_ref());
let mut d = MultiBzDecoder::new(reader);
let mut data = Vec::new();
assert_eq!(d.read_to_end(&mut data).unwrap(), uncompressed_bytes.len());
assert_eq!(data, uncompressed_bytes);
}
}
+125
View File
@@ -0,0 +1,125 @@
//! Bzip compression for Rust
//!
//! This library contains bindings to libbz2 to support bzip compression and
//! decompression for Rust. The streams offered in this library are primarily
//! found in the `reader` and `writer` modules. Both compressors and
//! decompressors are available in each module depending on what operation you
//! need.
//!
//! Access to the raw decompression/compression stream is also provided through
//! the `raw` module which has a much closer interface to libbz2.
//!
//! # Example
//!
//! ```
//! use std::io::prelude::*;
//! use bzip2::Compression;
//! use bzip2::read::{BzEncoder, BzDecoder};
//!
//! // Round trip some bytes from a byte source, into a compressor, into a
//! // decompressor, and finally into a vector.
//! let data = "Hello, World!".as_bytes();
//! let compressor = BzEncoder::new(data, Compression::best());
//! let mut decompressor = BzDecoder::new(compressor);
//!
//! let mut contents = String::new();
//! decompressor.read_to_string(&mut contents).unwrap();
//! assert_eq!(contents, "Hello, World!");
//! ```
//!
//! # Multistreams (e.g. Wikipedia or pbzip2)
//!
//! Some tools such as pbzip2 or data from sources such as Wikipedia
//! are encoded as so called bzip2 "multistreams," meaning they
//! contain back to back chunks of bzip'd data. `BzDecoder` does not
//! attempt to convert anything after the the first bzip chunk in the
//! source stream. Thus, if you wish to decode all bzip chunks from
//! the input until end of file, use `MultiBzDecoder`.
//!
//! *Protip*: If you use `BzDecoder` to decode data and the output is
//! incomplete and exactly 900K bytes, you probably need a
//! `MultiBzDecoder`.
//!
//! # Async I/O
//!
//! This crate optionally can support async I/O streams with the Tokio stack via
//! the `tokio` feature of this crate:
//!
//! ```toml
//! bzip2 = { version = "0.4", features = ["tokio"] }
//! ```
//!
//! All methods are internally capable of working with streams that may return
//! `ErrorKind::WouldBlock` when they're not ready to perform the particular
//! operation.
//!
//! Note that care needs to be taken when using these objects, however. The
//! Tokio runtime, in particular, requires that data is fully flushed before
//! dropping streams. For compatibility with blocking streams all streams are
//! flushed/written when they are dropped, and this is not always a suitable
//! time to perform I/O. If I/O streams are flushed before drop, however, then
//! these operations will be a noop.
#![deny(missing_docs)]
#![doc(html_root_url = "https://docs.rs/bzip2/")]
extern crate bzip2_sys as ffi;
extern crate libc;
#[cfg(test)]
extern crate partial_io;
#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
extern crate rand;
#[cfg(feature = "tokio")]
#[macro_use]
extern crate tokio_io;
#[cfg(feature = "tokio")]
extern crate futures;
pub use mem::{Action, Compress, Decompress, Error, Status};
mod mem;
pub mod bufread;
pub mod read;
pub mod write;
/// When compressing data, the compression level can be specified by a value in
/// this enum.
#[derive(Copy, Clone, Debug)]
pub struct Compression(u32);
impl Compression {
/// Create a new compression spec with a specific numeric level (0-9).
pub fn new(level: u32) -> Compression {
Compression(level)
}
/// Do not compress.
pub fn none() -> Compression {
Compression(0)
}
/// Optimize for the best speed of encoding.
pub fn fast() -> Compression {
Compression(1)
}
/// Optimize for the size of data being encoded.
pub fn best() -> Compression {
Compression(9)
}
/// Return the compression level as an integer.
pub fn level(&self) -> u32 {
self.0
}
}
impl Default for Compression {
/// Choose the default compression, a balance between speed and size.
fn default() -> Compression {
Compression(6)
}
}
+324
View File
@@ -0,0 +1,324 @@
//! Raw low-level manipulations of bz streams.
use std::error;
use std::fmt;
use std::marker;
use std::mem;
use std::slice;
use libc::{c_int, c_uint};
use {ffi, Compression};
/// Representation of an in-memory compression stream.
///
/// An instance of `Compress` can be used to compress a stream of bz2 data.
pub struct Compress {
inner: Stream<DirCompress>,
}
/// Representation of an in-memory decompression stream.
///
/// An instance of `Decompress` can be used to inflate a stream of bz2-encoded
/// data.
pub struct Decompress {
inner: Stream<DirDecompress>,
}
struct Stream<D: Direction> {
// libbz2 requires a stable address for this stream.
raw: Box<ffi::bz_stream>,
_marker: marker::PhantomData<D>,
}
unsafe impl<D: Direction> Send for Stream<D> {}
unsafe impl<D: Direction> Sync for Stream<D> {}
trait Direction {
unsafe fn destroy(stream: *mut ffi::bz_stream) -> c_int;
}
enum DirCompress {}
enum DirDecompress {}
/// Possible actions to take on compression.
#[derive(PartialEq, Eq, Copy, Debug, Clone)]
pub enum Action {
/// Normal compression.
Run = ffi::BZ_RUN as isize,
/// Request that the current compression block is terminate.
Flush = ffi::BZ_FLUSH as isize,
/// Request that the compression stream be finalized.
Finish = ffi::BZ_FINISH as isize,
}
/// Result of compression or decompression
#[derive(PartialEq, Eq, Copy, Debug, Clone)]
pub enum Status {
/// Decompression went fine, nothing much to report.
Ok,
/// The Flush action on a compression went ok.
FlushOk,
/// THe Run action on compression went ok.
RunOk,
/// The Finish action on compression went ok.
FinishOk,
/// The stream's end has been met, meaning that no more data can be input.
StreamEnd,
/// There was insufficient memory in the input or output buffer to complete
/// the request, but otherwise everything went normally.
MemNeeded,
}
/// Fatal errors encountered when compressing/decompressing bytes.
///
/// These errors indicate that progress could not be made in any form due to
/// input or output parameters.
#[derive(PartialEq, Eq, Copy, Debug, Clone)]
pub enum Error {
/// The sequence of operations called on a decompression/compression stream
/// were invalid. See methods for details.
Sequence,
/// The data being decompressed was invalid, or it was not a valid bz2
/// stream.
Data,
/// The magic bz2 header wasn't present when decompressing.
DataMagic,
/// The parameters to this function were invalid.
Param,
}
impl Compress {
/// Creates a new stream prepared for compression.
///
/// The `work_factor` parameter controls how the compression phase behaves
/// when presented with worst case, highly repetitive, input data. If
/// compression runs into difficulties caused by repetitive data, the
/// library switches from the standard sorting algorithm to a fallback
/// algorithm. The fallback is slower than the standard algorithm by perhaps
/// a factor of three, but always behaves reasonably, no matter how bad the
/// input.
///
/// Lower values of `work_factor` reduce the amount of effort the standard
/// algorithm will expend before resorting to the fallback. You should set
/// this parameter carefully; too low, and many inputs will be handled by
/// the fallback algorithm and so compress rather slowly, too high, and your
/// average-to-worst case compression times can become very large. The
/// default value of 30 gives reasonable behaviour over a wide range of
/// circumstances.
///
/// Allowable values range from 0 to 250 inclusive. 0 is a special case,
/// equivalent to using the default value of 30.
pub fn new(lvl: Compression, work_factor: u32) -> Compress {
unsafe {
let mut raw = Box::new(mem::zeroed());
assert_eq!(
ffi::BZ2_bzCompressInit(&mut *raw, lvl.level() as c_int, 0, work_factor as c_int),
0
);
Compress {
inner: Stream {
raw: raw,
_marker: marker::PhantomData,
},
}
}
}
/// Compress a block of input into a block of output.
///
/// If anything other than BZ_OK is seen, `Err` is returned. The action
/// given must be one of Run, Flush or Finish.
pub fn compress(
&mut self,
input: &[u8],
output: &mut [u8],
action: Action,
) -> Result<Status, Error> {
// apparently 0-length compression requests which don't actually make
// any progress are returned as BZ_PARAM_ERROR, which we don't want, to
// just translate to a success here.
if input.len() == 0 && action == Action::Run {
return Ok(Status::RunOk);
}
self.inner.raw.next_in = input.as_ptr() as *mut _;
self.inner.raw.avail_in = input.len().min(c_uint::MAX as usize) as c_uint;
self.inner.raw.next_out = output.as_mut_ptr() as *mut _;
self.inner.raw.avail_out = output.len().min(c_uint::MAX as usize) as c_uint;
unsafe {
match ffi::BZ2_bzCompress(&mut *self.inner.raw, action as c_int) {
ffi::BZ_RUN_OK => Ok(Status::RunOk),
ffi::BZ_FLUSH_OK => Ok(Status::FlushOk),
ffi::BZ_FINISH_OK => Ok(Status::FinishOk),
ffi::BZ_STREAM_END => Ok(Status::StreamEnd),
ffi::BZ_SEQUENCE_ERROR => Err(Error::Sequence),
c => panic!("unknown return status: {}", c),
}
}
}
/// Compress a block of input into an output vector.
///
/// This function will not grow `output`, but it will fill the space after
/// its current length up to its capacity. The length of the vector will be
/// adjusted appropriately.
pub fn compress_vec(
&mut self,
input: &[u8],
output: &mut Vec<u8>,
action: Action,
) -> Result<Status, Error> {
let cap = output.capacity();
let len = output.len();
unsafe {
let before = self.total_out();
let ret = {
let ptr = output.as_mut_ptr().offset(len as isize);
let out = slice::from_raw_parts_mut(ptr, cap - len);
self.compress(input, out, action)
};
output.set_len((self.total_out() - before) as usize + len);
return ret;
}
}
/// Total number of bytes processed as input
pub fn total_in(&self) -> u64 {
self.inner.total_in()
}
/// Total number of bytes processed as output
pub fn total_out(&self) -> u64 {
self.inner.total_out()
}
}
impl Decompress {
/// Creates a new stream prepared for decompression.
///
/// If `small` is true, then the library will use an alternative
/// decompression algorithm which uses less memory but at the cost of
/// decompressing more slowly (roughly speaking, half the speed, but the
/// maximum memory requirement drops to around 2300k). See
pub fn new(small: bool) -> Decompress {
unsafe {
let mut raw = Box::new(mem::zeroed());
assert_eq!(ffi::BZ2_bzDecompressInit(&mut *raw, 0, small as c_int), 0);
Decompress {
inner: Stream {
raw: raw,
_marker: marker::PhantomData,
},
}
}
}
/// Decompress a block of input into a block of output.
pub fn decompress(&mut self, input: &[u8], output: &mut [u8]) -> Result<Status, Error> {
self.inner.raw.next_in = input.as_ptr() as *mut _;
self.inner.raw.avail_in = input.len().min(c_uint::MAX as usize) as c_uint;
self.inner.raw.next_out = output.as_mut_ptr() as *mut _;
self.inner.raw.avail_out = output.len().min(c_uint::MAX as usize) as c_uint;
unsafe {
match ffi::BZ2_bzDecompress(&mut *self.inner.raw) {
ffi::BZ_OK => Ok(Status::Ok),
ffi::BZ_MEM_ERROR => Ok(Status::MemNeeded),
ffi::BZ_STREAM_END => Ok(Status::StreamEnd),
ffi::BZ_PARAM_ERROR => Err(Error::Param),
ffi::BZ_DATA_ERROR => Err(Error::Data),
ffi::BZ_DATA_ERROR_MAGIC => Err(Error::DataMagic),
ffi::BZ_SEQUENCE_ERROR => Err(Error::Sequence),
c => panic!("wut: {}", c),
}
}
}
/// Decompress a block of input into an output vector.
///
/// This function will not grow `output`, but it will fill the space after
/// its current length up to its capacity. The length of the vector will be
/// adjusted appropriately.
pub fn decompress_vec(&mut self, input: &[u8], output: &mut Vec<u8>) -> Result<Status, Error> {
let cap = output.capacity();
let len = output.len();
unsafe {
let before = self.total_out();
let ret = {
let ptr = output.as_mut_ptr().offset(len as isize);
let out = slice::from_raw_parts_mut(ptr, cap - len);
self.decompress(input, out)
};
output.set_len((self.total_out() - before) as usize + len);
return ret;
}
}
/// Total number of bytes processed as input
pub fn total_in(&self) -> u64 {
self.inner.total_in()
}
/// Total number of bytes processed as output
pub fn total_out(&self) -> u64 {
self.inner.total_out()
}
}
impl<D: Direction> Stream<D> {
fn total_in(&self) -> u64 {
(self.raw.total_in_lo32 as u64) | ((self.raw.total_in_hi32 as u64) << 32)
}
fn total_out(&self) -> u64 {
(self.raw.total_out_lo32 as u64) | ((self.raw.total_out_hi32 as u64) << 32)
}
}
impl error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let description = match self {
Error::Sequence => "bzip2: sequence of operations invalid",
Error::Data => "bzip2: invalid data",
Error::DataMagic => "bzip2: bz2 header missing",
Error::Param => "bzip2: invalid parameters",
};
f.write_str(description)
}
}
impl From<Error> for std::io::Error {
fn from(data: Error) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::Other, data)
}
}
impl Direction for DirCompress {
unsafe fn destroy(stream: *mut ffi::bz_stream) -> c_int {
ffi::BZ2_bzCompressEnd(stream)
}
}
impl Direction for DirDecompress {
unsafe fn destroy(stream: *mut ffi::bz_stream) -> c_int {
ffi::BZ2_bzDecompressEnd(stream)
}
}
impl<D: Direction> Drop for Stream<D> {
fn drop(&mut self) {
unsafe {
let _ = D::destroy(&mut *self.raw);
}
}
}
+383
View File
@@ -0,0 +1,383 @@
//! Reader-based compression/decompression streams
use std::io::prelude::*;
use std::io::{self, BufReader};
#[cfg(feature = "tokio")]
use futures::Poll;
#[cfg(feature = "tokio")]
use tokio_io::{AsyncRead, AsyncWrite};
use bufread;
use Compression;
/// A compression stream which wraps an uncompressed stream of data. Compressed
/// data will be read from the stream.
pub struct BzEncoder<R> {
inner: bufread::BzEncoder<BufReader<R>>,
}
/// A decompression stream which wraps a compressed stream of data. Decompressed
/// data will be read from the stream.
pub struct BzDecoder<R> {
inner: bufread::BzDecoder<BufReader<R>>,
}
impl<R: Read> BzEncoder<R> {
/// Create a new compression stream which will compress at the given level
/// to read compress output to the give output stream.
pub fn new(r: R, level: Compression) -> BzEncoder<R> {
BzEncoder {
inner: bufread::BzEncoder::new(BufReader::new(r), level),
}
}
/// Acquires a reference to the underlying stream
pub fn get_ref(&self) -> &R {
self.inner.get_ref().get_ref()
}
/// Acquires a mutable reference to the underlying stream
///
/// Note that mutation of the stream may result in surprising results if
/// this encoder is continued to be used.
pub fn get_mut(&mut self) -> &mut R {
self.inner.get_mut().get_mut()
}
/// Unwrap the underlying writer, finishing the compression stream.
pub fn into_inner(self) -> R {
self.inner.into_inner().into_inner()
}
/// Returns the number of bytes produced by the compressor
/// (e.g. the number of bytes read from this stream)
///
/// Note that, due to buffering, this only bears any relation to
/// total_in() when the compressor chooses to flush its data
/// (unfortunately, this won't happen in general
/// at the end of the stream, because the compressor doesn't know
/// if there's more data to come). At that point,
/// `total_out() / total_in()` would be the compression ratio.
pub fn total_out(&self) -> u64 {
self.inner.total_out()
}
/// Returns the number of bytes consumed by the compressor
/// (e.g. the number of bytes read from the underlying stream)
pub fn total_in(&self) -> u64 {
self.inner.total_in()
}
}
impl<R: Read> Read for BzEncoder<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncRead> AsyncRead for BzEncoder<R> {}
impl<W: Write + Read> Write for BzEncoder<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.get_mut().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.get_mut().flush()
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncWrite + Read> AsyncWrite for BzEncoder<R> {
fn shutdown(&mut self) -> Poll<(), io::Error> {
self.get_mut().shutdown()
}
}
impl<R: Read> BzDecoder<R> {
/// Create a new decompression stream, which will read compressed
/// data from the given input stream and decompress it.
pub fn new(r: R) -> BzDecoder<R> {
BzDecoder {
inner: bufread::BzDecoder::new(BufReader::new(r)),
}
}
/// Acquires a reference to the underlying stream
pub fn get_ref(&self) -> &R {
self.inner.get_ref().get_ref()
}
/// Acquires a mutable reference to the underlying stream
///
/// Note that mutation of the stream may result in surprising results if
/// this encoder is continued to be used.
pub fn get_mut(&mut self) -> &mut R {
self.inner.get_mut().get_mut()
}
/// Unwrap the underlying writer, finishing the compression stream.
pub fn into_inner(self) -> R {
self.inner.into_inner().into_inner()
}
/// Returns the number of bytes produced by the decompressor
/// (e.g. the number of bytes read from this stream)
///
/// Note that, due to buffering, this only bears any relation to
/// total_in() when the decompressor reaches a sync point
/// (e.g. where the original compressed stream was flushed).
/// At that point, `total_in() / total_out()` is the compression ratio.
pub fn total_out(&self) -> u64 {
self.inner.total_out()
}
/// Returns the number of bytes consumed by the decompressor
/// (e.g. the number of bytes read from the underlying stream)
pub fn total_in(&self) -> u64 {
self.inner.total_in()
}
}
impl<R: Read> Read for BzDecoder<R> {
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
self.inner.read(into)
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncRead + Read> AsyncRead for BzDecoder<R> {}
impl<W: Write + Read> Write for BzDecoder<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.get_mut().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.get_mut().flush()
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncWrite + Read> AsyncWrite for BzDecoder<R> {
fn shutdown(&mut self) -> Poll<(), io::Error> {
self.get_mut().shutdown()
}
}
/// A bzip2 streaming decoder that decodes all members of a multistream
///
/// Wikipedia, particularly, uses bzip2 multistream for their dumps.
pub struct MultiBzDecoder<R> {
inner: bufread::MultiBzDecoder<BufReader<R>>,
}
impl<R: Read> MultiBzDecoder<R> {
/// Creates a new decoder from the given reader, immediately parsing the
/// (first) gzip header. If the gzip stream contains multiple members all will
/// be decoded.
pub fn new(r: R) -> MultiBzDecoder<R> {
MultiBzDecoder {
inner: bufread::MultiBzDecoder::new(BufReader::new(r)),
}
}
}
impl<R> MultiBzDecoder<R> {
/// Acquires a reference to the underlying reader.
pub fn get_ref(&self) -> &R {
self.inner.get_ref().get_ref()
}
/// Acquires a mutable reference to the underlying stream.
///
/// Note that mutation of the stream may result in surprising results if
/// this encoder is continued to be used.
pub fn get_mut(&mut self) -> &mut R {
self.inner.get_mut().get_mut()
}
/// Consumes this decoder, returning the underlying reader.
pub fn into_inner(self) -> R {
self.inner.into_inner().into_inner()
}
}
impl<R: Read> Read for MultiBzDecoder<R> {
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
self.inner.read(into)
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncRead> AsyncRead for MultiBzDecoder<R> {}
impl<R: Read + Write> Write for MultiBzDecoder<R> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.get_mut().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.get_mut().flush()
}
}
#[cfg(feature = "tokio")]
impl<R: AsyncWrite + AsyncRead> AsyncWrite for MultiBzDecoder<R> {
fn shutdown(&mut self) -> Poll<(), io::Error> {
self.get_mut().shutdown()
}
}
#[cfg(test)]
mod tests {
use partial_io::{GenInterrupted, PartialRead, PartialWithErrors};
use rand::distributions::Standard;
use rand::{thread_rng, Rng};
use read::{BzDecoder, BzEncoder, MultiBzDecoder};
use std::io::prelude::*;
use Compression;
#[test]
fn smoke() {
let m: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8];
let mut c = BzEncoder::new(m, Compression::default());
let mut data = vec![];
c.read_to_end(&mut data).unwrap();
let mut d = BzDecoder::new(&data[..]);
let mut data2 = Vec::new();
d.read_to_end(&mut data2).unwrap();
assert_eq!(data2, m);
}
#[test]
fn smoke2() {
let m: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8];
let c = BzEncoder::new(m, Compression::default());
let mut d = BzDecoder::new(c);
let mut data = vec![];
d.read_to_end(&mut data).unwrap();
assert_eq!(data, [1, 2, 3, 4, 5, 6, 7, 8]);
}
#[test]
fn smoke3() {
let m = vec![3u8; 128 * 1024 + 1];
let c = BzEncoder::new(&m[..], Compression::default());
let mut d = BzDecoder::new(c);
let mut data = vec![];
d.read_to_end(&mut data).unwrap();
assert!(data == &m[..]);
}
#[test]
fn self_terminating() {
let m = vec![3u8; 128 * 1024 + 1];
let mut c = BzEncoder::new(&m[..], Compression::default());
let mut result = Vec::new();
c.read_to_end(&mut result).unwrap();
let v = thread_rng()
.sample_iter(&Standard)
.take(1024)
.collect::<Vec<_>>();
for _ in 0..200 {
result.extend(v.iter().map(|x: &u8| *x));
}
let mut d = BzDecoder::new(&result[..]);
let mut data = Vec::with_capacity(m.len());
unsafe {
data.set_len(m.len());
}
assert!(d.read(&mut data).unwrap() == m.len());
assert!(data == &m[..]);
}
#[test]
fn zero_length_read_at_eof() {
let m = Vec::new();
let mut c = BzEncoder::new(&m[..], Compression::default());
let mut result = Vec::new();
c.read_to_end(&mut result).unwrap();
let mut d = BzDecoder::new(&result[..]);
let mut data = Vec::new();
assert!(d.read(&mut data).unwrap() == 0);
}
#[test]
fn zero_length_read_with_data() {
let m = vec![3u8; 128 * 1024 + 1];
let mut c = BzEncoder::new(&m[..], Compression::default());
let mut result = Vec::new();
c.read_to_end(&mut result).unwrap();
let mut d = BzDecoder::new(&result[..]);
let mut data = Vec::new();
assert!(d.read(&mut data).unwrap() == 0);
}
#[test]
fn multistream_read_till_eof() {
let m = vec![3u8; 128 * 1024 + 1];
let repeat = 3;
let mut result = Vec::new();
for _i in 0..repeat {
let mut c = BzEncoder::new(&m[..], Compression::default());
c.read_to_end(&mut result).unwrap();
}
let mut d = MultiBzDecoder::new(&result[..]);
let mut data = Vec::new();
let a = d.read_to_end(&mut data).unwrap();
let b = m.len() * repeat;
assert!(a == b, "{} {}", a, b);
}
#[test]
fn empty() {
let r = BzEncoder::new(&[][..], Compression::default());
let mut r = BzDecoder::new(r);
let mut v2 = Vec::new();
r.read_to_end(&mut v2).unwrap();
assert!(v2.len() == 0);
}
#[test]
fn qc() {
::quickcheck::quickcheck(test as fn(_) -> _);
fn test(v: Vec<u8>) -> bool {
let r = BzEncoder::new(&v[..], Compression::default());
let mut r = BzDecoder::new(r);
let mut v2 = Vec::new();
r.read_to_end(&mut v2).unwrap();
v == v2
}
}
#[test]
fn qc_partial() {
quickcheck6::quickcheck(test as fn(_, _, _) -> _);
fn test(
v: Vec<u8>,
encode_ops: PartialWithErrors<GenInterrupted>,
decode_ops: PartialWithErrors<GenInterrupted>,
) -> bool {
let r = BzEncoder::new(PartialRead::new(&v[..], encode_ops), Compression::default());
let mut r = BzDecoder::new(PartialRead::new(r, decode_ops));
let mut v2 = Vec::new();
r.read_to_end(&mut v2).unwrap();
v == v2
}
}
}
+377
View File
@@ -0,0 +1,377 @@
//! Writer-based compression/decompression streams
use std::io;
use std::io::prelude::*;
#[cfg(feature = "tokio")]
use futures::Poll;
#[cfg(feature = "tokio")]
use tokio_io::{AsyncRead, AsyncWrite};
use {Action, Compress, Compression, Decompress, Status};
/// A compression stream which will have uncompressed data written to it and
/// will write compressed data to an output stream.
pub struct BzEncoder<W: Write> {
data: Compress,
obj: Option<W>,
buf: Vec<u8>,
done: bool,
}
/// A compression stream which will have compressed data written to it and
/// will write uncompressed data to an output stream.
pub struct BzDecoder<W: Write> {
data: Decompress,
obj: Option<W>,
buf: Vec<u8>,
done: bool,
}
impl<W: Write> BzEncoder<W> {
/// Create a new compression stream which will compress at the given level
/// to write compress output to the give output stream.
pub fn new(obj: W, level: Compression) -> BzEncoder<W> {
BzEncoder {
data: Compress::new(level, 30),
obj: Some(obj),
buf: Vec::with_capacity(32 * 1024),
done: false,
}
}
fn dump(&mut self) -> io::Result<()> {
while self.buf.len() > 0 {
let n = match self.obj.as_mut().unwrap().write(&self.buf) {
Ok(n) => n,
Err(ref err) if err.kind() == io::ErrorKind::Interrupted => continue,
Err(err) => return Err(err),
};
self.buf.drain(..n);
}
Ok(())
}
/// Acquires a reference to the underlying writer.
pub fn get_ref(&self) -> &W {
self.obj.as_ref().unwrap()
}
/// Acquires a mutable reference to the underlying writer.
///
/// Note that mutating the output/input state of the stream may corrupt this
/// object, so care must be taken when using this method.
pub fn get_mut(&mut self) -> &mut W {
self.obj.as_mut().unwrap()
}
/// Attempt to finish this output stream, writing out final chunks of data.
///
/// Note that this function can only be used once data has finished being
/// written to the output stream. After this function is called then further
/// calls to `write` may result in a panic.
///
/// # Panics
///
/// Attempts to write data to this stream may result in a panic after this
/// function is called.
pub fn try_finish(&mut self) -> io::Result<()> {
while !self.done {
self.dump()?;
let res = self.data.compress_vec(&[], &mut self.buf, Action::Finish);
if res == Ok(Status::StreamEnd) {
self.done = true;
break;
}
}
self.dump()
}
/// Consumes this encoder, flushing the output stream.
///
/// This will flush the underlying data stream and then return the contained
/// writer if the flush succeeded.
///
/// Note that this function may not be suitable to call in a situation where
/// the underlying stream is an asynchronous I/O stream. To finish a stream
/// the `try_finish` (or `shutdown`) method should be used instead. To
/// re-acquire ownership of a stream it is safe to call this method after
/// `try_finish` or `shutdown` has returned `Ok`.
pub fn finish(mut self) -> io::Result<W> {
self.try_finish()?;
Ok(self.obj.take().unwrap())
}
/// Returns the number of bytes produced by the compressor
///
/// Note that, due to buffering, this only bears any relation to
/// `total_in()` after a call to `flush()`. At that point,
/// `total_out() / total_in()` is the compression ratio.
pub fn total_out(&self) -> u64 {
self.data.total_out()
}
/// Returns the number of bytes consumed by the compressor
/// (e.g. the number of bytes written to this stream.)
pub fn total_in(&self) -> u64 {
self.data.total_in()
}
}
impl<W: Write> Write for BzEncoder<W> {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
loop {
self.dump()?;
let total_in = self.total_in();
self.data
.compress_vec(data, &mut self.buf, Action::Run)
.unwrap();
let written = (self.total_in() - total_in) as usize;
if written > 0 || data.len() == 0 {
return Ok(written);
}
}
}
fn flush(&mut self) -> io::Result<()> {
loop {
self.dump()?;
let before = self.total_out();
self.data
.compress_vec(&[], &mut self.buf, Action::Flush)
.unwrap();
if before == self.total_out() {
break;
}
}
self.obj.as_mut().unwrap().flush()
}
}
#[cfg(feature = "tokio")]
impl<W: AsyncWrite> AsyncWrite for BzEncoder<W> {
fn shutdown(&mut self) -> Poll<(), io::Error> {
try_nb!(self.try_finish());
self.get_mut().shutdown()
}
}
impl<W: Read + Write> Read for BzEncoder<W> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.get_mut().read(buf)
}
}
#[cfg(feature = "tokio")]
impl<W: AsyncRead + AsyncWrite> AsyncRead for BzEncoder<W> {}
impl<W: Write> Drop for BzEncoder<W> {
fn drop(&mut self) {
if self.obj.is_some() {
let _ = self.try_finish();
}
}
}
impl<W: Write> BzDecoder<W> {
/// Create a new decoding stream which will decompress all data written
/// to it into `obj`.
pub fn new(obj: W) -> BzDecoder<W> {
BzDecoder {
data: Decompress::new(false),
obj: Some(obj),
buf: Vec::with_capacity(32 * 1024),
done: false,
}
}
/// Acquires a reference to the underlying writer.
pub fn get_ref(&self) -> &W {
self.obj.as_ref().unwrap()
}
/// Acquires a mutable reference to the underlying writer.
///
/// Note that mutating the output/input state of the stream may corrupt this
/// object, so care must be taken when using this method.
pub fn get_mut(&mut self) -> &mut W {
self.obj.as_mut().unwrap()
}
fn dump(&mut self) -> io::Result<()> {
while self.buf.len() > 0 {
let n = match self.obj.as_mut().unwrap().write(&self.buf) {
Ok(n) => n,
Err(ref err) if err.kind() == io::ErrorKind::Interrupted => continue,
Err(err) => return Err(err),
};
self.buf.drain(..n);
}
Ok(())
}
/// Attempt to finish this output stream, writing out final chunks of data.
///
/// Note that this function can only be used once data has finished being
/// written to the output stream. After this function is called then further
/// calls to `write` may result in a panic.
///
/// # Panics
///
/// Attempts to write data to this stream may result in a panic after this
/// function is called.
pub fn try_finish(&mut self) -> io::Result<()> {
while !self.done {
self.write(&[])?;
}
self.dump()
}
/// Unwrap the underlying writer, finishing the compression stream.
///
/// Note that this function may not be suitable to call in a situation where
/// the underlying stream is an asynchronous I/O stream. To finish a stream
/// the `try_finish` (or `shutdown`) method should be used instead. To
/// re-acquire ownership of a stream it is safe to call this method after
/// `try_finish` or `shutdown` has returned `Ok`.
pub fn finish(&mut self) -> io::Result<W> {
self.try_finish()?;
Ok(self.obj.take().unwrap())
}
/// Returns the number of bytes produced by the decompressor
///
/// Note that, due to buffering, this only bears any relation to
/// `total_in()` after a call to `flush()`. At that point,
/// `total_in() / total_out()` is the compression ratio.
pub fn total_out(&self) -> u64 {
self.data.total_out()
}
/// Returns the number of bytes consumed by the decompressor
/// (e.g. the number of bytes written to this stream.)
pub fn total_in(&self) -> u64 {
self.data.total_in()
}
}
impl<W: Write> Write for BzDecoder<W> {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
if self.done {
return Ok(0);
}
loop {
self.dump()?;
let before = self.total_in();
let res = self.data.decompress_vec(data, &mut self.buf);
let written = (self.total_in() - before) as usize;
let res = res.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
if res == Status::StreamEnd {
self.done = true;
}
if written > 0 || data.len() == 0 || self.done {
return Ok(written);
}
}
}
fn flush(&mut self) -> io::Result<()> {
self.dump()?;
self.obj.as_mut().unwrap().flush()
}
}
#[cfg(feature = "tokio")]
impl<W: AsyncWrite> AsyncWrite for BzDecoder<W> {
fn shutdown(&mut self) -> Poll<(), io::Error> {
try_nb!(self.try_finish());
self.get_mut().shutdown()
}
}
impl<W: Read + Write> Read for BzDecoder<W> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.get_mut().read(buf)
}
}
#[cfg(feature = "tokio")]
impl<W: AsyncRead + AsyncWrite> AsyncRead for BzDecoder<W> {}
impl<W: Write> Drop for BzDecoder<W> {
fn drop(&mut self) {
if self.obj.is_some() {
let _ = self.try_finish();
}
}
}
#[cfg(test)]
mod tests {
use super::{BzDecoder, BzEncoder};
use partial_io::{GenInterrupted, PartialWithErrors, PartialWrite};
use std::io::prelude::*;
use std::iter::repeat;
#[test]
fn smoke() {
let d = BzDecoder::new(Vec::new());
let mut c = BzEncoder::new(d, ::Compression::default());
c.write_all(b"12834").unwrap();
let s = repeat("12345").take(100000).collect::<String>();
c.write_all(s.as_bytes()).unwrap();
let data = c.finish().unwrap().finish().unwrap();
assert_eq!(&data[0..5], b"12834");
assert_eq!(data.len(), 500005);
assert!(format!("12834{}", s).as_bytes() == &*data);
}
#[test]
fn write_empty() {
let d = BzDecoder::new(Vec::new());
let mut c = BzEncoder::new(d, ::Compression::default());
c.write(b"").unwrap();
let data = c.finish().unwrap().finish().unwrap();
assert_eq!(&data[..], b"");
}
#[test]
fn qc() {
::quickcheck::quickcheck(test as fn(_) -> _);
fn test(v: Vec<u8>) -> bool {
let w = BzDecoder::new(Vec::new());
let mut w = BzEncoder::new(w, ::Compression::default());
w.write_all(&v).unwrap();
v == w.finish().unwrap().finish().unwrap()
}
}
#[test]
fn qc_partial() {
quickcheck6::quickcheck(test as fn(_, _, _) -> _);
fn test(
v: Vec<u8>,
encode_ops: PartialWithErrors<GenInterrupted>,
decode_ops: PartialWithErrors<GenInterrupted>,
) -> bool {
let w = BzDecoder::new(PartialWrite::new(Vec::new(), decode_ops));
let mut w = BzEncoder::new(PartialWrite::new(w, encode_ops), ::Compression::default());
w.write_all(&v).unwrap();
v == w
.finish()
.unwrap()
.into_inner()
.finish()
.unwrap()
.into_inner()
}
}
}