Skip to main content

zstd_native/
lib.rs

1//! Pure Rust Zstandard (zstd, RFC 8878) decompression and compression,
2//! built to match or beat C libzstd 1.5.7 in speed. No C code, `no_std` +
3//! `alloc` capable.
4//!
5//! # One-shot
6//!
7//! ```
8//! // A frame holding "hello" as a raw block.
9//! let compressed = [0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x05, 0x29, 0x00, 0x00, b'h', b'e', b'l', b'l', b'o'];
10//! assert_eq!(zstd_native::decompress(&compressed)?, b"hello");
11//! # Ok::<(), zstd_native::Error>(())
12//! ```
13//!
14//! [`Decompressor`] keeps its tables and buffers between calls (and can
15//! hold a [`Dictionary`]); [`decompress_to_slice`] writes into a buffer
16//! you provide.
17//!
18//! # Streaming
19//!
20//! [`Decoder`] reads a zstd stream from any `std::io::Read` (frame after
21//! frame); [`StreamDecoder`] is the push API underneath (input and output
22//! in pieces of any size, no `std` needed).
23//!
24//! ```
25//! use std::io::Read;
26//! # let compressed: &[u8] = &[0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x05, 0x29, 0x00, 0x00, b'h', b'e', b'l', b'l', b'o'];
27//! let mut text = String::new();
28//! zstd_native::Decoder::new(compressed).read_to_string(&mut text)?;
29//! # assert_eq!(text, "hello");
30//! # Ok::<(), std::io::Error>(())
31//! ```
32//!
33//! # Compression
34//!
35//! [`compress`] (and [`Compressor`], [`compress_to_slice`]) produce the
36//! same bytes as libzstd 1.5.7 at every level. [`Encoder`] compresses into
37//! any `std::io::Write`; [`StreamEncoder`] is the push API underneath
38//! (libzstd's `ZSTD_compressStream2`, byte-identical for the same calls).
39//! All of them take dictionaries too ([`compress_with_dictionary`],
40//! [`Compressor::with_dictionary`], or an [`EncoderDictionary`] prepared
41//! once), with libzstd's output. With `std`, [`Compressor`],
42//! [`StreamEncoder`] and [`Encoder`] also compress with worker threads
43//! (`set_workers`, libzstd's `ZSTD_c_nbWorkers`), with libzstd's
44//! multithreaded output. Their `set_checksum` ends frames with a content
45//! checksum (`ZSTD_c_checksumFlag`, off by default).
46//!
47//! ```
48//! use std::io::Write;
49//! let mut enc = zstd_native::Encoder::new(Vec::new(), 3);
50//! enc.write_all(b"hello, hello, hello")?;
51//! let compressed = enc.finish()?;
52//! assert_eq!(zstd_native::decompress(&compressed).unwrap(), b"hello, hello, hello");
53//! # Ok::<(), std::io::Error>(())
54//! ```
55//!
56//! # Speed
57//!
58//! The hot loops (4-stream Huffman decoding, sequence decoding and
59//! execution) are compiled twice, generic and with BMI2, and the CPU picks
60//! one at run time (with `std`; without it the compile-time target
61//! features decide). The `portable` feature forces the generic code.
62#![no_std]
63#![cfg_attr(docsrs, feature(doc_cfg))]
64#![warn(missing_docs)]
65
66extern crate alloc;
67#[cfg(any(feature = "std", test))]
68extern crate std;
69
70/// Aligns the code that follows to a 64-byte boundary plus `$pad` bytes
71/// of `nop`, for the top of a hot loop (libzstd does the same before its
72/// sequence loop). The hot loops' speed swings by a few percent with where
73/// the linker puts them; this pins their placement to the function instead
74/// of the whole binary. `$pad` is tuned per loop so that the loop's first
75/// instruction (after the compiler's own preheader tail) lands where it
76/// measured fastest. The padding runs once per loop entry.
77macro_rules! align_hot_loop {
78    ($pad:literal) => {
79        #[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
80        // SAFETY: an alignment directive and `nop`s; they touch no state.
81        #[allow(unsafe_code, unused_unsafe)]
82        unsafe {
83            core::arch::asm!(
84                ".p2align 6",
85                concat!(".rept ", $pad),
86                "nop",
87                ".endr",
88                options(nomem, nostack, preserves_flags)
89            );
90        }
91    };
92}
93
94mod bits;
95mod block;
96mod cpu;
97mod decoder;
98mod dict;
99mod enc;
100mod error;
101mod frame;
102mod fse;
103pub(crate) mod huf;
104#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
105mod huf_asm;
106#[cfg(feature = "std")]
107mod io;
108mod stream;
109mod xxhash;
110
111pub use decoder::{Decompressor, content_size, decompress, decompress_to_slice};
112pub use dict::Dictionary;
113pub use enc::{
114    CompressProgress, Compressor, EncoderDictionary, EndOp, StreamEncoder, compress,
115    compress_bound, compress_to_slice, compress_with_dictionary,
116};
117pub use error::Error;
118pub use frame::FrameHeader;
119#[cfg(feature = "std")]
120pub use io::{Decoder, Encoder};
121pub use stream::{Progress, StreamDecoder};
122pub use xxhash::xxh64;
123
124#[doc(hidden)]
125pub mod __private {
126    pub use crate::block::{long_blocks, set_seq_loop};
127    pub use crate::cpu::{selected_paths, set_asm};
128    pub use crate::huf::{
129        bench_read as huf_bench_read, first_tree_description as huf_first_tree_description,
130    };
131}