Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 10:29:08 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions

1
vendor/yazi/.cargo-checksum.json vendored Normal file
View File

@@ -0,0 +1 @@
{"files":{"Cargo.toml":"7d9dff169f99a01552370c09c6076e25adc7f0ec431745e0d7ae6811d015481f","LICENSE-APACHE":"7cfd738c53d61c79f07e348f622bf7707c9084237054d37fbe07788a75f5881c","LICENSE-MIT":"df62e3ef3f207c91073fedd78b4156a278681d0dd3f942379242c62c6a71a3ec","README.md":"444831f29edb53c943c6b2cb3992121e6911e2d4a8eefec02dbeb34c05347710","src/decode.rs":"e535f5c0f6b698802a8d0bfafdc8b432fa48c9ed3badc0640bd619d8abe6ebf5","src/encode.rs":"3e381dad3093b5f517e6aeb16c9ea2ac6eaf0c49139658423a79560da2767bb5","src/lib.rs":"97d6783d70da4596a3287871133c5f3886367e371b03bccd621ea92bfd813046"},"package":"e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5"}

45
vendor/yazi/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,45 @@
# 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 = "2021"
name = "yazi"
version = "0.2.1"
authors = ["Chad Brokaw <cbrokaw@gmail.com>"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "DEFLATE/zlib compression and decompression."
homepage = "https://github.com/dfrg/yazi"
readme = "README.md"
keywords = [
"deflate",
"zlib",
"compression",
"decompression",
]
categories = ["compression"]
license = "Apache-2.0 OR MIT"
repository = "https://github.com/dfrg/yazi"
[lib]
name = "yazi"
path = "src/lib.rs"
[features]
default = ["std"]
std = []
[target.'cfg(target_family = "wasm")'.dev-dependencies.wasm-bindgen-test]
version = "0.3.37"

201
vendor/yazi/LICENSE-APACHE vendored Normal file
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.

19
vendor/yazi/LICENSE-MIT vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2020 Chad Brokaw
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.

56
vendor/yazi/README.md vendored Normal file
View File

@@ -0,0 +1,56 @@
# Yazi - Yet another zlib implementation
Yazi is a pure Rust implementation of the RFC 1950 DEFLATE specification with support for
the zlib wrapper. It provides streaming compression and decompression.
[![Crates.io][crates-badge]][crates-url]
[![Docs.rs][docs-badge]][docs-url]
[![Apache 2.0 or MIT license.][license-badge]][license-url]
[crates-badge]: https://img.shields.io/crates/v/yazi.svg
[crates-url]: https://crates.io/crates/yazi
[docs-badge]: https://docs.rs/yazi/badge.svg
[docs-url]: https://docs.rs/yazi
[license-badge]: https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg
[license-url]: #license
## Usage
The following demonstrates simple usage for compressing and decompressing in-memory buffers:
```rust
use yazi::*;
// Your source data.
let data = &(0..=255).cycle().take(8192).collect::<Vec<u8>>()[..];
// Compress it into a Vec<u8> with a zlib wrapper using the default compression level.
let compressed = compress(data, Format::Zlib, CompressionLevel::Default).unwrap();
// Decompress it into a Vec<u8>.
let (decompressed, checksum) = decompress(&compressed, Format::Zlib).unwrap();
// Verify the checksum.
assert_eq!(Adler32::from_buf(&decompressed).finish(), checksum.unwrap());
// Verify that the decompressed data matches the original.
assert_eq!(data, &decompressed[..]);
```
For detail on more advanced usage, see the full API [documentation](https://docs.rs/yazi).
## License
Licensed under either of
- Apache License, Version 2.0
([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT license
([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
at your option.
## Contribution
Contributions are welcome by pull request. The [Rust code of conduct] applies.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
licensed as above, without any additional terms or conditions.
[Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct

1329
vendor/yazi/src/decode.rs vendored Normal file

File diff suppressed because it is too large Load Diff

1748
vendor/yazi/src/encode.rs vendored Normal file

File diff suppressed because it is too large Load Diff

440
vendor/yazi/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,440 @@
//! Yet another zlib implementation.
//!
//! This crate is an implementation of the RFC 1950 DEFLATE specification with
//! support for the zlib wrapper. There are many fine options for such in the
//! Rust ecosystem, but I was looking for one that was small and relatively
//! simple with reasonable performance/compression ratio and support for heap-free
//! compression/decompression scenarios. This crate aims to tick those boxes
//! while also providing composable streaming support based on the standard I/O
//! mechanisms.
//!
//! See the quick start guide below for basic usage or jump to the [compression](#compression)
//! or [decompression](#decompression) section for more detail.
//!
//! # Quick Start
//!
//! So you've got some bytes, they all fit in memory, you don't need to reuse allocations,
//! and you just want to compress or decompress them. This section is for you.
//!
//! Cargo.toml:
//! ```toml
//! [dependencies]
//! yazi = "0.1.4"
//! ```
//!
//! The [`compress`] and [`decompress`] functions are provided for the most common use cases:
//! ```
//! use yazi::*;
//! // Your source data.
//! let data = &(0..=255).cycle().take(8192).collect::<Vec<u8>>()[..];
//! // Compress it into a Vec<u8> with a zlib wrapper using the default compression level.
//! let compressed = compress(data, Format::Zlib, CompressionLevel::Default).unwrap();
//! // Decompress it into a Vec<u8>.
//! let (decompressed, checksum) = decompress(&compressed, Format::Zlib).unwrap();
//! // Verify the checksum.
//! assert_eq!(Adler32::from_buf(&decompressed).finish(), checksum.unwrap());
//! // Verify that the decompressed data matches the original.
//! assert_eq!(&decompressed[..], data);
//! ```
//!
//! Read on for more detailed usage.
//!
//! # Compression
//!
//! To compress data, you'll need to create an instance of the [`Encoder`] struct.
//! The [`new`](Encoder::new) method can be used to construct an encoder on the
//! stack, but the internal buffers are large (~300k) and may cause a stack overflow
//! so it is advisable to use the [`boxed`](Encoder::boxed) method to allocate
//! the encoder on the heap.
//!
//! Newly constructed encoders are configured to output a raw DEFLATE bitstream using a
//! medium compression level and a default strategy. Call [`set_format`](Encoder::set_format)
//! to change the output [`Format`]. Raw DEFLATE and zlib are supported. The
//! [`set_level`](Encoder::set_level) method allows you to choose the preferred
//! [`CompressionLevel`] from a set of basic options or a specific level between 1 and 10.
//! The [`CompressionStrategy`] can be changed with the [`set_strategy`](Encoder::set_strategy)
//! method. This allows you to, for example, force the encoder to output only static blocks.
//!
//! To create an encoder that outputs a zlib bitstream and spends some extra time to potentially
//! produce a result with a higher compression ratio:
//! ```
//! use yazi::{CompressionLevel, Encoder, Format};
//! let mut encoder = Encoder::boxed();
//! encoder.set_format(Format::Zlib);
//! encoder.set_level(CompressionLevel::BestSize);
//! ```
//!
//! The encoder itself does not provide any functionality. It simply stores state and
//! configuration. To actually compress data, you'll need an [`EncoderStream`]. A stream
//! is a binding between an encoder and some specific output that will receive the
//! compressed data. This design allows an encoder to be reused with different types
//! of outputs without paying the allocation and initialization cost each time.
//!
//! Streaming supports outputs of the following forms:
//! - Fixed buffers, created with the [`stream_into_buf`](Encoder::stream_into_buf) method.
//! - Vectors, created with the [`stream_into_vec`](Encoder::stream_into_vec) method.
//! - Any type that implements [`std::io::Write`], created with the generic
//! [`stream`](Encoder::stream) method.
//!
//! Once you have an [`EncoderStream`], simply call [`write`](EncoderStream::write) one
//! or more times, feeding your raw data into the stream. If available, you can submit
//! the entire input buffer at once, or in arbitrarily sized chunks down to a single
//! byte. After all data has been written, call [`finish`](EncoderStream::finish) on
//! the stream which will consume it, flush all remaining input and output, and
//! finalize the operation. The finish method returns a [`Result`] containing the
//! total number of compressed bytes written to the output on success, or an
//! [`Error`] describing the problem on failure.
//!
//! Let's write a function that compresses some arbitrary bytes into a vector:
//! ```
//! fn compress_bytes(buf: &[u8]) -> Result<Vec<u8>, yazi::Error> {
//! use yazi::Encoder;
//! let mut encoder = Encoder::boxed();
//! let mut vec = Vec::new();
//! let mut stream = encoder.stream_into_vec(&mut vec);
//! stream.write(buf)?;
//! stream.finish()?;
//! Ok(vec)
//! }
//! ```
//!
//! Now let's do something a bit more interesting, and given two paths, compress
//! one file into another:
//! ```
//! fn compress_file(source: &str, dest: &str) -> Result<u64, yazi::Error> {
//! use yazi::Encoder;
//! use std::fs::File;
//! use std::io::{copy, BufWriter};
//! let mut encoder = Encoder::boxed();
//! // yazi does not perform any internal buffering beyond what is necessary
//! // for correctness.
//! let mut target = BufWriter::new(File::create(dest)?);
//! let mut stream = encoder.stream(&mut target);
//! copy(&mut File::open(source)?, &mut stream)?;
//! stream.finish()
//! }
//! ```
//!
//! Here, we can see that [`EncoderStream`] also implements [`std::io::Write`], so we
//! can pass it directly to [`std::io::copy`]. This allows streams to be composable
//! with the standard I/O facilities and other libraries that support those interfaces.
//!
//! # Decompression
//!
//! If you've already read the section on compression, the API for decompression
//! is essentially identical with the types replaced by [`Decoder`] and [`DecoderStream`].
//! The documentation is copied here almost verbatim for the sake of completeness and for
//! those who might have skipped directly to this section.
//!
//! To decompress data, you'll need to create an instance of the [`Decoder`] struct.
//! The [`new`](Decoder::new) method can be used to construct a decoder on the stack,
//! and unlike encoders, the decoder struct is relatively small (~10k) and generally
//! safe to stack allocate. You can create a decoder on the heap with the
//! [`boxed`](Decoder::boxed) method if you prefer.
//!
//! Newly constructed decoders are configured to decompress a raw DEFLATE bitstream. Call
//! [`set_format`](Decoder::set_format) to change the input [`Format`]. Raw DEFLATE and
//! zlib are supported. No other configuration is necessary for decompression.
//!
//! To create a decoder that decompresses a zlib bitstream:
//! ```
//! use yazi::{Decoder, Format};
//! let mut decoder = Decoder::new();
//! decoder.set_format(Format::Zlib);
//! ```
//!
//! The decoder itself does not provide any functionality. It simply stores state and
//! configuration. To actually decompress data, you'll need a
//! [`DecoderStream`]. A stream is a binding between a
//! decoder and some specific output that will receive the decompressed data. This
//! design allows a decoder to be reused with different types of outputs without paying the
//! allocation and initialization cost each time.
//!
//! Streaming supports outputs of the following forms:
//! - Fixed buffers, created with the [`stream_into_buf`](Decoder::stream_into_buf) method.
//! - Vectors, created with the [`stream_into_vec`](Decoder::stream_into_vec) method.
//! - Any type that implements [`std::io::Write`], created with the generic
//! [`stream`](Decoder::stream) method.
//!
//! Once you have a [`DecoderStream`], simply call [`write`](DecoderStream::write) one or
//! more times, feeding your compressed data into the stream. If available, you can submit
//! the entire input buffer at once, or in arbitrarily sized chunks down to a single byte.
//! After all data has been written, call [`finish`](DecoderStream::finish) on the stream
//! which will consume it, flush all remaining input and output, and finalize the operation.
//! The finish method returns a [`Result`] containing the total number of decompressed bytes
//! written to the output along with an optional Adler-32 checksum (if the stream was
//! zlib-encoded) on success, or an [`Error`] describing the problem on failure.
//!
//! Let's write a function that decompresses a zlib bitstream into a vector and verifies
//! the checksum:
//! ```
//! fn decompress_zlib(buf: &[u8]) -> Result<Vec<u8>, yazi::Error> {
//! use yazi::{Adler32, Decoder, Error, Format};
//! let mut decoder = Decoder::new();
//! decoder.set_format(Format::Zlib);
//! let mut vec = Vec::new();
//! let mut stream = decoder.stream_into_vec(&mut vec);
//! stream.write(buf)?;
//! // checksum is an Option<u32>
//! let (_, checksum) = stream.finish()?;
//! if Adler32::from_buf(&vec).finish() != checksum.unwrap() {
//! return Err(Error::InvalidBitstream);
//! }
//! Ok(vec)
//! }
//! ```
//!
//! Now let's do something a bit more interesting, and given two paths, decompress
//! one file into another:
//! ```
//! fn decompress_file(source: &str, dest: &str) -> Result<(u64, Option<u32>), yazi::Error> {
//! use yazi::Decoder;
//! use std::fs::File;
//! use std::io::{copy, BufWriter};
//! let mut decoder = Decoder::new();
//! // yazi does not perform any internal buffering beyond what is necessary
//! // for correctness.
//! let mut target = BufWriter::new(File::create(dest)?);
//! let mut stream = decoder.stream(&mut target);
//! copy(&mut File::open(source)?, &mut stream)?;
//! stream.finish()
//! }
//! ```
//!
//! Here, we can see that [`DecoderStream`] also implements [`std::io::Write`], so we can
//! pass it directly to [`std::io::copy`]. This allows streams to be composable with the
//! standard I/O facilities and other libraries that support those interfaces.
//!
//! # Implementation Notes
//!
//! The compressor is based heavily on both [miniz](https://github.com/richgel999/miniz)
//! by Rich Geldreich and [miniz_oxide](https://github.com/Frommi/miniz_oxide)
//! by Frommi. The available compression levels and strategies are the same and
//! it should produce an identical bitstream for a given set of options. The
//! decompressor is based on the techniques in [libdeflate](https://github.com/ebiggers/libdeflate)
//! by Eric Biggers.
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
mod decode;
mod encode;
#[cfg(feature = "std")]
use std::io;
pub use decode::{decompress, Decoder, DecoderStream};
pub use encode::{compress, CompressionLevel, CompressionStrategy, Encoder, EncoderStream};
/// Defines the format for a compressed bitstream.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Format {
/// Raw DEFLATE data.
Raw,
/// Zlib header with an Adler-32 footer.
Zlib,
}
/// Errors that may occur during compression or decompression.
#[derive(Debug)]
pub enum Error {
/// Not enough input was provided.
Underflow,
/// The bitstream was corrupt.
InvalidBitstream,
/// Output buffer was too small.
Overflow,
/// Attempt to write into a finished stream.
Finished,
/// A system I/O error.
///
/// Only available with the `std` feature enabled.
#[cfg(feature = "std")]
Io(io::Error),
}
#[cfg(feature = "std")]
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
/// Rolling Adler-32 checksum.
#[derive(Copy, Clone)]
pub struct Adler32(u32);
impl Adler32 {
/// Creates a new checksum initialized to the default value.
pub fn new() -> Self {
Self(1)
}
/// Creates a checksum from a buffer.
pub fn from_buf(buf: &[u8]) -> Self {
let mut checksum = Self::new();
checksum.update(buf);
checksum
}
/// Updates the checksum with bytes provided by the specified buffer.
pub fn update(&mut self, buf: &[u8]) {
let mut s1 = self.0 & 0xFFFF;
let mut s2 = (self.0 >> 16) & 0xFFFF;
for chunk in buf.chunks(5550) {
for b in chunk {
s1 += *b as u32;
s2 += s1;
}
s1 %= 65521;
s2 %= 65521;
}
self.0 = (s2 << 16) | s1;
}
/// Returns the checksum.
pub fn finish(self) -> u32 {
self.0
}
}
impl Default for Adler32 {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec::Vec;
#[cfg(target_family = "wasm")]
use wasm_bindgen_test::wasm_bindgen_test as test;
fn generate_bytes() -> Vec<u8> {
const BYTES: &[u8; 26] = b"abcdefghijklmnopqrstuvwxyz";
let mut buf = Vec::new();
for i in 0..4096 {
if i % 3 == 0 {
buf.extend_from_slice(&BYTES[13..]);
} else if i & 1 != 0 {
buf.extend_from_slice(BYTES);
} else {
buf.extend(BYTES.iter().rev());
}
}
buf
}
#[test]
fn compress_decompress() {
let buf = generate_bytes();
let mut compressed = Vec::new();
let mut encoder = Encoder::boxed();
let mut stream = encoder.stream_into_vec(&mut compressed);
stream.write(&buf).unwrap();
stream.finish().unwrap();
let mut decompressed = Vec::new();
let mut decoder = Decoder::new();
let mut stream = decoder.stream_into_vec(&mut decompressed);
stream.write(&compressed).unwrap();
stream.finish().unwrap();
assert_eq!(buf, decompressed);
}
#[test]
fn compress_decompress_zlib() {
let buf = generate_bytes();
let mut compressed = Vec::new();
let mut encoder = Encoder::boxed();
encoder.set_format(Format::Zlib);
let mut stream = encoder.stream_into_vec(&mut compressed);
stream.write(&buf).unwrap();
stream.finish().unwrap();
let mut decompressed = Vec::new();
let mut decoder = Decoder::new();
decoder.set_format(Format::Zlib);
let mut stream = decoder.stream_into_vec(&mut decompressed);
stream.write(&compressed).unwrap();
let (_, checksum) = stream.finish().unwrap();
assert_eq!(buf, decompressed);
let mut adler = Adler32::new();
adler.update(&decompressed);
assert_eq!(adler.finish(), checksum.unwrap());
}
#[test]
fn compress_decompress_static() {
let buf = generate_bytes();
let mut compressed = Vec::new();
let mut encoder = Encoder::boxed();
encoder.set_strategy(CompressionStrategy::Static);
let mut stream = encoder.stream_into_vec(&mut compressed);
stream.write(&buf).unwrap();
stream.finish().unwrap();
let mut decompressed = Vec::new();
let mut decoder = Decoder::new();
let mut stream = decoder.stream_into_vec(&mut decompressed);
stream.write(&compressed).unwrap();
stream.finish().unwrap();
assert_eq!(buf, decompressed);
}
#[test]
fn compress_decompress_raw() {
let buf = generate_bytes();
let mut compressed = Vec::new();
let mut encoder = Encoder::boxed();
encoder.set_level(CompressionLevel::None);
let mut stream = encoder.stream_into_vec(&mut compressed);
stream.write(&buf).unwrap();
stream.finish().unwrap();
let mut decompressed = Vec::new();
let mut decoder = Decoder::new();
let mut stream = decoder.stream_into_vec(&mut decompressed);
stream.write(&compressed).unwrap();
stream.finish().unwrap();
assert_eq!(buf, decompressed);
}
#[test]
fn compress_decompress_streaming_1byte() {
let buf = generate_bytes();
let mut compressed = Vec::new();
let mut encoder = Encoder::boxed();
let mut stream = encoder.stream_into_vec(&mut compressed);
for &b in &buf {
stream.write(&[b]).unwrap();
}
stream.finish().unwrap();
let mut decompressed = Vec::new();
let mut decoder = Decoder::new();
let mut stream = decoder.stream_into_vec(&mut decompressed);
for &b in &compressed {
stream.write(&[b]).unwrap();
}
stream.finish().unwrap();
assert_eq!(buf, decompressed);
}
#[test]
fn compress_decompress_streaming_64bytes() {
let buf = generate_bytes();
let mut compressed = Vec::new();
let mut encoder = Encoder::boxed();
let mut stream = encoder.stream_into_vec(&mut compressed);
for chunk in buf.chunks(64) {
stream.write(chunk).unwrap();
}
stream.finish().unwrap();
let mut decompressed = Vec::new();
let mut decoder = Decoder::new();
let mut stream = decoder.stream_into_vec(&mut decompressed);
for chunk in compressed.chunks(64) {
stream.write(chunk).unwrap();
}
stream.finish().unwrap();
assert_eq!(buf, decompressed);
}
}