bzip2-0.3.3/.gitignore010066400017500001750000000000221314364224300127520ustar0000000000000000target Cargo.lock bzip2-0.3.3/.travis.yml010066400017500001750000000013671314364224300131100ustar0000000000000000language: rust rust: - stable - beta - nightly sudo: false before_script: - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH script: - export CARGO_TARGET_DIR=`pwd`/target - cargo build --verbose - cargo test --verbose - cargo test --verbose --features tokio - rustdoc --test README.md -L target/debug -L target/debug/deps - cargo doc --no-deps - cargo doc --no-deps --manifest-path=bzip2-sys/Cargo.toml after_success: - travis-cargo --only nightly doc-upload notifications: email: on_success: never env: global: secure: "PXNga5meeArqD5RcInRiqDIHCsVqYlBtx6NSAQfCcKgo8z3qE5A2ig3txIS0rWNWbv+j2nlmOes6mljLx3Bx9O99hXIM5d2/UKHrzCWm8vJYmK6cw51r58MmZh4TMNo+p5aBN2aclluv5W1pueC1ndQ3QPGcVE4JgboUQNPIveU=" bzip2-0.3.3/Cargo.toml.orig010066400017500001750000000015271327261163300136660ustar0000000000000000[package] name = "bzip2" version = "0.3.3" authors = ["Alex Crichton "] license = "MIT/Apache-2.0" readme = "README.md" keywords = ["bzip", "encoding"] repository = "https://github.com/alexcrichton/bzip2-rs" homepage = "https://github.com/alexcrichton/bzip2-rs" documentation = "https://docs.rs/bzip2" description = """ Bindings to libbzip2 for bzip2 compression and decompression exposed as Reader/Writer streams. """ categories = ["compression", "api-bindings"] [workspace] [dependencies] libc = "0.2" bzip2-sys = { version = "0.1", path = "bzip2-sys" } tokio-io = { version = "0.1", optional = true } futures = { version = "0.1", optional = true } [dev-dependencies] rand = "0.3" partial-io = { version = "^0.2.1", features = ["quickcheck"] } quickcheck = "0.4" tokio-core = "0.1" [features] tokio = ["tokio-io", "futures"] bzip2-0.3.3/Cargo.toml0000644000000026550000000000000101320ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "bzip2" version = "0.3.3" authors = ["Alex Crichton "] description = "Bindings to libbzip2 for bzip2 compression and decompression exposed as\nReader/Writer streams.\n" homepage = "https://github.com/alexcrichton/bzip2-rs" documentation = "https://docs.rs/bzip2" readme = "README.md" keywords = ["bzip", "encoding"] categories = ["compression", "api-bindings"] license = "MIT/Apache-2.0" repository = "https://github.com/alexcrichton/bzip2-rs" [dependencies.bzip2-sys] version = "0.1" [dependencies.futures] version = "0.1" optional = true [dependencies.libc] version = "0.2" [dependencies.tokio-io] version = "0.1" optional = true [dev-dependencies.partial-io] version = "^0.2.1" features = ["quickcheck"] [dev-dependencies.quickcheck] version = "0.4" [dev-dependencies.rand] version = "0.3" [dev-dependencies.tokio-core] version = "0.1" [features] tokio = ["tokio-io", "futures"] bzip2-0.3.3/LICENSE-APACHE010066400017500001750000000251371314364224300127240ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. bzip2-0.3.3/LICENSE-MIT010066400017500001750000000020411314364224300124210ustar0000000000000000Copyright (c) 2014 Alex Crichton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. bzip2-0.3.3/README.md010066400017500001750000000017171327261131000122470ustar0000000000000000# bzip2 [![Build Status](https://travis-ci.org/alexcrichton/bzip2-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/bzip2-rs) [![Build status](https://ci.appveyor.com/api/projects/status/joowqvvwfhxgdw5x?svg=true)](https://ci.appveyor.com/project/alexcrichton/bzip2-rs) [Documentation](https://docs.rs/bzip2) A streaming compression/decompression library for rust with bindings to libbz2. ```toml # Cargo.toml [dependencies] bzip2 = "0.3.2" ``` # License This project is licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. bzip2-0.3.3/appveyor.yml010066400017500001750000000010541314364224300133600ustar0000000000000000environment: matrix: - TARGET: x86_64-pc-windows-msvc - TARGET: i686-pc-windows-msvc - TARGET: i686-pc-windows-gnu install: - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - SET PATH=%PATH%;C:\MinGW\bin - rustc -V - cargo -V build: false test_script: - cargo test --verbose --target %TARGET% - cargo test --verbose --target %TARGET% --features tokio bzip2-0.3.3/src/bufread.rs010066400017500001750000000157271314364224300135510ustar0000000000000000//! I/O streams for wrapping `BufRead` types as encoders/decoders use std::io::prelude::*; use std::io; #[cfg(feature = "tokio")] use futures::Poll; #[cfg(feature = "tokio")] use tokio_io::{AsyncRead, AsyncWrite}; use {Compress, Decompress, Compression, Action, 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 { 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 { obj: R, data: Decompress, done: bool, } impl BzEncoder { /// 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 { BzEncoder { obj: r, data: Compress::new(level, 30), done: false, } } } impl BzEncoder { /// 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 Read for BzEncoder { fn read(&mut self, buf: &mut [u8]) -> io::Result { if self.done { return Ok(0) } loop { let (read, consumed, eof, ret); { let input = try!(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 AsyncRead for BzEncoder { } impl Write for BzEncoder { fn write(&mut self, buf: &[u8]) -> io::Result { self.get_mut().write(buf) } fn flush(&mut self) -> io::Result<()> { self.get_mut().flush() } } #[cfg(feature = "tokio")] impl AsyncWrite for BzEncoder { fn shutdown(&mut self) -> Poll<(), io::Error> { self.get_mut().shutdown() } } impl BzDecoder { /// Creates a new decoder which will decompress data read from the given /// stream. pub fn new(r: R) -> BzDecoder { BzDecoder { obj: r, data: Decompress::new(false), done: false, } } } impl BzDecoder { /// 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 Read for BzDecoder { fn read(&mut self, buf: &mut [u8]) -> io::Result { if self.done { return Ok(0) } loop { let (read, consumed, eof, ret); { let input = try!(self.obj.fill_buf()); eof = input.is_empty(); 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; } self.obj.consume(consumed); let ret = try!(ret.map_err(|e| { io::Error::new(io::ErrorKind::InvalidInput, e) })); if ret == Status::StreamEnd { self.done = true; return Ok(read) } if read > 0 || eof || buf.len() == 0 { return Ok(read) } } } } #[cfg(feature = "tokio")] impl AsyncRead for BzDecoder { } impl Write for BzDecoder { fn write(&mut self, buf: &[u8]) -> io::Result { self.get_mut().write(buf) } fn flush(&mut self) -> io::Result<()> { self.get_mut().flush() } } #[cfg(feature = "tokio")] impl AsyncWrite for BzDecoder { fn shutdown(&mut self) -> Poll<(), io::Error> { self.get_mut().shutdown() } } bzip2-0.3.3/src/lib.rs010066400017500001750000000052651314364224400127040ustar0000000000000000//! 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!"); //! ``` //! //! # 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.3", 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, warnings)] #![doc(html_root_url = "https://docs.rs/bzip2/0.3")] extern crate bzip2_sys as ffi; extern crate libc; #[cfg(test)] extern crate rand; #[cfg(test)] extern crate partial_io; #[cfg(test)] extern crate quickcheck; #[cfg(feature = "tokio")] #[macro_use] extern crate tokio_io; #[cfg(feature = "tokio")] extern crate futures; pub use mem::{Compress, Decompress, Action, Status, Error}; 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 enum Compression { /// Optimize for the best speed of encoding. Fastest = 1, /// Optimize for the size of data being encoded. Best = 9, /// Choose the default compression, a balance between speed and size. Default = 6, } bzip2-0.3.3/src/mem.rs010066400017500001750000000242651327261131000127060ustar0000000000000000//! 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, } /// 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, } struct Stream { // libbz2 requires a stable address for this stream. raw: Box, _marker: marker::PhantomData, } unsafe impl Send for Stream {} unsafe impl Sync for Stream {} 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 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 { // 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() as c_uint; self.inner.raw.next_out = output.as_mut_ptr() as *mut _; self.inner.raw.avail_out = output.len() 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, action: Action) -> Result { 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 { self.inner.raw.next_in = input.as_ptr() as *mut _; self.inner.raw.avail_in = input.len() as c_uint; self.inner.raw.next_out = output.as_mut_ptr() as *mut _; self.inner.raw.avail_out = output.len() 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) -> Result { 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 Stream { 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 { fn description(&self) -> &str { "bz2 data error" } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { error::Error::description(self).fmt(f) } } 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 Drop for Stream { fn drop(&mut self) { unsafe { let _ = D::destroy(&mut *self.raw); } } } bzip2-0.3.3/src/read.rs010066400017500001750000000212371314364224400130460ustar0000000000000000//! 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 { inner: bufread::BzEncoder>, } /// A decompression stream which wraps a compressed stream of data. Decompressed /// data will be read from the stream. pub struct BzDecoder { inner: bufread::BzDecoder>, } impl BzEncoder { /// 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 { 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 Read for BzEncoder { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.inner.read(buf) } } #[cfg(feature = "tokio")] impl AsyncRead for BzEncoder { } impl Write for BzEncoder { fn write(&mut self, buf: &[u8]) -> io::Result { self.get_mut().write(buf) } fn flush(&mut self) -> io::Result<()> { self.get_mut().flush() } } #[cfg(feature = "tokio")] impl AsyncWrite for BzEncoder { fn shutdown(&mut self) -> Poll<(), io::Error> { self.get_mut().shutdown() } } impl BzDecoder { /// Create a new decompression stream, which will read compressed /// data from the given input stream and decompress it. pub fn new(r: R) -> BzDecoder { 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 Read for BzDecoder { fn read(&mut self, into: &mut [u8]) -> io::Result { self.inner.read(into) } } #[cfg(feature = "tokio")] impl AsyncRead for BzDecoder { } impl Write for BzDecoder { fn write(&mut self, buf: &[u8]) -> io::Result { self.get_mut().write(buf) } fn flush(&mut self) -> io::Result<()> { self.get_mut().flush() } } #[cfg(feature = "tokio")] impl AsyncWrite for BzDecoder { fn shutdown(&mut self) -> Poll<(), io::Error> { self.get_mut().shutdown() } } #[cfg(test)] mod tests { use std::io::prelude::*; use read::{BzEncoder, BzDecoder}; use Compression; use rand::{thread_rng, Rng}; use partial_io::{GenInterrupted, PartialRead, PartialWithErrors}; #[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().gen_iter::().take(1024).collect::>(); for _ in 0..200 { result.extend(v.iter().map(|x| *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 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) -> 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() { ::quickcheck::quickcheck(test as fn(_, _, _) -> _); fn test(v: Vec, encode_ops: PartialWithErrors, decode_ops: PartialWithErrors) -> 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 } } } bzip2-0.3.3/src/write.rs010066400017500001750000000265311314364224400132670ustar0000000000000000//! Writer-based compression/decompression streams use std::io::prelude::*; use std::io; #[cfg(feature = "tokio")] use futures::Poll; #[cfg(feature = "tokio")] use tokio_io::{AsyncRead, AsyncWrite}; use {Action, Status, Compression, Compress, Decompress}; /// A compression stream which will have uncompressed data written to it and /// will write compressed data to an output stream. pub struct BzEncoder { data: Compress, obj: Option, buf: Vec, 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 { data: Decompress, obj: Option, buf: Vec, done: bool, } impl BzEncoder { /// 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 { 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 { try!(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 { try!(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 Write for BzEncoder { fn write(&mut self, data: &[u8]) -> io::Result { loop { try!(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 { try!(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 AsyncWrite for BzEncoder { fn shutdown(&mut self) -> Poll<(), io::Error> { try_nb!(self.try_finish()); self.get_mut().shutdown() } } impl Read for BzEncoder { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.get_mut().read(buf) } } #[cfg(feature = "tokio")] impl AsyncRead for BzEncoder { } impl Drop for BzEncoder { fn drop(&mut self) { if self.obj.is_some() { let _ = self.try_finish(); } } } impl BzDecoder { /// Create a new decoding stream which will decompress all data written /// to it into `obj`. pub fn new(obj: W) -> BzDecoder { 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 { try!(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 { try!(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 Write for BzDecoder { fn write(&mut self, data: &[u8]) -> io::Result { if self.done { return Ok(0) } loop { try!(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 = try!(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<()> { try!(self.dump()); self.obj.as_mut().unwrap().flush() } } #[cfg(feature = "tokio")] impl AsyncWrite for BzDecoder { fn shutdown(&mut self) -> Poll<(), io::Error> { try_nb!(self.try_finish()); self.get_mut().shutdown() } } impl Read for BzDecoder { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.get_mut().read(buf) } } #[cfg(feature = "tokio")] impl AsyncRead for BzDecoder { } impl Drop for BzDecoder { fn drop(&mut self) { if self.obj.is_some() { let _ = self.try_finish(); } } } #[cfg(test)] mod tests { use std::io::prelude::*; use std::iter::repeat; use partial_io::{GenInterrupted, PartialWithErrors, PartialWrite}; use super::{BzEncoder, BzDecoder}; #[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::(); 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) -> 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() { ::quickcheck::quickcheck(test as fn(_, _, _) -> _); fn test(v: Vec, encode_ops: PartialWithErrors, decode_ops: PartialWithErrors) -> 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() } } } bzip2-0.3.3/tests/tokio.rs010066400017500001750000000067701314364224300136370ustar0000000000000000#![cfg(feature = "tokio")] extern crate tokio_core; extern crate bzip2; extern crate tokio_io; extern crate futures; extern crate rand; use std::thread; use std::net::{Shutdown, TcpListener}; use std::io::{Read, Write}; use bzip2::Compression; use bzip2::read; use bzip2::write; use futures::Future; use rand::{Rng, thread_rng}; use tokio_core::net::TcpStream; use tokio_core::reactor::Core; use tokio_io::AsyncRead; use tokio_io::io::{copy, shutdown}; #[test] fn tcp_stream_echo_pattern() { const N: u8 = 16; const M: usize = 16 * 1024; let mut core = Core::new().unwrap(); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let t = thread::spawn(move || { let a = listener.accept().unwrap().0; let b = a.try_clone().unwrap(); let t = thread::spawn(move || { let mut b = read::BzDecoder::new(b); let mut buf = [0; M]; for i in 0..N { b.read_exact(&mut buf).unwrap(); for byte in buf.iter() { assert_eq!(*byte, i); } } assert_eq!(b.read(&mut buf).unwrap(), 0); }); let mut a = write::BzEncoder::new(a, Compression::Default); for i in 0..N { let buf = [i; M]; a.write_all(&buf).unwrap(); } a.finish().unwrap() .shutdown(Shutdown::Write).unwrap(); t.join().unwrap(); }); let handle = core.handle(); let stream = TcpStream::connect(&addr, &handle); let copy = stream.and_then(|s| { let (a, b) = s.split(); let a = read::BzDecoder::new(a); let b = write::BzEncoder::new(b, Compression::Default); copy(a, b) }).then(|result| { let (amt, _a, b) = result.unwrap(); assert_eq!(amt, (N as u64) * (M as u64)); shutdown(b).map(|_| ()) }); core.run(copy).unwrap(); t.join().unwrap(); } #[test] fn echo_random() { let v = thread_rng().gen_iter::().take(1024 * 1024).collect::>(); let mut core = Core::new().unwrap(); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let v2 = v.clone(); let t = thread::spawn(move || { let a = listener.accept().unwrap().0; let b = a.try_clone().unwrap(); let mut v3 = v2.clone(); let t = thread::spawn(move || { let mut b = read::BzDecoder::new(b); let mut buf = [0; 1024]; while v3.len() > 0 { let n = b.read(&mut buf).unwrap(); for (actual, expected) in buf[..n].iter().zip(&v3) { assert_eq!(*actual, *expected); } v3.drain(..n); } assert_eq!(b.read(&mut buf).unwrap(), 0); }); let mut a = write::BzEncoder::new(a, Compression::Default); a.write_all(&v2).unwrap(); a.finish().unwrap() .shutdown(Shutdown::Write).unwrap(); t.join().unwrap(); }); let handle = core.handle(); let stream = TcpStream::connect(&addr, &handle); let copy = stream.and_then(|s| { let (a, b) = s.split(); let a = read::BzDecoder::new(a); let b = write::BzEncoder::new(b, Compression::Default); copy(a, b) }).then(|result| { let (amt, _a, b) = result.unwrap(); assert_eq!(amt, v.len() as u64); shutdown(b).map(|_| ()) }); core.run(copy).unwrap(); t.join().unwrap(); }