Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 78e54915e4
commit 165d899fd8
16428 changed files with 6973006 additions and 25 deletions
Binary file not shown.
Binary file not shown.
+352
View File
@@ -0,0 +1,352 @@
//! Adaptors between compression crates and Rust's modern asynchronous IO types.
//!
//! # Feature Organization
//!
//! This crate is divided up along two axes, which can each be individually selected via Cargo
//! features.
//!
//! All features are disabled by default, you should enable just the ones you need from the lists
//! below.
//!
//! If you want to pull in everything there are three group features defined:
//!
//! Feature | Does
//! ---------|------
//! `all` | Activates all implementations and algorithms.
//! `all-implementations` | Activates all implementations, needs to be paired with a selection of algorithms
//! `all-algorithms` | Activates all algorithms, needs to be paired with a selection of implementations
//!
//! ## IO implementation
//!
//! The first division is which underlying asynchronous IO trait will be wrapped, these are
//! available as separate features that have corresponding top-level modules:
//!
//! Feature | Type
//! ---------|------
// TODO: Kill rustfmt on this section, `#![rustfmt::skip::attributes(cfg_attr)]` should do it, but
// that's unstable
#![cfg_attr(
feature = "futures-io",
doc = "[`futures-io`](crate::futures) | [`futures::io::AsyncBufRead`](futures_io::AsyncBufRead), [`futures::io::AsyncWrite`](futures_io::AsyncWrite)"
)]
#![cfg_attr(
not(feature = "futures-io"),
doc = "`futures-io` (*inactive*) | `futures::io::AsyncBufRead`, `futures::io::AsyncWrite`"
)]
#![cfg_attr(
feature = "tokio",
doc = "[`tokio`](crate::tokio) | [`tokio::io::AsyncBufRead`](::tokio::io::AsyncBufRead), [`tokio::io::AsyncWrite`](::tokio::io::AsyncWrite)"
)]
#![cfg_attr(
not(feature = "tokio"),
doc = "`tokio` (*inactive*) | `tokio::io::AsyncBufRead`, `tokio::io::AsyncWrite`"
)]
//!
//! ## Compression algorithm
//!
//! The second division is which compression schemes to support, there are currently a few
//! available choices, these determine which types will be available inside the above modules:
//!
//! Feature | Types
//! ---------|------
#![cfg_attr(
feature = "brotli",
doc = "`brotli` | [`BrotliEncoder`](?search=BrotliEncoder), [`BrotliDecoder`](?search=BrotliDecoder)"
)]
#![cfg_attr(
not(feature = "brotli"),
doc = "`brotli` (*inactive*) | `BrotliEncoder`, `BrotliDecoder`"
)]
#![cfg_attr(
feature = "bzip2",
doc = "`bzip2` | [`BzEncoder`](?search=BzEncoder), [`BzDecoder`](?search=BzDecoder)"
)]
#![cfg_attr(
not(feature = "bzip2"),
doc = "`bzip2` (*inactive*) | `BzEncoder`, `BzDecoder`"
)]
#![cfg_attr(
feature = "deflate",
doc = "`deflate` | [`DeflateEncoder`](?search=DeflateEncoder), [`DeflateDecoder`](?search=DeflateDecoder)"
)]
#![cfg_attr(
not(feature = "deflate"),
doc = "`deflate` (*inactive*) | `DeflateEncoder`, `DeflateDecoder`"
)]
#![cfg_attr(
feature = "gzip",
doc = "`gzip` | [`GzipEncoder`](?search=GzipEncoder), [`GzipDecoder`](?search=GzipDecoder)"
)]
#![cfg_attr(
not(feature = "gzip"),
doc = "`gzip` (*inactive*) | `GzipEncoder`, `GzipDecoder`"
)]
#![cfg_attr(
feature = "lzma",
doc = "`lzma` | [`LzmaEncoder`](?search=LzmaEncoder), [`LzmaDecoder`](?search=LzmaDecoder)"
)]
#![cfg_attr(
not(feature = "lzma"),
doc = "`lzma` (*inactive*) | `LzmaEncoder`, `LzmaDecoder`"
)]
#![cfg_attr(
feature = "xz",
doc = "`xz` | [`XzEncoder`](?search=XzEncoder), [`XzDecoder`](?search=XzDecoder)"
)]
#![cfg_attr(
not(feature = "xz"),
doc = "`xz` (*inactive*) | `XzEncoder`, `XzDecoder`"
)]
#![cfg_attr(
feature = "zlib",
doc = "`zlib` | [`ZlibEncoder`](?search=ZlibEncoder), [`ZlibDecoder`](?search=ZlibDecoder)"
)]
#![cfg_attr(
not(feature = "zlib"),
doc = "`zlib` (*inactive*) | `ZlibEncoder`, `ZlibDecoder`"
)]
#![cfg_attr(
feature = "zstd",
doc = "`zstd` | [`ZstdEncoder`](?search=ZstdEncoder), [`ZstdDecoder`](?search=ZstdDecoder)"
)]
#![cfg_attr(
not(feature = "zstd"),
doc = "`zstd` (*inactive*) | `ZstdEncoder`, `ZstdDecoder`"
)]
//!
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))]
#![warn(
missing_docs,
rust_2018_idioms,
missing_copy_implementations,
missing_debug_implementations
)]
#![cfg_attr(not(all), allow(unused))]
#[cfg(any(feature = "bzip2", feature = "flate2", feature = "xz2"))]
use std::convert::TryInto;
#[macro_use]
mod macros;
mod codec;
#[cfg(feature = "futures-io")]
pub mod futures;
#[cfg(feature = "tokio")]
pub mod tokio;
mod unshared;
mod util;
#[cfg(feature = "brotli")]
use brotli::enc::backward_references::BrotliEncoderParams;
/// Level of compression data should be compressed with.
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
pub enum Level {
/// Fastest quality of compression, usually produces bigger size.
Fastest,
/// Best quality of compression, usually produces the smallest size.
Best,
/// Default quality of compression defined by the selected compression algorithm.
Default,
/// Precise quality based on the underlying compression algorithms'
/// qualities. The interpretation of this depends on the algorithm chosen
/// and the specific implementation backing it.
/// Qualities are implicitly clamped to the algorithm's maximum.
Precise(i32),
}
impl Level {
#[cfg(feature = "brotli")]
fn into_brotli(self, mut params: BrotliEncoderParams) -> BrotliEncoderParams {
match self {
Self::Fastest => params.quality = 0,
Self::Best => params.quality = 11,
Self::Precise(quality) => params.quality = quality.clamp(0, 11),
Self::Default => (),
}
params
}
#[cfg(feature = "bzip2")]
fn into_bzip2(self) -> bzip2::Compression {
let fastest = bzip2::Compression::fast();
let best = bzip2::Compression::best();
match self {
Self::Fastest => fastest,
Self::Best => best,
Self::Precise(quality) => bzip2::Compression::new(
quality
.try_into()
.unwrap_or(0)
.clamp(fastest.level(), best.level()),
),
Self::Default => bzip2::Compression::default(),
}
}
#[cfg(feature = "flate2")]
fn into_flate2(self) -> flate2::Compression {
let fastest = flate2::Compression::fast();
let best = flate2::Compression::best();
match self {
Self::Fastest => fastest,
Self::Best => best,
Self::Precise(quality) => flate2::Compression::new(
quality
.try_into()
.unwrap_or(0)
.clamp(fastest.level(), best.level()),
),
Self::Default => flate2::Compression::default(),
}
}
#[cfg(feature = "zstd")]
fn into_zstd(self) -> i32 {
let (fastest, best) = libzstd::compression_level_range().into_inner();
match self {
Self::Fastest => fastest,
Self::Best => best,
Self::Precise(quality) => quality.clamp(fastest, best),
Self::Default => libzstd::DEFAULT_COMPRESSION_LEVEL,
}
}
#[cfg(feature = "xz2")]
fn into_xz2(self) -> u32 {
match self {
Self::Fastest => 0,
Self::Best => 9,
Self::Precise(quality) => quality.try_into().unwrap_or(0).min(9),
Self::Default => 5,
}
}
}
#[cfg(feature = "zstd")]
/// This module contains zstd-specific types for async-compression.
pub mod zstd {
use libzstd::stream::raw::CParameter::*;
/// A compression parameter for zstd. This is a stable wrapper around zstd's own `CParameter`
/// type, to abstract over different versions of the zstd library.
///
/// See the [zstd documentation](https://facebook.github.io/zstd/zstd_manual.html) for more
/// information on these parameters.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct CParameter(libzstd::stream::raw::CParameter);
impl CParameter {
/// Window size in bytes (as a power of two)
pub fn window_log(value: u32) -> Self {
Self(WindowLog(value))
}
/// Size of the initial probe table in 4-byte entries (as a power of two)
pub fn hash_log(value: u32) -> Self {
Self(HashLog(value))
}
/// Size of the multi-probe table in 4-byte entries (as a power of two)
pub fn chain_log(value: u32) -> Self {
Self(ChainLog(value))
}
/// Number of search attempts (as a power of two)
pub fn search_log(value: u32) -> Self {
Self(SearchLog(value))
}
/// Minimum size of matches searched for
pub fn min_match(value: u32) -> Self {
Self(MinMatch(value))
}
/// Strategy-dependent length modifier
pub fn target_length(value: u32) -> Self {
Self(TargetLength(value))
}
/// Enable long-distance matching mode to look for and emit long-distance references.
///
/// This increases the default window size.
pub fn enable_long_distance_matching(value: bool) -> Self {
Self(EnableLongDistanceMatching(value))
}
/// Size of the long-distance matching table (as a power of two)
pub fn ldm_hash_log(value: u32) -> Self {
Self(LdmHashLog(value))
}
/// Minimum size of long-distance matches searched for
pub fn ldm_min_match(value: u32) -> Self {
Self(LdmMinMatch(value))
}
/// Size of each bucket in the LDM hash table for collision resolution (as a power of two)
pub fn ldm_bucket_size_log(value: u32) -> Self {
Self(LdmBucketSizeLog(value))
}
/// Frequency of using the LDM hash table (as a power of two)
pub fn ldm_hash_rate_log(value: u32) -> Self {
Self(LdmHashRateLog(value))
}
/// Emit the size of the content (default: true).
pub fn content_size_flag(value: bool) -> Self {
Self(ContentSizeFlag(value))
}
/// Emit a checksum (default: false).
pub fn checksum_flag(value: bool) -> Self {
Self(ChecksumFlag(value))
}
/// Emit a dictionary ID when using a custom dictionary (default: true).
pub fn dict_id_flag(value: bool) -> Self {
Self(DictIdFlag(value))
}
/// Number of threads to spawn.
///
/// If set to 0, compression functions will block; if set to 1 or more, compression will
/// run in background threads and `flush` pushes bytes through the compressor.
///
/// # Panics
///
/// This parameter requires feature `zstdmt` to be enabled, otherwise it will cause a panic
/// when used in `ZstdEncoder::with_quality_and_params()` calls.
//
// TODO: make this a normal feature guarded fn on next breaking release
#[cfg_attr(docsrs, doc(cfg(feature = "zstdmt")))]
pub fn nb_workers(value: u32) -> Self {
Self(NbWorkers(value))
}
/// Number of bytes given to each worker.
///
/// If set to 0, zstd selects a job size based on compression parameters.
pub fn job_size(value: u32) -> Self {
Self(JobSize(value))
}
pub(crate) fn as_zstd(&self) -> libzstd::stream::raw::CParameter {
self.0
}
}
}
Binary file not shown.
+11
View File
@@ -0,0 +1,11 @@
use compression_codecs::brotli::params::EncoderParams;
#[macro_use]
mod utils;
test_cases!(brotli);
#[test]
pub fn brotli_params() {
let _ = EncoderParams::default();
}
+4
View File
@@ -0,0 +1,4 @@
#[macro_use]
mod utils;
test_cases!(bzip2);
+4
View File
@@ -0,0 +1,4 @@
#[macro_use]
mod utils;
test_cases!(deflate);
+19
View File
@@ -0,0 +1,19 @@
use async_compression::tokio::{bufread, write};
use std::io::ErrorKind;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::test]
async fn truncated_stream_returns_unexpected_eof_on_read_and_shutdown() {
let input = tokio::io::BufReader::new(&[0x00][..]);
let mut decoder = bufread::Deflate64Decoder::new(input);
let mut output = Vec::new();
let error = decoder.read_to_end(&mut output).await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::UnexpectedEof);
let mut decoder = write::Deflate64Decoder::new(Vec::new());
decoder.write_all(&[0x00]).await.unwrap();
let error = decoder.shutdown().await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::UnexpectedEof);
}
+142
View File
@@ -0,0 +1,142 @@
#[macro_use]
mod utils;
test_cases!(gzip);
#[allow(unused)]
use utils::{algos::gzip::sync, InputStream};
#[cfg(feature = "futures-io")]
use utils::algos::gzip::futures::bufread;
#[allow(unused)]
fn compress_with_header(data: &[u8]) -> Vec<u8> {
use flate2::{Compression, GzBuilder};
use std::io::Write;
let mut bytes = Vec::new();
{
let mut gz = GzBuilder::new()
.filename("hello_world.txt")
.comment("test file, please delete")
.extra(vec![1, 2, 3, 4])
.write(&mut bytes, Compression::fast());
gz.write_all(data).unwrap();
}
bytes
}
#[test]
#[ntest::timeout(1000)]
#[cfg(feature = "futures-io")]
fn gzip_bufread_decompress_with_extra_header() {
let bytes = compress_with_header(&[1, 2, 3, 4, 5, 6]);
let input = InputStream::from(vec![bytes]);
let output = bufread::decompress(bufread::from(&input));
assert_eq!(output, &[1, 2, 3, 4, 5, 6][..]);
}
#[test]
#[ntest::timeout(1000)]
#[cfg(feature = "futures-io")]
fn gzip_bufread_chunks_decompress_with_extra_header() {
let bytes = compress_with_header(&[1, 2, 3, 4, 5, 6]);
let input = InputStream::from(bytes.chunks(2));
let output = bufread::decompress(bufread::from(&input));
assert_eq!(output, &[1, 2, 3, 4, 5, 6][..]);
}
#[test]
#[ntest::timeout(1000)]
#[cfg(feature = "futures-io")]
fn gzip_bufread_chunks_compress_flushes_when_reader_pending() {
use crate::utils::block_on;
use async_compression::futures::bufread::GzipEncoder;
use futures::AsyncRead;
use futures::AsyncReadExt;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll};
struct Input {
remaining: usize,
chunks_sent: Arc<AtomicUsize>,
chunks_received: Arc<AtomicUsize>,
}
impl AsyncRead for Input {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
if self.chunks_received.load(Ordering::Relaxed)
< self.chunks_sent.load(Ordering::Relaxed)
{
Poll::Pending
} else {
let bytes = b"X".repeat(buf.len().min(64).min(self.remaining));
buf[..bytes.len()].copy_from_slice(&bytes);
let this = self.get_mut();
this.remaining -= bytes.len();
this.chunks_sent.fetch_add(1, Ordering::Relaxed);
Poll::Ready(Ok(bytes.len()))
}
}
}
let chunks_sent = Arc::new(AtomicUsize::new(0));
let chunks_received = Arc::new(AtomicUsize::new(0));
let input = futures::io::BufReader::new(Input {
remaining: 4 * 1024,
chunks_sent: Arc::clone(&chunks_sent),
chunks_received: Arc::clone(&chunks_received),
});
let mut encoder = GzipEncoder::new(input);
let mut encoded_buffer: [u8; 64] = [0; 64];
block_on(async {
while let Ok(read) = encoder.read(&mut encoded_buffer).await {
if read == 0 {
break;
}
chunks_received.fetch_add(1, Ordering::Relaxed);
}
});
assert_eq!(
chunks_sent.load(Ordering::Relaxed),
chunks_received.load(Ordering::Relaxed)
);
}
#[test]
#[ntest::timeout(1000)]
#[cfg(feature = "futures-io")]
fn gzip_bufread_chunks_decompress_without_footer_emits_all_payload() {
use flate2::bufread::GzDecoder;
use std::io::Read;
let mut bytes = compress_with_header(&[1, 2, 3, 4, 5, 6]);
// Remove the footer.
bytes.truncate(bytes.len() - 8);
let mut decoder = GzDecoder::new(bytes.as_slice());
let mut output = vec![];
let result = decoder.read_to_end(&mut output);
assert!(result.is_err());
assert_eq!(output, &[1, 2, 3, 4, 5, 6][..]);
}
+4
View File
@@ -0,0 +1,4 @@
#[macro_use]
mod utils;
test_cases!(lz4);
+4
View File
@@ -0,0 +1,4 @@
#[macro_use]
mod utils;
test_cases!(lzma);
@@ -0,0 +1,8 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc 56136f76bf926382b1bf5a24304af3826b03e674763b5c99d41496e40f56c1c3 # shrinks to ref input = [0, 0, 0, 0, 0, 0, 0], chunk_size = 1
cc e6c96e0924384950a67cc69e8ce9d7da5a11873cac62705241d7176ba9b20875 # shrinks to ref input = InputStream([]), level = Precise(11)
+145
View File
@@ -0,0 +1,145 @@
use compression_core::Level;
use ::proptest::{
arbitrary::any,
prop_oneof,
strategy::{Just, Strategy},
};
mod utils;
#[allow(dead_code)]
fn any_level() -> impl Strategy<Value = Level> {
prop_oneof![
Just(Level::Fastest),
Just(Level::Best),
Just(Level::Default),
any::<i32>().prop_map(Level::Precise),
]
}
#[allow(unused_macros)]
macro_rules! io_tests {
($impl:ident, $variant:ident) => {
mod $impl {
mod bufread {
use crate::utils::{algos::$variant::{$impl::{read, bufread}, sync}, InputStream};
use proptest::{prelude::{any, ProptestConfig}, proptest};
use std::iter::FromIterator;
proptest! {
#[test]
fn compress(ref input in any::<InputStream>()) {
let compressed = bufread::compress(bufread::from(input));
let output = sync::decompress(&compressed);
assert_eq!(output, input.bytes());
}
#[test]
fn decompress(
ref bytes in any::<Vec<u8>>(),
chunk_size in 1..20usize,
) {
let compressed = sync::compress(bytes);
let input = InputStream::from(Vec::from_iter(compressed.chunks(chunk_size).map(Vec::from)));
let output = bufread::decompress(bufread::from(&input));
assert_eq!(&output, bytes);
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(32))]
#[test]
fn compress_with_level(
ref input in any::<InputStream>(),
level in crate::any_level(),
) {
let encoder = bufread::Encoder::with_quality(bufread::from(input), level);
let compressed = read::to_vec(encoder);
let output = sync::decompress(&compressed);
assert_eq!(output, input.bytes());
}
}
}
mod write {
use crate::utils::{algos::$variant::{$impl::write, sync}, InputStream};
use proptest::{prelude::{any, ProptestConfig}, proptest};
proptest! {
#[test]
fn compress(
ref input in any::<InputStream>(),
limit in 1..20usize,
) {
let compressed = write::compress(input.as_ref(), limit);
let output = sync::decompress(&compressed);
assert_eq!(output, input.bytes());
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(32))]
#[test]
fn compress_with_level(
ref input in any::<InputStream>(),
limit in 1..20usize,
level in crate::any_level(),
) {
let compressed = write::to_vec(
input.as_ref(),
|input| Box::pin(write::Encoder::with_quality(input, level)),
limit,
);
let output = sync::decompress(&compressed);
assert_eq!(output, input.bytes());
}
}
}
}
}
}
#[allow(unused_macros)]
macro_rules! tests {
($variant:ident) => {
mod $variant {
#[cfg(feature = "futures-io")]
io_tests!(futures, $variant);
#[cfg(feature = "tokio")]
io_tests!(tokio, $variant);
}
};
}
mod proptest {
#[cfg(feature = "brotli")]
tests!(brotli);
#[cfg(feature = "bzip2")]
tests!(bzip2);
#[cfg(feature = "deflate")]
tests!(deflate);
#[cfg(feature = "gzip")]
tests!(gzip);
#[cfg(feature = "lz4")]
tests!(lz4);
#[cfg(feature = "lzma")]
tests!(lzma);
#[cfg(feature = "xz")]
tests!(xz);
#[cfg(feature = "zlib")]
tests!(zlib);
#[cfg(feature = "zstd")]
tests!(zstd);
}
+327
View File
@@ -0,0 +1,327 @@
macro_rules! io_algo {
($impl:ident, $algo:ident($encoder:ident, $decoder:ident)) => {
pub mod $impl {
pub mod read {
pub use crate::utils::impls::$impl::read::{poll_read, to_vec};
}
pub mod bufread {
pub use crate::utils::impls::$impl::bufread::{from, AsyncBufRead};
pub use async_compression::$impl::bufread::{
$decoder as Decoder, $encoder as Encoder,
};
use crate::utils::{pin_mut, Level};
pub fn compress(input: impl AsyncBufRead) -> Vec<u8> {
pin_mut!(input);
super::read::to_vec(Encoder::with_quality(input, Level::Fastest))
}
pub fn decompress(input: impl AsyncBufRead) -> Vec<u8> {
pin_mut!(input);
super::read::to_vec(Decoder::new(input))
}
}
pub mod write {
pub use crate::utils::impls::$impl::write::to_vec;
pub use async_compression::$impl::write::{
$decoder as Decoder, $encoder as Encoder,
};
use crate::utils::Level;
pub fn compress(input: &[Vec<u8>], limit: usize) -> Vec<u8> {
to_vec(
input,
|input| Box::pin(Encoder::with_quality(input, Level::Fastest)),
limit,
)
}
pub fn decompress(input: &[Vec<u8>], limit: usize) -> Vec<u8> {
to_vec(input, |input| Box::pin(Decoder::new(input)), limit)
}
}
}
};
}
macro_rules! algos {
($(pub mod $name:ident($feat:literal, $encoder:ident, $decoder:ident) { pub mod sync { $($tt:tt)* } })*) => {
$(
#[cfg(feature = $feat)]
pub mod $name {
pub mod sync { $($tt)* }
#[cfg(feature = "futures-io")]
io_algo!(futures, $name($encoder, $decoder));
#[cfg(feature = "tokio")]
io_algo!(tokio, $name($encoder, $decoder));
}
)*
}
}
algos! {
pub mod brotli("brotli", BrotliEncoder, BrotliDecoder) {
pub mod sync {
pub use crate::utils::impls::sync::to_vec;
pub fn compress(bytes: &[u8]) -> Vec<u8> {
use brotli::{enc::backward_references::BrotliEncoderParams, CompressorReader};
let params = BrotliEncoderParams { quality: 1, ..Default::default() };
to_vec(CompressorReader::with_params(bytes, 0, &params))
}
pub fn decompress(bytes: &[u8]) -> Vec<u8> {
use brotli::Decompressor;
to_vec(Decompressor::new(bytes, 0))
}
}
}
pub mod bzip2("bzip2", BzEncoder, BzDecoder) {
pub mod sync {
pub use crate::utils::impls::sync::to_vec;
pub fn compress(bytes: &[u8]) -> Vec<u8> {
use bzip2::{bufread::BzEncoder, Compression};
to_vec(BzEncoder::new(bytes, Compression::fast()))
}
pub fn decompress(bytes: &[u8]) -> Vec<u8> {
use bzip2::bufread::BzDecoder;
to_vec(BzDecoder::new(bytes))
}
}
}
pub mod deflate("deflate", DeflateEncoder, DeflateDecoder) {
pub mod sync {
pub use crate::utils::impls::sync::to_vec;
pub fn compress(bytes: &[u8]) -> Vec<u8> {
use flate2::{bufread::DeflateEncoder, Compression};
to_vec(DeflateEncoder::new(bytes, Compression::fast()))
}
pub fn decompress(bytes: &[u8]) -> Vec<u8> {
use flate2::bufread::DeflateDecoder;
to_vec(DeflateDecoder::new(bytes))
}
}
}
pub mod zlib("zlib", ZlibEncoder, ZlibDecoder) {
pub mod sync {
pub use crate::utils::impls::sync::to_vec;
pub fn compress(bytes: &[u8]) -> Vec<u8> {
use flate2::{bufread::ZlibEncoder, Compression};
to_vec(ZlibEncoder::new(bytes, Compression::fast()))
}
pub fn decompress(bytes: &[u8]) -> Vec<u8> {
use flate2::bufread::ZlibDecoder;
to_vec(ZlibDecoder::new(bytes))
}
}
}
pub mod gzip("gzip", GzipEncoder, GzipDecoder) {
pub mod sync {
pub use crate::utils::impls::sync::to_vec;
pub fn compress(bytes: &[u8]) -> Vec<u8> {
use flate2::{bufread::GzEncoder, Compression};
to_vec(GzEncoder::new(bytes, Compression::fast()))
}
pub fn decompress(bytes: &[u8]) -> Vec<u8> {
use flate2::bufread::GzDecoder;
to_vec(GzDecoder::new(bytes))
}
}
}
pub mod zstd("zstd", ZstdEncoder, ZstdDecoder) {
pub mod sync {
pub use crate::utils::impls::sync::to_vec;
pub fn compress(bytes: &[u8]) -> Vec<u8> {
use libzstd::stream::read::Encoder;
use libzstd::DEFAULT_COMPRESSION_LEVEL;
to_vec(Encoder::new(bytes, DEFAULT_COMPRESSION_LEVEL).unwrap())
}
pub fn decompress(bytes: &[u8]) -> Vec<u8> {
use libzstd::stream::read::Decoder;
to_vec(Decoder::new(bytes).unwrap())
}
}
}
pub mod xz("xz", XzEncoder, XzDecoder) {
pub mod sync {
pub use crate::utils::impls::sync::to_vec;
pub fn compress(bytes: &[u8]) -> Vec<u8> {
use liblzma::bufread::XzEncoder;
to_vec(XzEncoder::new(bytes, 0))
}
pub fn decompress(bytes: &[u8]) -> Vec<u8> {
use liblzma::bufread::XzDecoder;
to_vec(XzDecoder::new(bytes))
}
}
}
pub mod lzma("lzma", LzmaEncoder, LzmaDecoder) {
pub mod sync {
pub use crate::utils::impls::sync::to_vec;
pub fn compress(bytes: &[u8]) -> Vec<u8> {
use liblzma::bufread::XzEncoder;
use liblzma::stream::{LzmaOptions, Stream};
to_vec(XzEncoder::new_stream(
bytes,
Stream::new_lzma_encoder(&LzmaOptions::new_preset(0).unwrap()).unwrap(),
))
}
pub fn decompress(bytes: &[u8]) -> Vec<u8> {
use liblzma::bufread::XzDecoder;
use liblzma::stream::Stream;
to_vec(XzDecoder::new_stream(
bytes,
Stream::new_lzma_decoder(u64::MAX).unwrap(),
))
}
}
}
pub mod lz4("lz4", Lz4Encoder, Lz4Decoder) {
pub mod sync {
pub use crate::utils::impls::sync::to_vec;
pub fn compress(bytes: &[u8]) -> Vec<u8> {
use std::io::Write;
use lz4::EncoderBuilder;
let mut encoder = EncoderBuilder::new().build(vec![]).unwrap();
encoder.write_all(bytes).unwrap();
let (compressed_bytes, result) = encoder.finish();
result.unwrap();
compressed_bytes
}
pub fn decompress(bytes: &[u8]) -> Vec<u8> {
use lz4::Decoder;
to_vec(Decoder::new(bytes).unwrap())
}
}
}
}
macro_rules! io_algo_parallel {
($impl:ident, $algo:ident($encoder:ident, $decoder:ident)) => {
pub mod $impl {
const THREADS: std::num::NonZeroU32 = std::num::NonZeroU32::new(16).unwrap();
pub mod read {
pub use crate::utils::impls::$impl::read::{poll_read, to_vec};
}
pub mod bufread {
pub use crate::utils::impls::$impl::bufread::{from, AsyncBufRead};
pub use async_compression::$impl::bufread::{
$decoder as Decoder, $encoder as Encoder,
};
use super::THREADS;
use crate::utils::{pin_mut, Level};
pub fn compress(input: impl AsyncBufRead) -> Vec<u8> {
pin_mut!(input);
super::read::to_vec(Encoder::parallel(input, Level::Fastest, THREADS))
}
pub fn decompress(input: impl AsyncBufRead) -> Vec<u8> {
pin_mut!(input);
super::read::to_vec(Decoder::parallel(input, THREADS))
}
}
pub mod write {
pub use crate::utils::impls::$impl::write::to_vec;
pub use async_compression::$impl::write::{
$decoder as Decoder, $encoder as Encoder,
};
use super::THREADS;
use crate::utils::Level;
pub fn compress(input: &[Vec<u8>], limit: usize) -> Vec<u8> {
to_vec(
input,
|input| Box::pin(Encoder::parallel(input, Level::Fastest, THREADS)),
limit,
)
}
pub fn decompress(input: &[Vec<u8>], limit: usize) -> Vec<u8> {
to_vec(
input,
|input| Box::pin(Decoder::parallel(input, THREADS)),
limit,
)
}
}
}
};
}
macro_rules! algos_parallel {
($(pub mod $name:ident($feat:literal, $encoder:ident, $decoder:ident) { pub mod sync { $($tt:tt)* } })*) => {
$(
#[cfg(feature = $feat)]
pub mod $name {
pub mod sync { $($tt)* }
#[cfg(feature = "futures-io")]
io_algo_parallel!(futures, $name($encoder, $decoder));
#[cfg(feature = "tokio")]
io_algo_parallel!(tokio, $name($encoder, $decoder));
}
)*
}
}
algos_parallel! {
pub mod xz_parallel("xz-parallel", XzEncoder, XzDecoder) {
pub mod sync {
pub use crate::utils::impls::sync::to_vec;
pub fn compress(bytes: &[u8]) -> Vec<u8> {
use liblzma::bufread::XzEncoder;
to_vec(XzEncoder::new(bytes, 0))
}
pub fn decompress(bytes: &[u8]) -> Vec<u8> {
use liblzma::bufread::XzDecoder;
to_vec(XzDecoder::new(bytes))
}
}
}
}
+155
View File
@@ -0,0 +1,155 @@
pub mod sync {
use std::io::Read;
pub fn to_vec(mut read: impl Read) -> Vec<u8> {
let mut output = vec![];
read.read_to_end(&mut output).unwrap();
output
}
}
#[cfg(feature = "futures-io")]
pub mod futures {
pub mod bufread {
pub use futures::io::AsyncBufRead;
use crate::utils::{InputStream, TrackEof};
use futures::stream::{StreamExt as _, TryStreamExt as _};
pub fn from(input: &InputStream) -> impl AsyncBufRead {
// By using the stream here we ensure that each chunk will require a separate
// read/poll_fill_buf call to process to help test reading multiple chunks.
TrackEof::new(input.stream().map(Ok).into_async_read())
}
}
pub mod read {
use crate::utils::{block_on, pin_mut};
use futures::io::{copy_buf, AsyncRead, AsyncReadExt, BufReader, Cursor};
pub fn to_vec(read: impl AsyncRead) -> Vec<u8> {
// TODO: https://github.com/rust-lang-nursery/futures-rs/issues/1510
// All current test cases are < 100kB
let mut output = Cursor::new(vec![0; 102_400]);
pin_mut!(read);
// With more flushing from encoders, 4 appears to be the minimal buffer size that works.
let len = block_on(copy_buf(BufReader::with_capacity(4, read), &mut output)).unwrap();
let mut output = output.into_inner();
output.truncate(len as usize);
output
}
pub fn poll_read(reader: impl AsyncRead, output: &mut [u8]) -> std::io::Result<usize> {
pin_mut!(reader);
block_on(reader.read(output))
}
}
pub mod write {
use crate::utils::{block_on, Pin, TrackClosed};
use futures::io::{AsyncWrite, AsyncWriteExt as _};
use futures_test::io::AsyncWriteTestExt as _;
pub fn to_vec(
input: &[Vec<u8>],
create_writer: impl for<'a> FnOnce(
&'a mut (dyn AsyncWrite + Unpin),
) -> Pin<Box<dyn AsyncWrite + 'a>>,
limit: usize,
) -> Vec<u8> {
let mut output = Vec::new();
{
let mut test_writer = TrackClosed::new(
(&mut output)
.limited_write(limit)
.interleave_pending_write(),
);
{
let mut writer = create_writer(&mut test_writer);
for chunk in input {
block_on(writer.write_all(chunk)).unwrap();
block_on(writer.flush()).unwrap();
}
block_on(writer.close()).unwrap();
}
assert!(test_writer.is_closed());
}
output
}
}
}
#[cfg(feature = "tokio")]
pub mod tokio {
pub mod bufread {
use crate::utils::{InputStream, TrackEof};
use bytes::Bytes;
use futures::stream::StreamExt;
pub use tokio::io::AsyncBufRead;
use tokio_util::io::StreamReader;
pub fn from(input: &InputStream) -> impl AsyncBufRead {
// By using the stream here we ensure that each chunk will require a separate
// read/poll_fill_buf call to process to help test reading multiple chunks.
TrackEof::new(StreamReader::new(
input.stream().map(Bytes::from).map(std::io::Result::Ok),
))
}
}
pub mod read {
use crate::utils::{block_on, pin_mut, tokio_ext::copy_buf};
use std::io::Cursor;
use tokio::io::{AsyncRead, AsyncReadExt, BufReader};
pub fn to_vec(read: impl AsyncRead) -> Vec<u8> {
let mut output = Cursor::new(vec![0; 102_400]);
pin_mut!(read);
// With more flushing from encoders, 4 appears to be the minimal buffer size that works.
let len = block_on(copy_buf(BufReader::with_capacity(4, read), &mut output)).unwrap();
let mut output = output.into_inner();
output.truncate(len as usize);
output
}
pub fn poll_read(reader: impl AsyncRead, output: &mut [u8]) -> std::io::Result<usize> {
pin_mut!(reader);
block_on(reader.read(output))
}
}
pub mod write {
use crate::utils::{
block_on, tokio_ext::AsyncWriteTestExt as _, track_closed::TrackClosed, Pin,
};
use std::io::Cursor;
use tokio::io::{AsyncWrite, AsyncWriteExt as _};
pub fn to_vec(
input: &[Vec<u8>],
create_writer: impl for<'a> FnOnce(
&'a mut (dyn AsyncWrite + Unpin),
) -> Pin<Box<dyn AsyncWrite + 'a>>,
limit: usize,
) -> Vec<u8> {
let mut output = Cursor::new(Vec::new());
{
let mut test_writer = TrackClosed::new(
(&mut output)
.limited_write(limit)
.interleave_pending_write(),
);
{
let mut writer = create_writer(&mut test_writer);
for chunk in input {
block_on(writer.write_all(chunk)).unwrap();
block_on(writer.flush()).unwrap();
}
block_on(writer.shutdown()).unwrap();
}
assert!(test_writer.is_closed());
}
output.into_inner()
}
}
}
+48
View File
@@ -0,0 +1,48 @@
use futures::stream::Stream;
use futures_test::stream::StreamTestExt as _;
use proptest_derive::Arbitrary;
#[derive(Arbitrary, Debug, Clone)]
pub struct InputStream(Vec<Vec<u8>>);
impl InputStream {
pub fn new(input: Vec<Vec<u8>>) -> Self {
InputStream(input)
}
pub fn as_ref(&self) -> &[Vec<u8>] {
&self.0
}
pub fn stream(&self) -> impl Stream<Item = Vec<u8>> {
// The resulting stream here will interleave empty chunks before and after each chunk, and
// then interleave a `Poll::Pending` between each yielded chunk, that way we test the
// handling of these two conditions in every point of the tested stream.
futures::stream::iter(
self.0
.clone()
.into_iter()
.flat_map(|bytes| vec![vec![], bytes])
.chain(Some(vec![])),
)
.interleave_pending()
}
pub fn bytes(&self) -> Vec<u8> {
self.0.iter().flatten().cloned().collect()
}
pub fn len(&self) -> usize {
self.0.iter().map(Vec::len).sum()
}
}
impl<I> From<I> for InputStream
where
I: IntoIterator,
I::Item: Into<Vec<u8>>,
{
fn from(input: I) -> InputStream {
Self::new(input.into_iter().map(|b| b.into()).collect())
}
}
+25
View File
@@ -0,0 +1,25 @@
#![allow(dead_code, unused_imports, unused_macros)] // Different tests use a different subset of functions
mod input_stream;
#[cfg(feature = "tokio")]
mod tokio_ext;
mod track_closed;
mod track_eof;
#[macro_use]
mod test_cases;
pub mod algos;
pub mod impls;
pub use self::{input_stream::InputStream, track_closed::TrackClosed, track_eof::TrackEof};
pub use compression_core::Level;
pub use futures::{executor::block_on, pin_mut, stream::Stream};
pub use std::{future::Future, io::Result, iter::FromIterator, pin::Pin};
pub fn one_to_six_stream() -> InputStream {
InputStream::new(vec![vec![1, 2, 3], vec![4, 5, 6]])
}
pub fn one_to_six() -> &'static [u8] {
&[1, 2, 3, 4, 5, 6]
}
+495
View File
@@ -0,0 +1,495 @@
macro_rules! io_test_cases {
($impl:ident, $variant:ident) => {
mod $impl {
mod bufread {
mod compress {
use crate::utils::{
algos::$variant::{
sync,
$impl::{bufread, read},
},
one_to_six, one_to_six_stream, InputStream, Level,
};
#[test]
#[ntest::timeout(1000)]
fn empty() {
let mut input: &[u8] = &[];
let compressed = bufread::compress(&mut input);
let output = sync::decompress(&compressed);
assert_eq!(output, &[][..]);
}
#[test]
#[ntest::timeout(1000)]
fn to_full_output() {
let mut output = [];
let encoder = bufread::Encoder::new(bufread::from(&one_to_six_stream()));
let result = read::poll_read(encoder, &mut output);
assert!(matches!(result, Ok(0)));
}
#[test]
#[ntest::timeout(1000)]
fn empty_chunk() {
let input = InputStream::new(vec![vec![]]);
let compressed = bufread::compress(bufread::from(&input));
let output = sync::decompress(&compressed);
assert_eq!(output, input.bytes());
}
#[test]
#[ntest::timeout(1000)]
fn short() {
let compressed = bufread::compress(bufread::from(&one_to_six_stream()));
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
#[test]
#[ntest::timeout(1000)]
fn long() {
let input = InputStream::new(vec![
(0..32_768).map(|_| rand::random()).collect(),
(0..32_768).map(|_| rand::random()).collect(),
]);
let compressed = bufread::compress(bufread::from(&input));
let output = sync::decompress(&compressed);
assert_eq!(output, input.bytes());
}
#[test]
fn with_level_best() {
let encoder = bufread::Encoder::with_quality(
bufread::from(&one_to_six_stream()),
Level::Best,
);
let compressed = read::to_vec(encoder);
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
#[test]
fn with_level_default() {
let encoder = bufread::Encoder::new(bufread::from(&one_to_six_stream()));
let compressed = read::to_vec(encoder);
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
#[test]
fn with_level_0() {
let encoder = bufread::Encoder::with_quality(
bufread::from(&one_to_six_stream()),
Level::Precise(0),
);
let compressed = read::to_vec(encoder);
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
#[test]
fn with_level_max() {
let encoder = bufread::Encoder::with_quality(
bufread::from(&one_to_six_stream()),
Level::Precise(i32::MAX),
);
let compressed = read::to_vec(encoder);
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
}
mod decompress {
use crate::utils::{
algos::$variant::{
sync,
$impl::{bufread, read},
},
one_to_six, one_to_six_stream, InputStream,
};
#[test]
#[ntest::timeout(1000)]
fn empty() {
let compressed = sync::compress(&[]);
let input = InputStream::new(vec![compressed]);
let output = bufread::decompress(bufread::from(&input));
assert_eq!(output, &[][..]);
}
#[test]
#[ntest::timeout(1000)]
fn to_full_output() {
let mut output = [];
let decoder = bufread::Decoder::new(bufread::from(&one_to_six_stream()));
let result = read::poll_read(decoder, &mut output);
assert!(matches!(result, Ok(0)));
}
#[test]
#[ntest::timeout(1000)]
fn zeros() {
let compressed = sync::compress(&[0; 10]);
let input = InputStream::new(vec![compressed]);
let output = bufread::decompress(bufread::from(&input));
assert_eq!(output, &[0; 10][..]);
}
#[test]
#[ntest::timeout(1000)]
fn short() {
let compressed = sync::compress(&[1, 2, 3, 4, 5, 6]);
let input = InputStream::new(vec![compressed]);
let output = bufread::decompress(bufread::from(&input));
assert_eq!(output, one_to_six());
}
#[test]
#[ntest::timeout(1000)]
fn short_chunks() {
let compressed = sync::compress(&[1, 2, 3, 4, 5, 6]);
let input = InputStream::from(compressed.chunks(2));
let output = bufread::decompress(bufread::from(&input));
assert_eq!(output, one_to_six());
}
#[test]
#[ntest::timeout(1000)]
fn trailer() {
let mut compressed = sync::compress(&[1, 2, 3, 4, 5, 6]);
compressed.extend_from_slice(&[7, 8, 9, 10]);
let input = InputStream::new(vec![compressed]);
let mut reader = bufread::from(&input);
let output = bufread::decompress(&mut reader);
let trailer = read::to_vec(reader);
assert_eq!(output, one_to_six());
assert_eq!(trailer, &[7, 8, 9, 10][..]);
}
#[test]
#[ntest::timeout(1000)]
fn long() {
let bytes: Vec<u8> = (0..65_536).map(|_| rand::random()).collect();
let compressed = sync::compress(&bytes);
let input = InputStream::new(vec![compressed]);
let output = bufread::decompress(bufread::from(&input));
assert_eq!(output, bytes);
}
#[test]
#[ntest::timeout(1000)]
fn long_chunks() {
let bytes: Vec<u8> = (0..65_536).map(|_| rand::random()).collect();
let compressed = sync::compress(&bytes);
let input = InputStream::from(compressed.chunks(1024));
let output = bufread::decompress(bufread::from(&input));
assert_eq!(output, bytes);
}
#[test]
#[ntest::timeout(1000)]
fn multiple_members() {
let compressed = [
sync::compress(&[1, 2, 3, 4, 5, 6]),
sync::compress(&[6, 5, 4, 3, 2, 1]),
]
.join(&[][..]);
let input = InputStream::new(vec![compressed]);
let mut decoder = bufread::Decoder::new(bufread::from(&input));
decoder.multiple_members(true);
let output = read::to_vec(decoder);
assert_eq!(output, &[1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1][..]);
}
#[test]
#[ntest::timeout(1000)]
fn corrupt_second_member() {
let first = sync::compress(&[1, 2, 3, 4, 5, 6]);
let mut second = sync::compress(&[0; 2048]);
let corrupt = second.len() - 2;
second[corrupt] ^= 0xff;
let compressed = [first, second].join(&[][..]);
let input = InputStream::new(vec![compressed]);
let result = std::panic::catch_unwind(|| {
let mut decoder = bufread::Decoder::new(bufread::from(&input));
decoder.multiple_members(true);
read::to_vec(decoder)
});
assert!(result.is_err());
}
#[test]
#[ntest::timeout(1000)]
fn truncated() {
let compressed = sync::compress(&[1, 2, 3, 4, 5, 6]);
// Truncate the compressed data (remove last 20 bytes or half, whichever is less)
let truncate_amount = std::cmp::min(20, compressed.len() / 2);
let truncated = &compressed[..compressed.len() - truncate_amount];
let input = InputStream::new(vec![truncated.to_vec()]);
// Try to decompress - should get an error for incomplete stream
// The error manifests as a panic when read::to_vec calls unwrap()
let result =
std::panic::catch_unwind(|| bufread::decompress(bufread::from(&input)));
// Should fail for truncated stream
assert!(result.is_err(), "Expected error for truncated stream");
}
}
}
mod write {
mod compress {
use crate::utils::{
algos::$variant::{sync, $impl::write},
one_to_six, one_to_six_stream, InputStream, Level,
};
#[test]
#[ntest::timeout(1000)]
fn empty() {
let input = InputStream::new(vec![]);
let compressed = write::compress(input.as_ref(), 65_536);
let output = sync::decompress(&compressed);
assert_eq!(output, &[][..]);
}
#[test]
#[ntest::timeout(1000)]
fn empty_chunk() {
let input = InputStream::new(vec![vec![]]);
let compressed = write::compress(input.as_ref(), 65_536);
let output = sync::decompress(&compressed);
assert_eq!(output, input.bytes());
}
#[test]
#[ntest::timeout(1000)]
fn short() {
let compressed = write::compress(one_to_six_stream().as_ref(), 65_536);
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
#[test]
#[ntest::timeout(1000)]
fn short_chunk_output() {
let compressed = write::compress(one_to_six_stream().as_ref(), 2);
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
#[test]
#[ntest::timeout(1000)]
fn long() {
let input = InputStream::new(vec![
(0..32_768).map(|_| rand::random()).collect(),
(0..32_768).map(|_| rand::random()).collect(),
]);
let compressed = write::compress(input.as_ref(), 65_536);
let output = sync::decompress(&compressed);
assert_eq!(output, input.bytes());
}
#[test]
#[ntest::timeout(1000)]
fn long_chunk_output() {
let input = InputStream::new(vec![
(0..32_768).map(|_| rand::random()).collect(),
(0..32_768).map(|_| rand::random()).collect(),
]);
let compressed = write::compress(input.as_ref(), 20);
let output = sync::decompress(&compressed);
assert_eq!(output, input.bytes());
}
#[test]
fn with_level_best() {
let compressed = write::to_vec(
one_to_six_stream().as_ref(),
|input| Box::pin(write::Encoder::with_quality(input, Level::Best)),
65_536,
);
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
#[test]
fn with_level_default() {
let compressed = write::to_vec(
one_to_six_stream().as_ref(),
|input| Box::pin(write::Encoder::new(input)),
65_536,
);
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
#[test]
fn with_level_0() {
let compressed = write::to_vec(
one_to_six_stream().as_ref(),
|input| {
Box::pin(write::Encoder::with_quality(input, Level::Precise(0)))
},
65_536,
);
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
#[test]
fn with_level_max() {
let compressed = write::to_vec(
one_to_six_stream().as_ref(),
|input| {
Box::pin(write::Encoder::with_quality(
input,
Level::Precise(i32::MAX),
))
},
65_536,
);
let output = sync::decompress(&compressed);
assert_eq!(output, one_to_six());
}
}
mod decompress {
use crate::utils::{
algos::$variant::{sync, $impl::write},
one_to_six, InputStream,
};
#[test]
#[ntest::timeout(1000)]
fn empty() {
let compressed = sync::compress(&[]);
let input = InputStream::new(vec![compressed]);
let output = write::decompress(input.as_ref(), 65_536);
assert_eq!(output, &[][..]);
}
#[test]
#[ntest::timeout(1000)]
fn zeros() {
let compressed = sync::compress(&[0; 10]);
let input = InputStream::new(vec![compressed]);
let output = write::decompress(input.as_ref(), 65_536);
assert_eq!(output, &[0; 10][..]);
}
#[test]
#[ntest::timeout(1000)]
fn short() {
let compressed = sync::compress(&[1, 2, 3, 4, 5, 6]);
let input = InputStream::new(vec![compressed]);
let output = write::decompress(input.as_ref(), 65_536);
assert_eq!(output, one_to_six());
}
#[test]
#[ntest::timeout(1000)]
fn short_chunks() {
let compressed = sync::compress(&[1, 2, 3, 4, 5, 6]);
let input = InputStream::from(compressed.chunks(2));
let output = write::decompress(input.as_ref(), 65_536);
assert_eq!(output, one_to_six());
}
#[test]
#[ntest::timeout(1000)]
fn long() {
let bytes: Vec<u8> = (0..65_536).map(|_| rand::random()).collect();
let compressed = sync::compress(&bytes);
let input = InputStream::new(vec![compressed]);
let output = write::decompress(input.as_ref(), 65_536);
assert_eq!(output, bytes);
}
#[test]
#[ntest::timeout(1000)]
fn long_chunks() {
let bytes: Vec<u8> = (0..65_536).map(|_| rand::random()).collect();
let compressed = sync::compress(&bytes);
let input = InputStream::from(compressed.chunks(1024));
let output = write::decompress(input.as_ref(), 65_536);
assert_eq!(output, bytes);
}
}
}
}
};
}
macro_rules! test_cases {
($variant:ident) => {
mod $variant {
#[cfg(feature = "futures-io")]
io_test_cases!(futures, $variant);
#[cfg(feature = "tokio")]
io_test_cases!(tokio, $variant);
}
};
}
@@ -0,0 +1,52 @@
use core::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use futures::ready;
use tokio::io::{AsyncBufRead, AsyncWrite};
pub fn copy_buf<R, W>(reader: R, writer: &mut W) -> CopyBuf<'_, R, W>
where
R: AsyncBufRead + Unpin,
W: AsyncWrite + Unpin + ?Sized,
{
CopyBuf {
reader,
writer,
amt: 0,
}
}
#[derive(Debug)]
pub struct CopyBuf<'a, R, W: ?Sized> {
reader: R,
writer: &'a mut W,
amt: u64,
}
impl<R, W> Future for CopyBuf<'_, R, W>
where
R: AsyncBufRead + Unpin,
W: AsyncWrite + Unpin + ?Sized,
{
type Output = std::io::Result<u64>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
loop {
let buffer = ready!(Pin::new(&mut this.reader).poll_fill_buf(cx))?;
if buffer.is_empty() {
ready!(Pin::new(&mut this.writer).poll_flush(cx))?;
return Poll::Ready(Ok(this.amt));
}
let i = ready!(Pin::new(&mut this.writer).poll_write(cx, buffer))?;
if i == 0 {
return Poll::Ready(Err(std::io::ErrorKind::WriteZero.into()));
}
this.amt += i as u64;
Pin::new(&mut this.reader).consume(i);
}
}
}
@@ -0,0 +1,66 @@
use std::{
pin::Pin,
task::{Context, Poll},
};
pub struct InterleavePending<T> {
inner: T,
pended: bool,
}
impl<T> InterleavePending<T> {
pub(crate) fn new(inner: T) -> Self {
Self {
inner,
pended: false,
}
}
}
impl<W: tokio::io::AsyncWrite + Unpin> tokio::io::AsyncWrite for InterleavePending<W> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
if self.pended {
let next = Pin::new(&mut self.inner).poll_write(cx, buf);
if next.is_ready() {
self.pended = false;
}
next
} else {
cx.waker().wake_by_ref();
self.pended = true;
Poll::Pending
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
if self.pended {
let next = Pin::new(&mut self.inner).poll_flush(cx);
if next.is_ready() {
self.pended = false;
}
next
} else {
cx.waker().wake_by_ref();
self.pended = true;
Poll::Pending
}
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
if self.pended {
let next = Pin::new(&mut self.inner).poll_shutdown(cx);
if next.is_ready() {
self.pended = false;
}
next
} else {
cx.waker().wake_by_ref();
self.pended = true;
Poll::Pending
}
}
}
@@ -0,0 +1,35 @@
use std::{
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug)]
pub struct Limited<Io> {
io: Io,
limit: usize,
}
impl<Io> Limited<Io> {
pub(crate) fn new(io: Io, limit: usize) -> Limited<Io> {
Limited { io, limit }
}
}
impl<W: tokio::io::AsyncWrite + Unpin> tokio::io::AsyncWrite for Limited<W> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
let limit = self.limit;
Pin::new(&mut self.io).poll_write(cx, &buf[..std::cmp::min(limit, buf.len())])
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.io).poll_shutdown(cx)
}
}
+23
View File
@@ -0,0 +1,23 @@
mod copy_buf;
mod interleave_pending;
mod limited;
pub use copy_buf::copy_buf;
pub trait AsyncWriteTestExt: tokio::io::AsyncWrite {
fn interleave_pending_write(self) -> interleave_pending::InterleavePending<Self>
where
Self: Sized + Unpin,
{
interleave_pending::InterleavePending::new(self)
}
fn limited_write(self, limit: usize) -> limited::Limited<Self>
where
Self: Sized + Unpin,
{
limited::Limited::new(self, limit)
}
}
impl<T: tokio::io::AsyncWrite> AsyncWriteTestExt for T {}
+89
View File
@@ -0,0 +1,89 @@
#[cfg_attr(not(feature = "all-implementations"), allow(unused))]
use std::{
io::Result,
pin::Pin,
task::{Context, Poll},
};
pub struct TrackClosed<W> {
inner: W,
closed: bool,
}
impl<W> TrackClosed<W> {
pub fn new(inner: W) -> Self {
Self {
inner,
closed: false,
}
}
pub fn is_closed(&self) -> bool {
self.closed
}
}
#[cfg(feature = "futures-io")]
impl<W: futures::io::AsyncWrite + Unpin> futures::io::AsyncWrite for TrackClosed<W> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
assert!(!self.closed);
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
assert!(!self.closed);
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
assert!(!self.closed);
match Pin::new(&mut self.inner).poll_close(cx) {
Poll::Ready(Ok(())) => {
self.closed = true;
Poll::Ready(Ok(()))
}
other => other,
}
}
fn poll_write_vectored(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[std::io::IoSlice<'_>],
) -> Poll<Result<usize>> {
assert!(!self.closed);
Pin::new(&mut self.inner).poll_write_vectored(cx, bufs)
}
}
#[cfg(feature = "tokio")]
impl<W: tokio::io::AsyncWrite + Unpin> tokio::io::AsyncWrite for TrackClosed<W> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
assert!(!self.closed);
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
assert!(!self.closed);
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
assert!(!self.closed);
match Pin::new(&mut self.inner).poll_shutdown(cx) {
Poll::Ready(Ok(())) => {
self.closed = true;
Poll::Ready(Ok(()))
}
other => other,
}
}
}
+107
View File
@@ -0,0 +1,107 @@
#[cfg_attr(not(feature = "all-implementations"), allow(unused))]
use std::{
io::Result,
pin::Pin,
task::{Context, Poll},
};
pub struct TrackEof<R> {
inner: R,
eof: bool,
}
impl<R: Unpin> TrackEof<R> {
pub fn new(inner: R) -> Self {
Self { inner, eof: false }
}
pub fn project(self: Pin<&mut Self>) -> (Pin<&mut R>, &mut bool) {
let Self { inner, eof } = Pin::into_inner(self);
(Pin::new(inner), eof)
}
}
#[cfg(feature = "futures-io")]
impl<R: futures::io::AsyncRead + Unpin> futures::io::AsyncRead for TrackEof<R> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
let (inner, eof) = self.project();
assert!(!*eof);
match inner.poll_read(cx, buf) {
Poll::Ready(Ok(0)) => {
if !buf.is_empty() {
*eof = true;
}
Poll::Ready(Ok(0))
}
other => other,
}
}
}
#[cfg(feature = "futures-io")]
impl<R: futures::io::AsyncBufRead + Unpin> futures::io::AsyncBufRead for TrackEof<R> {
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> {
let (inner, eof) = self.project();
assert!(!*eof);
match inner.poll_fill_buf(cx) {
Poll::Ready(Ok(buf)) => {
if buf.is_empty() {
*eof = true;
}
Poll::Ready(Ok(buf))
}
other => other,
}
}
fn consume(self: Pin<&mut Self>, amt: usize) {
self.project().0.consume(amt)
}
}
#[cfg(feature = "tokio")]
impl<R: tokio::io::AsyncRead + Unpin> tokio::io::AsyncRead for TrackEof<R> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> Poll<Result<()>> {
let (inner, eof) = self.project();
assert!(!*eof);
let len = buf.filled().len();
match inner.poll_read(cx, buf) {
Poll::Ready(Ok(())) => {
if buf.filled().len() == len && buf.remaining() > 0 {
*eof = true;
}
Poll::Ready(Ok(()))
}
other => other,
}
}
}
#[cfg(feature = "tokio")]
impl<R: tokio::io::AsyncBufRead + Unpin> tokio::io::AsyncBufRead for TrackEof<R> {
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> {
let (inner, eof) = self.project();
assert!(!*eof);
match inner.poll_fill_buf(cx) {
Poll::Ready(Ok(buf)) => {
if buf.is_empty() {
*eof = true;
}
Poll::Ready(Ok(buf))
}
other => other,
}
}
fn consume(self: Pin<&mut Self>, amt: usize) {
self.project().0.consume(amt)
}
}
+58
View File
@@ -0,0 +1,58 @@
#[allow(unused)]
use futures::{executor::block_on, io::AsyncReadExt};
#[macro_use]
mod utils;
test_cases!(xz);
#[cfg(feature = "xz-parallel")]
test_cases!(xz_parallel);
#[allow(unused)]
use utils::{algos::xz::sync, InputStream};
#[cfg(feature = "futures-io")]
use utils::algos::xz::futures::{bufread, read};
#[test]
#[ntest::timeout(1000)]
#[cfg(feature = "futures-io")]
fn bufread_multiple_members_with_padding() {
let compressed = [
sync::compress(&[1, 2, 3, 4, 5, 6]),
vec![0, 0, 0, 0],
sync::compress(&[6, 5, 4, 3, 2, 1]),
vec![0, 0, 0, 0],
]
.join(&[][..]);
let input = InputStream::from(vec![compressed]);
let mut decoder = bufread::Decoder::new(bufread::from(&input));
decoder.multiple_members(true);
let output = read::to_vec(decoder);
assert_eq!(output, &[1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1][..]);
}
#[test]
#[ntest::timeout(1000)]
#[cfg(feature = "futures-io")]
fn bufread_multiple_members_with_invalid_padding() {
let compressed = [
sync::compress(&[1, 2, 3, 4, 5, 6]),
vec![0, 0, 0],
sync::compress(&[6, 5, 4, 3, 2, 1]),
vec![0, 0, 0, 0],
]
.join(&[][..]);
let input = InputStream::from(vec![compressed]);
let mut decoder = bufread::Decoder::new(bufread::from(&input));
decoder.multiple_members(true);
let mut output = Vec::new();
assert!(block_on(decoder.read_to_end(&mut output)).is_err());
}
+4
View File
@@ -0,0 +1,4 @@
#[macro_use]
mod utils;
test_cases!(zlib);
+35
View File
@@ -0,0 +1,35 @@
#![cfg(not(windows))]
use tokio::io::AsyncWriteExt as _;
#[tokio::test]
async fn trained_zstd_decode_no_dict() {
let compressed = include_bytes!("./artifacts/lib.rs.zst");
let mut decoder = async_compression::tokio::write::ZstdDecoder::new(Vec::new());
decoder.write_all(compressed).await.unwrap_err();
}
#[tokio::test]
async fn trained_zstd_decode_with_dict() {
let source = include_bytes!("./artifacts/lib.rs");
let dict = include_bytes!("./artifacts/dictionary-rust");
let compressed = include_bytes!("./artifacts/lib.rs.zst");
let mut decoder =
async_compression::tokio::write::ZstdDecoder::with_dict(Vec::new(), dict).unwrap();
decoder.write_all(compressed).await.unwrap();
decoder.shutdown().await.unwrap();
assert_eq!(decoder.into_inner(), source);
}
#[tokio::test]
async fn trained_zstd_decode_with_wrong_dict() {
let dict = include_bytes!("./artifacts/dictionary-rust-other");
let compressed = include_bytes!("./artifacts/lib.rs.zst");
let mut decoder =
async_compression::tokio::write::ZstdDecoder::with_dict(Vec::new(), dict).unwrap();
decoder.write_all(compressed).await.unwrap_err();
}
+45
View File
@@ -0,0 +1,45 @@
#![cfg(not(windows))]
use compression_codecs::zstd::params::DParameter;
use tokio::io::AsyncWriteExt as _;
#[tokio::test]
async fn zstd_decode_large_window_size_default() {
let compressed = include_bytes!("./artifacts/long-window-size-lib.rs.zst");
// Default decoder should throw with an error, window size maximum is too low.
let mut decoder = async_compression::tokio::write::ZstdDecoder::new(Vec::new());
decoder.write_all(compressed).await.unwrap_err();
}
#[tokio::test]
async fn zstd_decode_large_window_size_explicit_small_window_size() {
let compressed = include_bytes!("./artifacts/long-window-size-lib.rs.zst");
// Short window decoder should throw with an error, window size maximum is too low.
let mut decoder = async_compression::tokio::write::ZstdDecoder::with_params(
Vec::new(),
&[DParameter::window_log_max(16)],
);
decoder.write_all(compressed).await.unwrap_err();
}
#[tokio::test]
async fn zstd_decode_large_window_size_explicit_large_window_size() {
let compressed = include_bytes!("./artifacts/long-window-size-lib.rs.zst");
let source = include_bytes!("./artifacts/lib.rs");
// Long window decoder should succeed as the window size is large enough to decompress the given input.
let mut long_window_size_decoder = async_compression::tokio::write::ZstdDecoder::with_params(
Vec::new(),
&[DParameter::window_log_max(31)],
);
// Long window size decoder should successfully decode the given input data.
long_window_size_decoder
.write_all(compressed)
.await
.unwrap();
long_window_size_decoder.shutdown().await.unwrap();
assert_eq!(long_window_size_decoder.into_inner(), source);
}
+133
View File
@@ -0,0 +1,133 @@
#[macro_use]
mod utils;
test_cases!(zstd);
#[cfg(any(feature = "tokio", feature = "futures-io"))]
mod pending {
use std::{io, task::Poll};
// Repeated polling while waiting for input must not repeatedly call zstd
// with empty input: after 16 no-progress calls its context becomes unusable.
fn chunks(
input: &[u8],
chunk_size: usize,
) -> impl ::futures::Stream<Item = io::Result<Vec<u8>>> + '_ {
let mut chunks = input.chunks(chunk_size);
let mut pending = 32;
::futures::stream::poll_fn(move |cx| {
if pending > 0 {
pending -= 1;
cx.waker().wake_by_ref();
return Poll::Pending;
}
pending = 32;
Poll::Ready(chunks.next().map(|chunk| Ok(chunk.to_vec())))
})
}
macro_rules! pending_tests {
($runtime:ident, $feature:literal, |$stream:ident| $reader:block) => {
#[cfg(feature = $feature)]
mod $runtime {
use super::chunks;
use ::$runtime::io::AsyncReadExt as _;
use async_compression::$runtime::bufread::ZstdDecoder;
use std::io;
async fn decode(
input: &[u8],
chunk_size: usize,
output_size: usize,
multiple_members: bool,
) -> io::Result<Vec<u8>> {
let $stream = chunks(input, chunk_size);
let reader = $reader;
let mut decoder = ZstdDecoder::new(reader);
decoder.multiple_members(multiple_members);
let mut output = Vec::new();
let mut buffer = vec![0; output_size];
loop {
let len = decoder.read(&mut buffer).await?;
if len == 0 {
return Ok(output);
}
output.extend_from_slice(&buffer[..len]);
}
}
#[test]
#[ntest::timeout(10000)]
fn repeated_pending() {
::futures::executor::block_on(async {
let data: Vec<u8> = (0u32..4096)
.flat_map(|i| i.wrapping_mul(2654435761).to_le_bytes())
.collect();
for data in [vec![], vec![b'x'; 65536], data] {
let compressed = libzstd::encode_all(data.as_slice(), 0).unwrap();
for chunk_size in [1, 1024] {
for output_size in [1, 8192] {
for multiple_members in [false, true] {
let output = decode(
&compressed,
chunk_size,
output_size,
multiple_members,
)
.await
.unwrap();
assert_eq!(output, data);
}
}
}
}
});
}
#[test]
#[ntest::timeout(10000)]
fn repeated_pending_between_members() {
::futures::executor::block_on(async {
let members = [vec![b'a'; 65536], vec![], vec![b'b'; 65536]];
let compressed: Vec<u8> = members
.iter()
.flat_map(|data| libzstd::encode_all(data.as_slice(), 0).unwrap())
.collect();
let output = decode(&compressed, 1, 7, true).await.unwrap();
assert_eq!(output, members.concat());
});
}
#[test]
#[ntest::timeout(10000)]
fn repeated_pending_truncated_input() {
::futures::executor::block_on(async {
let compressed = libzstd::encode_all(&[b'a'; 65536][..], 0).unwrap();
for end in [1, compressed.len() / 2, compressed.len() - 1] {
let error =
decode(&compressed[..end], 1, 8192, true).await.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
}
});
}
#[test]
#[ntest::timeout(10000)]
fn repeated_pending_invalid_input() {
::futures::executor::block_on(async {
assert!(decode(b"not a zstd frame", 1, 8192, true).await.is_err());
});
}
}
};
}
pending_tests!(tokio, "tokio", |stream| {
use ::futures::TryStreamExt as _;
tokio_util::io::StreamReader::new(stream.map_ok(std::io::Cursor::new))
});
pending_tests!(futures, "futures-io", |stream| {
use ::futures::TryStreamExt as _;
stream.into_async_read()
});
}