structured_zstd/encoding/mod.rs
1//! Structures and utilities used for compressing/encoding data into the Zstd format.
2
3pub(crate) mod block_header;
4pub(crate) mod blocks;
5pub(crate) mod frame_header;
6pub(crate) mod match_generator;
7pub(crate) mod util;
8
9mod frame_compressor;
10mod levels;
11mod streaming_encoder;
12pub use frame_compressor::FrameCompressor;
13pub use match_generator::MatchGeneratorDriver;
14pub use streaming_encoder::StreamingEncoder;
15
16use crate::io::{Read, Write};
17use alloc::vec::Vec;
18
19/// Convenience function to compress some source into a target without reusing any resources of the compressor
20/// ```rust
21/// use structured_zstd::encoding::{compress, CompressionLevel};
22/// let data: &[u8] = &[0,0,0,0,0,0,0,0,0,0,0,0];
23/// let mut target = Vec::new();
24/// compress(data, &mut target, CompressionLevel::Fastest);
25/// ```
26pub fn compress<R: Read, W: Write>(source: R, target: W, level: CompressionLevel) {
27 let mut frame_enc = FrameCompressor::new(level);
28 frame_enc.set_source(source);
29 frame_enc.set_drain(target);
30 frame_enc.compress();
31}
32
33/// Convenience function to compress some source into a Vec without reusing any resources of the compressor
34/// ```rust
35/// use structured_zstd::encoding::{compress_to_vec, CompressionLevel};
36/// let data: &[u8] = &[0,0,0,0,0,0,0,0,0,0,0,0];
37/// let compressed = compress_to_vec(data, CompressionLevel::Fastest);
38/// ```
39pub fn compress_to_vec<R: Read>(source: R, level: CompressionLevel) -> Vec<u8> {
40 let mut vec = Vec::new();
41 compress(source, &mut vec, level);
42 vec
43}
44
45/// The compression mode used impacts the speed of compression,
46/// and resulting compression ratios. Faster compression will result
47/// in worse compression ratios, and vice versa.
48#[derive(Copy, Clone, Debug)]
49pub enum CompressionLevel {
50 /// This level does not compress the data at all, and simply wraps
51 /// it in a Zstandard frame.
52 Uncompressed,
53 /// This level is roughly equivalent to Zstd compression level 1
54 Fastest,
55 /// This level uses the crate's dedicated `dfast`-style matcher to
56 /// target a better speed/ratio tradeoff than [`CompressionLevel::Fastest`].
57 ///
58 /// It represents this crate's "default" compression setting and may
59 /// evolve in future versions as the implementation moves closer to
60 /// reference zstd level 3 behavior.
61 Default,
62 /// This level is roughly equivalent to Zstd level 7.
63 ///
64 /// Uses the hash-chain matcher with a lazy2 matching strategy: the encoder
65 /// evaluates up to two positions ahead before committing to a match,
66 /// trading speed for a better compression ratio than [`CompressionLevel::Default`].
67 Better,
68 /// This level is roughly equivalent to Zstd level 11.
69 ///
70 /// Uses the hash-chain matcher with a deep lazy2 matching strategy and
71 /// a 16 MiB window. Compared to [`CompressionLevel::Better`], this level
72 /// uses larger hash and chain tables (2 M / 1 M entries vs 1 M / 512 K),
73 /// a deeper search (32 candidates vs 16), and a higher target match
74 /// length (128 vs 48), trading speed for the best compression ratio
75 /// available in this crate.
76 Best,
77 /// Numeric compression level.
78 ///
79 /// Levels 1–22 correspond to the C zstd level numbering. Higher values
80 /// produce smaller output at the cost of more CPU time. Negative values
81 /// select ultra-fast modes that trade ratio for speed. Level 0 is
82 /// treated as [`DEFAULT_LEVEL`](Self::DEFAULT_LEVEL), matching C zstd
83 /// semantics.
84 ///
85 /// Named variants map to specific numeric levels:
86 /// [`Fastest`](Self::Fastest) = 1, [`Default`](Self::Default) = 3,
87 /// [`Better`](Self::Better) = 7, [`Best`](Self::Best) = 11.
88 /// [`Best`](Self::Best) remains the highest-ratio named preset, but
89 /// [`Level`](Self::Level) values above 11 can target stronger (slower)
90 /// tuning than the named hierarchy.
91 ///
92 /// Levels above 11 use progressively larger windows and deeper search
93 /// with the lazy2 hash-chain backend. Levels that require strategies
94 /// this crate has not yet implemented (btopt, btultra) are approximated
95 /// with the closest available matcher.
96 ///
97 /// Semver note: this variant was added after the initial enum shape and
98 /// is a breaking API change for downstream crates that exhaustively
99 /// `match` on [`CompressionLevel`] without a wildcard arm.
100 Level(i32),
101}
102
103impl CompressionLevel {
104 /// The minimum supported numeric compression level (ultra-fast mode).
105 pub const MIN_LEVEL: i32 = -131072;
106 /// The maximum supported numeric compression level.
107 pub const MAX_LEVEL: i32 = 22;
108 /// The default numeric compression level (equivalent to [`Default`](Self::Default)).
109 pub const DEFAULT_LEVEL: i32 = 3;
110
111 /// Create a compression level from a numeric value.
112 ///
113 /// Returns named variants for canonical levels (`0`/`3`, `1`, `7`, `11`)
114 /// and [`Level`](Self::Level) for all other values.
115 ///
116 /// With the default matcher backend (`MatchGeneratorDriver`), values
117 /// outside [`MIN_LEVEL`](Self::MIN_LEVEL)..=[`MAX_LEVEL`](Self::MAX_LEVEL)
118 /// are silently clamped during built-in level parameter resolution.
119 pub const fn from_level(level: i32) -> Self {
120 match level {
121 0 | Self::DEFAULT_LEVEL => Self::Default,
122 1 => Self::Fastest,
123 7 => Self::Better,
124 11 => Self::Best,
125 _ => Self::Level(level),
126 }
127 }
128}
129
130/// Trait used by the encoder that users can use to extend the matching facilities with their own algorithm
131/// making their own tradeoffs between runtime, memory usage and compression ratio
132///
133/// This trait operates on buffers that represent the chunks of data the matching algorithm wants to work on.
134/// Each one of these buffers is referred to as a *space*. One or more of these buffers represent the window
135/// the decoder will need to decode the data again.
136///
137/// This library asks the Matcher for a new buffer using `get_next_space` to allow reusing of allocated buffers when they are no longer part of the
138/// window of data that is being used for matching.
139///
140/// The library fills the buffer with data that is to be compressed and commits them back to the matcher using `commit_space`.
141///
142/// Then it will either call `start_matching` or, if the space is deemed not worth compressing, `skip_matching` is called.
143///
144/// This is repeated until no more data is left to be compressed.
145pub trait Matcher {
146 /// Get a space where we can put data to be matched on. Will be encoded as one block. The maximum allowed size is 128 kB.
147 fn get_next_space(&mut self) -> alloc::vec::Vec<u8>;
148 /// Get a reference to the last commited space
149 fn get_last_space(&mut self) -> &[u8];
150 /// Commit a space to the matcher so it can be matched against
151 fn commit_space(&mut self, space: alloc::vec::Vec<u8>);
152 /// Just process the data in the last commited space for future matching
153 fn skip_matching(&mut self);
154 /// Process the data in the last commited space for future matching AND generate matches for the data
155 fn start_matching(&mut self, handle_sequence: impl for<'a> FnMut(Sequence<'a>));
156 /// Reset this matcher so it can be used for the next new frame
157 fn reset(&mut self, level: CompressionLevel);
158 /// Provide a hint about the total uncompressed size for the next frame.
159 ///
160 /// Implementations may use this to select smaller hash tables and windows
161 /// for small inputs, matching the C zstd source-size-class behavior.
162 /// Called before [`reset`](Self::reset) when the caller knows the input
163 /// size (e.g. from pledged content size or file metadata).
164 ///
165 /// The default implementation is a no-op for custom matchers and
166 /// test stubs. The built-in runtime matcher (`MatchGeneratorDriver`)
167 /// overrides this hook and applies the hint during level resolution.
168 fn set_source_size_hint(&mut self, _size: u64) {}
169 /// Prime matcher state with dictionary history before compressing the next frame.
170 /// Default implementation is a no-op for custom matchers that do not support this.
171 fn prime_with_dictionary(&mut self, _dict_content: &[u8], _offset_hist: [u32; 3]) {}
172 /// Returns whether this matcher can consume dictionary priming state and produce
173 /// dictionary-dependent sequences. Defaults to `false` for custom matchers.
174 fn supports_dictionary_priming(&self) -> bool {
175 false
176 }
177 /// The size of the window the decoder will need to execute all sequences produced by this matcher.
178 ///
179 /// Must return a positive (non-zero) value; returning 0 causes
180 /// [`StreamingEncoder`] to reject the first write with an invalid-input error
181 /// (`InvalidInput` with `std`, `Other` with `no_std`).
182 ///
183 /// Must remain stable for the lifetime of a frame.
184 /// It may change only after `reset()` is called for the next frame
185 /// (for example because the compression level changed).
186 fn window_size(&self) -> u64;
187}
188
189#[derive(PartialEq, Eq, Debug)]
190/// Sequences that a [`Matcher`] can produce
191pub enum Sequence<'data> {
192 /// Is encoded as a sequence for the decoder sequence execution.
193 ///
194 /// First the literals will be copied to the decoded data,
195 /// then `match_len` bytes are copied from `offset` bytes back in the decoded data
196 Triple {
197 literals: &'data [u8],
198 offset: usize,
199 match_len: usize,
200 },
201 /// This is returned as the last sequence in a block
202 ///
203 /// These literals will just be copied at the end of the sequence execution by the decoder
204 Literals { literals: &'data [u8] },
205}