1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Zstandard encoder — frame compression, streaming, dictionary support.
//!
//! Four entry points cover the common use cases:
//!
//! * [`compress`] — one-shot helper that builds a self-contained
//! Zstandard frame from a `Read` source to a `Write` sink. The
//! input is consumed incrementally from `Read`, so input buffering
//! stays bounded; however, the compressed output is buffered in
//! memory until the frame is complete so the Frame Content Size
//! field can be filled in the header — peak memory is
//! `O(compressed_size)` (worst-case `O(input_size)` for
//! incompressible payloads, plus a small frame overhead). The
//! savings vs [`compress_to_vec`] come from not materialising the
//! input alongside the output.
//! * [`compress_to_vec`] — same one-shot path as [`compress`] but
//! the input is eagerly drained into an internal `Vec` first
//! (`read_to_end`) so the encoder can be handed a `&[u8]` and a
//! precise source-size hint. Peak memory is therefore ≈
//! `input_size + output_size`; prefer [`compress`] or
//! [`StreamingEncoder`] when the input is large or unbounded.
//! * [`StreamingEncoder`] — implements [`crate::io::Write`], which
//! re-exports [`std::io::Write`] under the `std` feature and falls
//! back to a `no_std`-friendly trait otherwise. Accepts bytes
//! incrementally and flushes compressed output as blocks fill.
//! Requires `set_pledged_content_size` before the first write if
//! the Frame Content Size field is to be populated.
//! * [`FrameCompressor`] — lower-level builder that owns the matcher and
//! the per-frame configuration; the streaming and one-shot helpers are
//! thin wrappers over it. Reach for it when you need to swap in a custom
//! [`Matcher`] implementation or share the matcher across frames.
//!
//! Compression intensity is selected via [`CompressionLevel`], which
//! provides both named presets (`Fastest`, `Default`, `Better`, `Best`) and
//! numeric levels (`from_level(n)`) that mirror C zstd's level numbering
//! (negative for ultra-fast, `0` = default, `1..=22` for the standard
//! range).
//!
//! All produced frames are valid RFC 8878 Zstandard streams and decode
//! through both this crate's [`crate::decoding`] module and upstream C zstd.
pub
pub
pub
pub
pub
pub
pub
// `#111` encoder architecture rewrite. `cost_model`, `opt`,
// `strategy`, `dfast`, `row`, and `simple` host the relocated
// cost-model types, the optimal-parser plain-data types, the
// const-generic [`strategy::Strategy`] trait + per-level [`strategy::
// StrategyTag`] dispatcher, and the Dfast / Row / Simple matchers
// respectively. `match_table::helpers` hosts the shared match-finder
// primitives. The rewrite plan is tracked in
// <https://github.com/structured-world/structured-zstd/issues/111>;
// per-phase boundaries are `perf/post-pr-110-baseline` (start),
// `perf/post-pr-121-baseline` (post-Phase-2).
pub
pub
pub
pub
// LDM uses `twox_hash::XxHash64` (per-window XXH64 over the
// `min_match_length` byte slice, donor `zstd_ldm.c:315`). The
// `twox-hash` dependency is gated behind the `hash` feature so
// `default-features = false` builds (no_std, embedded) don't pull
// it in. `BtMatcher::ldm_producer` and the `cfg(feature = "hash")`
// blocks inside `BtMatcher::prepare_ldm_candidates` /
// `BtMatcher::reset` carry the same gate; the call site in
// `match_generator.rs::start_matching_optimal` invokes
// `prepare_ldm_candidates` unconditionally because the
// gating is internal to the method body (under
// `not(feature = "hash")` the method shrinks to the legacy
// `ldm_sequences.clear()` stub).
pub
pub
pub
pub
pub
pub
pub use FrameCompressor;
pub use MatchGeneratorDriver;
pub use StreamingEncoder;
use crate;
use Vec;
pub const BETTER_WINDOW_LOG: u8 = 23;
/// Worst-case compressed-size bound for `src_size` uncompressed
/// bytes. Mirrors the upstream `ZSTD_COMPRESSBOUND(srcSize)` macro
/// from `lib/zstd.h` (zstd 1.5.7) — the C *macro*, NOT the public
/// `ZSTD_compressBound()` function. The function adds frame/block-
/// header headroom in some code paths; the macro is a tighter
/// expression suitable for sizing an internal output Vec, which is
/// the only call site here. Callers that need a hard upper bound on
/// the wire-format compressed size should NOT reuse this — use the
/// `zstd-sys` function call directly. If the macro changes in a
/// future upstream revision, treat the upstream header as
/// authoritative and re-derive this function — do not trust the
/// inline copy without cross-checking.
///
/// Inline approximation (this revision):
///
/// ```text
/// srcSize
/// + (srcSize >> 8)
/// + (srcSize < 128 KiB ? ((128 KiB - srcSize) >> 11) : 0)
/// ```
///
/// Consulted by [`compress_slice_to_vec`] for the small-input branch
/// of its output-`Vec` seed: the seed is
/// `min(compress_bound(src), OUTPUT_BLOCK_CAP = 128 KiB)`, so for
/// inputs that fit within one donor block (`≤ ~128 KiB`) the
/// destination never reallocates inside the measured window. Without
/// the bound, `Vec::push` growth doubles in powers of two and pins
/// `~2 × final_compressed_size` resident at the last realloc, which
/// shows up as ~1 MiB of peak-RSS noise on 1 MiB inputs and prevents
/// FFI-parity on the memory bench. For inputs larger than the cap the
/// `Vec` still grows by amortized doubling — see
/// [`compress_slice_to_vec`] for the trade-off rationale.
pub const
/// Convenience function to compress some source into a target without reusing any resources of the compressor
/// ```rust
/// use structured_zstd::encoding::{compress, CompressionLevel};
/// let data: &[u8] = &[0,0,0,0,0,0,0,0,0,0,0,0];
/// let mut target = Vec::new();
/// compress(data, &mut target, CompressionLevel::Fastest);
/// ```
/// Convenience function to compress some source into a Vec without reusing any resources of the compressor.
///
/// This helper eagerly buffers the full input (`Read`) before compression so it
/// can provide a source-size hint to the one-shot encoder path. Peak memory can
/// therefore be roughly `input_size + output_size`. For very large payloads or
/// tighter memory budgets, prefer streaming APIs such as [`StreamingEncoder`].
///
/// **Peak-memory shape change in this revision.** The implementation
/// delegates to [`compress_slice_to_vec`], which seeds the output
/// `Vec` with `min(compress_bound(input.len()), OUTPUT_BLOCK_CAP =
/// 128 KiB)` instead of the previous `Vec::new()` (zero-capacity +
/// power-of-two growth). For inputs in the few-KiB to ~128 KiB range
/// this is a strict improvement (no doubling spikes inside the
/// measured window). For inputs significantly larger than 128 KiB the
/// allocation curve still grows by amortized doubling but starts from
/// a 128 KiB floor rather than 0. Downstream consumers that measure
/// peak RSS on this entry point will see a different curve than
/// pre-revision; bench shape, not steady-state, is what changed.
///
/// **This is NOT a streaming API.** The source is fully buffered
/// into a `Vec<u8>` before any compression work begins, so peak input
/// memory is bounded by `source.len()` (not "constant regardless of
/// payload size" as a stream-shaped encoder would offer). The RSS
/// notes below apply to the materialization-then-compress shape; if
/// the source is large enough that holding it in memory is not
/// acceptable, use [`StreamingEncoder`] which consumes chunks
/// incrementally without the up-front Vec build.
///
/// The other side of the peak shape is the input buffering: this
/// helper drives `read_to_end` to materialize the full source into a
/// `Vec<u8>` before forwarding the slice to [`compress_slice_to_vec`].
/// For a `Read` whose size is unknown ahead of time, `read_to_end`
/// grows that input `Vec` via power-of-two doubling — peak input
/// allocation can be up to 2× the final source length transiently.
/// At the moment that input buffer crosses ~128 KiB the output Vec
/// seed kicks in concurrently. The total live working set on this
/// entry point is approximately
/// `input.capacity() + output_vec_seed + internal_accumulators`,
/// where `output_vec_seed` is `min(compress_bound(input.len()), 128
/// KiB)` and `internal_accumulators` covers
/// `FrameCompressor::all_blocks` (pre-reserved at frame start, up to
/// ~130 KiB at default block cap) plus per-block scratch (hash tables,
/// literal/sequence staging). Round the helper's RSS peak to
/// `input.capacity() + output_vec_seed + ~130 KiB internal +
/// per-block scratch` rather than the bare `input.capacity() + 128
/// KiB` figure quoted in earlier revisions, which only accounted for
/// the output seed. [`StreamingEncoder`] avoids the input
/// materialization step entirely and is the right entry point when
/// the source is large or unbounded.
///
/// ```rust
/// use structured_zstd::encoding::{compress_to_vec, CompressionLevel};
/// let data: &[u8] = &[0,0,0,0,0,0,0,0,0,0,0,0];
/// let compressed = compress_to_vec(data, CompressionLevel::Fastest);
/// ```
/// Compress a contiguous byte slice into a fresh `Vec<u8>` without
/// the input-buffering step that [`compress_to_vec`] performs to
/// adapt a `Read` source. Donor-parity peak-memory shape: the input
/// is read by reference, and the output `Vec` is seeded with
/// `min(compress_bound(src), OUTPUT_BLOCK_CAP = 128 KiB)`.
///
/// The seed is intentionally capped at one donor block
/// (`OUTPUT_BLOCK_CAP = 128 KiB`). Three regimes:
///
/// * Inputs up to ~127 KiB where `compress_bound(src) <
/// OUTPUT_BLOCK_CAP` — the `min` picks the tighter bound and the
/// `Vec` never reallocates inside the measured window (cheap, no
/// doubling spikes, no over-allocation).
/// * Inputs around 128 KiB where `compress_bound(src) >=
/// OUTPUT_BLOCK_CAP` — the `min` clamps to the cap, so the "no
/// reallocation" property holds only as long as the actual
/// compressed output also fits within `OUTPUT_BLOCK_CAP`. For
/// high-entropy inputs near the cap boundary the `Vec` may grow
/// by one doubling step before the next block lands.
/// * Larger inputs — the `Vec` grows via amortized doubling, with
/// peak transient memory ≈ 2× current compressed size at the last
/// realloc. Deliberate trade-off against pinning
/// `compress_bound(src)` upfront, which on the 100 MiB
/// `large-log-stream` scenario pinned 100.4 MiB even though the
/// actual compressed output was ≪ 1 MiB.
///
/// # Panics
///
/// Panics on encoder error (matches the failure surface of
/// [`compress_to_vec`], which this function backs). The internal
/// [`FrameCompressor::compress`] call propagates `io::Error` from the
/// output [`Vec`] writer; under the in-tree default writer that
/// channel is infallible and any error becomes a `panic`. Out-of-
/// memory during `Vec::with_capacity` or the encoder's per-block
/// scratch allocations is handled by the global allocator's abort
/// policy. Migrating to a fallible variant requires plumbing
/// `Result` through `FrameCompressor::compress` — out of scope for
/// the slice/Vec entry points which mirror the donor `ZSTD_compress`
/// shape (no error return on the bulk path).
///
/// ```rust
/// use structured_zstd::encoding::{compress_slice_to_vec, CompressionLevel};
/// let data: &[u8] = &[0,0,0,0,0,0,0,0,0,0,0,0];
/// let compressed = compress_slice_to_vec(data, CompressionLevel::Fastest);
/// ```
/// The compression mode used impacts the speed of compression,
/// and resulting compression ratios. Faster compression will result
/// in worse compression ratios, and vice versa.
/// Trait used by the encoder that users can use to extend the matching facilities with their own algorithm
/// making their own tradeoffs between runtime, memory usage and compression ratio
///
/// This trait operates on buffers that represent the chunks of data the matching algorithm wants to work on.
/// Each one of these buffers is referred to as a *space*. One or more of these buffers represent the window
/// the decoder will need to decode the data again.
///
/// 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
/// window of data that is being used for matching.
///
/// The library fills the buffer with data that is to be compressed and commits them back to the matcher using `commit_space`.
///
/// Then it will either call `start_matching` or, if the space is deemed not worth compressing, `skip_matching` is called.
///
/// This is repeated until no more data is left to be compressed.
/// Sequences that a [`Matcher`] can produce