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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! 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.
//!
//! For memory budgeting, [`estimated_compression_workspace_bytes`] reports
//! the approximate steady-state heap footprint of a one-shot compression at
//! a given level (window + match-finder tables + block staging).
pub
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, upstream zstd `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
pub
pub use ;
pub use ;
pub use ;
pub use ;
pub use StreamingEncoder;
use crate;
use Vec;
/// 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`].
///
/// **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). 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.
///
/// 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. The live working set on this entry point is
/// roughly `input.capacity()` plus the block-accumulation buffer and
/// per-block scratch carried by [`compress_slice_to_vec`], plus the
/// exactly-sized output `Vec`. [`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.
///
/// One-shot wrapper over
/// [`FrameCompressor::compress_independent_frame`]: the input is read by
/// reference (the eligible Fast path scans it in place, no per-block
/// history copy), and the returned `Vec` is allocated exactly once at the
/// final frame size after compression. Peak transient memory is the
/// block-accumulation buffer (grown via amortized doubling, ≈ 2× current
/// compressed size at the last realloc) plus the exactly-sized output. The
/// worst-case compressed-size bound is never pinned upfront, so a highly
/// compressible 100 MiB input does not charge ~100 MiB of worst-case
/// expansion against peak.
///
/// To compress many slices, construct one [`FrameCompressor`] and call
/// [`compress_independent_frame_into`](FrameCompressor::compress_independent_frame_into)
/// in a loop instead, which reuses the matcher tables, scratch, and output
/// buffer across frames (this function allocates and primes from scratch
/// each call).
///
/// # Panics
///
/// Panics on encoder error (matches the failure surface of
/// [`compress_to_vec`], which this function backs). Out-of-memory during
/// the output / per-block scratch allocations is handled by the global
/// allocator's abort policy. The slice/Vec entry points mirror the upstream zstd
/// `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);
/// ```
/// Worst-case compressed-frame size for an input of `src_size` bytes.
///
/// A destination buffer of this size is always large enough to hold the
/// output of [`compress_slice_to_vec`] (or any single-frame compression) for
/// an input of `src_size` bytes, so a caller sizing a fixed buffer once (the
/// shape the C `ZSTD_compress` entry point needs) never has to grow it.
///
/// Mirrors the upstream `ZSTD_COMPRESSBOUND` formula exactly:
/// `src_size + (src_size >> 8) + margin`, where `margin` is
/// `(128 KiB - src_size) >> 11` for inputs below 128 KiB and `0` otherwise.
/// The margin guarantees `bound(a) + bound(b) <= bound(a + b)` for blocks of
/// at least 128 KiB, which keeps multi-frame concatenation sizing sound.
///
/// Saturates at [`usize::MAX`] if the formula would overflow on a
/// pathologically large `src_size` — no allocation that large can exist, so
/// the saturated value is the correct "cannot fit" sentinel rather than a
/// masked wrap.
///
/// ```rust
/// use structured_zstd::encoding::{compress_bound, compress_slice_to_vec, CompressionLevel};
/// let data = [7u8; 4096];
/// assert!(compress_slice_to_vec(&data, CompressionLevel::Default).len() <= compress_bound(data.len()));
/// ```
pub const
/// Compress a byte slice into a fresh `Vec<u8>` using fine-grained
/// [`CompressionParameters`] (#27) instead of a bare
/// [`CompressionLevel`].
///
/// One-shot wrapper over [`FrameCompressor::set_parameters`] +
/// [`FrameCompressor::compress_independent_frame`]. The produced frame is
/// a valid RFC 8878 stream regardless of the knobs chosen.
///
/// ```rust
/// use structured_zstd::encoding::{
/// compress_with_parameters, CompressionLevel, CompressionParameters, Strategy,
/// };
/// let data: &[u8] = b"the quick brown fox jumps over the lazy dog";
/// let params = CompressionParameters::builder(CompressionLevel::Level(5))
/// .strategy(Strategy::Greedy)
/// .build()
/// .unwrap();
/// let compressed = compress_with_parameters(data, ¶ms);
/// assert!(!compressed.is_empty());
/// ```
/// 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