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 ///
68 /// **Limitation:** hash-chain tables use 32-bit positions. For single-frame
69 /// inputs exceeding ~4 GiB, matches can still be found for roughly one
70 /// window past that point; once all in-window positions exceed `u32::MAX`
71 /// (≈4 GiB + window size), matching becomes effectively repcode-only.
72 /// Prefer [`CompressionLevel::Default`] for very large single-frame streams
73 /// until table rebasing is implemented.
74 Better,
75 /// This level is roughly equivalent to Zstd level 11.
76 ///
77 /// Uses the hash-chain matcher with a deep lazy2 matching strategy and
78 /// a 16 MiB window. Compared to [`CompressionLevel::Better`], this level
79 /// uses larger hash and chain tables (2 M / 1 M entries vs 1 M / 512 K),
80 /// a deeper search (32 candidates vs 16), and a higher target match
81 /// length (128 vs 48), trading speed for the best compression ratio
82 /// available in this crate.
83 ///
84 /// **Limitation:** hash-chain tables use 32-bit positions. For single-frame
85 /// inputs exceeding ~4 GiB, matches can still be found for roughly one
86 /// window past that point; once all in-window positions exceed `u32::MAX`
87 /// (≈4 GiB + window size), matching becomes effectively repcode-only.
88 /// Prefer [`CompressionLevel::Default`] for very large single-frame
89 /// streams until table rebasing is implemented.
90 Best,
91 /// Numeric compression level.
92 ///
93 /// Levels 1–22 correspond to the C zstd level numbering. Higher values
94 /// produce smaller output at the cost of more CPU time. Negative values
95 /// select ultra-fast modes that trade ratio for speed. Level 0 is
96 /// treated as [`DEFAULT_LEVEL`](Self::DEFAULT_LEVEL), matching C zstd
97 /// semantics.
98 ///
99 /// Named variants map to specific numeric levels:
100 /// [`Fastest`](Self::Fastest) = 1, [`Default`](Self::Default) = 3,
101 /// [`Better`](Self::Better) = 7, [`Best`](Self::Best) = 11.
102 /// [`Best`](Self::Best) remains the highest-ratio named preset, but
103 /// [`Level`](Self::Level) values above 11 can target stronger (slower)
104 /// tuning than the named hierarchy.
105 ///
106 /// Levels above 11 use progressively larger windows and deeper search
107 /// with the lazy2 hash-chain backend. Levels that require strategies
108 /// this crate has not yet implemented (btopt, btultra) are approximated
109 /// with the closest available matcher.
110 ///
111 /// **Limitation:** large hash-chain levels still use 32-bit positions.
112 /// For single-frame inputs exceeding ~4 GiB, matches can still be found
113 /// for roughly one window past that point; once all in-window positions
114 /// exceed `u32::MAX` (≈4 GiB + window size), matching becomes effectively
115 /// repcode-only. Prefer [`CompressionLevel::Default`] for very large
116 /// single-frame streams until table rebasing is implemented.
117 ///
118 /// Semver note: this variant was added after the initial enum shape and
119 /// is a breaking API change for downstream crates that exhaustively
120 /// `match` on [`CompressionLevel`] without a wildcard arm.
121 Level(i32),
122}
123
124impl CompressionLevel {
125 /// The minimum supported numeric compression level (ultra-fast mode).
126 pub const MIN_LEVEL: i32 = -131072;
127 /// The maximum supported numeric compression level.
128 pub const MAX_LEVEL: i32 = 22;
129 /// The default numeric compression level (equivalent to [`Default`](Self::Default)).
130 pub const DEFAULT_LEVEL: i32 = 3;
131
132 /// Create a compression level from a numeric value.
133 ///
134 /// Returns named variants for canonical levels (`0`/`3`, `1`, `7`, `11`)
135 /// and [`Level`](Self::Level) for all other values.
136 ///
137 /// With the default matcher backend (`MatchGeneratorDriver`), values
138 /// outside [`MIN_LEVEL`](Self::MIN_LEVEL)..=[`MAX_LEVEL`](Self::MAX_LEVEL)
139 /// are silently clamped during built-in level parameter resolution.
140 pub const fn from_level(level: i32) -> Self {
141 match level {
142 0 | Self::DEFAULT_LEVEL => Self::Default,
143 1 => Self::Fastest,
144 7 => Self::Better,
145 11 => Self::Best,
146 _ => Self::Level(level),
147 }
148 }
149}
150
151/// Trait used by the encoder that users can use to extend the matching facilities with their own algorithm
152/// making their own tradeoffs between runtime, memory usage and compression ratio
153///
154/// This trait operates on buffers that represent the chunks of data the matching algorithm wants to work on.
155/// Each one of these buffers is referred to as a *space*. One or more of these buffers represent the window
156/// the decoder will need to decode the data again.
157///
158/// 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
159/// window of data that is being used for matching.
160///
161/// The library fills the buffer with data that is to be compressed and commits them back to the matcher using `commit_space`.
162///
163/// Then it will either call `start_matching` or, if the space is deemed not worth compressing, `skip_matching` is called.
164///
165/// This is repeated until no more data is left to be compressed.
166pub trait Matcher {
167 /// 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.
168 fn get_next_space(&mut self) -> alloc::vec::Vec<u8>;
169 /// Get a reference to the last commited space
170 fn get_last_space(&mut self) -> &[u8];
171 /// Commit a space to the matcher so it can be matched against
172 fn commit_space(&mut self, space: alloc::vec::Vec<u8>);
173 /// Just process the data in the last commited space for future matching
174 fn skip_matching(&mut self);
175 /// Process the data in the last commited space for future matching AND generate matches for the data
176 fn start_matching(&mut self, handle_sequence: impl for<'a> FnMut(Sequence<'a>));
177 /// Reset this matcher so it can be used for the next new frame
178 fn reset(&mut self, level: CompressionLevel);
179 /// Provide a hint about the total uncompressed size for the next frame.
180 ///
181 /// Implementations may use this to select smaller hash tables and windows
182 /// for small inputs, matching the C zstd source-size-class behavior.
183 /// Called before [`reset`](Self::reset) when the caller knows the input
184 /// size (e.g. from pledged content size or file metadata).
185 ///
186 /// The default implementation is a no-op for custom matchers and
187 /// test stubs. The built-in runtime matcher (`MatchGeneratorDriver`)
188 /// overrides this hook and applies the hint during level resolution.
189 fn set_source_size_hint(&mut self, _size: u64) {}
190 /// Prime matcher state with dictionary history before compressing the next frame.
191 /// Default implementation is a no-op for custom matchers that do not support this.
192 fn prime_with_dictionary(&mut self, _dict_content: &[u8], _offset_hist: [u32; 3]) {}
193 /// Returns whether this matcher can consume dictionary priming state and produce
194 /// dictionary-dependent sequences. Defaults to `false` for custom matchers.
195 fn supports_dictionary_priming(&self) -> bool {
196 false
197 }
198 /// The size of the window the decoder will need to execute all sequences produced by this matcher.
199 ///
200 /// Must return a positive (non-zero) value; returning 0 causes
201 /// [`StreamingEncoder`] to reject the first write with an invalid-input error
202 /// (`InvalidInput` with `std`, `Other` with `no_std`).
203 ///
204 /// Must remain stable for the lifetime of a frame.
205 /// It may change only after `reset()` is called for the next frame
206 /// (for example because the compression level changed).
207 fn window_size(&self) -> u64;
208}
209
210#[derive(PartialEq, Eq, Debug)]
211/// Sequences that a [`Matcher`] can produce
212pub enum Sequence<'data> {
213 /// Is encoded as a sequence for the decoder sequence execution.
214 ///
215 /// First the literals will be copied to the decoded data,
216 /// then `match_len` bytes are copied from `offset` bytes back in the decoded data
217 Triple {
218 literals: &'data [u8],
219 offset: usize,
220 match_len: usize,
221 },
222 /// This is returned as the last sequence in a block
223 ///
224 /// These literals will just be copied at the end of the sequence execution by the decoder
225 Literals { literals: &'data [u8] },
226}