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
File diff suppressed because one or more lines are too long
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "d34d64e4762d69e394c255f16aea71ed6e08f439"
},
"path_in_vcs": "crates/async-compression"
}
+335
View File
@@ -0,0 +1,335 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.4.47](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.46...async-compression-v0.4.47) - 2026-09-14
### Fixed
- *(zstd)* avoid no-progress errors while awaiting input ([#486](https://github.com/Nullus157/async-compression/pull/486))
## [0.4.46](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.45...async-compression-v0.4.46) - 2026-09-09
### Other
- Return UnexpectedEof when deflate64 does not progress ([#483](https://github.com/Nullus157/async-compression/pull/483))
## [0.4.45](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.44...async-compression-v0.4.45) - 2026-09-07
### Other
- *(deps)* update zstd requirement from 0.13 to 0.14 ([#481](https://github.com/Nullus157/async-compression/pull/481))
## [0.4.44](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.43...async-compression-v0.4.44) - 2026-09-02
### Other
- updated the following local packages: compression-core, compression-codecs
## [0.4.43](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.42...async-compression-v0.4.43) - 2026-07-28
### Other
- Fix hang when decoding a corrupt subsequent zstd frame ([#470](https://github.com/Nullus157/async-compression/pull/470))
## [0.4.42](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.41...async-compression-v0.4.42) - 2026-04-21
### Other
- Include license files in published crates ([#467](https://github.com/Nullus157/async-compression/pull/467))
- Fix async-compression CHANGELOG ordering ([#463](https://github.com/Nullus157/async-compression/pull/463))
## [0.4.41](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.40...async-compression-v0.4.41) - 2026-02-25
### Fixed
- On error the encoder/decoder now emit everything it was able to decode. ([#454](https://github.com/Nullus157/async-compression/pull/454))
## [0.4.40](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.39...async-compression-v0.4.40) - 2026-02-18
### Other
- Fix update of bytes read in the encoder state machine. ([#456](https://github.com/Nullus157/async-compression/pull/456))
- *(deps)* update rand requirement from 0.9 to 0.10 ([#449](https://github.com/Nullus157/async-compression/pull/449))
## [0.4.39](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.38...async-compression-v0.4.39) - 2026-02-07
### Other
- Revert "Fix decoding of empty response streams." ([#446](https://github.com/Nullus157/async-compression/pull/446))
## [0.4.38](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.37...async-compression-v0.4.38) - 2026-02-06
### Other
- Fix decoding of empty response streams. ([#444](https://github.com/Nullus157/async-compression/pull/444))
- *(deps)* update proptest-derive requirement from 0.7 to 0.8 ([#442](https://github.com/Nullus157/async-compression/pull/442))
## [0.4.37](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.36...async-compression-v0.4.37) - 2026-01-10
### Other
- Set async-compression msrv ([#440](https://github.com/Nullus157/async-compression/pull/440))
- Fix BufWriter::flush_buf: propagate error before reset ([#438](https://github.com/Nullus157/async-compression/pull/438))
- Switch futures_core::ready to standard library api ([#436](https://github.com/Nullus157/async-compression/pull/436))
## [0.4.36](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.35...async-compression-v0.4.36) - 2025-12-11
### Other
- updated the following local packages: compression-codecs
## [0.4.35](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.34...async-compression-v0.4.35) - 2025-12-07
### Other
- updated the following local packages: compression-codecs
## [0.4.34](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.33...async-compression-v0.4.34) - 2025-11-21
### Added
- Add uninitialized output buffer support ([#414](https://github.com/Nullus157/async-compression/pull/414))
### Other
- Simplify `AsyncBufWrite` ([#423](https://github.com/Nullus157/async-compression/pull/423))
- Refactor `bufread::decoder`: Extract poll ready check ([#418](https://github.com/Nullus157/async-compression/pull/418))
- Optimize condition for removing written data in BufWriter ([#415](https://github.com/Nullus157/async-compression/pull/415))
## [0.4.33](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.32...async-compression-v0.4.33) - 2025-11-06
### Fixed
- `UnexpectedEof` on truncated input ([#412](https://github.com/Nullus157/async-compression/pull/412))
### Other
- Update async-compression to use codecs v2 ([#410](https://github.com/Nullus157/async-compression/pull/410))
- Dedup `write::Encoder` and simplify `write::Decoder` impl ([#409](https://github.com/Nullus157/async-compression/pull/409))
- Dedup `write::Decoder::poll_write` ([#408](https://github.com/Nullus157/async-compression/pull/408))
- Optimize `BufWriter::poll_*` method ([#407](https://github.com/Nullus157/async-compression/pull/407))
- Dedup `write::{AsyncBufWriter, BufWriter, Decoder}` ([#406](https://github.com/Nullus157/async-compression/pull/406))
- Early return in `do_poll_read` instead of keep polling ([#404](https://github.com/Nullus157/async-compression/pull/404))
- Deduplicate `bufread::Encoder` impl ([#402](https://github.com/Nullus157/async-compression/pull/402))
- Rename `impl_do_poll_read!` to `impl_decoder!` ([#403](https://github.com/Nullus157/async-compression/pull/403))
- *(deps)* update proptest-derive requirement from 0.6 to 0.7 ([#399](https://github.com/Nullus157/async-compression/pull/399))
- Deduplicate `generic::bufread::Decoder` impl of tokio/futures-io ([#391](https://github.com/Nullus157/async-compression/pull/391))
- Disable nightly feature `doc_auto_cfg` on docsrs ([#392](https://github.com/Nullus157/async-compression/pull/392))
## [0.4.32](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.31...async-compression-v0.4.32) - 2025-09-25
### Other
- updated the following local packages: compression-codecs
## [0.4.31](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.30...async-compression-v0.4.31) - 2025-09-25
### Other
- Flush compressed data out of encoders more often ([#383](https://github.com/Nullus157/async-compression/pull/383))
## [0.4.30](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.29...async-compression-v0.4.30) - 2025-08-31
### Other
- rm unused dep from async-compression and compression-codecs ([#381](https://github.com/Nullus157/async-compression/pull/381))
## [0.4.29](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.28...async-compression-v0.4.29) - 2025-08-28
### Other
- Update Deps.rs badge ([#380](https://github.com/Nullus157/async-compression/pull/380))
- move async-compression to crates/ ([#379](https://github.com/Nullus157/async-compression/pull/379))
## [0.4.28](https://github.com/Nullus157/async-compression/compare/async-compression-v0.4.27...async-compression-v0.4.28) - 2025-08-23
### Fixed
- fix wasi ci testing and update doc in README ([#367](https://github.com/Nullus157/async-compression/pull/367))
### Other
- Fix Cargo.toml: add back version for async-compression ([#372](https://github.com/Nullus157/async-compression/pull/372))
- Have separate package.version field for compression-* ([#369](https://github.com/Nullus157/async-compression/pull/369))
- Re-export compression_codecs as codecs ([#368](https://github.com/Nullus157/async-compression/pull/368))
- Fix breaking API change ([#366](https://github.com/Nullus157/async-compression/pull/366))
- Fix docs.rs build for compression-codecs ([#365](https://github.com/Nullus157/async-compression/pull/365))
- Separate codecs as a separate crate, allow direct configuration ([#363](https://github.com/Nullus157/async-compression/pull/363))
- *(deps)* bump actions/checkout from 4 to 5 ([#360](https://github.com/Nullus157/async-compression/pull/360))
- Fix doc link for futures-io ([#361](https://github.com/Nullus157/async-compression/pull/361))
## [0.4.27](https://github.com/Nullus157/async-compression/compare/v0.4.26...v0.4.27) - 2025-07-13
### Fixed
- Zstd fastest level now does compression. ([#357](https://github.com/Nullus157/async-compression/pull/357))
## [0.4.26](https://github.com/Nullus157/async-compression/compare/v0.4.25...v0.4.26) - 2025-07-13
### Features
- Add multi-thread support for XZ. ([#353](https://github.com/Nullus157/async-compression/pull/353))
## [0.4.25](https://github.com/Nullus157/async-compression/compare/v0.4.24...v0.4.25) - 2025-06-17
### Changed
- Update `bzip2` dependency to `0.6`. ([#350](https://github.com/Nullus157/async-compression/pull/350))
## [0.4.24](https://github.com/Nullus157/async-compression/compare/v0.4.23...v0.4.24) - 2025-06-09
### Other
- Fix clippy error
- narrow tokio requirement to account for RUSTSEC-2025-0023
- move constructors back to top of rustdoc pages
## [0.4.23](https://github.com/Nullus157/async-compression/compare/v0.4.22...v0.4.23) - 2025-04-21
### Changed
- Update `brotli` dependency to `8.0`.
- Update `liblzma` dependency to `0.4`.
## [0.4.22](https://github.com/Nullus157/async-compression/compare/v0.4.21...v0.4.22) - 2025-03-25
### Added
- Add LZ4 encoders and decoders.
- Expose `DeflateEncoder::{total_in, total_out}()` methods.
## [0.4.21](https://github.com/Nullus157/async-compression/compare/v0.4.20...v0.4.21) - 2025-03-15
### Fixed
- When flate encoding, do not mark internal state as flushed if it ran out of buffer space.
- Add debug assertion in `produce` method to check buffer capacity in implementations for `BufWriter`.
## [0.4.20](https://github.com/Nullus157/async-compression/compare/v0.4.19...v0.4.20) - 2025-02-28
### Added
- Add support for `wasm32-wasip1-*` targets.
## [0.4.19](https://github.com/Nullus157/async-compression/compare/v0.4.18...v0.4.19) - 2025-02-27
### Changed
- Update `bzip2` dependency to `0.5`.
### Fixed
- Ensure that flush finishes before continuing.
## [0.4.18](https://github.com/Nullus157/async-compression/compare/v0.4.17...v0.4.18) - 2024-11-23
### Fixed
- Adjust `Level::Precise` clamp range for flate2.
## [0.4.17](https://github.com/Nullus157/async-compression/compare/v0.4.16...v0.4.17) - 2024-10-20
### Fixed
- Fix occasional panics when consuming from pending buffers.
## [0.4.16](https://github.com/Nullus157/async-compression/compare/v0.4.15...v0.4.16) - 2024-10-16
### Other
- Implement pass-through `AsyncBufRead` on write-based encoders & decoders.
## [0.4.15](https://github.com/Nullus157/async-compression/compare/v0.4.14...v0.4.15) - 2024-10-13
### Feature
- Implement pass-through `AsyncRead` or `AsyncWrite` where appropriate.
- Relax `AsyncRead`/`AsyncWrite` bounds on `*::{get_ref, get_mut, get_pin_mut, into_inner}()` methods.
## [0.4.14](https://github.com/Nullus157/async-compression/compare/v0.4.13...v0.4.14) - 2024-10-10
### Fixed
- In Tokio-based decoders, attempt to decode from internal state even if nothing was read.
## [0.4.13](https://github.com/Nullus157/async-compression/compare/v0.4.12...v0.4.13) - 2024-10-02
### Feature
- Update `brotli` dependency to to `7`.
## [0.4.12](https://github.com/Nullus157/async-compression/compare/v0.4.11...v0.4.12) - 2024-07-21
### Feature
- Enable customizing Zstd decoding parameters.
## [0.4.11](https://github.com/Nullus157/async-compression/compare/v0.4.10...v0.4.11) - 2024-05-30
### Other
- Expose total_in/total_out from underlying flate2 encoder types.
## [0.4.10](https://github.com/Nullus157/async-compression/compare/v0.4.9...v0.4.10) - 2024-05-09
### Other
- *(deps)* update brotli requirement from 5.0 to 6.0 ([#274](https://github.com/Nullus157/async-compression/pull/274))
- Fix pipeline doc: Warn on unexpected cfgs instead of error ([#276](https://github.com/Nullus157/async-compression/pull/276))
- Update name of release-pr.yml
- Create release.yml
- Create release-pr.yml
## 0.4.9
- bump dep brotli from 4.0 to 5.0
## 0.4.8
- bump dep brotli from 3.3 to 4.0
## 0.4.7
- Flush available data in decoder even when there's no incoming input.
## 0.4.6
- Return errors instead of panicking in all encode and decode operations.
## 0.4.5
- Add `{Lzma, Xz}Decoder::with_mem_limit()` methods.
## 0.4.4
- Update `zstd` dependency to `0.13`.
## 0.4.3
- Implement `Default` for `brotli::EncoderParams`.
## 0.4.2
- Add top-level `brotli` module containing stable `brotli` crate wrapper types.
- Add `BrotliEncoder::with_quality_and_params()` constructors.
- Add `Deflate64Decoder` behind new crate feature `deflate64`.
## 0.4.1 - 2023-07-10
- Add `Zstd{Encoder,Decoder}::with_dict()` constructors.
- Add `zstdmt` crate feature that enables `zstd-safe/zstdmt`, allowing multi-threaded functionality to work as expected.
## 0.4.0 - 2023-05-10
- `Level::Precise` variant now takes a `i32` instead of `u32`.
- Add top-level `zstd` module containing stable `zstd` crate wrapper types.
- Add `ZstdEncoder::with_quality_and_params()` constructors.
- Update `zstd` dependency to `0.12`.
- Remove deprecated `stream`, `futures-bufread` and `futures-write` crate features.
- Remove Tokio 0.2.x and 0.3.x support (`tokio-02` and `tokio-03` crate features).
## 0.3.15 - 2022-10-08
- `Level::Default::into_zstd()` now returns zstd's default value `3`.
- Fix endianness when reading the `extra` field of a gzip header.
+993
View File
@@ -0,0 +1,993 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "alloc-no-stdlib"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
[[package]]
name = "alloc-stdlib"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "async-compression"
version = "0.4.47"
dependencies = [
"brotli",
"bytes",
"bzip2",
"compression-codecs",
"compression-core",
"deflate64",
"flate2",
"futures",
"futures-io",
"futures-test",
"liblzma",
"lz4",
"ntest",
"pin-project-lite",
"proptest",
"proptest-derive",
"rand 0.10.2",
"tokio",
"tokio-util",
"zstd",
"zstd-safe",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bit-set"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "brotli"
version = "8.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"brotli-decompressor",
]
[[package]]
name = "brotli-decompressor"
version = "5.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
]
[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "bzip2"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
dependencies = [
"libbz2-rs-sys",
]
[[package]]
name = "cc"
version = "1.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3eb0f42d6c360dc3f8a821f6bf2fdea7f72bfd36b3076eb0e6d1e9e0752fff4"
dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures",
"rand_core 0.10.1",
]
[[package]]
name = "compression-codecs"
version = "0.4.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "257c7085cbb71be72d8fb97edff08b03d86d5d9f2222b9cc34a6bec87093bc10"
dependencies = [
"brotli",
"bzip2",
"compression-core",
"deflate64",
"flate2",
"liblzma",
"lz4",
"memchr",
"zstd",
"zstd-safe",
]
[[package]]
name = "compression-core"
version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e8ccc4ea9f6acc32d102c0f6d471d11d913ad15f20c04de743374861fa1d414"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
dependencies = [
"cfg-if",
]
[[package]]
name = "deflate64"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "find-msvc-tools"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d"
[[package]]
name = "flate2"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"crc32fast",
"miniz_oxide",
"zlib-rs",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "futures"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"
dependencies = [
"futures-channel",
"futures-core",
"futures-executor",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-executor"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
[[package]]
name = "futures-macro"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.5",
]
[[package]]
name = "futures-sink"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
[[package]]
name = "futures-task"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
name = "futures-test"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4d0ceb932f7909033988f82e244109c50e5f3978ca031c576533dd3480a7605"
dependencies = [
"futures-core",
"futures-executor",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"futures-util",
"pin-project",
]
[[package]]
name = "futures-util"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
"pin-project-lite",
"slab",
]
[[package]]
name = "getrandom"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"libc",
"r-efi 5.3.0",
"wasip2",
]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi 6.0.0",
"rand_core 0.10.1",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "hermit-abi"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "jobserver"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom 0.4.3",
"libc",
]
[[package]]
name = "libbz2-rs-sys"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "liblzma"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fe0a34ca854fd4f20c07f696fc8675aec78f87d88d29f5e10257a7490a1b2e1"
dependencies = [
"liblzma-sys",
"num_cpus",
]
[[package]]
name = "liblzma-sys"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c7e3581f367a78d7b7e7ae948d023310556f0cfc13156c2e4e00e25616492b9"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "lz4"
version = "1.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a20b523e860d03443e98350ceaac5e71c6ba89aea7d960769ec3ce37f4de5af4"
dependencies = [
"lz4-sys",
]
[[package]]
name = "lz4-sys"
version = "1.11.1+lz4-1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bd8c0d6c6ed0cd30b3652886bb8711dc4bb01d637a68105a3d5158039b418e6"
dependencies = [
"cc",
"libc",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "ntest"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54d1aa56874c2152c24681ed0df95ee155cc06c5c61b78e2d1e8c0cae8bc5326"
dependencies = [
"ntest_test_cases",
"ntest_timeout",
]
[[package]]
name = "ntest_test_cases"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6913433c6319ef9b2df316bb8e3db864a41724c2bb8f12555e07dc4ec69d3db1"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "ntest_timeout"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9224be3459a0c1d6e9b0f42ab0e76e98b29aef5aba33c0487dfcf47ea08b5150"
dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "num_cpus"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
dependencies = [
"hermit-abi",
"libc",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "pin-project"
version = "1.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"
dependencies = [
"pin-project-internal",
]
[[package]]
name = "pin-project-internal"
version = "1.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "proptest"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
dependencies = [
"bit-set",
"bit-vec",
"bitflags",
"num-traits",
"rand 0.9.5",
"rand_chacha",
"rand_xorshift",
"regex-syntax",
"rusty-fork",
"tempfile",
"unarray",
]
[[package]]
name = "proptest-derive"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c57924a81864dddafba92e1bf92f9bf82f97096c44489548a60e888e1547549b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
dependencies = [
"rand_chacha",
"rand_core 0.9.5",
]
[[package]]
name = "rand"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
dependencies = [
"chacha20",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core 0.9.5",
]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_xorshift"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
dependencies = [
"rand_core 0.9.5",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rustix"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "rusty-fork"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
dependencies = [
"fnv",
"quick-error",
"tempfile",
"wait-timeout",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.5",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "tokio"
version = "1.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
dependencies = [
"bytes",
"pin-project-lite",
"tokio-macros",
]
[[package]]
name = "tokio-macros"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.5",
]
[[package]]
name = "tokio-util"
version = "0.7.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
dependencies = [
"bytes",
"futures-core",
"futures-sink",
"pin-project-lite",
"tokio",
]
[[package]]
name = "toml_datetime"
version = "1.1.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.15+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
dependencies = [
"winnow",
]
[[package]]
name = "unarray"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "wasip2"
version = "1.0.4+wasi-0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "winnow"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
dependencies = [
"memchr",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "zerocopy"
version = "0.8.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zlib-rs"
version = "0.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12"
[[package]]
name = "zstd"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf06bd8162af0734b344780deb55b42a2429ae430870d13fcc12f238e880fe6e"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae42c0555055784c70058d19ba8e275528e8a99a706684868ace5da4e716a4ab"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.1.0+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0"
dependencies = [
"cc",
"pkg-config",
]
+280
View File
@@ -0,0 +1,280 @@
# 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 are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
rust-version = "1.83"
name = "async-compression"
version = "0.4.47"
authors = [
"Wim Looman <wim@nemo157.com>",
"Allen Bui <fairingrey@gmail.com>",
]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = """
Adaptors between compression crates and Rust's modern asynchronous IO types.
"""
readme = "README.md"
categories = [
"compression",
"asynchronous",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/Nullus157/async-compression"
resolver = "2"
[package.metadata.docs.rs]
all-features = true
[features]
all = [
"all-implementations",
"all-algorithms",
]
all-algorithms = [
"brotli",
"bzip2",
"deflate",
"deflate64",
"gzip",
"lz4",
"lzma",
"xz",
"xz-parallel",
"zlib",
"zstd",
]
all-implementations = [
"futures-io",
"tokio",
]
brotli = ["compression-codecs/brotli"]
bzip2 = ["compression-codecs/bzip2"]
deflate = ["compression-codecs/deflate"]
deflate64 = ["compression-codecs/deflate64"]
gzip = ["compression-codecs/gzip"]
lz4 = ["compression-codecs/lz4"]
lzma = ["compression-codecs/lzma"]
xz = [
"compression-codecs/xz",
"lzma",
]
xz-parallel = [
"compression-codecs/xz-parallel",
"xz",
]
xz2 = [
"compression-codecs/xz2",
"xz",
]
zlib = ["compression-codecs/zlib"]
zstd = ["compression-codecs/zstd"]
zstdmt = [
"compression-codecs/zstdmt",
"zstd",
]
[lib]
name = "async_compression"
path = "src/lib.rs"
[[example]]
name = "lzma_filters"
path = "examples/lzma_filters.rs"
required-features = [
"xz",
"tokio",
]
[[example]]
name = "zlib_tokio_write"
path = "examples/zlib_tokio_write.rs"
required-features = [
"zlib",
"tokio",
]
[[example]]
name = "zstd_gzip"
path = "examples/zstd_gzip.rs"
required-features = [
"zstd",
"gzip",
"tokio",
]
[[test]]
name = "brotli"
path = "tests/brotli.rs"
required-features = ["brotli"]
[[test]]
name = "bzip2"
path = "tests/bzip2.rs"
required-features = ["bzip2"]
[[test]]
name = "deflate"
path = "tests/deflate.rs"
required-features = ["deflate"]
[[test]]
name = "deflate64"
path = "tests/deflate64.rs"
required-features = [
"deflate64",
"tokio",
]
[[test]]
name = "gzip"
path = "tests/gzip.rs"
required-features = ["gzip"]
[[test]]
name = "lz4"
path = "tests/lz4.rs"
required-features = ["lz4"]
[[test]]
name = "lzma"
path = "tests/lzma.rs"
required-features = ["lzma"]
[[test]]
name = "proptest"
path = "tests/proptest.rs"
[[test]]
name = "xz"
path = "tests/xz.rs"
required-features = ["xz"]
[[test]]
name = "zlib"
path = "tests/zlib.rs"
required-features = ["zlib"]
[[test]]
name = "zstd"
path = "tests/zstd.rs"
required-features = ["zstd"]
[[test]]
name = "zstd-dict"
path = "tests/zstd-dict.rs"
required-features = [
"zstd",
"tokio",
]
[[test]]
name = "zstd-window-size"
path = "tests/zstd-window-size.rs"
required-features = [
"zstd",
"tokio",
]
[dependencies.compression-codecs]
version = "0.4.42"
[dependencies.compression-core]
version = "0.4.33"
[dependencies.futures-io]
version = "0.3"
features = ["std"]
optional = true
default-features = false
[dependencies.pin-project-lite]
version = "0.2"
[dependencies.tokio]
version = "1.24.2"
optional = true
default-features = false
[dev-dependencies.brotli]
version = "8"
[dev-dependencies.bytes]
version = "1"
[dev-dependencies.bzip2]
version = "0.6"
[dev-dependencies.deflate64]
version = "0.1.5"
[dev-dependencies.flate2]
version = "1.0.13"
[dev-dependencies.futures]
version = "0.3.5"
[dev-dependencies.futures-test]
version = "0.3.5"
[dev-dependencies.liblzma]
version = "0.4.2"
[dev-dependencies.libzstd]
version = "0.14.0"
default-features = false
package = "zstd"
[dev-dependencies.lz4]
version = "1.28.1"
[dev-dependencies.ntest]
version = "0.9"
[dev-dependencies.proptest]
version = "1"
[dev-dependencies.proptest-derive]
version = "0.8"
[dev-dependencies.rand]
version = "0.10"
[dev-dependencies.tokio]
version = "1.38.2"
features = [
"io-util",
"macros",
"rt-multi-thread",
"io-std",
]
default-features = false
[dev-dependencies.tokio-util]
version = "0.7"
features = ["io"]
default-features = false
[dev-dependencies.zstd-safe]
version = "8"
default-features = false
[lints.rust]
rust_2018_idioms = "deny"
[lints.rust.missing_debug_implementations]
level = "deny"
priority = -1
+148
View File
@@ -0,0 +1,148 @@
[package]
name = "async-compression"
version = "0.4.47"
description = """
Adaptors between compression crates and Rust's modern asynchronous IO types.
"""
authors.workspace = true
categories.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
[package.metadata.docs.rs]
all-features = true
[features]
# groups
all = ["all-implementations", "all-algorithms"]
all-implementations = ["futures-io", "tokio"]
all-algorithms = [
"brotli",
"bzip2",
"deflate",
"deflate64",
"gzip",
"lz4",
"lzma",
"xz",
"xz-parallel",
"zlib",
"zstd",
]
# algorithms
brotli = ["compression-codecs/brotli"]
bzip2 = ["compression-codecs/bzip2"]
deflate = ["compression-codecs/deflate"]
deflate64 = ["compression-codecs/deflate64"]
gzip = ["compression-codecs/gzip"]
lz4 = ["compression-codecs/lz4"]
lzma = ["compression-codecs/lzma"]
xz = ["compression-codecs/xz", "lzma"]
xz-parallel = ["compression-codecs/xz-parallel", "xz"]
xz2 = ["compression-codecs/xz2", "xz"]
zlib = ["compression-codecs/zlib"]
zstd = ["compression-codecs/zstd"]
zstdmt = ["compression-codecs/zstdmt", "zstd"]
[dependencies]
# core dependencies
pin-project-lite.workspace = true
compression-codecs.workspace = true
compression-core.workspace = true
# optional dependencies
futures-io = { version = "0.3", default-features = false, features = [
"std",
], optional = true }
tokio = { version = "1.24.2", optional = true, default-features = false }
[dev-dependencies]
bytes = "1"
futures = "0.3.5"
futures-test = "0.3.5"
ntest = "0.9"
proptest = "1"
proptest-derive = "0.8"
rand = "0.10"
tokio = { version = "1.38.2", default-features = false, features = [
"io-util",
"macros",
"rt-multi-thread",
"io-std",
] }
tokio-util = { version = "0.7", default-features = false, features = ["io"] }
brotli = "8"
bzip2 = "0.6"
flate2 = "1.0.13"
libzstd = { package = "zstd", version = "0.14.0", default-features = false }
lz4 = "1.28.1"
liblzma = "0.4.2"
zstd-safe = { version = "8", default-features = false }
deflate64 = "0.1.5"
[lints]
workspace = true
[[test]]
name = "brotli"
required-features = ["brotli"]
[[test]]
name = "bzip2"
required-features = ["bzip2"]
[[test]]
name = "deflate"
required-features = ["deflate"]
[[test]]
name = "deflate64"
required-features = ["deflate64", "tokio"]
[[test]]
name = "gzip"
required-features = ["gzip"]
[[test]]
name = "lz4"
required-features = ["lz4"]
[[test]]
name = "lzma"
required-features = ["lzma"]
[[test]]
name = "xz"
required-features = ["xz"]
[[test]]
name = "zlib"
required-features = ["zlib"]
[[test]]
name = "zstd"
required-features = ["zstd"]
[[test]]
name = "zstd-dict"
required-features = ["zstd", "tokio"]
[[test]]
name = "zstd-window-size"
required-features = ["zstd", "tokio"]
[[example]]
name = "zlib_tokio_write"
required-features = ["zlib", "tokio"]
[[example]]
name = "zstd_gzip"
required-features = ["zstd", "gzip", "tokio"]
[[example]]
name = "lzma_filters"
required-features = ["xz", "tokio"]
+201
View File
@@ -0,0 +1,201 @@
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.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018 the rustasync developers
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.
+88
View File
@@ -0,0 +1,88 @@
# async-compression
[![crates.io version][1]][2] ![build status][3]
[![downloads][5]][6] [![docs.rs docs][7]][8]
![MIT or Apache 2.0 licensed][9]
[![dependency status][10]][11]
This crate provides adaptors between compression crates and Rust's modern
asynchronous IO types.
- [Documentation][8]
- [Crates.io][2]
- [Releases][releases]
## Development
When developing you will need to enable appropriate features for the different
test cases to run, the simplest is `cargo test --all-features`, but you can
enable different subsets of features as appropriate for the code you are
testing to avoid compiling all dependencies, e.g. `cargo test --features
tokio,gzip`.
To prepare for a pull request, you can run several other checks:
1. `fmt`
```bash
cargo fmt --all
cargo clippy --no-deps
```
2. `build`
```bash
cargo build --lib --all-features
```
3. `nextest`
```bash
cargo --locked nextest run --workspace --all-features
```
4. `hack check`
```bash
cargo hack check --workspace --feature-powerset --all-targets --skip 'all,all-algorithms,all-implementations'
```
5. `wasm32` - Linux only
```bash
gh release download --repo WebAssembly/wasi-sdk --pattern 'wasi-sysroot-*.tar.gz'
mkdir -p wasi-sysroot
tar xf wasi-sysroot-*.tar.gz --strip-components=1 -C wasi-sysroot
rustup target add wasm32-wasip1-threads
export "CFLAGS_wasm32_wasip1_threads=--sysroot=\"${PWD}/wasi-sysroot\" -I\"${PWD}/wasi-sysroot/include/wasm32-wasip1-threads\" -L-I\"${PWD}/wasi-sysroot/lib/wasm32-wasip1-threads\""
cargo build --lib --features all-implementations,brotli,bzip2,deflate,gzip,lz4,lzma,xz,zlib,zstd,deflate64 --target wasm32-wasip1-threads
```
## License
Licensed under either of
- [Apache License, Version 2.0](LICENSE-APACHE)
- [MIT license](LICENSE-MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you shall be dual licensed as above, without any
additional terms or conditions.
[1]: https://img.shields.io/crates/v/async-compression.svg?style=flat-square
[2]: https://crates.io/crates/async-compression
[3]: https://img.shields.io/github/actions/workflow/status/Nullus157/async-compression/base.yml?style=flat-square
[5]: https://img.shields.io/crates/d/async-compression.svg?style=flat-square
[6]: https://crates.io/crates/async-compression
[7]: https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square
[8]: https://docs.rs/async-compression
[9]: https://img.shields.io/crates/l/async-compression.svg?style=flat-square
[10]: https://deps.rs/crate/async-compression/latest/status.svg?style=flat-square
[11]: https://deps.rs/crate/async-compression
[releases]: https://github.com/Nullus157/async-compression/releases
+95
View File
@@ -0,0 +1,95 @@
//! Run this example with the following command in a terminal:
//!
//! ```console
//! $ echo -n 'example' | zstd | cargo run --example zstd_gzip --features="tokio,zstd,gzip" | gunzip -c
//! 7example
//! ```
//!
//! Note that the "7" prefix (input length) is printed to stdout but will likely show up as shown
//! above. This is not an encoding error; see the code in `main`.
use std::convert::TryFrom;
use std::io::Result;
use compression_codecs::lzma::params::{
LzmaDecoderParams, LzmaEncoderParams, LzmaFilter, LzmaFilters, LzmaOptions,
};
use tokio::io::{stdin, stdout, BufReader, Stdin, Stdout};
use tokio::io::{
AsyncReadExt as _, // for `read_to_end`
AsyncWriteExt as _, // for `write_all` and `shutdown`
};
const OPTIONS: &str = r"
Usage: lzma_filter [OPTIONS]
Read stdin and output result to stdout
Options:
-d Decompress (Default)
-c Compress
";
fn usage(msg: &str) -> Result<()> {
if !msg.is_empty() {
eprintln!("{msg}...")
}
eprintln!("{}", OPTIONS);
std::process::exit(1);
}
/// Read compressed and output decompressed or
/// Read decompressed and output compressed
/// echo "this is a test" | lzma_filters -- -c | lzma_filters -- -d | xxd
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
if args.len() != 2 {
return usage("too many args");
}
let stdin = stdin();
let stdout = stdout();
let filters =
LzmaFilters::default().add_filter(LzmaFilter::Lzma2(LzmaOptions::default().preset(7)));
let mut stdout = if args[1] == "-d" {
decompress(stdin, filters, stdout).await?
} else if args[1] == "-c" {
compress(stdin, filters, stdout).await?
} else {
return usage(&format!("invalid argument: {}", args[1]));
};
stdout.flush().await?;
stdout.shutdown().await?;
Ok(())
}
async fn decompress(stdin: Stdin, filters: LzmaFilters, mut stdout: Stdout) -> Result<Stdout> {
let params = LzmaDecoderParams::Raw { filters };
let codec = compression_codecs::Xz2Decoder::try_from(params).expect("Could not create encoder");
let codec = compression_codecs::LzmaDecoder::from(codec);
let mut reader =
async_compression::tokio::bufread::LzmaDecoder::with_codec(BufReader::new(stdin), codec);
let mut buf = vec![];
reader.read_to_end(&mut buf).await?;
stdout.write_all(&buf).await?;
Ok(stdout)
}
async fn compress(mut stdin: Stdin, filters: LzmaFilters, stdout: Stdout) -> Result<Stdout> {
let params = LzmaEncoderParams::Raw { filters };
let codec = compression_codecs::Xz2Encoder::try_from(params).expect("Could not create encoder");
let codec = compression_codecs::LzmaEncoder::from(codec);
let mut writer = async_compression::tokio::write::LzmaEncoder::with_codec(stdout, codec);
let mut buf = vec![];
stdin.read_to_end(&mut buf).await?;
writer.write_all(&buf).await?;
writer.shutdown().await?;
Ok(writer.into_inner())
}
+35
View File
@@ -0,0 +1,35 @@
//! Run this example with the following command in a terminal:
//!
//! ```console
//! $ cargo run --example zlib_tokio_write --features="tokio,zlib"
//! "example"
//! ```
use std::io::Result;
use async_compression::tokio::write::{ZlibDecoder, ZlibEncoder};
use tokio::io::AsyncWriteExt as _; // for `write_all` and `shutdown`
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
let data = b"example";
let compressed_data = compress(data).await?;
let de_compressed_data = decompress(&compressed_data).await?;
assert_eq!(de_compressed_data, data);
println!("{:?}", String::from_utf8(de_compressed_data).unwrap());
Ok(())
}
async fn compress(in_data: &[u8]) -> Result<Vec<u8>> {
let mut encoder = ZlibEncoder::new(Vec::new());
encoder.write_all(in_data).await?;
encoder.shutdown().await?;
Ok(encoder.into_inner())
}
async fn decompress(in_data: &[u8]) -> Result<Vec<u8>> {
let mut decoder = ZlibDecoder::new(Vec::new());
decoder.write_all(in_data).await?;
decoder.shutdown().await?;
Ok(decoder.into_inner())
}
+42
View File
@@ -0,0 +1,42 @@
//! Run this example with the following command in a terminal:
//!
//! ```console
//! $ echo -n 'example' | zstd | cargo run --example zstd_gzip --features="tokio,zstd,gzip" | gunzip -c
//! 7example
//! ```
//!
//! Note that the "7" prefix (input length) is printed to stdout but will likely show up as shown
//! above. This is not an encoding error; see the code in `main`.
use std::io::Result;
use async_compression::tokio::{bufread::ZstdDecoder, write::GzipEncoder};
use tokio::io::{stderr, stdin, stdout, BufReader};
use tokio::io::{
AsyncReadExt as _, // for `read_to_end`
AsyncWriteExt as _, // for `write_all` and `shutdown`
};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
// Read zstd encoded data from stdin and decode
let mut reader = ZstdDecoder::new(BufReader::new(stdin()));
let mut x: Vec<u8> = vec![];
reader.read_to_end(&mut x).await?;
// print to stderr the length of the decoded data
let mut error = stderr();
error.write_all(x.len().to_string().as_bytes()).await?;
error.shutdown().await?;
// print to stdin encoded gzip data
let mut writer = GzipEncoder::new(stdout());
writer.write_all(&x).await?;
writer.shutdown().await?;
// flush stdout
let mut res = writer.into_inner();
res.flush().await?;
Ok(())
}
@@ -0,0 +1,51 @@
use crate::{
codecs::DecodeV2,
core::util::{PartialBuffer, WriteBuffer},
generic::bufread::impl_decoder,
};
use core::{
pin::Pin,
task::{Context, Poll},
};
use futures_io::{AsyncBufRead, AsyncRead, AsyncWrite};
use std::io::{IoSlice, Result};
impl_decoder!();
impl<R: AsyncBufRead, D: DecodeV2> AsyncRead for Decoder<R, D> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
if buf.is_empty() {
return Poll::Ready(Ok(0));
}
let mut output = WriteBuffer::new_initialized(buf);
self.do_poll_read(cx, &mut output)
.map_ok(|()| output.written_len())
}
}
impl<R: AsyncWrite, D> AsyncWrite for Decoder<R, D> {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> {
self.get_pin_mut().poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.get_pin_mut().poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.get_pin_mut().poll_close(cx)
}
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<Result<usize>> {
self.get_pin_mut().poll_write_vectored(cx, bufs)
}
}
@@ -0,0 +1,51 @@
use crate::{
codecs::EncodeV2,
core::util::{PartialBuffer, WriteBuffer},
generic::bufread::impl_encoder,
};
use futures_io::{AsyncBufRead, AsyncRead, AsyncWrite, IoSlice};
use std::{
io::Result,
pin::Pin,
task::{Context, Poll},
};
impl_encoder!();
impl<R: AsyncBufRead, E: EncodeV2> AsyncRead for Encoder<R, E> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
if buf.is_empty() {
return Poll::Ready(Ok(0));
}
let mut output = WriteBuffer::new_initialized(buf);
self.do_poll_read(cx, &mut output)
.map_ok(|()| output.written_len())
}
}
impl<R: AsyncWrite, E> AsyncWrite for Encoder<R, E> {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> {
self.get_pin_mut().poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.get_pin_mut().poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.get_pin_mut().poll_close(cx)
}
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<Result<usize>> {
self.get_pin_mut().poll_write_vectored(cx, bufs)
}
}
@@ -0,0 +1,4 @@
mod decoder;
mod encoder;
pub use self::{decoder::Decoder, encoder::Encoder};
@@ -0,0 +1,126 @@
macro_rules! decoder {
($(#[$attr:meta])* $name:ident<$inner:ident> $({ $($inherent_methods:tt)* })*) => {
pin_project_lite::pin_project! {
$(#[$attr])*
///
/// This structure implements an [`AsyncRead`](futures_io::AsyncRead) interface and will
/// read compressed data from an underlying stream and emit a stream of uncompressed data.
#[derive(Debug)]
pub struct $name<$inner> {
#[pin]
inner: crate::futures::bufread::Decoder<$inner, crate::codecs::$name>,
}
}
impl<$inner: futures_io::AsyncBufRead> $name<$inner> {
/// Creates a new decoder which will read compressed data from the given stream and
/// emit an uncompressed stream.
pub fn new(read: $inner) -> $name<$inner> {
$name {
inner: crate::futures::bufread::Decoder::new(read, crate::codecs::$name::new()),
}
}
/// Creates a new decoder with the given codec, which will read compressed data from the given stream and
/// emit an uncompressed stream.
pub fn with_codec(read: $inner, codec: crate::codecs::$name) -> $name<$inner> {
$name {
inner: crate::futures::bufread::Decoder::new(read, codec)
}
}
$($($inherent_methods)*)*
}
impl<$inner> $name<$inner> {
/// Configure multi-member/frame decoding, if enabled this will reset the decoder state
/// when reaching the end of a compressed member/frame and expect either EOF or another
/// compressed member/frame to follow it in the stream.
pub fn multiple_members(&mut self, enabled: bool) {
self.inner.multiple_members(enabled);
}
/// Acquires a reference to the underlying reader that this decoder is wrapping.
pub fn get_ref(&self) -> &$inner {
self.inner.get_ref()
}
/// Acquires a mutable reference to the underlying reader that this decoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this decoder.
pub fn get_mut(&mut self) -> &mut $inner {
self.inner.get_mut()
}
/// Acquires a pinned mutable reference to the underlying reader that this decoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this decoder.
pub fn get_pin_mut(self: std::pin::Pin<&mut Self>) -> std::pin::Pin<&mut $inner> {
self.project().inner.get_pin_mut()
}
/// Consumes this decoder returning the underlying reader.
///
/// Note that this may discard internal state of this decoder, so care should be taken
/// to avoid losing resources when this is called.
pub fn into_inner(self) -> $inner {
self.inner.into_inner()
}
}
impl<$inner: futures_io::AsyncBufRead> futures_io::AsyncRead for $name<$inner> {
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut [u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.project().inner.poll_read(cx, buf)
}
}
impl<$inner: futures_io::AsyncWrite> futures_io::AsyncWrite for $name<$inner> {
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.get_pin_mut().poll_write(cx, buf)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.get_pin_mut().poll_flush(cx)
}
fn poll_close(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.get_pin_mut().poll_close(cx)
}
fn poll_write_vectored(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
bufs: &[std::io::IoSlice<'_>]
) -> std::task::Poll<std::io::Result<usize>> {
self.get_pin_mut().poll_write_vectored(cx, bufs)
}
}
const _: () = {
use crate::core::util::{_assert_send, _assert_sync};
use core::pin::Pin;
use futures_io::AsyncBufRead;
_assert_send::<$name<Pin<Box<dyn AsyncBufRead + Send>>>>();
_assert_sync::<$name<Pin<Box<dyn AsyncBufRead + Sync>>>>();
};
}
}
@@ -0,0 +1,114 @@
macro_rules! encoder {
($(#[$attr:meta])* $name:ident<$inner:ident> $({ $($inherent_methods:tt)* })*) => {
pin_project_lite::pin_project! {
$(#[$attr])*
///
/// This structure implements an [`AsyncRead`](futures_io::AsyncRead) interface and will
/// read uncompressed data from an underlying stream and emit a stream of compressed data.
#[derive(Debug)]
pub struct $name<$inner> {
#[pin]
inner: crate::futures::bufread::Encoder<$inner, crate::codecs::$name>,
}
}
impl<$inner: futures_io::AsyncBufRead> $name<$inner> {
$(
/// Creates a new encoder which will read uncompressed data from the given stream
/// and emit an compressed stream.
///
$($inherent_methods)*
)*
/// Creates a new encoder with the given codec, which will read uncompressed data from the given stream
/// and emit an compressed stream.
pub fn with_codec(read: $inner, codec: crate::codecs::$name) -> $name<$inner> {
$name {
inner: crate::futures::bufread::Encoder::new(read, codec)
}
}
/// Acquires a reference to the underlying reader that this encoder is wrapping.
pub fn get_ref(&self) -> &$inner {
self.inner.get_ref()
}
/// Acquires a mutable reference to the underlying reader that this encoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this encoder.
pub fn get_mut(&mut self) -> &mut $inner {
self.inner.get_mut()
}
/// Acquires a pinned mutable reference to the underlying reader that this encoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this encoder.
pub fn get_pin_mut(self: std::pin::Pin<&mut Self>) -> std::pin::Pin<&mut $inner> {
self.project().inner.get_pin_mut()
}
/// Consumes this encoder returning the underlying reader.
///
/// Note that this may discard internal state of this encoder, so care should be taken
/// to avoid losing resources when this is called.
pub fn into_inner(self) -> $inner {
self.inner.into_inner()
}
}
impl<$inner: futures_io::AsyncBufRead> futures_io::AsyncRead for $name<$inner> {
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut [u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.project().inner.poll_read(cx, buf)
}
}
impl<$inner: futures_io::AsyncWrite> futures_io::AsyncWrite for $name<$inner> {
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.project().inner.poll_write(cx, buf)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_flush(cx)
}
fn poll_close(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_close(cx)
}
fn poll_write_vectored(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
bufs: &[std::io::IoSlice<'_>]
) -> std::task::Poll<std::io::Result<usize>> {
self.project().inner.poll_write_vectored(cx, bufs)
}
}
const _: () = {
use crate::core::util::{_assert_send, _assert_sync};
use core::pin::Pin;
use futures_io::AsyncBufRead;
_assert_send::<$name<Pin<Box<dyn AsyncBufRead + Send>>>>();
_assert_sync::<$name<Pin<Box<dyn AsyncBufRead + Sync>>>>();
};
}
}
@@ -0,0 +1,4 @@
#[macro_use]
mod decoder;
#[macro_use]
mod encoder;
+10
View File
@@ -0,0 +1,10 @@
//! Types which operate over [`AsyncBufRead`](futures_io::AsyncBufRead) streams, both encoders and
//! decoders for various formats.
#[macro_use]
mod macros;
mod generic;
pub(crate) use generic::{Decoder, Encoder};
algos!(futures::bufread<R>);
+4
View File
@@ -0,0 +1,4 @@
//! Implementations for IO traits exported by [`futures-io`](::futures_io).
pub mod bufread;
pub mod write;
@@ -0,0 +1,27 @@
// Originally sourced from `futures_util::io::buf_writer`, needs to be redefined locally so that
// the `AsyncBufWrite` impl can access its internals, and changed a bit to make it more efficient
// with those methods.
use crate::generic::write::impl_buf_writer;
use futures_io::{AsyncSeek, AsyncWrite, SeekFrom};
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
impl_buf_writer!(poll_close);
impl<W: AsyncWrite + AsyncSeek> AsyncSeek for BufWriter<W> {
/// Seek to the offset, in bytes, in the underlying writer.
///
/// Seeking always writes out the internal buffer before seeking.
fn poll_seek(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
pos: SeekFrom,
) -> Poll<io::Result<u64>> {
ready!(self.as_mut().flush_buf(cx))?;
self.project().writer.poll_seek(cx, pos)
}
}
@@ -0,0 +1,27 @@
use crate::{futures::write::BufWriter, generic::write::impl_decoder};
use futures_io::{AsyncBufRead, AsyncRead, AsyncWrite, IoSliceMut};
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
impl_decoder!(poll_close);
impl<W: AsyncRead, D> AsyncRead for Decoder<W, D> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
self.get_pin_mut().poll_read(cx, buf)
}
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<io::Result<usize>> {
self.get_pin_mut().poll_read_vectored(cx, bufs)
}
}
@@ -0,0 +1,27 @@
use crate::{futures::write::BufWriter, generic::write::impl_encoder};
use futures_io::{AsyncBufRead, AsyncRead, AsyncWrite, IoSliceMut};
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
impl_encoder!(poll_close);
impl<W: AsyncRead, E> AsyncRead for Encoder<W, E> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
self.get_pin_mut().poll_read(cx, buf)
}
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<io::Result<usize>> {
self.get_pin_mut().poll_read_vectored(cx, bufs)
}
}
@@ -0,0 +1,4 @@
mod decoder;
mod encoder;
pub use self::{decoder::Decoder, encoder::Encoder};
@@ -0,0 +1,132 @@
macro_rules! decoder {
($(#[$attr:meta])* $name:ident<$inner:ident> $({ $($inherent_methods:tt)* })*) => {
pin_project_lite::pin_project! {
$(#[$attr])*
///
/// This structure implements an [`AsyncWrite`](futures_io::AsyncWrite) interface and will
/// take in compressed data and write it, uncompressed, to an underlying stream.
#[derive(Debug)]
pub struct $name<$inner> {
#[pin]
inner: crate::futures::write::Decoder<$inner, crate::codecs::$name>,
}
}
impl<$inner: futures_io::AsyncWrite> $name<$inner> {
/// Creates a new decoder which will take in compressed data and write it, uncompressed,
/// to the given stream.
pub fn new(read: $inner) -> $name<$inner> {
$name {
inner: crate::futures::write::Decoder::new(read, crate::codecs::$name::new()),
}
}
/// Creates a new decoder with the given codec, which will take in compressed data and write it, uncompressed,
/// to the given stream.
pub fn with_codec(read: $inner, codec: crate::codecs::$name) -> $name<$inner> {
$name {
inner: crate::futures::write::Decoder::new(read, codec)
}
}
$($($inherent_methods)*)*
}
impl<$inner> $name<$inner> {
/// Acquires a reference to the underlying reader that this decoder is wrapping.
pub fn get_ref(&self) -> &$inner {
self.inner.get_ref()
}
/// Acquires a mutable reference to the underlying reader that this decoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this decoder.
pub fn get_mut(&mut self) -> &mut $inner {
self.inner.get_mut()
}
/// Acquires a pinned mutable reference to the underlying reader that this decoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this decoder.
pub fn get_pin_mut(self: std::pin::Pin<&mut Self>) -> std::pin::Pin<&mut $inner> {
self.project().inner.get_pin_mut()
}
/// Consumes this decoder returning the underlying reader.
///
/// Note that this may discard internal state of this decoder, so care should be taken
/// to avoid losing resources when this is called.
pub fn into_inner(self) -> $inner {
self.inner.into_inner()
}
}
impl<$inner: futures_io::AsyncWrite> futures_io::AsyncWrite for $name<$inner> {
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.project().inner.poll_write(cx, buf)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_flush(cx)
}
fn poll_close(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_close(cx)
}
}
impl<$inner: futures_io::AsyncRead> futures_io::AsyncRead for $name<$inner> {
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut [u8]
) -> std::task::Poll<std::io::Result<usize>> {
self.get_pin_mut().poll_read(cx, buf)
}
fn poll_read_vectored(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
bufs: &mut [futures_io::IoSliceMut<'_>]
) -> std::task::Poll<std::io::Result<usize>> {
self.get_pin_mut().poll_read_vectored(cx, bufs)
}
}
impl<$inner: futures_io::AsyncBufRead> futures_io::AsyncBufRead for $name<$inner> {
fn poll_fill_buf(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>
) -> std::task::Poll<std::io::Result<&[u8]>> {
self.get_pin_mut().poll_fill_buf(cx)
}
fn consume(self: std::pin::Pin<&mut Self>, amt: usize) {
self.get_pin_mut().consume(amt)
}
}
const _: () = {
use crate::core::util::{_assert_send, _assert_sync};
use core::pin::Pin;
use futures_io::AsyncWrite;
_assert_send::<$name<Pin<Box<dyn AsyncWrite + Send>>>>();
_assert_sync::<$name<Pin<Box<dyn AsyncWrite + Sync>>>>();
};
}
}
@@ -0,0 +1,129 @@
macro_rules! encoder {
($(#[$attr:meta])* $name:ident<$inner:ident> $({ $($inherent_methods:tt)* })*) => {
pin_project_lite::pin_project! {
$(#[$attr])*
///
/// This structure implements an [`AsyncWrite`](futures_io::AsyncWrite) interface and will
/// take in uncompressed data and write it compressed to an underlying stream.
#[derive(Debug)]
pub struct $name<$inner> {
#[pin]
inner: crate::futures::write::Encoder<$inner, crate::codecs::$name>,
}
}
impl<$inner: futures_io::AsyncWrite> $name<$inner> {
$(
/// Creates a new encoder which will take in uncompressed data and write it
/// compressed to the given stream.
///
$($inherent_methods)*
)*
/// Creates a new encoder with the given codec, which will take in uncompressed data and write it
/// compressed to the given stream.
pub fn with_codec(read: $inner, codec: crate::codecs::$name) -> $name<$inner> {
$name {
inner: crate::futures::write::Encoder::new(read, codec)
}
}
}
impl<$inner> $name<$inner> {
/// Acquires a reference to the underlying writer that this encoder is wrapping.
pub fn get_ref(&self) -> &$inner {
self.inner.get_ref()
}
/// Acquires a mutable reference to the underlying writer that this encoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the writer which
/// may otherwise confuse this encoder.
pub fn get_mut(&mut self) -> &mut $inner {
self.inner.get_mut()
}
/// Acquires a pinned mutable reference to the underlying writer that this encoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the writer which
/// may otherwise confuse this encoder.
pub fn get_pin_mut(self: std::pin::Pin<&mut Self>) -> std::pin::Pin<&mut $inner> {
self.project().inner.get_pin_mut()
}
/// Consumes this encoder returning the underlying writer.
///
/// Note that this may discard internal state of this encoder, so care should be taken
/// to avoid losing resources when this is called.
pub fn into_inner(self) -> $inner {
self.inner.into_inner()
}
}
impl<$inner: futures_io::AsyncWrite> futures_io::AsyncWrite for $name<$inner> {
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.project().inner.poll_write(cx, buf)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_flush(cx)
}
fn poll_close(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_close(cx)
}
}
impl<$inner: futures_io::AsyncRead> futures_io::AsyncRead for $name<$inner> {
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut [u8]
) -> std::task::Poll<std::io::Result<usize>> {
self.get_pin_mut().poll_read(cx, buf)
}
fn poll_read_vectored(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
bufs: &mut [futures_io::IoSliceMut<'_>]
) -> std::task::Poll<std::io::Result<usize>> {
self.get_pin_mut().poll_read_vectored(cx, bufs)
}
}
impl<$inner: futures_io::AsyncBufRead> futures_io::AsyncBufRead for $name<$inner> {
fn poll_fill_buf(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>
) -> std::task::Poll<std::io::Result<&[u8]>> {
self.get_pin_mut().poll_fill_buf(cx)
}
fn consume(self: std::pin::Pin<&mut Self>, amt: usize) {
self.get_pin_mut().consume(amt)
}
}
const _: () = {
use crate::core::util::{_assert_send, _assert_sync};
use core::pin::Pin;
use futures_io::AsyncWrite;
_assert_send::<$name<Pin<Box<dyn AsyncWrite + Send>>>>();
_assert_sync::<$name<Pin<Box<dyn AsyncWrite + Sync>>>>();
};
}
}
@@ -0,0 +1,4 @@
#[macro_use]
mod decoder;
#[macro_use]
mod encoder;
+16
View File
@@ -0,0 +1,16 @@
//! Types which operate over [`AsyncWrite`](futures_io::AsyncWrite) streams, both encoders and
//! decoders for various formats.
#[macro_use]
mod macros;
mod generic;
mod buf_writer;
use self::{
buf_writer::BufWriter,
generic::{Decoder, Encoder},
};
use crate::generic::write::AsyncBufWrite;
algos!(futures::write<W>);
+243
View File
@@ -0,0 +1,243 @@
use crate::{
codecs::DecodeV2,
core::util::{PartialBuffer, WriteBuffer},
};
use std::{io::Result, ops::ControlFlow, panic::AssertUnwindSafe};
#[derive(Debug)]
enum State {
Decoding,
Flushing,
Done,
Next,
Error(AssertUnwindSafe<std::io::Error>),
}
#[derive(Debug)]
pub struct Decoder {
state: State,
multiple_members: bool,
}
impl Default for Decoder {
fn default() -> Self {
Self {
state: State::Decoding,
multiple_members: false,
}
}
}
impl Decoder {
pub fn multiple_members(&mut self, enabled: bool) {
self.multiple_members = enabled;
}
pub fn do_poll_read(
&mut self,
output: &mut WriteBuffer<'_>,
decoder: &mut dyn DecodeV2,
input: &mut PartialBuffer<&[u8]>,
mut first: bool,
) -> ControlFlow<Result<()>> {
loop {
self.state = match self.state {
State::Decoding => {
if input.unwritten().is_empty() && !first {
// Avoid attempting to reinitialise the decoder if the
// reader has returned EOF.
self.multiple_members = false;
State::Flushing
} else {
match decoder.decode(input, output) {
Ok(true) => State::Flushing,
// ignore the first error, occurs when input is empty
// but we need to run decode to flush
Err(err) if !first => {
self.state = State::Error(AssertUnwindSafe(err));
if output.written_len() > 0 {
return ControlFlow::Break(Ok(()));
} else {
continue;
}
}
// poll for more data for the next decode
_ => break,
}
}
}
State::Flushing => {
let before = output.written_len();
let result = decoder.finish(output).and_then(|finished| {
if !finished
&& output.written_len() == before
&& !output.has_no_spare_space()
{
Err(std::io::ErrorKind::UnexpectedEof.into())
} else {
Ok(finished)
}
});
match result {
Ok(true) => {
if self.multiple_members {
if let Err(err) = decoder.reinit() {
self.state = State::Error(AssertUnwindSafe(err));
if output.written_len() > 0 {
return ControlFlow::Break(Ok(()));
} else {
continue;
}
}
// Poll again only if the decode stage consumed all the input.
first = input.unwritten().is_empty();
State::Next
} else {
State::Done
}
}
Ok(false) => State::Flushing,
Err(err) => {
self.state = State::Error(AssertUnwindSafe(err));
if output.written_len() > 0 {
return ControlFlow::Break(Ok(()));
} else {
continue;
}
}
}
}
State::Done => return ControlFlow::Break(Ok(())),
State::Next => {
if input.unwritten().is_empty() {
if first {
// poll for more data to check if there's another stream
break;
}
State::Done
} else {
State::Decoding
}
}
State::Error(_) => {
let State::Error(err) = std::mem::replace(&mut self.state, State::Done) else {
unreachable!()
};
return ControlFlow::Break(Err(err.0));
}
};
if output.has_no_spare_space() {
return ControlFlow::Break(Ok(()));
}
}
if output.has_no_spare_space() {
ControlFlow::Break(Ok(()))
} else {
ControlFlow::Continue(())
}
}
}
macro_rules! impl_decoder {
() => {
use crate::generic::bufread::Decoder as GenericDecoder;
use std::{ops::ControlFlow, task::ready};
use pin_project_lite::pin_project;
pin_project! {
#[derive(Debug)]
pub struct Decoder<R, D> {
#[pin]
reader: R,
decoder: D,
inner: GenericDecoder,
}
}
impl<R: AsyncBufRead, D: DecodeV2> Decoder<R, D> {
pub fn new(reader: R, decoder: D) -> Self {
Self {
reader,
decoder,
inner: GenericDecoder::default(),
}
}
}
impl<R, D> Decoder<R, D> {
pub fn get_ref(&self) -> &R {
&self.reader
}
pub fn get_mut(&mut self) -> &mut R {
&mut self.reader
}
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R> {
self.project().reader
}
pub fn into_inner(self) -> R {
self.reader
}
pub fn multiple_members(&mut self, enabled: bool) {
self.inner.multiple_members(enabled);
}
}
fn do_poll_read(
inner: &mut GenericDecoder,
decoder: &mut dyn DecodeV2,
mut reader: Pin<&mut dyn AsyncBufRead>,
cx: &mut Context<'_>,
output: &mut WriteBuffer<'_>,
) -> Poll<Result<()>> {
if let ControlFlow::Break(res) =
inner.do_poll_read(output, decoder, &mut PartialBuffer::new(&[][..]), true)
{
return Poll::Ready(res);
}
loop {
let mut input = PartialBuffer::new(match reader.as_mut().poll_fill_buf(cx)? {
Poll::Ready(input) => input,
Poll::Pending if output.written().is_empty() => return Poll::Pending,
_ => return Poll::Ready(Ok(())),
});
let control_flow = inner.do_poll_read(output, decoder, &mut input, false);
let bytes_read = input.written().len();
reader.as_mut().consume(bytes_read);
if let ControlFlow::Break(res) = control_flow {
break Poll::Ready(res);
}
}
}
impl<R: AsyncBufRead, D: DecodeV2> Decoder<R, D> {
fn do_poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
output: &mut WriteBuffer<'_>,
) -> Poll<Result<()>> {
let this = self.project();
do_poll_read(this.inner, this.decoder, this.reader, cx, output)
}
}
};
}
pub(crate) use impl_decoder;
+233
View File
@@ -0,0 +1,233 @@
use crate::{
codecs::EncodeV2,
core::util::{PartialBuffer, WriteBuffer},
};
use std::{io::Result, ops::ControlFlow, panic::AssertUnwindSafe};
#[derive(Debug)]
enum State {
Encoding(usize),
Flushing,
Finishing,
Done,
Error(AssertUnwindSafe<std::io::Error>),
}
#[derive(Debug)]
pub struct Encoder {
state: State,
}
impl Default for Encoder {
fn default() -> Self {
Self {
state: State::Encoding(0),
}
}
}
impl Encoder {
/// `input` - should be `None` if `Poll::Pending`.
pub fn do_poll_read(
&mut self,
output: &mut WriteBuffer<'_>,
encoder: &mut dyn EncodeV2,
mut input: Option<&mut PartialBuffer<&[u8]>>,
) -> ControlFlow<Result<()>> {
loop {
self.state = match &mut self.state {
State::Encoding(read) => match input.as_mut() {
None => {
if *read == 0 {
if output.written().is_empty() {
// Poll for more data
break;
} else {
return ControlFlow::Break(Ok(()));
}
} else {
State::Flushing
}
}
Some(input) => {
if input.unwritten().is_empty() {
State::Finishing
} else {
if let Err(err) = encoder.encode(input, output) {
self.state = State::Error(AssertUnwindSafe(err));
if output.written_len() > 0 {
return ControlFlow::Break(Ok(()));
} else {
continue;
}
}
*read += input.written().len();
// Poll for more data
break;
}
}
},
State::Flushing => match encoder.flush(output) {
Ok(true) => {
self.state = State::Encoding(0);
// Poll for more data
break;
}
Ok(false) => State::Flushing,
Err(err) => {
self.state = State::Error(AssertUnwindSafe(err));
if output.written_len() > 0 {
return ControlFlow::Break(Ok(()));
} else {
continue;
}
}
},
State::Finishing => match encoder.finish(output) {
Ok(true) => State::Done,
Ok(false) => State::Finishing,
Err(err) => {
self.state = State::Error(AssertUnwindSafe(err));
if output.written_len() > 0 {
return ControlFlow::Break(Ok(()));
} else {
continue;
}
}
},
State::Done => return ControlFlow::Break(Ok(())),
State::Error(_) => {
let State::Error(err) = std::mem::replace(&mut self.state, State::Done) else {
unreachable!()
};
return ControlFlow::Break(Err(err.0));
}
};
if output.has_no_spare_space() {
return ControlFlow::Break(Ok(()));
}
}
if output.has_no_spare_space() {
ControlFlow::Break(Ok(()))
} else {
ControlFlow::Continue(())
}
}
}
macro_rules! impl_encoder {
() => {
use crate::generic::bufread::Encoder as GenericEncoder;
use std::{ops::ControlFlow, task::ready};
use pin_project_lite::pin_project;
pin_project! {
#[derive(Debug)]
pub struct Encoder<R, E> {
#[pin]
reader: R,
encoder: E,
inner: GenericEncoder,
}
}
impl<R: AsyncBufRead, E: EncodeV2> Encoder<R, E> {
pub fn new(reader: R, encoder: E) -> Self {
Self {
reader,
encoder,
inner: Default::default(),
}
}
pub fn with_capacity(reader: R, encoder: E, _cap: usize) -> Self {
Self::new(reader, encoder)
}
}
impl<R, E> Encoder<R, E> {
pub fn get_ref(&self) -> &R {
&self.reader
}
pub fn get_mut(&mut self) -> &mut R {
&mut self.reader
}
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R> {
self.project().reader
}
pub(crate) fn get_encoder_ref(&self) -> &E {
&self.encoder
}
pub fn into_inner(self) -> R {
self.reader
}
}
fn do_poll_read(
inner: &mut GenericEncoder,
encoder: &mut dyn EncodeV2,
mut reader: Pin<&mut dyn AsyncBufRead>,
cx: &mut Context<'_>,
output: &mut WriteBuffer<'_>,
) -> Poll<Result<()>> {
if let ControlFlow::Break(res) = inner.do_poll_read(output, encoder, None) {
return Poll::Ready(res);
}
loop {
let mut input = match reader.as_mut().poll_fill_buf(cx) {
Poll::Pending => None,
Poll::Ready(res) => Some(PartialBuffer::new(res?)),
};
let control_flow = inner.do_poll_read(output, encoder, input.as_mut());
let is_pending = input.is_none();
if let Some(input) = input {
let len = input.written().len();
reader.as_mut().consume(len);
}
if let ControlFlow::Break(res) = control_flow {
break Poll::Ready(res);
}
if is_pending {
if output.written().is_empty() {
return Poll::Pending;
} else {
return Poll::Ready(Ok(()));
}
}
}
}
impl<R: AsyncBufRead, E: EncodeV2> Encoder<R, E> {
fn do_poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
output: &mut WriteBuffer<'_>,
) -> Poll<Result<()>> {
let this = self.project();
do_poll_read(this.inner, this.encoder, this.reader, cx, output)
}
}
};
}
pub(crate) use impl_encoder;
+5
View File
@@ -0,0 +1,5 @@
mod decoder;
mod encoder;
pub(crate) use decoder::*;
pub(crate) use encoder::*;
+2
View File
@@ -0,0 +1,2 @@
pub(crate) mod bufread;
pub(crate) mod write;
+21
View File
@@ -0,0 +1,21 @@
use super::Buffer;
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
pub(crate) trait AsyncBufWrite {
/// Attempt to return an internal buffer to write to, flushing data out to the inner reader if
/// it is full.
///
/// On success, returns `Poll::Ready(Ok(buf))`.
///
/// If the buffer is full and cannot be flushed, the method returns `Poll::Pending` and
/// arranges for the current task context (`cx`) to receive a notification when the object
/// becomes readable or is closed.
fn poll_partial_flush_buf(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<io::Result<Buffer<'_>>>;
}
+275
View File
@@ -0,0 +1,275 @@
// Originally sourced from `futures_util::io::buf_writer`, needs to be redefined locally so that
// the `AsyncBufWrite` impl can access its internals, and changed a bit to make it more efficient
// with those methods.
use super::AsyncBufWrite;
use compression_core::util::WriteBuffer;
use std::{
fmt, io,
pin::Pin,
task::{ready, Context, Poll},
};
const DEFAULT_BUF_SIZE: usize = 8192;
pub struct BufWriter {
buf: Box<[u8]>,
written: usize,
buffered: usize,
}
impl fmt::Debug for BufWriter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GenericBufWriter")
.field(
"buffer",
&format_args!("{}/{}", self.buffered, self.buf.len()),
)
.field("written", &self.written)
.finish()
}
}
impl BufWriter {
/// Creates a new `BufWriter` with a default buffer capacity. The default is currently 8 KB,
/// but may change in the future.
pub fn new() -> Self {
Self::with_capacity(DEFAULT_BUF_SIZE)
}
/// Creates a new `BufWriter` with the specified buffer capacity.
pub fn with_capacity(cap: usize) -> Self {
Self {
buf: vec![0; cap].into(),
written: 0,
buffered: 0,
}
}
/// Remove the already written data
fn remove_written(&mut self) {
self.buf.copy_within(self.written..self.buffered, 0);
self.buffered -= self.written;
self.written = 0;
}
fn do_flush(
&mut self,
poll_write: &mut dyn FnMut(&[u8]) -> Poll<io::Result<usize>>,
) -> Poll<io::Result<()>> {
while self.written < self.buffered {
let bytes_written = ready!(poll_write(&self.buf[self.written..self.buffered]))?;
if bytes_written == 0 {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::WriteZero,
"failed to write the buffered data",
)));
}
self.written += bytes_written;
}
Poll::Ready(Ok(()))
}
fn partial_flush_buf(
&mut self,
poll_write: &mut dyn FnMut(&[u8]) -> Poll<io::Result<usize>>,
) -> Poll<io::Result<()>> {
let ret = if let Poll::Ready(res) = self.do_flush(poll_write) {
res
} else {
Ok(())
};
if self.written > 0 || self.buffered < self.buf.len() {
Poll::Ready(ret)
} else {
ret?;
Poll::Pending
}
}
pub fn flush_buf(
&mut self,
poll_write: &mut dyn FnMut(&[u8]) -> Poll<io::Result<usize>>,
) -> Poll<io::Result<()>> {
ready!(self.do_flush(poll_write))?;
debug_assert_eq!(self.buffered, self.written);
self.buffered = 0;
self.written = 0;
Poll::Ready(Ok(()))
}
pub fn poll_write(
&mut self,
buf: &[u8],
poll_write: &mut dyn FnMut(&[u8]) -> Poll<io::Result<usize>>,
) -> Poll<io::Result<usize>> {
if buf.len() >= self.buf.len() {
ready!(self.flush_buf(poll_write))?;
poll_write(buf)
} else if (self.buf.len() - self.buffered) >= buf.len() {
self.buf[self.buffered..].copy_from_slice(buf);
self.buffered += buf.len();
Poll::Ready(Ok(buf.len()))
} else {
ready!(self.partial_flush_buf(poll_write))?;
if self.written > 0 {
self.remove_written();
}
let len = buf.len().min(self.buf.len() - self.buffered);
self.buf[self.buffered..self.buffered + len].copy_from_slice(&buf[..len]);
self.buffered += len;
Poll::Ready(Ok(len))
}
}
pub fn poll_partial_flush_buf(
&mut self,
poll_write: &mut dyn FnMut(&[u8]) -> Poll<io::Result<usize>>,
) -> Poll<io::Result<Buffer<'_>>> {
ready!(self.partial_flush_buf(poll_write))?;
// when the flushed data is larger than or equal to half of yet-to-be-flushed data,
// the copyback could use version of memcpy that do copies from the head of the buffer.
// Anything smaller than that, an overlap would happen that forces use of memmove.
if self.written >= (self.buffered / 3)
|| self.written >= 512
|| self.buffered == self.buf.len()
{
self.remove_written();
}
Poll::Ready(Ok(Buffer {
write_buffer: WriteBuffer::new_initialized(&mut self.buf[self.buffered..]),
buffered: &mut self.buffered,
}))
}
}
pub struct Buffer<'a> {
buffered: &'a mut usize,
pub write_buffer: WriteBuffer<'a>,
}
impl Drop for Buffer<'_> {
fn drop(&mut self) {
*self.buffered += self.write_buffer.written_len();
}
}
macro_rules! impl_buf_writer {
($poll_close: tt) => {
use crate::generic::write::{AsyncBufWrite, BufWriter as GenericBufWriter, Buffer};
use pin_project_lite::pin_project;
use std::task::ready;
pin_project! {
#[derive(Debug)]
pub struct BufWriter<W> {
#[pin]
writer: W,
inner: GenericBufWriter,
}
}
impl<W> BufWriter<W> {
/// Creates a new `BufWriter` with a default buffer capacity. The default is currently 8 KB,
/// but may change in the future.
pub fn new(writer: W) -> Self {
Self {
writer,
inner: GenericBufWriter::new(),
}
}
/// Creates a new `BufWriter` with the specified buffer capacity.
pub fn with_capacity(cap: usize, writer: W) -> Self {
Self {
writer,
inner: GenericBufWriter::with_capacity(cap),
}
}
/// Gets a reference to the underlying writer.
pub fn get_ref(&self) -> &W {
&self.writer
}
/// Gets a mutable reference to the underlying writer.
///
/// It is inadvisable to directly write to the underlying writer.
pub fn get_mut(&mut self) -> &mut W {
&mut self.writer
}
/// Gets a pinned mutable reference to the underlying writer.
///
/// It is inadvisable to directly write to the underlying writer.
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut W> {
self.project().writer
}
/// Consumes this `BufWriter`, returning the underlying writer.
///
/// Note that any leftover data in the internal buffer is lost.
pub fn into_inner(self) -> W {
self.writer
}
}
fn get_poll_write<'a, 'b, W: AsyncWrite>(
mut writer: Pin<&'a mut W>,
cx: &'a mut Context<'b>,
) -> impl for<'buf> FnMut(&'buf [u8]) -> Poll<io::Result<usize>> + use<'a, 'b, W> {
move |buf| writer.as_mut().poll_write(cx, buf)
}
impl<W: AsyncWrite> BufWriter<W> {
fn flush_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = self.project();
this.inner.flush_buf(&mut get_poll_write(this.writer, cx))
}
}
impl<W: AsyncWrite> AsyncWrite for BufWriter<W> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let this = self.project();
this.inner
.poll_write(buf, &mut get_poll_write(this.writer, cx))
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
ready!(self.as_mut().flush_buf(cx))?;
self.project().writer.poll_flush(cx)
}
fn $poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
ready!(self.as_mut().flush_buf(cx))?;
self.project().writer.$poll_close(cx)
}
}
impl<W: AsyncWrite> AsyncBufWrite for BufWriter<W> {
fn poll_partial_flush_buf(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<io::Result<Buffer<'_>>> {
let this = self.project();
this.inner
.poll_partial_flush_buf(&mut get_poll_write(this.writer, cx))
}
}
};
}
pub(crate) use impl_buf_writer;
+244
View File
@@ -0,0 +1,244 @@
use crate::{
codecs::DecodeV2,
core::util::{PartialBuffer, WriteBuffer},
generic::write::AsyncBufWrite,
};
use std::{
io,
pin::Pin,
task::{ready, Context, Poll},
};
#[derive(Debug)]
enum State {
Decoding,
Finishing,
Done,
}
#[derive(Debug)]
pub struct Decoder {
state: State,
}
impl Default for Decoder {
fn default() -> Self {
Self {
state: State::Decoding,
}
}
}
impl Decoder {
fn do_poll_write(
&mut self,
cx: &mut Context<'_>,
input: &mut PartialBuffer<&[u8]>,
mut writer: Pin<&mut dyn AsyncBufWrite>,
decoder: &mut dyn DecodeV2,
) -> Poll<io::Result<()>> {
loop {
let mut output = ready!(writer.as_mut().poll_partial_flush_buf(cx))?;
let output = &mut output.write_buffer;
self.state = match self.state {
State::Decoding => {
if decoder.decode(input, output)? {
State::Finishing
} else {
State::Decoding
}
}
State::Finishing => {
if decoder.finish(output)? {
State::Done
} else {
State::Finishing
}
}
State::Done => {
return Poll::Ready(Err(io::Error::other("Write after end of stream")));
}
};
if let State::Done = self.state {
return Poll::Ready(Ok(()));
}
if input.unwritten().is_empty() {
return Poll::Ready(Ok(()));
}
}
}
pub fn poll_write(
&mut self,
cx: &mut Context<'_>,
buf: &[u8],
writer: Pin<&mut dyn AsyncBufWrite>,
decoder: &mut dyn DecodeV2,
) -> Poll<io::Result<usize>> {
if buf.is_empty() {
return Poll::Ready(Ok(0));
}
let mut input = PartialBuffer::new(buf);
match self.do_poll_write(cx, &mut input, writer, decoder)? {
Poll::Pending if input.written().is_empty() => Poll::Pending,
_ => Poll::Ready(Ok(input.written().len())),
}
}
pub fn do_poll_flush(
&mut self,
cx: &mut Context<'_>,
mut writer: Pin<&mut dyn AsyncBufWrite>,
decoder: &mut dyn DecodeV2,
) -> Poll<io::Result<()>> {
loop {
let mut output = ready!(writer.as_mut().poll_partial_flush_buf(cx))?;
let output = &mut output.write_buffer;
let (state, done) = match self.state {
State::Decoding => {
let done = decoder.flush(output)?;
(State::Decoding, done)
}
State::Finishing => {
let before = output.written_len();
if decoder.finish(output)? {
(State::Done, false)
} else if output.written_len() == before && !output.has_no_spare_space() {
return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into()));
} else {
(State::Finishing, false)
}
}
State::Done => (State::Done, true),
};
self.state = state;
if done {
break Poll::Ready(Ok(()));
}
}
}
pub fn do_close(&mut self) {
if let State::Decoding = self.state {
self.state = State::Finishing;
}
}
pub fn is_done(&self) -> bool {
matches!(self.state, State::Done)
}
}
macro_rules! impl_decoder {
($poll_close: tt) => {
use crate::{
codecs::DecodeV2, core::util::PartialBuffer, generic::write::Decoder as GenericDecoder,
};
use pin_project_lite::pin_project;
use std::task::ready;
pin_project! {
#[derive(Debug)]
pub struct Decoder<W, D> {
#[pin]
writer: BufWriter<W>,
decoder: D,
inner: GenericDecoder,
}
}
impl<W: AsyncWrite, D: DecodeV2> Decoder<W, D> {
pub fn new(writer: W, decoder: D) -> Self {
Self {
writer: BufWriter::new(writer),
decoder,
inner: Default::default(),
}
}
}
impl<W, D> Decoder<W, D> {
pub fn get_ref(&self) -> &W {
self.writer.get_ref()
}
pub fn get_mut(&mut self) -> &mut W {
self.writer.get_mut()
}
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut W> {
self.project().writer.get_pin_mut()
}
pub fn into_inner(self) -> W {
self.writer.into_inner()
}
}
impl<W: AsyncWrite, D: DecodeV2> Decoder<W, D> {
fn do_poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let mut this = self.project();
this.inner.do_poll_flush(cx, this.writer, this.decoder)
}
}
impl<W: AsyncWrite, D: DecodeV2> AsyncWrite for Decoder<W, D> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let mut this = self.project();
this.inner.poll_write(cx, buf, this.writer, this.decoder)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
ready!(self.as_mut().do_poll_flush(cx))?;
self.project().writer.poll_flush(cx)
}
fn $poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.as_mut().project().inner.do_close();
ready!(self.as_mut().do_poll_flush(cx))?;
let this = self.project();
if this.inner.is_done() {
this.writer.$poll_close(cx)
} else {
Poll::Ready(Err(io::Error::other(
"Attempt to close before finishing input",
)))
}
}
}
impl<W: AsyncBufRead, D> AsyncBufRead for Decoder<W, D> {
fn poll_fill_buf(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<io::Result<&[u8]>> {
self.get_pin_mut().poll_fill_buf(cx)
}
fn consume(self: Pin<&mut Self>, amt: usize) {
self.get_pin_mut().consume(amt)
}
}
};
}
pub(crate) use impl_decoder;
+230
View File
@@ -0,0 +1,230 @@
use crate::{
codecs::EncodeV2,
core::util::{PartialBuffer, WriteBuffer},
generic::write::AsyncBufWrite,
};
use std::{
io,
pin::Pin,
task::{ready, Context, Poll},
};
#[derive(Debug)]
enum State {
Encoding,
Finishing,
Done,
}
#[derive(Debug)]
pub struct Encoder {
state: State,
}
impl Default for Encoder {
fn default() -> Self {
Self {
state: State::Encoding,
}
}
}
impl Encoder {
fn do_poll_write(
&mut self,
cx: &mut Context<'_>,
input: &mut PartialBuffer<&[u8]>,
mut writer: Pin<&mut dyn AsyncBufWrite>,
encoder: &mut dyn EncodeV2,
) -> Poll<io::Result<()>> {
loop {
let mut output = ready!(writer.as_mut().poll_partial_flush_buf(cx))?;
let output = &mut output.write_buffer;
self.state = match self.state {
State::Encoding => {
encoder.encode(input, output)?;
State::Encoding
}
State::Finishing | State::Done => {
break Poll::Ready(Err(io::Error::other("Write after close")));
}
};
if input.unwritten().is_empty() {
break Poll::Ready(Ok(()));
}
}
}
pub fn poll_write(
&mut self,
cx: &mut Context<'_>,
buf: &[u8],
writer: Pin<&mut dyn AsyncBufWrite>,
encoder: &mut dyn EncodeV2,
) -> Poll<io::Result<usize>> {
if buf.is_empty() {
return Poll::Ready(Ok(0));
}
let mut input = PartialBuffer::new(buf);
match self.do_poll_write(cx, &mut input, writer, encoder)? {
Poll::Pending if input.written().is_empty() => Poll::Pending,
_ => Poll::Ready(Ok(input.written().len())),
}
}
pub fn do_poll_flush(
&mut self,
cx: &mut Context<'_>,
mut writer: Pin<&mut dyn AsyncBufWrite>,
encoder: &mut dyn EncodeV2,
) -> Poll<io::Result<()>> {
loop {
let mut output = ready!(writer.as_mut().poll_partial_flush_buf(cx))?;
let output = &mut output.write_buffer;
let done = match self.state {
State::Encoding => encoder.flush(output)?,
State::Finishing | State::Done => {
break Poll::Ready(Err(io::Error::other("Flush after close")));
}
};
if done {
break Poll::Ready(Ok(()));
}
}
}
pub fn do_poll_close(
&mut self,
cx: &mut Context<'_>,
mut writer: Pin<&mut dyn AsyncBufWrite>,
encoder: &mut dyn EncodeV2,
) -> Poll<io::Result<()>> {
loop {
let mut output = ready!(writer.as_mut().poll_partial_flush_buf(cx))?;
let output = &mut output.write_buffer;
self.state = match self.state {
State::Encoding | State::Finishing => {
if encoder.finish(output)? {
State::Done
} else {
State::Finishing
}
}
State::Done => State::Done,
};
if let State::Done = self.state {
break Poll::Ready(Ok(()));
}
}
}
}
macro_rules! impl_encoder {
($poll_close: tt) => {
use crate::{codecs::EncodeV2, generic::write::Encoder as GenericEncoder};
use pin_project_lite::pin_project;
use std::task::ready;
pin_project! {
#[derive(Debug)]
pub struct Encoder<W, E> {
#[pin]
writer: BufWriter<W>,
encoder: E,
inner: GenericEncoder,
}
}
impl<W, E> Encoder<W, E> {
pub fn get_ref(&self) -> &W {
self.writer.get_ref()
}
pub fn get_mut(&mut self) -> &mut W {
self.writer.get_mut()
}
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut W> {
self.project().writer.get_pin_mut()
}
pub(crate) fn get_encoder_ref(&self) -> &E {
&self.encoder
}
pub fn into_inner(self) -> W {
self.writer.into_inner()
}
pub fn new(writer: W, encoder: E) -> Self {
Self {
writer: BufWriter::new(writer),
encoder,
inner: Default::default(),
}
}
pub fn with_capacity(writer: W, encoder: E, cap: usize) -> Self {
Self {
writer: BufWriter::with_capacity(cap, writer),
encoder,
inner: Default::default(),
}
}
}
impl<W: AsyncWrite, E: EncodeV2> AsyncWrite for Encoder<W, E> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let this = self.project();
this.inner.poll_write(cx, buf, this.writer, this.encoder)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let mut this = self.project();
ready!(this
.inner
.do_poll_flush(cx, this.writer.as_mut(), this.encoder))?;
this.writer.poll_flush(cx)
}
fn $poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let mut this = self.project();
ready!(this
.inner
.do_poll_close(cx, this.writer.as_mut(), this.encoder))?;
this.writer.$poll_close(cx)
}
}
impl<W: AsyncBufRead, E> AsyncBufRead for Encoder<W, E> {
fn poll_fill_buf(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<io::Result<&[u8]>> {
self.get_pin_mut().poll_fill_buf(cx)
}
fn consume(self: Pin<&mut Self>, amt: usize) {
self.get_pin_mut().consume(amt)
}
}
};
}
pub(crate) use impl_encoder;
+9
View File
@@ -0,0 +1,9 @@
mod buf_write;
mod buf_writer;
mod decoder;
mod encoder;
pub(crate) use buf_write::*;
pub(crate) use buf_writer::*;
pub(crate) use decoder::*;
pub(crate) use encoder::*;
+172
View File
@@ -0,0 +1,172 @@
//! 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
#![allow(unexpected_cfgs)]
#![cfg_attr(
feature = "futures-io",
doc = "[`futures-io`](futures_io) | [`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`] | [`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 = "lz4",
doc = "`lz4` | [`Lz4Encoder`](?search=Lz4Encoder), [`Lz4Decoder`](?search=Lz4Decoder)"
)]
#![cfg_attr(
not(feature = "lz4"),
doc = "`lz4` (*inactive*) | `Lz4Encoder`, `Lz4Decoder`"
)]
#![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(
feature = "deflate64",
doc = "`deflate64` | (encoder not implemented), [`Deflate64Decoder`](?search=Deflate64Decoder)"
)]
#![cfg_attr(
not(feature = "deflate64"),
doc = "`deflate64` (*inactive*) | (encoder not implemented), `Deflate64Decoder`"
)]
//!
//! ## Multi-thread support
//! The `xz` compression algorithm supports multi-threaded compression and decompression.
//! Enable the `xz-parallel` feature to enable multi-threading support.
//!
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(not(all), allow(unused))]
#[macro_use]
mod macros;
/// Generic, async runtime agonistc implementation of en/decoders
mod generic;
#[cfg(feature = "futures-io")]
pub mod futures;
#[cfg(feature = "tokio")]
pub mod tokio;
pub use compression_codecs as codecs;
pub use compression_core as core;
pub use core::Level;
#[cfg(feature = "zstd")]
pub use codecs::zstd::params as zstd;
#[cfg(feature = "lz4")]
pub use codecs::lz4::params as lz4;
#[cfg(feature = "brotli")]
pub use codecs::brotli::params as brotli;
+379
View File
@@ -0,0 +1,379 @@
macro_rules! algos {
(@algo $algo:ident [$algo_s:expr] $decoder:ident $encoder:ident <$inner:ident>
{ @enc $($encoder_methods:tt)* }
{ @dec $($decoder_methods:tt)* }
) => {
#[cfg(feature = $algo_s)]
decoder! {
#[doc = concat!("A ", $algo_s, " decoder, or decompressor")]
#[cfg(feature = $algo_s)]
$decoder<$inner>
{ $($decoder_methods)* }
}
#[cfg(feature = $algo_s)]
encoder! {
#[doc = concat!("A ", $algo_s, " encoder, or compressor.")]
#[cfg(feature = $algo_s)]
$encoder<$inner> {
pub fn new(inner: $inner) -> Self {
Self::with_quality(inner, crate::core::Level::Default)
}
}
{ $($encoder_methods)* }
}
};
(@algo $algo:ident [$algo_s:expr] $decoder:ident $encoder:ident <$inner:ident>
{ @dec $($decoder_methods:tt)* }
) => {
#[cfg(feature = $algo_s)]
decoder! {
#[doc = concat!("A ", $algo_s, " decoder, or decompressor")]
#[cfg(feature = $algo_s)]
$decoder<$inner>
{ $($decoder_methods)* }
}
};
($($mod:ident)::+ <$inner:ident>) => {
algos!(@algo brotli ["brotli"] BrotliDecoder BrotliEncoder <$inner>
{ @enc
pub fn with_quality(inner: $inner, level: crate::core::Level) -> Self {
// let params = brotli::enc::backward_references::BrotliEncoderParams::default();
let params = crate::codecs::brotli::params::EncoderParams::default();
let params = params.quality(level);
Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::BrotliEncoder::new(params),
),
}
}
/// Creates a new encoder, using the specified compression level and parameters, which
/// will read uncompressed data from the given stream and emit a compressed stream.
pub fn with_params(
inner: $inner,
params: crate::codecs::brotli::params::EncoderParams,
) -> Self {
Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::BrotliEncoder::new(params),
),
}
}
}
{ @dec }
);
algos!(@algo bzip2 ["bzip2"] BzDecoder BzEncoder <$inner>
{ @enc
pub fn with_quality(inner: $inner, level: crate::core::Level) -> Self {
let params = crate::codecs::bzip2::params::Bzip2EncoderParams::from(level);
Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::BzEncoder::new(params, 0),
),
}
}
}
{ @dec }
);
algos!(@algo deflate ["deflate"] DeflateDecoder DeflateEncoder <$inner>
{ @enc
pub fn with_quality(inner: $inner, level: crate::core::Level) -> Self {
let mut params = crate::codecs::flate::params::FlateEncoderParams::from(level);
Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::DeflateEncoder::new(params),
),
}
}
/// Returns the total number of input bytes which have been processed by this compression object.
pub fn total_in(&self) -> u64 {
self.inner.get_encoder_ref().get_ref().get_ref().total_in()
}
/// Returns the total number of output bytes which have been produced by this compression object.
pub fn total_out(&self) -> u64 {
self.inner.get_encoder_ref().get_ref().get_ref().total_out()
}
}
{ @dec }
);
algos!(@algo deflate ["deflate64"] Deflate64Decoder Deflate64Encoder <$inner>
{ @dec }
);
algos!(@algo gzip ["gzip"] GzipDecoder GzipEncoder <$inner>
{ @enc
pub fn with_quality(inner: $inner, level: crate::core::Level) -> Self {
let params = crate::codecs::flate::params::FlateEncoderParams::from(level);
Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::GzipEncoder::new(params),
),
}
}
}
{ @dec }
);
algos!(@algo zlib ["zlib"] ZlibDecoder ZlibEncoder <$inner>
{ @enc
pub fn with_quality(inner: $inner, level: crate::core::Level) -> Self {
let params = crate::codecs::flate::params::FlateEncoderParams::from(level);
Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::ZlibEncoder::new(params),
),
}
}
/// Returns the total number of input bytes which have been processed by this compression object.
pub fn total_in(&self) -> u64 {
self.inner.get_encoder_ref().get_ref().get_ref().total_in()
}
/// Returns the total number of output bytes which have been produced by this compression object.
pub fn total_out(&self) -> u64 {
self.inner.get_encoder_ref().get_ref().get_ref().total_out()
}
}
{ @dec }
);
algos!(@algo zstd ["zstd"] ZstdDecoder ZstdEncoder <$inner>
{ @enc
pub fn with_quality(inner: $inner, level: crate::core::Level) -> Self {
let params = crate::codecs::zstd::params::CParameter::quality(level);
Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::ZstdEncoder::new(params),
),
}
}
/// Creates a new encoder, using the specified compression level and parameters, which
/// will read uncompressed data from the given stream and emit a compressed stream.
///
/// # Panics
///
/// Panics if this function is called with a [`CParameter::nb_workers()`] parameter and
/// the `zstdmt` crate feature is _not_ enabled.
///
/// [`CParameter::nb_workers()`]: crate::codecs::zstd::params::CParameter
//
// TODO: remove panic note on next breaking release, along with `CParameter::nb_workers`
// change
pub fn with_quality_and_params(inner: $inner, level: crate::core::Level, params: &[crate::codecs::zstd::params::CParameter]) -> Self {
let level = crate::codecs::zstd::params::CParameter::quality(level);
Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::ZstdEncoder::new_with_params(level, params),
),
}
}
/// Creates a new encoder, using the specified compression level and pre-trained
/// dictionary, which will read uncompressed data from the given stream and emit a
/// compressed stream.
///
/// Dictionaries provide better compression ratios for small files, but are required to
/// be present during decompression.
///
/// # Errors
///
/// Returns error when `dictionary` is not valid.
pub fn with_dict(inner: $inner, level: crate::core::Level, dictionary: &[u8]) -> ::std::io::Result<Self> {
let level = crate::codecs::zstd::params::CParameter::quality(level);
Ok(Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::ZstdEncoder::new_with_dict(level, dictionary)?,
),
})
}
}
{ @dec
/// Creates a new decoder, using the specified parameters, which will read compressed
/// data from the given stream and emit a decompressed stream.
pub fn with_params(inner: $inner, params: &[crate::codecs::zstd::params::DParameter]) -> Self {
Self {
inner: crate::$($mod::)+generic::Decoder::new(
inner,
crate::codecs::ZstdDecoder::new_with_params(params),
),
}
}
/// Creates a new decoder, using the specified compression level and pre-trained
/// dictionary, which will read compressed data from the given stream and emit an
/// uncompressed stream.
///
/// Dictionaries provide better compression ratios for small files, but are required to
/// be present during decompression. The dictionary used must be the same as the one
/// used for compression.
///
/// # Errors
///
/// Returns error when `dictionary` is not valid.
pub fn with_dict(inner: $inner, dictionary: &[u8]) -> ::std::io::Result<Self> {
Ok(Self {
inner: crate::$($mod::)+generic::Decoder::new(
inner,
crate::codecs::ZstdDecoder::new_with_dict(dictionary)?,
),
})
}
}
);
algos!(@algo xz ["xz"] XzDecoder XzEncoder <$inner>
{ @enc
pub fn with_quality(inner: $inner, level: crate::core::Level) -> Self {
Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::XzEncoder::new(level),
),
}
}
/// Creates a new multi-threaded encoder.
///
/// Note that flushing will severely impact multi-threaded performance.
#[cfg(feature = "xz-parallel")]
pub fn parallel(inner: $inner, level: crate::core::Level, threads: std::num::NonZeroU32) -> Self {
Self {
inner: crate::$($mod::)+generic::Encoder::new(
inner,
crate::codecs::XzEncoder::parallel(threads, level),
),
}
}
}
{ @dec
/// Creates a new decoder with the specified limit of memory.
///
/// # Errors
///
/// An IO error may be returned during decoding if the specified limit is too small.
pub fn with_mem_limit(read: $inner, memlimit: u64) -> Self {
Self {
inner: crate::$($mod::)+generic::Decoder::new(
read,
crate::codecs::XzDecoder::with_memlimit(memlimit),
),
}
}
/// Creates a new multi-threaded decoder.
#[cfg(feature = "xz-parallel")]
pub fn parallel(read: $inner, threads: std::num::NonZeroU32) -> Self {
use std::convert::TryInto;
Self {
inner: crate::$($mod::)+generic::Decoder::new(
read,
crate::codecs::XzDecoder::parallel(threads, usize::MAX.try_into().unwrap()),
),
}
}
/// Creates a new multi-threaded decoder with the specified limit of memory.
///
/// # Errors
///
/// An IO error may be returned during decoding if the specified limit is too small.
#[cfg(feature = "xz-parallel")]
pub fn parallel_with_mem_limit(read: $inner, threads: std::num::NonZeroU32, memlimit: u64) -> Self {
Self {
inner: crate::$($mod::)+generic::Decoder::new(
read,
crate::codecs::XzDecoder::parallel(threads, memlimit),
),
}
}
}
);
algos!(@algo lzma ["lzma"] LzmaDecoder LzmaEncoder <$inner>
{ @enc
pub fn with_quality(inner: $inner, level: crate::core::Level) -> Self {
let encoder = crate::codecs::LzmaEncoder::new(level);
let inner = crate::$($mod::)+generic::Encoder::new(inner, encoder);
Self {
inner
}
}
}
{ @dec
/// Creates a new decoder with the specified limit of memory.
///
/// # Errors
///
/// An IO error may be returned during decoding if the specified limit is too small.
pub fn with_mem_limit(read: $inner, memlimit: u64) -> Self {
Self {
inner: crate::$($mod::)+generic::Decoder::new(
read,
crate::codecs::LzmaDecoder::with_memlimit(memlimit),
),
}
}
}
);
algos!(@algo lz4 ["lz4"] Lz4Decoder Lz4Encoder <$inner>
{ @enc
pub fn with_quality(inner: $inner, level: crate::core::Level) -> Self {
Self::with_quality_and_params(inner, level, crate::codecs::lz4::params::EncoderParams::default())
}
/// Creates a new encoder, using the specified compression level and parameters, which
/// will read uncompressed data from the given stream and emit a compressed stream.
pub fn with_quality_and_params(
inner: $inner,
level: crate::core::Level,
mut params: crate::codecs::lz4::params::EncoderParams,
) -> Self {
let params = params.level(level);
let encoder = crate::codecs::Lz4Encoder::new(params);
let cap = encoder.buffer_size();
Self {
inner: crate::$($mod::)+generic::Encoder::with_capacity(
inner,
encoder,
cap,
),
}
}
}
{ @dec }
);
}
}
@@ -0,0 +1,54 @@
use crate::{
codecs::DecodeV2,
core::util::{PartialBuffer, WriteBuffer},
generic::bufread::impl_decoder,
};
use std::{
io::{IoSlice, Result},
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncBufRead, AsyncRead, AsyncWrite, ReadBuf};
impl_decoder!();
impl<R: AsyncBufRead, D: DecodeV2> AsyncRead for Decoder<R, D> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<Result<()>> {
super::poll_read(buf, |output| self.do_poll_read(cx, output))
}
}
impl<R: AsyncWrite, D> AsyncWrite for Decoder<R, D> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
self.get_pin_mut().poll_write(cx, buf)
}
fn poll_write_vectored(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
mut bufs: &[IoSlice<'_>],
) -> Poll<Result<usize>> {
self.get_pin_mut().poll_write_vectored(cx, bufs)
}
fn is_write_vectored(&self) -> bool {
self.get_ref().is_write_vectored()
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.get_pin_mut().poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.get_pin_mut().poll_shutdown(cx)
}
}
@@ -0,0 +1,53 @@
use crate::{
codecs::EncodeV2,
core::util::{PartialBuffer, WriteBuffer},
generic::bufread::impl_encoder,
};
use std::{
io::{IoSlice, Result},
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncBufRead, AsyncRead, AsyncWrite, ReadBuf};
impl_encoder!();
impl<R: AsyncBufRead, E: EncodeV2> AsyncRead for Encoder<R, E> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<Result<()>> {
super::poll_read(buf, |output| self.do_poll_read(cx, output))
}
}
impl<R: AsyncWrite, E> AsyncWrite for Encoder<R, E> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
self.get_pin_mut().poll_write(cx, buf)
}
fn poll_write_vectored(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
mut bufs: &[IoSlice<'_>],
) -> Poll<Result<usize>> {
self.get_pin_mut().poll_write_vectored(cx, bufs)
}
fn is_write_vectored(&self) -> bool {
self.get_ref().is_write_vectored()
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.get_pin_mut().poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
self.get_pin_mut().poll_shutdown(cx)
}
}
@@ -0,0 +1,34 @@
mod decoder;
mod encoder;
pub use self::{decoder::Decoder, encoder::Encoder};
use crate::core::util::WriteBuffer;
use std::{io::Result, task::Poll};
use tokio::io::ReadBuf;
fn poll_read(
buf: &mut ReadBuf<'_>,
do_poll_read: impl FnOnce(&mut WriteBuffer<'_>) -> Poll<Result<()>>,
) -> Poll<Result<()>> {
if buf.remaining() == 0 {
return Poll::Ready(Ok(()));
}
let initialized = buf.initialized().len() - buf.filled().len();
// Safety: `WriteBuffer` has the same safety invariant as `ReadBuf`
let mut output = WriteBuffer::new_uninitialized(unsafe { buf.unfilled_mut() });
// Safety: `ReadBuf` ensures that it is initialized
unsafe { output.assume_init(initialized) };
let res = do_poll_read(&mut output);
let initialized = output.initialized_len();
let written = output.written_len();
// Safety: We trust our implementation to have properly initialized it
unsafe { buf.assume_init(initialized) };
buf.advance(written);
res
}
@@ -0,0 +1,130 @@
macro_rules! decoder {
($(#[$attr:meta])* $name:ident<$inner:ident> $({ $($inherent_methods:tt)* })*) => {
pin_project_lite::pin_project! {
$(#[$attr])*
///
/// This structure implements an [`AsyncRead`](tokio::io::AsyncRead) interface and will
/// read compressed data from an underlying stream and emit a stream of uncompressed data.
#[derive(Debug)]
pub struct $name<$inner> {
#[pin]
inner: crate::tokio::bufread::Decoder<$inner, crate::codecs::$name>,
}
}
impl<$inner: tokio::io::AsyncBufRead> $name<$inner> {
/// Creates a new decoder which will read compressed data from the given stream and
/// emit an uncompressed stream.
pub fn new(read: $inner) -> $name<$inner> {
$name {
inner: crate::tokio::bufread::Decoder::new(read, crate::codecs::$name::new()),
}
}
/// Creates a new decoder with the given codec, which will read compressed data from the given stream and
/// emit an uncompressed stream.
pub fn with_codec(read: $inner, codec: crate::codecs::$name) -> $name<$inner> {
$name {
inner: crate::tokio::bufread::Decoder::new(read, codec)
}
}
$($($inherent_methods)*)*
}
impl<$inner> $name<$inner> {
/// Configure multi-member/frame decoding, if enabled this will reset the decoder state
/// when reaching the end of a compressed member/frame and expect either EOF or another
/// compressed member/frame to follow it in the stream.
pub fn multiple_members(&mut self, enabled: bool) {
self.inner.multiple_members(enabled);
}
/// Acquires a reference to the underlying reader that this decoder is wrapping.
pub fn get_ref(&self) -> &$inner {
self.inner.get_ref()
}
/// Acquires a mutable reference to the underlying reader that this decoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this decoder.
pub fn get_mut(&mut self) -> &mut $inner {
self.inner.get_mut()
}
/// Acquires a pinned mutable reference to the underlying reader that this decoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this decoder.
pub fn get_pin_mut(self: std::pin::Pin<&mut Self>) -> std::pin::Pin<&mut $inner> {
self.project().inner.get_pin_mut()
}
/// Consumes this decoder returning the underlying reader.
///
/// Note that this may discard internal state of this decoder, so care should be taken
/// to avoid losing resources when this is called.
pub fn into_inner(self) -> $inner {
self.inner.into_inner()
}
}
impl<$inner: tokio::io::AsyncBufRead> tokio::io::AsyncRead for $name<$inner> {
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_read(cx, buf)
}
}
impl<$inner: tokio::io::AsyncWrite> tokio::io::AsyncWrite for $name<$inner> {
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.get_pin_mut().poll_write(cx, buf)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.get_pin_mut().poll_flush(cx)
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.get_pin_mut().poll_shutdown(cx)
}
fn poll_write_vectored(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
bufs: &[std::io::IoSlice<'_>],
) -> std::task::Poll<std::io::Result<usize>> {
self.get_pin_mut().poll_write_vectored(cx, bufs)
}
fn is_write_vectored(&self) -> bool {
self.get_ref().is_write_vectored()
}
}
const _: () = {
use crate::core::util::{_assert_send, _assert_sync};
use core::pin::Pin;
use tokio::io::AsyncBufRead;
_assert_send::<$name<Pin<Box<dyn AsyncBufRead + Send>>>>();
_assert_sync::<$name<Pin<Box<dyn AsyncBufRead + Sync>>>>();
};
}
}
@@ -0,0 +1,120 @@
macro_rules! encoder {
($(#[$attr:meta])* $name:ident<$inner:ident> $({ $($inherent_methods:tt)* })*) => {
pin_project_lite::pin_project! {
$(#[$attr])*
///
/// This structure implements an [`AsyncRead`](tokio::io::AsyncRead) interface and will
/// read uncompressed data from an underlying stream and emit a stream of compressed data.
#[derive(Debug)]
pub struct $name<$inner> {
#[pin]
inner: crate::tokio::bufread::Encoder<$inner, crate::codecs::$name>,
}
}
impl<$inner: tokio::io::AsyncBufRead> $name<$inner> {
$(
/// Creates a new encoder which will read uncompressed data from the given stream
/// and emit an compressed stream.
///
$($inherent_methods)*
)*
/// Creates a new encoder with the given codec, which will read uncompressed data from the given stream
/// and emit an compressed stream.
pub fn with_codec(read: $inner, codec: crate::codecs::$name) -> $name<$inner> {
$name {
inner: crate::tokio::bufread::Encoder::new(read, codec)
}
}
}
impl<$inner> $name<$inner> {
/// Acquires a reference to the underlying reader that this encoder is wrapping.
pub fn get_ref(&self) -> &$inner {
self.inner.get_ref()
}
/// Acquires a mutable reference to the underlying reader that this encoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this encoder.
pub fn get_mut(&mut self) -> &mut $inner {
self.inner.get_mut()
}
/// Acquires a pinned mutable reference to the underlying reader that this encoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this encoder.
pub fn get_pin_mut(self: std::pin::Pin<&mut Self>) -> std::pin::Pin<&mut $inner> {
self.project().inner.get_pin_mut()
}
/// Consumes this encoder returning the underlying reader.
///
/// Note that this may discard internal state of this encoder, so care should be taken
/// to avoid losing resources when this is called.
pub fn into_inner(self) -> $inner {
self.inner.into_inner()
}
}
impl<$inner: tokio::io::AsyncBufRead> tokio::io::AsyncRead for $name<$inner> {
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_read(cx, buf)
}
}
impl<$inner: tokio::io::AsyncWrite> tokio::io::AsyncWrite for $name<$inner> {
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.get_pin_mut().poll_write(cx, buf)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.get_pin_mut().poll_flush(cx)
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.get_pin_mut().poll_shutdown(cx)
}
fn poll_write_vectored(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
bufs: &[std::io::IoSlice<'_>],
) -> std::task::Poll<std::io::Result<usize>> {
self.get_pin_mut().poll_write_vectored(cx, bufs)
}
fn is_write_vectored(&self) -> bool {
self.get_ref().is_write_vectored()
}
}
const _: () = {
use crate::core::util::{_assert_send, _assert_sync};
use core::pin::Pin;
use tokio::io::AsyncBufRead;
_assert_send::<$name<Pin<Box<dyn AsyncBufRead + Send>>>>();
_assert_sync::<$name<Pin<Box<dyn AsyncBufRead + Sync>>>>();
};
}
}
@@ -0,0 +1,4 @@
#[macro_use]
mod decoder;
#[macro_use]
mod encoder;
+10
View File
@@ -0,0 +1,10 @@
//! Types which operate over [`AsyncBufRead`](::tokio::io::AsyncBufRead) streams, both encoders and
//! decoders for various formats.
#[macro_use]
mod macros;
mod generic;
pub(crate) use generic::{Decoder, Encoder};
algos!(tokio::bufread<R>);
+4
View File
@@ -0,0 +1,4 @@
//! Implementations for IO traits exported by [`tokio` v1.x](::tokio).
pub mod bufread;
pub mod write;
+13
View File
@@ -0,0 +1,13 @@
// Originally sourced from `futures_util::io::buf_writer`, needs to be redefined locally so that
// the `AsyncBufWrite` impl can access its internals, and changed a bit to make it more efficient
// with those methods.
use crate::generic::write::impl_buf_writer;
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
use tokio::io::AsyncWrite;
impl_buf_writer!(poll_shutdown);
@@ -0,0 +1,19 @@
use crate::{generic::write::impl_decoder, tokio::write::BufWriter};
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncBufRead, AsyncRead, AsyncWrite, ReadBuf};
impl_decoder!(poll_shutdown);
impl<W: AsyncRead, D> AsyncRead for Decoder<W, D> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
self.get_pin_mut().poll_read(cx, buf)
}
}
@@ -0,0 +1,19 @@
use crate::{generic::write::impl_encoder, tokio::write::BufWriter};
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncBufRead, AsyncRead, AsyncWrite, ReadBuf};
impl_encoder!(poll_shutdown);
impl<W: AsyncRead, E> AsyncRead for Encoder<W, E> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
self.get_pin_mut().poll_read(cx, buf)
}
}
@@ -0,0 +1,4 @@
mod decoder;
mod encoder;
pub use self::{decoder::Decoder, encoder::Encoder};
@@ -0,0 +1,124 @@
macro_rules! decoder {
($(#[$attr:meta])* $name:ident<$inner:ident> $({ $($inherent_methods:tt)* })*) => {
pin_project_lite::pin_project! {
$(#[$attr])*
///
/// This structure implements an [`AsyncWrite`](tokio::io::AsyncWrite) interface and will
/// take in compressed data and write it uncompressed to an underlying stream.
#[derive(Debug)]
pub struct $name<$inner> {
#[pin]
inner: crate::tokio::write::Decoder<$inner, crate::codecs::$name>,
}
}
impl<$inner: tokio::io::AsyncWrite> $name<$inner> {
/// Creates a new decoder which will take in compressed data and write it, uncompressed,
/// to the given stream.
pub fn new(read: $inner) -> $name<$inner> {
$name {
inner: crate::tokio::write::Decoder::new(read, crate::codecs::$name::new()),
}
}
/// Creates a new decoder which will take in compressed data and write it, uncompressed,
/// to the given stream.
pub fn with_codec(read: $inner, codec: crate::codecs::$name) -> $name<$inner> {
$name {
inner: crate::tokio::write::Decoder::new(read, codec)
}
}
$($($inherent_methods)*)*
}
impl<$inner> $name<$inner> {
/// Acquires a reference to the underlying reader that this decoder is wrapping.
pub fn get_ref(&self) -> &$inner {
self.inner.get_ref()
}
/// Acquires a mutable reference to the underlying reader that this decoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this decoder.
pub fn get_mut(&mut self) -> &mut $inner {
self.inner.get_mut()
}
/// Acquires a pinned mutable reference to the underlying reader that this decoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the reader which
/// may otherwise confuse this decoder.
pub fn get_pin_mut(self: std::pin::Pin<&mut Self>) -> std::pin::Pin<&mut $inner> {
self.project().inner.get_pin_mut()
}
/// Consumes this decoder returning the underlying reader.
///
/// Note that this may discard internal state of this decoder, so care should be taken
/// to avoid losing resources when this is called.
pub fn into_inner(self) -> $inner {
self.inner.into_inner()
}
}
impl<$inner: tokio::io::AsyncWrite> tokio::io::AsyncWrite for $name<$inner> {
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.project().inner.poll_write(cx, buf)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_flush(cx)
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_shutdown(cx)
}
}
impl<$inner: tokio::io::AsyncRead> tokio::io::AsyncRead for $name<$inner> {
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.get_pin_mut().poll_read(cx, buf)
}
}
impl<$inner: tokio::io::AsyncBufRead> tokio::io::AsyncBufRead for $name<$inner> {
fn poll_fill_buf(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>
) -> std::task::Poll<std::io::Result<&[u8]>> {
self.get_pin_mut().poll_fill_buf(cx)
}
fn consume(self: std::pin::Pin<&mut Self>, amt: usize) {
self.get_pin_mut().consume(amt)
}
}
const _: () = {
use crate::core::util::{_assert_send, _assert_sync};
use core::pin::Pin;
use tokio::io::AsyncWrite;
_assert_send::<$name<Pin<Box<dyn AsyncWrite + Send>>>>();
_assert_sync::<$name<Pin<Box<dyn AsyncWrite + Sync>>>>();
};
}
}
@@ -0,0 +1,121 @@
macro_rules! encoder {
($(#[$attr:meta])* $name:ident<$inner:ident> $({ $($inherent_methods:tt)* })*) => {
pin_project_lite::pin_project! {
$(#[$attr])*
///
/// This structure implements an [`AsyncWrite`](tokio::io::AsyncWrite) interface and will
/// take in uncompressed data and write it compressed to an underlying stream.
#[derive(Debug)]
pub struct $name<$inner> {
#[pin]
inner: crate::tokio::write::Encoder<$inner, crate::codecs::$name>,
}
}
impl<$inner: tokio::io::AsyncWrite> $name<$inner> {
$(
/// Creates a new encoder which will take in uncompressed data and write it
/// compressed to the given stream.
///
$($inherent_methods)*
)*
/// Creates a new encoder with the given codec, which will take in uncompressed data and write it,
/// compressed, to the given stream.
pub fn with_codec(read: $inner, codec: crate::codecs::$name) -> $name<$inner> {
$name {
inner: crate::tokio::write::Encoder::new(read, codec)
}
}
}
impl<$inner> $name<$inner> {
/// Acquires a reference to the underlying writer that this encoder is wrapping.
pub fn get_ref(&self) -> &$inner {
self.inner.get_ref()
}
/// Acquires a mutable reference to the underlying writer that this encoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the writer which
/// may otherwise confuse this encoder.
pub fn get_mut(&mut self) -> &mut $inner {
self.inner.get_mut()
}
/// Acquires a pinned mutable reference to the underlying writer that this encoder is
/// wrapping.
///
/// Note that care must be taken to avoid tampering with the state of the writer which
/// may otherwise confuse this encoder.
pub fn get_pin_mut(self: std::pin::Pin<&mut Self>) -> std::pin::Pin<&mut $inner> {
self.project().inner.get_pin_mut()
}
/// Consumes this encoder returning the underlying writer.
///
/// Note that this may discard internal state of this encoder, so care should be taken
/// to avoid losing resources when this is called.
pub fn into_inner(self) -> $inner {
self.inner.into_inner()
}
}
impl<$inner: tokio::io::AsyncWrite> tokio::io::AsyncWrite for $name<$inner> {
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.project().inner.poll_write(cx, buf)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_flush(cx)
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.project().inner.poll_shutdown(cx)
}
}
impl<$inner: tokio::io::AsyncRead> tokio::io::AsyncRead for $name<$inner> {
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
self.get_pin_mut().poll_read(cx, buf)
}
}
impl<$inner: tokio::io::AsyncBufRead> tokio::io::AsyncBufRead for $name<$inner> {
fn poll_fill_buf(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>
) -> std::task::Poll<std::io::Result<&[u8]>> {
self.get_pin_mut().poll_fill_buf(cx)
}
fn consume(self: std::pin::Pin<&mut Self>, amt: usize) {
self.get_pin_mut().consume(amt)
}
}
const _: () = {
use crate::core::util::{_assert_send, _assert_sync};
use core::pin::Pin;
use tokio::io::AsyncWrite;
_assert_send::<$name<Pin<Box<dyn AsyncWrite + Send>>>>();
_assert_sync::<$name<Pin<Box<dyn AsyncWrite + Sync>>>>();
};
}
}
@@ -0,0 +1,4 @@
#[macro_use]
mod decoder;
#[macro_use]
mod encoder;
+16
View File
@@ -0,0 +1,16 @@
//! Types which operate over [`AsyncWrite`](tokio::io::AsyncWrite) streams, both encoders and
//! decoders for various formats.
#[macro_use]
mod macros;
mod generic;
mod buf_writer;
use self::{
buf_writer::BufWriter,
generic::{Decoder, Encoder},
};
use crate::generic::write::AsyncBufWrite;
algos!(tokio::write<W>);
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()
});
}