zstd_safe/lib.rs
1#![no_std]
2//! Minimal safe wrapper around zstd-sys.
3//!
4//! This crates provides a minimal translation of the [zstd-sys] methods.
5//! For a more comfortable high-level library, see the [zstd] crate.
6//!
7//! [zstd-sys]: https://crates.io/crates/zstd-sys
8//! [zstd]: https://crates.io/crates/zstd
9//!
10//! Most of the functions here map 1-for-1 to a function from
11//! [the C zstd library][zstd-c] mentioned in their descriptions.
12//! Check the [source documentation][doc] for more information on their
13//! behaviour.
14//!
15//! [doc]: https://facebook.github.io/zstd/zstd_manual.html
16//! [zstd-c]: https://facebook.github.io/zstd/
17//!
18//! Features denoted as experimental in the C library are hidden behind an
19//! `experimental` feature.
20#![cfg_attr(feature = "doc-cfg", feature(doc_cfg))]
21
22// TODO: Use alloc feature instead to implement stuff for Vec
23// TODO: What about Cursor?
24#[cfg(feature = "std")]
25extern crate std;
26
27#[cfg(test)]
28mod tests;
29
30#[cfg(feature = "seekable")]
31pub mod seekable;
32
33// Re-export zstd-sys
34pub use zstd_sys;
35
36/// How to compress data.
37pub use zstd_sys::ZSTD_strategy as Strategy;
38
39/// Frame progression state.
40#[cfg(feature = "experimental")]
41#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
42pub use zstd_sys::ZSTD_frameProgression as FrameProgression;
43
44/// Reset directive.
45// pub use zstd_sys::ZSTD_ResetDirective as ResetDirective;
46use core::ffi::{c_char, c_int, c_ulonglong, c_void};
47
48use core::marker::PhantomData;
49use core::num::{NonZeroU32, NonZeroU64};
50use core::ops::{Deref, DerefMut};
51use core::ptr::NonNull;
52use core::str;
53
54include!("constants.rs");
55
56#[cfg(feature = "experimental")]
57include!("constants_experimental.rs");
58
59#[cfg(feature = "seekable")]
60include!("constants_seekable.rs");
61
62/// Represents the compression level used by zstd.
63pub type CompressionLevel = i32;
64
65/// Represents a possible error from the zstd library.
66pub type ErrorCode = usize;
67
68/// Wrapper result around most zstd functions.
69///
70/// Either a success code (usually number of bytes written), or an error code.
71pub type SafeResult = Result<usize, ErrorCode>;
72
73/// The error code zstd itself returns for a parameter it does not support
74/// (`-ZSTD_error_parameter_unsupported` as a `size_t`), for the parameters
75/// that are refused on the Rust side of a call.
76#[cfg(feature = "experimental")]
77const PARAMETER_UNSUPPORTED_ERROR: ErrorCode =
78 (zstd_sys::ZSTD_ErrorCode::ZSTD_error_parameter_unsupported as usize)
79 .wrapping_neg();
80
81/// The error code zstd itself returns for an operation the context is in no
82/// state to perform (`-ZSTD_error_stage_wrong` as a `size_t`), for the places
83/// where that has to be decided on the Rust side of a call.
84const STAGE_WRONG_ERROR: ErrorCode =
85 (zstd_sys::ZSTD_ErrorCode::ZSTD_error_stage_wrong as usize).wrapping_neg();
86
87/// The error code `ZSTD_compress2()` returns when the destination is too
88/// small, leaving its frame in progress (`-ZSTD_error_dstSize_tooSmall`).
89const DST_SIZE_TOO_SMALL_ERROR: ErrorCode =
90 (zstd_sys::ZSTD_ErrorCode::ZSTD_error_dstSize_tooSmall as usize)
91 .wrapping_neg();
92
93/// The largest frame zstd compresses on the calling thread when its size is
94/// known (`ZSTDMT_JOBSIZE_MIN` in zstd 1.5; older versions used larger
95/// values, which only makes this cautious).
96const ZSTDMT_JOBSIZE_MIN: usize = 512 << 10;
97
98/// Indicates an error happened when parsing the frame content size.
99///
100/// The stream may be corrupted, or the given frame prefix was too small.
101#[derive(Debug)]
102pub struct ContentSizeError;
103
104impl core::fmt::Display for ContentSizeError {
105 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
106 f.write_str("Could not get content size")
107 }
108}
109
110/// Returns true if code represents error.
111fn is_error(code: usize) -> bool {
112 // Safety: Just FFI
113 unsafe { zstd_sys::ZSTD_isError(code) != 0 }
114}
115
116/// Parse the result code
117///
118/// Returns the number of bytes written if the code represents success,
119/// or the error message code otherwise.
120fn parse_code(code: usize) -> SafeResult {
121 if !is_error(code) {
122 Ok(code)
123 } else {
124 Err(code)
125 }
126}
127
128/// Parse a content size value.
129///
130/// zstd uses 2 special content size values to indicate either unknown size or parsing error.
131fn parse_content_size(
132 content_size: u64,
133) -> Result<Option<u64>, ContentSizeError> {
134 match content_size {
135 CONTENTSIZE_ERROR => Err(ContentSizeError),
136 CONTENTSIZE_UNKNOWN => Ok(None),
137 other => Ok(Some(other)),
138 }
139}
140
141fn ptr_void(src: &[u8]) -> *const c_void {
142 src.as_ptr() as *const c_void
143}
144
145fn ptr_mut_void(dst: &mut (impl WriteBuf + ?Sized)) -> *mut c_void {
146 dst.as_mut_ptr() as *mut c_void
147}
148
149/// Returns the ZSTD version.
150///
151/// Returns `major * 10_000 + minor * 100 + patch`.
152/// So 1.5.3 would be returned as `10_503`.
153pub fn version_number() -> u32 {
154 // Safety: Just FFI
155 unsafe { zstd_sys::ZSTD_versionNumber() as u32 }
156}
157
158/// Returns a string representation of the ZSTD version.
159///
160/// For example "1.5.3".
161pub fn version_string() -> &'static str {
162 // Safety: Assumes `ZSTD_versionString` returns a valid utf8 string.
163 unsafe { c_char_to_str(zstd_sys::ZSTD_versionString()) }
164}
165
166/// Returns the minimum (fastest) compression level supported.
167///
168/// This is likely going to be a _very_ large negative number.
169pub fn min_c_level() -> CompressionLevel {
170 // Safety: Just FFI
171 unsafe { zstd_sys::ZSTD_minCLevel() as CompressionLevel }
172}
173
174/// Returns the maximum (slowest) compression level supported.
175pub fn max_c_level() -> CompressionLevel {
176 // Safety: Just FFI
177 unsafe { zstd_sys::ZSTD_maxCLevel() as CompressionLevel }
178}
179
180/// Wraps the `ZSTD_compress` function.
181///
182/// This will try to compress `src` entirely and write the result to `dst`, returning the number of
183/// bytes written. If `dst` is too small to hold the compressed content, an error will be returned.
184///
185/// For streaming operations that don't require to store the entire input/output in memory, see
186/// `compress_stream`.
187pub fn compress<C: WriteBuf + ?Sized>(
188 dst: &mut C,
189 src: &[u8],
190 compression_level: CompressionLevel,
191) -> SafeResult {
192 // Safety: ZSTD_compress indeed returns how many bytes have been written.
193 unsafe {
194 dst.write_from(|buffer, capacity| {
195 parse_code(zstd_sys::ZSTD_compress(
196 buffer,
197 capacity,
198 ptr_void(src),
199 src.len(),
200 compression_level,
201 ))
202 })
203 }
204}
205
206/// Wraps the `ZSTD_decompress` function.
207///
208/// This is a one-step decompression (not streaming).
209///
210/// You will need to make sure `dst` is large enough to store all the decompressed content, or an
211/// error will be returned.
212///
213/// If decompression was a success, the number of bytes written will be returned.
214pub fn decompress<C: WriteBuf + ?Sized>(
215 dst: &mut C,
216 src: &[u8],
217) -> SafeResult {
218 // Safety: ZSTD_decompress indeed returns how many bytes have been written.
219 unsafe {
220 dst.write_from(|buffer, capacity| {
221 parse_code(zstd_sys::ZSTD_decompress(
222 buffer,
223 capacity,
224 ptr_void(src),
225 src.len(),
226 ))
227 })
228 }
229}
230
231/// Wraps the `ZSTD_getDecompressedSize` function.
232///
233/// Returns `None` if the size could not be found, or if the content is actually empty.
234#[deprecated(note = "Use ZSTD_getFrameContentSize instead")]
235pub fn get_decompressed_size(src: &[u8]) -> Option<NonZeroU64> {
236 // Safety: Just FFI
237 NonZeroU64::new(unsafe {
238 zstd_sys::ZSTD_getDecompressedSize(ptr_void(src), src.len()) as u64
239 })
240}
241
242/// Maximum compressed size in worst case single-pass scenario
243pub fn compress_bound(src_size: usize) -> usize {
244 // Safety: Just FFI
245 unsafe { zstd_sys::ZSTD_compressBound(src_size) }
246}
247
248/// Remembers an error that may have left a context in a state zstd considers
249/// undefined.
250///
251/// zstd.h says of both `ZSTD_compressStream2()` and `ZSTD_decompressStream()`
252/// that "if an operation ends with an error, it may leave [the context] in an
253/// undefined state", and that calling them again on such a state is undefined
254/// behaviour - the context has to be reset first. So once a streaming
255/// operation fails, refuse to run another one until something resets the
256/// context, and hand the original error back instead.
257#[derive(Clone, Debug, Default)]
258struct Poison(Option<ErrorCode>);
259
260impl Poison {
261 /// Fails with the error that poisoned the context, if there was one.
262 fn guard(&self) -> Result<(), ErrorCode> {
263 match self.0 {
264 Some(code) => Err(code),
265 None => Ok(()),
266 }
267 }
268
269 /// Remembers `res` if it failed, and passes it through.
270 fn record(&mut self, res: SafeResult) -> SafeResult {
271 if let Err(code) = res {
272 self.0 = Some(code);
273 }
274 res
275 }
276
277 /// The context was reset, so it is usable again.
278 fn clear(&mut self) {
279 self.0 = None;
280 }
281}
282
283/// What a `CCtx` knows about its worker threads (`NbWorkers`).
284#[derive(Clone, Copy, Debug, Default)]
285struct Workers {
286 /// `NbWorkers` was ever set to a non-zero value, see `guard_own_tables`.
287 ever: bool,
288 /// `NbWorkers` is currently set to a non-zero value.
289 requested: bool,
290 /// A frame was started while `NbWorkers` was set, and is not finished.
291 ///
292 /// Its jobs may be running on the worker threads, reading the context's
293 /// dictionary and job table. zstd up to 1.5.7 does not wait for them when
294 /// the frame is abandoned: not on a session reset, not before a short
295 /// frame (which it compresses on the calling thread), and not before
296 /// freeing the dictionary when the context is freed. So the frame is
297 /// drained first, see `CCtx::drain()`.
298 pending: bool,
299 /// `ZSTD_e_end` was given for the `pending` frame. zstd then answers
300 /// `ZSTD_e_continue` by resetting the session without waiting for the
301 /// jobs, so that is refused here first.
302 ended: bool,
303 /// A `ZSTD_e_end` call took all of its input: zstd made the frame's last
304 /// job. It would hand any new input to a worker as a job after the last
305 /// one, which waits forever, so that is refused here first.
306 last: bool,
307 /// The size pledged for the next frame is short (see `short`).
308 pledged_short: bool,
309 /// The `pending` frame is known to be compressed on the calling thread:
310 /// its size is known (pledged, or given whole with `ZSTD_e_end`), and is
311 /// short (zstd hands out no jobs for a frame of at most
312 /// `ZSTDMT_JOBSIZE_MIN`).
313 short: bool,
314 /// The `pending` frame may have handed jobs to the worker threads: it
315 /// took some input, and is not `short`.
316 jobs: bool,
317 /// A job failed. zstd up to 1.5.7 can then keep a job it had prepared but
318 /// not handed to a worker yet (`jobReady`), after clearing it: the next
319 /// multithreaded frame hands that empty job to a worker, which crashes.
320 /// That stays in the context's multithreading state, which only freeing
321 /// the context frees, so no other multithreaded frame is started on it.
322 broken: bool,
323 /// `StableOutBuffer` is enabled. Draining needs an output buffer of its
324 /// own, which zstd then refuses, so it is not allowed with workers.
325 stable_out: bool,
326}
327
328/// The `NbWorkers` zstd keeps when it accepts `value`: it clamps the value to
329/// its bounds rather than refusing it.
330fn accepted_workers(value: c_int) -> u32 {
331 // Safety: Just FFI
332 let bounds = unsafe {
333 zstd_sys::ZSTD_cParam_getBounds(
334 zstd_sys::ZSTD_cParameter::ZSTD_c_nbWorkers,
335 )
336 };
337 let upper = bounds.upperBound.max(0);
338 value.max(bounds.lowerBound).max(0).min(upper) as u32
339}
340
341/// Compression context
342///
343/// It is recommended to allocate a single context per thread and re-use it
344/// for many compression operations.
345///
346/// # Worker threads and leaks
347///
348/// With `CParameter::NbWorkers`, the jobs of a frame run on worker threads,
349/// which read the dictionary. Anything that abandons a frame in progress
350/// waits for them, dropping the context included (see
351/// [`CCtx::wait_for_workers()`]). A context that is leaked instead
352/// (`mem::forget`, `Box::leak`, a reference cycle) never waits: with a
353/// dictionary or prefix it only *borrows* ([`CCtx::ref_cdict()`],
354/// [`CCtx::ref_prefix()`]), the workers may then read it after it is
355/// dropped. Do not leak a context that is compressing with worker threads
356/// from borrowed data. A dictionary loaded with
357/// [`CCtx::load_dictionary()`] is copied, and leaks with the context.
358pub struct CCtx<'a>(
359 NonNull<zstd_sys::ZSTD_CCtx>,
360 PhantomData<&'a ()>,
361 Poison,
362 Workers,
363);
364
365impl Default for CCtx<'_> {
366 fn default() -> Self {
367 CCtx::create()
368 }
369}
370
371impl<'a> CCtx<'a> {
372 /// Tries to create a new context.
373 ///
374 /// Returns `None` if zstd returns a NULL pointer - may happen if allocation fails.
375 pub fn try_create() -> Option<Self> {
376 // Safety: Just FFI
377 Some(CCtx(
378 NonNull::new(unsafe { zstd_sys::ZSTD_createCCtx() })?,
379 PhantomData,
380 Poison::default(),
381 Workers::default(),
382 ))
383 }
384
385 /// Wrap `ZSTD_createCCtx`
386 ///
387 /// # Panics
388 ///
389 /// If zstd returns a NULL pointer.
390 pub fn create() -> Self {
391 Self::try_create()
392 .expect("zstd returned null pointer when creating new context")
393 }
394
395 /// Ends the session of a one-shot compression, and passes `res` through.
396 ///
397 /// zstd.h has these calls imply a reset, but most of them leave the stream
398 /// stage alone (and their source size behind as the pledged one), while
399 /// `ZSTD_compress2()` stays mid-frame when it fails. A later stream call
400 /// would then carry on from a state that still points at buffers and
401 /// dictionaries borrowed for that one call. So reset explicitly: the next
402 /// stream starts from scratch.
403 ///
404 /// Called as soon as zstd returns, inside the closure given to
405 /// `write_from`: that is the caller's code, which may panic afterwards.
406 fn finish_one_shot(&mut self, res: SafeResult) -> SafeResult {
407 self.reset(ResetDirective::SessionOnly).and(res)
408 }
409
410 /// Wraps the `ZSTD_compressCCtx()` function
411 pub fn compress<C: WriteBuf + ?Sized>(
412 &mut self,
413 dst: &mut C,
414 src: &[u8],
415 compression_level: CompressionLevel,
416 ) -> SafeResult {
417 // The one-shot calls run on the calling thread, but end by resetting
418 // the session (see `finish_one_shot`), and overwrite the parameters a
419 // multithreaded frame left open was started with: wait for its jobs
420 // first. That is done inside the closure, with the call it is for:
421 // `write_from` is the caller's code, and when it panics before
422 // running the closure, the frame is still in progress, and known as
423 // such.
424 // Safety: ZSTD_compressCCtx returns how many bytes were written.
425 unsafe {
426 dst.write_from(|buffer, capacity| {
427 self.drain();
428 let res = parse_code(zstd_sys::ZSTD_compressCCtx(
429 self.0.as_ptr(),
430 buffer,
431 capacity,
432 ptr_void(src),
433 src.len(),
434 compression_level,
435 ));
436 self.finish_one_shot(res)
437 })
438 }
439 }
440
441 /// Wraps the `ZSTD_compress2()` function.
442 pub fn compress2<C: WriteBuf + ?Sized>(
443 &mut self,
444 dst: &mut C,
445 src: &[u8],
446 ) -> SafeResult {
447 // What the call leaves behind is recorded as soon as zstd returns,
448 // inside the closure: `write_from` is the caller's code, and may
449 // panic after running it.
450 if !self.3.requested {
451 // Safety: ZSTD_compress2 returns how many bytes were written.
452 return unsafe {
453 dst.write_from(|buffer, capacity| {
454 let res = parse_code(zstd_sys::ZSTD_compress2(
455 self.0.as_ptr(),
456 buffer,
457 capacity,
458 ptr_void(src),
459 src.len(),
460 ));
461 // Unlike the others, this starts by resetting the
462 // session, which drops the pledged size, and ends it when
463 // it succeeds. When it fails, it stays mid-frame: make
464 // streaming calls wait for an explicit reset.
465 self.3.pledged_short = false;
466 self.2.clear();
467 self.2.record(res)
468 })
469 };
470 }
471
472 // With worker threads, a frame this leaves in progress must be one
473 // that can be waited for later, see `drain()`. `ZSTD_compress2()`
474 // runs its frame with stable buffers, and zstd would then refuse any
475 // other buffer: do what it does, but with ordinary ones. That costs
476 // nothing to a multithreaded frame, which copies its input and output
477 // anyway. A short frame, compressed on the calling thread, goes
478 // straight to the destination when it can hold the whole frame, and
479 // through a copy otherwise.
480 // Waiting for the frame in progress may find that one of its jobs
481 // failed: check `broken` after.
482 self.reset(ResetDirective::SessionOnly)?;
483 self.guard_broken()?;
484 // Safety: ZSTD_compressStream2 reports how many bytes it wrote in
485 // `output.pos`.
486 unsafe {
487 dst.write_from(|buffer, capacity| {
488 let mut output = zstd_sys::ZSTD_outBuffer {
489 dst: buffer,
490 size: capacity,
491 pos: 0,
492 };
493 let mut input = zstd_sys::ZSTD_inBuffer {
494 src: ptr_void(src),
495 size: src.len(),
496 pos: 0,
497 };
498 let raw = parse_code(zstd_sys::ZSTD_compressStream2(
499 self.0.as_ptr(),
500 &mut output,
501 &mut input,
502 zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
503 ));
504 self.track_frame(
505 raw,
506 zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
507 src.len(),
508 input.pos,
509 );
510 let res = match raw {
511 Ok(0) => Ok(output.pos),
512 // As `ZSTD_compress2()`: the frame stays in progress.
513 Ok(_) => Err(DST_SIZE_TOO_SMALL_ERROR),
514 Err(code) => Err(code),
515 };
516 self.2.record(res)
517 })
518 }
519 }
520
521 /// Wraps the `ZSTD_compress_usingDict()` function.
522 pub fn compress_using_dict<C: WriteBuf + ?Sized>(
523 &mut self,
524 dst: &mut C,
525 src: &[u8],
526 dict: &[u8],
527 compression_level: CompressionLevel,
528 ) -> SafeResult {
529 // Safety: ZSTD_compress_usingDict returns how many bytes were written.
530 unsafe {
531 dst.write_from(|buffer, capacity| {
532 // See `compress()`.
533 self.drain();
534 let res = parse_code(zstd_sys::ZSTD_compress_usingDict(
535 self.0.as_ptr(),
536 buffer,
537 capacity,
538 ptr_void(src),
539 src.len(),
540 ptr_void(dict),
541 dict.len(),
542 compression_level,
543 ));
544 self.finish_one_shot(res)
545 })
546 }
547 }
548
549 /// Wraps the `ZSTD_compress_usingCDict()` function.
550 pub fn compress_using_cdict<C: WriteBuf + ?Sized>(
551 &mut self,
552 dst: &mut C,
553 src: &[u8],
554 cdict: &CDict<'_>,
555 ) -> SafeResult {
556 // Safety: ZSTD_compress_usingCDict returns how many bytes were written.
557 unsafe {
558 dst.write_from(|buffer, capacity| {
559 // See `compress()`.
560 self.drain();
561 let res = parse_code(zstd_sys::ZSTD_compress_usingCDict(
562 self.0.as_ptr(),
563 buffer,
564 capacity,
565 ptr_void(src),
566 src.len(),
567 cdict.0.as_ptr(),
568 ));
569 self.finish_one_shot(res)
570 })
571 }
572 }
573
574 /// Initializes the context with the given compression level.
575 ///
576 /// This is equivalent to running:
577 /// * `reset()`
578 /// * `set_parameter(CompressionLevel, compression_level)`
579 ///
580 /// Abandons the current frame, if any. With worker threads, this first
581 /// waits for its jobs, see [`CCtx::wait_for_workers()`].
582 pub fn init(&mut self, compression_level: CompressionLevel) -> SafeResult {
583 // This also resets the session and unloads the dictionary.
584 self.drain();
585 self.2.clear();
586 // zstd drops the pledged size.
587 self.3.pledged_short = false;
588 // Safety: Just FFI
589 let code = unsafe {
590 zstd_sys::ZSTD_initCStream(self.0.as_ptr(), compression_level)
591 };
592 self.2.record(parse_code(code))
593 }
594
595 /// Wraps the `ZSTD_initCStream_srcSize()` function.
596 #[cfg(feature = "experimental")]
597 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
598 #[deprecated]
599 pub fn init_src_size(
600 &mut self,
601 compression_level: CompressionLevel,
602 pledged_src_size: u64,
603 ) -> SafeResult {
604 self.drain();
605 self.2.clear();
606 self.3.pledged_short = false;
607 // Safety: Just FFI
608 let code = unsafe {
609 zstd_sys::ZSTD_initCStream_srcSize(
610 self.0.as_ptr(),
611 compression_level as c_int,
612 pledged_src_size as c_ulonglong,
613 )
614 };
615 let res = parse_code(code);
616 if res.is_ok() {
617 // See `Workers::short`. Here, zstd takes 0 for an unknown size.
618 self.3.pledged_short = pledged_src_size != 0
619 && pledged_src_size <= ZSTDMT_JOBSIZE_MIN as u64;
620 }
621 res
622 }
623
624 /// Wraps the `ZSTD_initCStream_usingDict()` function.
625 #[cfg(feature = "experimental")]
626 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
627 #[deprecated]
628 pub fn init_using_dict(
629 &mut self,
630 dict: &[u8],
631 compression_level: CompressionLevel,
632 ) -> SafeResult {
633 self.drain();
634 self.2.clear();
635 // zstd drops the pledged size.
636 self.3.pledged_short = false;
637 // Safety: Just FFI
638 let code = unsafe {
639 zstd_sys::ZSTD_initCStream_usingDict(
640 self.0.as_ptr(),
641 ptr_void(dict),
642 dict.len(),
643 compression_level,
644 )
645 };
646 parse_code(code)
647 }
648
649 /// Wraps the `ZSTD_initCStream_usingCDict()` function.
650 ///
651 /// Dictionary must outlive the context.
652 ///
653 /// ```compile_fail,E0515
654 /// # #![allow(deprecated)]
655 /// fn compressor() -> zstd_safe::CCtx<'static> {
656 /// let cdict = zstd_safe::CDict::create(b"dictionary", 3);
657 /// let mut cctx = zstd_safe::CCtx::create();
658 /// cctx.init_using_cdict(&cdict).unwrap();
659 /// cctx // `cdict` would be dropped while `cctx` still points at it.
660 /// }
661 /// ```
662 #[cfg(feature = "experimental")]
663 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
664 #[deprecated]
665 pub fn init_using_cdict<'b>(&mut self, cdict: &'a CDict<'b>) -> SafeResult
666 where
667 'b: 'a, // Dictionary outlives the stream.
668 {
669 self.drain();
670 self.2.clear();
671 // zstd drops the pledged size.
672 self.3.pledged_short = false;
673 // Safety: Just FFI
674 let code = unsafe {
675 zstd_sys::ZSTD_initCStream_usingCDict(
676 self.0.as_ptr(),
677 cdict.0.as_ptr(),
678 )
679 };
680 self.2.record(parse_code(code))
681 }
682
683 /// Tries to load a dictionary.
684 ///
685 /// The dictionary content will be copied internally and does not need to be kept alive after
686 /// calling this function.
687 ///
688 /// If you need to use the same dictionary for multiple contexts, it may be more efficient to
689 /// create a `CDict` first, then loads that.
690 ///
691 /// The dictionary will apply to all compressed frames, until a new dictionary is set.
692 ///
693 /// Like zstd, this fails with a `stage_wrong` error while a frame is in
694 /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
695 pub fn load_dictionary(&mut self, dict: &[u8]) -> SafeResult {
696 self.guard_workers()?;
697 // Safety: Just FFI
698 parse_code(unsafe {
699 zstd_sys::ZSTD_CCtx_loadDictionary(
700 self.0.as_ptr(),
701 ptr_void(dict),
702 dict.len(),
703 )
704 })
705 }
706
707 /// Wraps the `ZSTD_CCtx_refCDict()` function.
708 ///
709 /// Dictionary must outlive the context. With worker threads, do not leak
710 /// the context, see [its documentation](CCtx#worker-threads-and-leaks).
711 ///
712 /// Like zstd, this fails with a `stage_wrong` error while a frame is in
713 /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
714 pub fn ref_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResult
715 where
716 'b: 'a,
717 {
718 self.guard_workers()?;
719 // Safety: Just FFI
720 parse_code(unsafe {
721 zstd_sys::ZSTD_CCtx_refCDict(self.0.as_ptr(), cdict.0.as_ptr())
722 })
723 }
724
725 /// Return to "no-dictionary" mode.
726 ///
727 /// This will disable any dictionary/prefix previously registered for future frames.
728 ///
729 /// Like zstd, this fails with a `stage_wrong` error while a frame is in
730 /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
731 pub fn disable_dictionary(&mut self) -> SafeResult {
732 self.guard_workers()?;
733 // Safety: Just FFI
734 parse_code(unsafe {
735 zstd_sys::ZSTD_CCtx_loadDictionary(
736 self.0.as_ptr(),
737 core::ptr::null(),
738 0,
739 )
740 })
741 }
742
743 /// Use some prefix as single-use dictionary for the next compressed frame.
744 ///
745 /// Just like a dictionary, decompression will need to be given the same prefix.
746 ///
747 /// This is best used if the "prefix" looks like the data to be compressed.
748 /// With worker threads, do not leak the context, see
749 /// [its documentation](CCtx#worker-threads-and-leaks).
750 ///
751 /// Like zstd, this fails with a `stage_wrong` error while a frame is in
752 /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
753 pub fn ref_prefix<'b>(&mut self, prefix: &'b [u8]) -> SafeResult
754 where
755 'b: 'a,
756 {
757 self.guard_workers()?;
758 // Safety: Just FFI
759 parse_code(unsafe {
760 zstd_sys::ZSTD_CCtx_refPrefix(
761 self.0.as_ptr(),
762 ptr_void(prefix),
763 prefix.len(),
764 )
765 })
766 }
767
768 /// Performs a step of a streaming compression operation.
769 ///
770 /// This will read some data from `input` and/or write some data to `output`.
771 ///
772 /// # Returns
773 ///
774 /// A hint for the "ideal" amount of input data to provide in the next call.
775 ///
776 /// This hint is only for performance purposes.
777 ///
778 /// Wraps the `ZSTD_compressStream()` function.
779 pub fn compress_stream<C: WriteBuf + ?Sized>(
780 &mut self,
781 output: &mut OutBuffer<'_, C>,
782 input: &mut InBuffer<'_>,
783 ) -> SafeResult {
784 use zstd_sys::ZSTD_EndDirective::ZSTD_e_continue;
785 self.2.guard()?;
786 if let Some(res) =
787 self.before_stream(input.pos == input.src.len(), ZSTD_e_continue)
788 {
789 // Any input is welcome.
790 return res.map(|_| Self::in_size());
791 }
792 let remaining = input.src.len().saturating_sub(input.pos);
793 let mut output = output.wrap();
794 let mut input = input.wrap();
795 // Safety: Just FFI
796 let code = unsafe {
797 zstd_sys::ZSTD_compressStream(
798 self.0.as_ptr(),
799 ptr_mut(&mut output),
800 ptr_mut(&mut input),
801 )
802 };
803 let taken = input.buf.pos.saturating_sub(input.parent.pos);
804 let res = output.check(parse_code(code));
805 let res = self.2.record(input.check(res));
806 self.track_frame(res, ZSTD_e_continue, remaining, taken);
807 res
808 }
809
810 /// Performs a step of a streaming compression operation.
811 ///
812 /// This will read some data from `input` and/or write some data to `output`.
813 ///
814 /// The `end_op` directive can be used to specify what to do after: nothing special, flush
815 /// internal buffers, or end the frame.
816 ///
817 /// # Returns
818 ///
819 /// An lower bound for the amount of data that still needs to be flushed out.
820 ///
821 /// This is useful when flushing or ending the frame: you need to keep calling this function
822 /// until it returns 0.
823 ///
824 /// Wraps the `ZSTD_compressStream2()` function.
825 pub fn compress_stream2<C: WriteBuf + ?Sized>(
826 &mut self,
827 output: &mut OutBuffer<'_, C>,
828 input: &mut InBuffer<'_>,
829 end_op: zstd_sys::ZSTD_EndDirective,
830 ) -> SafeResult {
831 self.2.guard()?;
832 if let Some(res) =
833 self.before_stream(input.pos == input.src.len(), end_op)
834 {
835 return res;
836 }
837 let remaining = input.src.len().saturating_sub(input.pos);
838 let mut output = output.wrap();
839 let mut input = input.wrap();
840 // Safety: Just FFI
841 let code = unsafe {
842 zstd_sys::ZSTD_compressStream2(
843 self.0.as_ptr(),
844 ptr_mut(&mut output),
845 ptr_mut(&mut input),
846 end_op,
847 )
848 };
849 let taken = input.buf.pos.saturating_sub(input.parent.pos);
850 let res = output.check(parse_code(code));
851 let res = self.2.record(input.check(res));
852 self.track_frame(res, end_op, remaining, taken);
853 res
854 }
855
856 /// Flush any intermediate buffer.
857 ///
858 /// To fully flush, you should keep calling this function until it returns `Ok(0)`.
859 ///
860 /// Wraps the `ZSTD_flushStream()` function.
861 pub fn flush_stream<C: WriteBuf + ?Sized>(
862 &mut self,
863 output: &mut OutBuffer<'_, C>,
864 ) -> SafeResult {
865 use zstd_sys::ZSTD_EndDirective::ZSTD_e_flush;
866 self.2.guard()?;
867 if let Some(res) = self.before_stream(true, ZSTD_e_flush) {
868 return res;
869 }
870 let mut output = output.wrap();
871 // Safety: Just FFI
872 let code = unsafe {
873 zstd_sys::ZSTD_flushStream(self.0.as_ptr(), ptr_mut(&mut output))
874 };
875 let res = self.2.record(output.check(parse_code(code)));
876 self.track_frame(res, ZSTD_e_flush, 0, 0);
877 res
878 }
879
880 /// Ends the stream.
881 ///
882 /// You should keep calling this function until it returns `Ok(0)`.
883 ///
884 /// Wraps the `ZSTD_endStream()` function.
885 pub fn end_stream<C: WriteBuf + ?Sized>(
886 &mut self,
887 output: &mut OutBuffer<'_, C>,
888 ) -> SafeResult {
889 use zstd_sys::ZSTD_EndDirective::ZSTD_e_end;
890 self.2.guard()?;
891 if let Some(res) = self.before_stream(true, ZSTD_e_end) {
892 return res;
893 }
894 let mut output = output.wrap();
895 // Safety: Just FFI
896 let code = unsafe {
897 zstd_sys::ZSTD_endStream(self.0.as_ptr(), ptr_mut(&mut output))
898 };
899 let res = self.2.record(output.check(parse_code(code)));
900 self.track_frame(res, ZSTD_e_end, 0, 0);
901 res
902 }
903
904 /// Decides whether a streaming call may reach zstd, see `Workers`.
905 ///
906 /// Returns what the call should return instead when it may not.
907 fn before_stream(
908 &self,
909 no_input: bool,
910 end_op: zstd_sys::ZSTD_EndDirective,
911 ) -> Option<SafeResult> {
912 use zstd_sys::ZSTD_EndDirective::{ZSTD_e_continue, ZSTD_e_end};
913 if !self.3.requested {
914 return None;
915 }
916 if self.3.broken {
917 return Some(Err(STAGE_WRONG_ERROR));
918 }
919 if self.3.pending {
920 if (self.3.ended && end_op == ZSTD_e_continue)
921 || (self.3.last && !no_input)
922 {
923 return Some(Err(STAGE_WRONG_ERROR));
924 }
925 } else if no_input && end_op != ZSTD_e_end {
926 // Starting a frame with nothing in it. If it was then ended,
927 // zstd up to 1.5.7 would hand an empty job to a worker, which its
928 // own wait on errors (`ZSTDMT_waitForAllJobsCompleted`) takes for
929 // done before the worker even starts. `drain()` does wait for it,
930 // so this is only a safeguard: wait for some input, nothing would
931 // have been written yet anyway. (A frame that starts with
932 // `ZSTD_e_end` takes the size of its input, so an empty one is
933 // compressed on the calling thread.)
934 return Some(Ok(0));
935 }
936 None
937 }
938
939 /// Records what a streaming call left open, see `Workers`.
940 ///
941 /// `given` is how much input the call was given, and `taken` how much of
942 /// it zstd took.
943 fn track_frame(
944 &mut self,
945 res: SafeResult,
946 end_op: zstd_sys::ZSTD_EndDirective,
947 given: usize,
948 taken: usize,
949 ) {
950 use zstd_sys::ZSTD_EndDirective::ZSTD_e_end;
951 // A pledged size is for the frame this call started or continued.
952 let pledged_short = core::mem::take(&mut self.3.pledged_short);
953 if !self.3.requested {
954 return;
955 }
956 if !self.3.pending {
957 // This call started the frame. Given whole, its size is the
958 // input's, whatever was pledged.
959 self.3.short = if end_op == ZSTD_e_end {
960 given <= ZSTDMT_JOBSIZE_MIN
961 } else {
962 pledged_short
963 };
964 }
965 self.3.jobs |= taken > 0 && !self.3.short;
966 match res {
967 Ok(0) if end_op == ZSTD_e_end => self.end_frame(),
968 Ok(_) => {
969 self.3.pending = true;
970 if end_op == ZSTD_e_end {
971 self.3.ended = true;
972 self.3.last |= taken == given;
973 }
974 }
975 // When a job failed, zstd waited for the others and reset the
976 // session (refused directives never get that far, nor does an
977 // output position past the buffer's end, which zstd would refuse
978 // while jobs are running: see `OutBuffer::wrap()`).
979 // Otherwise, there are no jobs. Either way, nothing is left to
980 // wait for.
981 Err(_) => {
982 self.3.broken |= self.3.jobs;
983 self.end_frame();
984 }
985 }
986 }
987
988 /// Records that no frame is in progress anymore.
989 fn end_frame(&mut self) {
990 self.3.pending = false;
991 self.3.ended = false;
992 self.3.last = false;
993 self.3.short = false;
994 self.3.jobs = false;
995 }
996
997 /// Waits for the jobs of the frame in progress, if any, so that it can
998 /// be abandoned.
999 ///
1000 /// Asking zstd to flush everything waits for every job to be done and
1001 /// its output flushed (here to a scratch buffer, and thrown away). This
1002 /// also hands a worker the job zstd prepared but could not hand out yet.
1003 /// That compresses what was left in zstd's input buffer as one more
1004 /// job: wasted work, but bounded by one job. Starting a new frame would
1005 /// avoid it, but zstd up to 1.5.7 can then hand that prepared job out
1006 /// after clearing it, and a worker crashes.
1007 fn drain(&mut self) {
1008 if !self.3.pending {
1009 return;
1010 }
1011 let mut scratch = [0u8; 4096];
1012 loop {
1013 let mut output = zstd_sys::ZSTD_outBuffer {
1014 dst: ptr_mut_void(&mut scratch[..]),
1015 size: scratch.len(),
1016 pos: 0,
1017 };
1018 let mut input = zstd_sys::ZSTD_inBuffer {
1019 src: ptr_void(&[]),
1020 size: 0,
1021 pos: 0,
1022 };
1023 // Safety: Just FFI, with buffers that live through the call.
1024 let code = unsafe {
1025 zstd_sys::ZSTD_compressStream2(
1026 self.0.as_ptr(),
1027 &mut output,
1028 &mut input,
1029 zstd_sys::ZSTD_EndDirective::ZSTD_e_flush,
1030 )
1031 };
1032 match parse_code(code) {
1033 Ok(0) => break,
1034 Ok(_) => continue,
1035 // A job failed: see `track_frame`.
1036 Err(_) => {
1037 self.3.broken |= self.3.jobs;
1038 break;
1039 }
1040 }
1041 }
1042 self.end_frame();
1043 }
1044
1045 /// Fails while a frame is in progress (zstd refuses these calls then).
1046 ///
1047 /// zstd up to 1.5.7 would also take them after the session was reset
1048 /// while worker threads were still running jobs, freeing what they read:
1049 /// every reset here waits for them first, and this keeps the error the
1050 /// same whatever the library does.
1051 fn guard_workers(&self) -> Result<(), ErrorCode> {
1052 if self.3.pending {
1053 return Err(STAGE_WRONG_ERROR);
1054 }
1055 Ok(())
1056 }
1057
1058 /// Fails if a multithreaded call failed on this context, see
1059 /// `Workers::broken`.
1060 fn guard_broken(&self) -> Result<(), ErrorCode> {
1061 if self.3.requested && self.3.broken {
1062 return Err(STAGE_WRONG_ERROR);
1063 }
1064 Ok(())
1065 }
1066
1067 /// Abandons the current frame, if any, and waits for the worker threads
1068 /// to be done with it.
1069 ///
1070 /// With `CParameter::NbWorkers`, the jobs of a frame run on worker
1071 /// threads, reading the dictionary. Anything that abandons a frame in
1072 /// progress waits for them first: a session reset (and `init()`, which
1073 /// implies one), a one-shot compression, and dropping the context. This
1074 /// is the same as `reset(SessionOnly)`. Waiting first compresses what was
1075 /// left of the frame's input as one more job, and throws the result away.
1076 ///
1077 /// After a job failed on a worker thread (for instance because the frame
1078 /// was given more than its pledged size), the context refuses any
1079 /// streaming call or `compress2()` while `NbWorkers` is set, and setting
1080 /// it again (with a `stage_wrong` error): zstd up to 1.5.7, the version
1081 /// bundled here, can leave a cleared job behind that the next
1082 /// multithreaded frame would hand to a worker, which crashes. Create a new
1083 /// context then, or set `NbWorkers` to 0.
1084 ///
1085 /// Once a `ZSTD_e_end` call took all of its input, a frame takes no more:
1086 /// that is refused with a `stage_wrong` error too, instead of the worker
1087 /// threads waiting forever for a job after the last one.
1088 pub fn wait_for_workers(&mut self) -> SafeResult {
1089 self.reset(ResetDirective::SessionOnly)
1090 }
1091
1092 /// Returns the size currently used by this context.
1093 ///
1094 /// This may change over time.
1095 pub fn sizeof(&self) -> usize {
1096 // Safety: Just FFI
1097 unsafe { zstd_sys::ZSTD_sizeof_CCtx(self.0.as_ptr()) }
1098 }
1099
1100 /// Resets the state of the context.
1101 ///
1102 /// Depending on the reset mode, it can reset the session, the parameters, or both.
1103 ///
1104 /// Resetting the session abandons the frame in progress, if any: with
1105 /// worker threads, this first waits for its jobs, see
1106 /// [`CCtx::wait_for_workers()`]. Like zstd, resetting only the parameters
1107 /// fails with a `stage_wrong` error while a frame is in progress.
1108 ///
1109 /// Wraps the `ZSTD_CCtx_reset()` function.
1110 pub fn reset(&mut self, reset: ResetDirective) -> SafeResult {
1111 let resets_parameters = !matches!(reset, ResetDirective::SessionOnly);
1112 if reset.resets_session() {
1113 self.drain();
1114 } else {
1115 self.guard_workers()?;
1116 }
1117 let resets_session = reset.resets_session();
1118 // Safety: Just FFI
1119 let res = parse_code(unsafe {
1120 zstd_sys::ZSTD_CCtx_reset(self.0.as_ptr(), reset.as_sys())
1121 });
1122 if res.is_ok() && resets_session {
1123 self.2.clear();
1124 self.3.pledged_short = false;
1125 }
1126 if res.is_ok() && resets_parameters {
1127 self.3.requested = false;
1128 self.3.stable_out = false;
1129 }
1130 res
1131 }
1132
1133 /// Sets a compression parameter.
1134 ///
1135 /// Some of these parameters need to be set during de-compression as well.
1136 ///
1137 /// Like zstd, changing `NbWorkers` fails with a `stage_wrong` error while
1138 /// a frame is in progress, and so does setting it to a non-zero value
1139 /// after a multithreaded call failed (see [`CCtx::wait_for_workers()`]).
1140 /// `NbWorkers` and `StableOutBuffer` cannot be used together.
1141 pub fn set_parameter(&mut self, param: CParameter) -> SafeResult {
1142 match param {
1143 CParameter::NbWorkers(workers) => {
1144 // zstd would resize the job table the old jobs still use.
1145 self.guard_workers()?;
1146 // What zstd will make of the value, see `accepted_workers`.
1147 if accepted_workers(workers as c_int) != 0 {
1148 if self.3.broken {
1149 return Err(STAGE_WRONG_ERROR);
1150 }
1151 #[cfg(feature = "experimental")]
1152 if self.3.stable_out {
1153 return Err(PARAMETER_UNSUPPORTED_ERROR);
1154 }
1155 }
1156 }
1157 // Waiting for the workers needs an output buffer of its own.
1158 #[cfg(feature = "experimental")]
1159 CParameter::StableOutBuffer(true) if self.3.requested => {
1160 return Err(PARAMETER_UNSUPPORTED_ERROR);
1161 }
1162 _ => (),
1163 }
1164 // TODO: Until bindgen properly generates a binding for this, we'll need to do it here.
1165
1166 #[cfg(feature = "experimental")]
1167 use zstd_sys::ZSTD_cParameter::{
1168 ZSTD_c_experimentalParam1 as ZSTD_c_rsyncable,
1169 ZSTD_c_experimentalParam10 as ZSTD_c_stableOutBuffer,
1170 ZSTD_c_experimentalParam11 as ZSTD_c_blockDelimiters,
1171 ZSTD_c_experimentalParam12 as ZSTD_c_validateSequences,
1172 ZSTD_c_experimentalParam13 as ZSTD_c_useBlockSplitter,
1173 ZSTD_c_experimentalParam14 as ZSTD_c_useRowMatchFinder,
1174 ZSTD_c_experimentalParam15 as ZSTD_c_deterministicRefPrefix,
1175 ZSTD_c_experimentalParam16 as ZSTD_c_prefetchCDictTables,
1176 ZSTD_c_experimentalParam17 as ZSTD_c_enableSeqProducerFallback,
1177 ZSTD_c_experimentalParam18 as ZSTD_c_maxBlockSize,
1178 ZSTD_c_experimentalParam19 as ZSTD_c_searchForExternalRepcodes,
1179 ZSTD_c_experimentalParam2 as ZSTD_c_format,
1180 ZSTD_c_experimentalParam3 as ZSTD_c_forceMaxWindow,
1181 ZSTD_c_experimentalParam4 as ZSTD_c_forceAttachDict,
1182 ZSTD_c_experimentalParam5 as ZSTD_c_literalCompressionMode,
1183 ZSTD_c_experimentalParam7 as ZSTD_c_srcSizeHint,
1184 ZSTD_c_experimentalParam8 as ZSTD_c_enableDedicatedDictSearch,
1185 ZSTD_c_experimentalParam9 as ZSTD_c_stableInBuffer,
1186 };
1187
1188 use zstd_sys::ZSTD_cParameter::*;
1189 use CParameter::*;
1190
1191 let (param, value) = match param {
1192 #[cfg(feature = "experimental")]
1193 RSyncable(rsyncable) => (ZSTD_c_rsyncable, rsyncable as c_int),
1194 #[cfg(feature = "experimental")]
1195 Format(format) => (ZSTD_c_format, format as c_int),
1196 #[cfg(feature = "experimental")]
1197 ForceMaxWindow(force) => (ZSTD_c_forceMaxWindow, force as c_int),
1198 #[cfg(feature = "experimental")]
1199 ForceAttachDict(force) => (ZSTD_c_forceAttachDict, force as c_int),
1200 #[cfg(feature = "experimental")]
1201 LiteralCompressionMode(mode) => {
1202 (ZSTD_c_literalCompressionMode, mode as c_int)
1203 }
1204 #[cfg(feature = "experimental")]
1205 SrcSizeHint(value) => (ZSTD_c_srcSizeHint, value as c_int),
1206 #[cfg(feature = "experimental")]
1207 EnableDedicatedDictSearch(enable) => {
1208 (ZSTD_c_enableDedicatedDictSearch, enable as c_int)
1209 }
1210 // In stable mode zstd keeps reading from the `InBuffer` of one
1211 // call during `flush_stream`/`end_stream`, but the slice is only
1212 // borrowed for that one call: the safe API cannot uphold this.
1213 #[cfg(feature = "experimental")]
1214 StableInBuffer(true) => return Err(PARAMETER_UNSUPPORTED_ERROR),
1215 #[cfg(feature = "experimental")]
1216 StableInBuffer(false) => (ZSTD_c_stableInBuffer, 0),
1217 #[cfg(feature = "experimental")]
1218 StableOutBuffer(stable) => {
1219 (ZSTD_c_stableOutBuffer, stable as c_int)
1220 }
1221 #[cfg(feature = "experimental")]
1222 BlockDelimiters(value) => (ZSTD_c_blockDelimiters, value as c_int),
1223 #[cfg(feature = "experimental")]
1224 ValidateSequences(validate) => {
1225 (ZSTD_c_validateSequences, validate as c_int)
1226 }
1227 #[cfg(feature = "experimental")]
1228 UseBlockSplitter(split) => {
1229 (ZSTD_c_useBlockSplitter, split as c_int)
1230 }
1231 #[cfg(feature = "experimental")]
1232 UseRowMatchFinder(mode) => {
1233 (ZSTD_c_useRowMatchFinder, mode as c_int)
1234 }
1235 #[cfg(feature = "experimental")]
1236 DeterministicRefPrefix(deterministic) => {
1237 (ZSTD_c_deterministicRefPrefix, deterministic as c_int)
1238 }
1239 #[cfg(feature = "experimental")]
1240 PrefetchCDictTables(prefetch) => {
1241 (ZSTD_c_prefetchCDictTables, prefetch as c_int)
1242 }
1243 #[cfg(feature = "experimental")]
1244 EnableSeqProducerFallback(enable) => {
1245 (ZSTD_c_enableSeqProducerFallback, enable as c_int)
1246 }
1247 #[cfg(feature = "experimental")]
1248 MaxBlockSize(value) => (ZSTD_c_maxBlockSize, value as c_int),
1249 #[cfg(feature = "experimental")]
1250 SearchForExternalRepcodes(value) => {
1251 (ZSTD_c_searchForExternalRepcodes, value as c_int)
1252 }
1253 TargetCBlockSize(value) => {
1254 (ZSTD_c_targetCBlockSize, value as c_int)
1255 }
1256 CompressionLevel(level) => (ZSTD_c_compressionLevel, level),
1257 WindowLog(value) => (ZSTD_c_windowLog, value as c_int),
1258 HashLog(value) => (ZSTD_c_hashLog, value as c_int),
1259 ChainLog(value) => (ZSTD_c_chainLog, value as c_int),
1260 SearchLog(value) => (ZSTD_c_searchLog, value as c_int),
1261 MinMatch(value) => (ZSTD_c_minMatch, value as c_int),
1262 TargetLength(value) => (ZSTD_c_targetLength, value as c_int),
1263 Strategy(strategy) => (ZSTD_c_strategy, strategy as c_int),
1264 EnableLongDistanceMatching(flag) => {
1265 (ZSTD_c_enableLongDistanceMatching, flag as c_int)
1266 }
1267 LdmHashLog(value) => (ZSTD_c_ldmHashLog, value as c_int),
1268 LdmMinMatch(value) => (ZSTD_c_ldmMinMatch, value as c_int),
1269 LdmBucketSizeLog(value) => {
1270 (ZSTD_c_ldmBucketSizeLog, value as c_int)
1271 }
1272 LdmHashRateLog(value) => (ZSTD_c_ldmHashRateLog, value as c_int),
1273 ContentSizeFlag(flag) => (ZSTD_c_contentSizeFlag, flag as c_int),
1274 ChecksumFlag(flag) => (ZSTD_c_checksumFlag, flag as c_int),
1275 DictIdFlag(flag) => (ZSTD_c_dictIDFlag, flag as c_int),
1276
1277 NbWorkers(value) => (ZSTD_c_nbWorkers, value as c_int),
1278
1279 JobSize(value) => (ZSTD_c_jobSize, value as c_int),
1280
1281 OverlapSizeLog(value) => (ZSTD_c_overlapLog, value as c_int),
1282 };
1283
1284 // Safety: Just FFI
1285 let res = parse_code(unsafe {
1286 zstd_sys::ZSTD_CCtx_setParameter(self.0.as_ptr(), param, value)
1287 });
1288 if res.is_ok() && matches!(param, ZSTD_c_nbWorkers) {
1289 let workers = accepted_workers(value) != 0;
1290 self.3.requested = workers;
1291 self.3.ever |= workers;
1292 }
1293 #[cfg(feature = "experimental")]
1294 if res.is_ok() && matches!(param, ZSTD_c_stableOutBuffer) {
1295 self.3.stable_out = value != 0;
1296 }
1297 res
1298 }
1299
1300 /// Guarantee that the input size will be this value.
1301 ///
1302 /// If given `None`, assumes the size is unknown.
1303 ///
1304 /// Unless explicitly disabled, this will cause the size to be written in the compressed frame
1305 /// header.
1306 ///
1307 /// If the actual data given to compress has a different size, an error will be returned.
1308 pub fn set_pledged_src_size(
1309 &mut self,
1310 pledged_src_size: Option<u64>,
1311 ) -> SafeResult {
1312 // Safety: Just FFI
1313 let res = parse_code(unsafe {
1314 zstd_sys::ZSTD_CCtx_setPledgedSrcSize(
1315 self.0.as_ptr(),
1316 pledged_src_size.unwrap_or(CONTENTSIZE_UNKNOWN) as c_ulonglong,
1317 )
1318 });
1319 if res.is_ok() {
1320 // See `Workers::short`.
1321 self.3.pledged_short = matches!(
1322 pledged_src_size,
1323 Some(size) if size <= ZSTDMT_JOBSIZE_MIN as u64
1324 );
1325 }
1326 res
1327 }
1328
1329 /// Fails if the tables of this context may not be the ones its applied
1330 /// parameters describe.
1331 ///
1332 /// Starting a multi-threaded frame overwrites the applied parameters with
1333 /// those of the workers, but leaves the context's own stage and workspace
1334 /// as the last single-threaded frame left them. If that frame was
1335 /// abandoned before its first block, zstd still accepts the calls that
1336 /// work on this context directly, and overruns a workspace that was sized
1337 /// for other parameters. The applied parameters cannot be queried, so
1338 /// refuse these calls as soon as a multi-threaded frame could have been
1339 /// started.
1340 #[cfg(feature = "experimental")]
1341 fn guard_own_tables(&self) -> Result<(), ErrorCode> {
1342 if self.3.ever {
1343 return Err(STAGE_WRONG_ERROR);
1344 }
1345 Ok(())
1346 }
1347
1348 /// Wraps the `ZSTD_getBlockSize()` function.
1349 #[cfg(feature = "experimental")]
1350 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
1351 pub fn get_block_size(&self) -> usize {
1352 // Safety: Just FFI
1353 unsafe { zstd_sys::ZSTD_getBlockSize(self.0.as_ptr()) }
1354 }
1355
1356 /// Wraps the `ZSTD_compressBlock()` function.
1357 ///
1358 /// Returns an error once `NbWorkers` was set to a non-zero value on this
1359 /// context.
1360 ///
1361 /// # Safety
1362 ///
1363 /// `src` becomes this context's history window, so it must stay allocated and unmodified until
1364 /// the next call to `compress_block` on this context (or until this context is dropped), as the
1365 /// following block is compressed against it.
1366 #[cfg(feature = "experimental")]
1367 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
1368 pub unsafe fn compress_block<C: WriteBuf + ?Sized>(
1369 &mut self,
1370 dst: &mut C,
1371 src: &[u8],
1372 ) -> SafeResult {
1373 self.guard_own_tables()?;
1374 // Safety: ZSTD_compressBlock returns the number of bytes written.
1375 unsafe {
1376 dst.write_from(|buffer, capacity| {
1377 parse_code(zstd_sys::ZSTD_compressBlock(
1378 self.0.as_ptr(),
1379 buffer,
1380 capacity,
1381 ptr_void(src),
1382 src.len(),
1383 ))
1384 })
1385 }
1386 }
1387
1388 /// Returns the recommended input buffer size.
1389 ///
1390 /// Using this size may result in minor performance boost.
1391 pub fn in_size() -> usize {
1392 // Safety: Just FFI
1393 unsafe { zstd_sys::ZSTD_CStreamInSize() }
1394 }
1395
1396 /// Returns the recommended output buffer size.
1397 ///
1398 /// Using this may result in minor performance boost.
1399 pub fn out_size() -> usize {
1400 // Safety: Just FFI
1401 unsafe { zstd_sys::ZSTD_CStreamOutSize() }
1402 }
1403
1404 /// Use a shared thread pool for this context.
1405 ///
1406 /// Thread pool must outlive the context.
1407 #[cfg(all(feature = "experimental", feature = "zstdmt"))]
1408 #[cfg_attr(
1409 feature = "doc-cfg",
1410 doc(cfg(all(feature = "experimental", feature = "zstdmt")))
1411 )]
1412 pub fn ref_thread_pool<'b>(&mut self, pool: &'b ThreadPool) -> SafeResult
1413 where
1414 'b: 'a,
1415 {
1416 parse_code(unsafe {
1417 zstd_sys::ZSTD_CCtx_refThreadPool(self.0.as_ptr(), pool.0.as_ptr())
1418 })
1419 }
1420
1421 /// Return to using a private thread pool for this context.
1422 #[cfg(all(feature = "experimental", feature = "zstdmt"))]
1423 #[cfg_attr(
1424 feature = "doc-cfg",
1425 doc(cfg(all(feature = "experimental", feature = "zstdmt")))
1426 )]
1427 pub fn disable_thread_pool(&mut self) -> SafeResult {
1428 parse_code(unsafe {
1429 zstd_sys::ZSTD_CCtx_refThreadPool(
1430 self.0.as_ptr(),
1431 core::ptr::null_mut(),
1432 )
1433 })
1434 }
1435
1436 #[cfg(feature = "experimental")]
1437 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
1438 pub fn get_frame_progression(&self) -> FrameProgression {
1439 // Safety: Just FFI
1440 unsafe { zstd_sys::ZSTD_getFrameProgression(self.0.as_ptr()) }
1441 }
1442}
1443
1444impl<'a> Drop for CCtx<'a> {
1445 fn drop(&mut self) {
1446 // zstd up to 1.5.7 frees the dictionary before it stops the worker
1447 // threads, and does not stop a shared pool's at all: wait for the
1448 // jobs of the frame in progress first.
1449 self.drain();
1450 // Safety: Just FFI
1451 unsafe {
1452 zstd_sys::ZSTD_freeCCtx(self.0.as_ptr());
1453 }
1454 }
1455}
1456
1457unsafe impl Send for CCtx<'_> {}
1458// Non thread-safe methods already take `&mut self`, so it's fine to implement Sync here.
1459unsafe impl Sync for CCtx<'_> {}
1460
1461unsafe fn c_char_to_str(text: *const c_char) -> &'static str {
1462 core::ffi::CStr::from_ptr(text)
1463 .to_str()
1464 .expect("bad error message from zstd")
1465}
1466
1467/// Returns the error string associated with an error code.
1468pub fn get_error_name(code: usize) -> &'static str {
1469 unsafe {
1470 // Safety: assumes ZSTD returns a well-formed utf8 string.
1471 let name = zstd_sys::ZSTD_getErrorName(code);
1472 c_char_to_str(name)
1473 }
1474}
1475
1476/// A Decompression Context.
1477///
1478/// The lifetime references the potential dictionary used for this context.
1479///
1480/// If no dictionary was used, it will most likely be `'static`.
1481///
1482/// Same as `DStream`.
1483pub struct DCtx<'a>(
1484 NonNull<zstd_sys::ZSTD_DCtx>,
1485 PhantomData<&'a ()>,
1486 Poison,
1487 DState,
1488);
1489
1490/// What a `DCtx` remembers about its own use.
1491#[derive(Clone, Copy, Debug, Default)]
1492struct DState {
1493 /// A streaming (or block) call ran since the session was last reset, so
1494 /// a stream may be open, see `finish_one_shot`.
1495 streamed: bool,
1496}
1497
1498impl Default for DCtx<'_> {
1499 fn default() -> Self {
1500 DCtx::create()
1501 }
1502}
1503
1504impl<'a> DCtx<'a> {
1505 /// Try to create a new decompression context.
1506 ///
1507 /// Returns `None` if the operation failed (for example, not enough memory).
1508 pub fn try_create() -> Option<Self> {
1509 Some(DCtx(
1510 NonNull::new(unsafe { zstd_sys::ZSTD_createDCtx() })?,
1511 PhantomData,
1512 Poison::default(),
1513 DState::default(),
1514 ))
1515 }
1516
1517 /// Creates a new decoding context.
1518 ///
1519 /// # Panics
1520 ///
1521 /// If the context creation fails.
1522 pub fn create() -> Self {
1523 Self::try_create()
1524 .expect("zstd returned null pointer when creating new context")
1525 }
1526
1527 /// Ends the session of a one-shot decompression, and passes `res` through.
1528 ///
1529 /// zstd.h has these calls imply a reset, but they leave the stream stage
1530 /// alone. A stream they interrupted would then carry on from a state that
1531 /// still points at buffers and dictionaries borrowed for that one call. So
1532 /// reset explicitly: the next stream starts from scratch.
1533 ///
1534 /// Only an open stream can carry on, though: a new one starts by setting
1535 /// everything up again from the context's own dictionary. So when no
1536 /// streaming call ran since the last reset, there is nothing to end, and
1537 /// skipping the reset saves a call per frame - which shows on tiny ones.
1538 ///
1539 /// Only the check is inlined: it runs once per frame.
1540 ///
1541 /// Called as soon as zstd returns, inside the closure given to
1542 /// `write_from`: that is the caller's code, which may panic afterwards.
1543 #[inline]
1544 fn finish_one_shot(&mut self, res: SafeResult) -> SafeResult {
1545 if self.3.streamed || self.2.guard().is_err() {
1546 self.reset_after_one_shot(res)
1547 } else {
1548 res
1549 }
1550 }
1551
1552 #[cold]
1553 #[inline(never)]
1554 fn reset_after_one_shot(&mut self, res: SafeResult) -> SafeResult {
1555 self.reset(ResetDirective::SessionOnly).and(res)
1556 }
1557
1558 /// Fully decompress the given frame.
1559 ///
1560 /// This decompress an entire frame in-memory. If you can have enough memory to store both the
1561 /// input and output buffer, then it may be faster that streaming decompression.
1562 ///
1563 /// Wraps the `ZSTD_decompressDCtx()` function.
1564 pub fn decompress<C: WriteBuf + ?Sized>(
1565 &mut self,
1566 dst: &mut C,
1567 src: &[u8],
1568 ) -> SafeResult {
1569 unsafe {
1570 dst.write_from(|buffer, capacity| {
1571 let res = parse_code(zstd_sys::ZSTD_decompressDCtx(
1572 self.0.as_ptr(),
1573 buffer,
1574 capacity,
1575 ptr_void(src),
1576 src.len(),
1577 ));
1578 self.finish_one_shot(res)
1579 })
1580 }
1581 }
1582
1583 /// Fully decompress the given frame using a dictionary.
1584 ///
1585 /// Dictionary must be identical to the one used during compression.
1586 ///
1587 /// If you plan on using the same dictionary multiple times, it is faster to create a `DDict`
1588 /// first and use `decompress_using_ddict`.
1589 ///
1590 /// Wraps `ZSTD_decompress_usingDict`
1591 pub fn decompress_using_dict<C: WriteBuf + ?Sized>(
1592 &mut self,
1593 dst: &mut C,
1594 src: &[u8],
1595 dict: &[u8],
1596 ) -> SafeResult {
1597 unsafe {
1598 dst.write_from(|buffer, capacity| {
1599 let res = parse_code(zstd_sys::ZSTD_decompress_usingDict(
1600 self.0.as_ptr(),
1601 buffer,
1602 capacity,
1603 ptr_void(src),
1604 src.len(),
1605 ptr_void(dict),
1606 dict.len(),
1607 ));
1608 self.finish_one_shot(res)
1609 })
1610 }
1611 }
1612
1613 /// Fully decompress the given frame using a dictionary.
1614 ///
1615 /// Dictionary must be identical to the one used during compression.
1616 ///
1617 /// Wraps the `ZSTD_decompress_usingDDict()` function.
1618 pub fn decompress_using_ddict<C: WriteBuf + ?Sized>(
1619 &mut self,
1620 dst: &mut C,
1621 src: &[u8],
1622 ddict: &DDict<'_>,
1623 ) -> SafeResult {
1624 unsafe {
1625 dst.write_from(|buffer, capacity| {
1626 let res = parse_code(zstd_sys::ZSTD_decompress_usingDDict(
1627 self.0.as_ptr(),
1628 buffer,
1629 capacity,
1630 ptr_void(src),
1631 src.len(),
1632 ddict.0.as_ptr(),
1633 ));
1634 self.finish_one_shot(res)
1635 })
1636 }
1637 }
1638
1639 /// Initializes an existing `DStream` for decompression.
1640 ///
1641 /// This is equivalent to calling:
1642 /// * `reset(SessionOnly)`
1643 /// * `disable_dictionary()`
1644 ///
1645 /// Wraps the `ZSTD_initCStream()` function.
1646 pub fn init(&mut self) -> SafeResult {
1647 self.2.clear();
1648 let code = unsafe { zstd_sys::ZSTD_initDStream(self.0.as_ptr()) };
1649 self.2.record(parse_code(code))
1650 }
1651
1652 /// Wraps the `ZSTD_initDStream_usingDict()` function.
1653 #[cfg(feature = "experimental")]
1654 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
1655 #[deprecated]
1656 pub fn init_using_dict(&mut self, dict: &[u8]) -> SafeResult {
1657 self.2.clear();
1658 let code = unsafe {
1659 zstd_sys::ZSTD_initDStream_usingDict(
1660 self.0.as_ptr(),
1661 ptr_void(dict),
1662 dict.len(),
1663 )
1664 };
1665 parse_code(code)
1666 }
1667
1668 /// Wraps the `ZSTD_initDStream_usingDDict()` function.
1669 ///
1670 /// Dictionary must outlive the context.
1671 ///
1672 /// ```compile_fail,E0515
1673 /// # #![allow(deprecated)]
1674 /// fn decompressor() -> zstd_safe::DCtx<'static> {
1675 /// let ddict = zstd_safe::DDict::create(b"dictionary");
1676 /// let mut dctx = zstd_safe::DCtx::create();
1677 /// dctx.init_using_ddict(&ddict).unwrap();
1678 /// dctx // `ddict` would be dropped while `dctx` still points at it.
1679 /// }
1680 /// ```
1681 #[cfg(feature = "experimental")]
1682 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
1683 #[deprecated]
1684 pub fn init_using_ddict<'b>(&mut self, ddict: &'a DDict<'b>) -> SafeResult
1685 where
1686 'b: 'a,
1687 {
1688 self.2.clear();
1689 // Safety: Just FFI
1690 let code = unsafe {
1691 zstd_sys::ZSTD_initDStream_usingDDict(
1692 self.0.as_ptr(),
1693 ddict.0.as_ptr(),
1694 )
1695 };
1696 self.2.record(parse_code(code))
1697 }
1698
1699 /// Resets the state of the context.
1700 ///
1701 /// Depending on the reset mode, it can reset the session, the parameters, or both.
1702 ///
1703 /// Wraps the `ZSTD_DCtx_reset()` function.
1704 pub fn reset(&mut self, reset: ResetDirective) -> SafeResult {
1705 let resets_session = reset.resets_session();
1706 let res = parse_code(unsafe {
1707 zstd_sys::ZSTD_DCtx_reset(self.0.as_ptr(), reset.as_sys())
1708 });
1709 if res.is_ok() && resets_session {
1710 self.2.clear();
1711 self.3.streamed = false;
1712 }
1713 res
1714 }
1715
1716 /// Loads a dictionary.
1717 ///
1718 /// This will let this context decompress frames that were compressed using this dictionary.
1719 ///
1720 /// The dictionary content will be copied internally and does not need to be kept alive after
1721 /// calling this function.
1722 ///
1723 /// If you need to use the same dictionary for multiple contexts, it may be more efficient to
1724 /// create a `DDict` first, then loads that.
1725 ///
1726 /// The dictionary will apply to all future frames, until a new dictionary is set.
1727 pub fn load_dictionary(&mut self, dict: &[u8]) -> SafeResult {
1728 parse_code(unsafe {
1729 zstd_sys::ZSTD_DCtx_loadDictionary(
1730 self.0.as_ptr(),
1731 ptr_void(dict),
1732 dict.len(),
1733 )
1734 })
1735 }
1736
1737 /// Return to "no-dictionary" mode.
1738 ///
1739 /// This will disable any dictionary/prefix previously registered for future frames.
1740 pub fn disable_dictionary(&mut self) -> SafeResult {
1741 parse_code(unsafe {
1742 zstd_sys::ZSTD_DCtx_loadDictionary(
1743 self.0.as_ptr(),
1744 core::ptr::null(),
1745 0,
1746 )
1747 })
1748 }
1749
1750 /// References a dictionary.
1751 ///
1752 /// This will let this context decompress frames compressed with the same dictionary.
1753 ///
1754 /// It will apply to all frames decompressed by this context (until a new dictionary is set).
1755 ///
1756 /// Wraps the `ZSTD_DCtx_refDDict()` function.
1757 pub fn ref_ddict<'b>(&mut self, ddict: &DDict<'b>) -> SafeResult
1758 where
1759 'b: 'a,
1760 {
1761 parse_code(unsafe {
1762 zstd_sys::ZSTD_DCtx_refDDict(self.0.as_ptr(), ddict.0.as_ptr())
1763 })
1764 }
1765
1766 /// Use some prefix as single-use dictionary for the next frame.
1767 ///
1768 /// Just like a dictionary, this only works if compression was done with the same prefix.
1769 ///
1770 /// But unlike a dictionary, this only applies to the next frame.
1771 ///
1772 /// Wraps the `ZSTD_DCtx_refPrefix()` function.
1773 pub fn ref_prefix<'b>(&mut self, prefix: &'b [u8]) -> SafeResult
1774 where
1775 'b: 'a,
1776 {
1777 parse_code(unsafe {
1778 zstd_sys::ZSTD_DCtx_refPrefix(
1779 self.0.as_ptr(),
1780 ptr_void(prefix),
1781 prefix.len(),
1782 )
1783 })
1784 }
1785
1786 /// Sets a decompression parameter.
1787 pub fn set_parameter(&mut self, param: DParameter) -> SafeResult {
1788 #[cfg(feature = "experimental")]
1789 use zstd_sys::ZSTD_dParameter::{
1790 ZSTD_d_experimentalParam1 as ZSTD_d_format,
1791 ZSTD_d_experimentalParam2 as ZSTD_d_stableOutBuffer,
1792 ZSTD_d_experimentalParam3 as ZSTD_d_forceIgnoreChecksum,
1793 ZSTD_d_experimentalParam4 as ZSTD_d_refMultipleDDicts,
1794 };
1795
1796 use zstd_sys::ZSTD_dParameter::*;
1797 use DParameter::*;
1798
1799 let (param, value) = match param {
1800 #[cfg(feature = "experimental")]
1801 Format(format) => (ZSTD_d_format, format as c_int),
1802 #[cfg(feature = "experimental")]
1803 StableOutBuffer(stable) => {
1804 (ZSTD_d_stableOutBuffer, stable as c_int)
1805 }
1806 #[cfg(feature = "experimental")]
1807 ForceIgnoreChecksum(force) => {
1808 (ZSTD_d_forceIgnoreChecksum, force as c_int)
1809 }
1810 #[cfg(feature = "experimental")]
1811 RefMultipleDDicts(value) => {
1812 (ZSTD_d_refMultipleDDicts, value as c_int)
1813 }
1814
1815 WindowLogMax(value) => (ZSTD_d_windowLogMax, value as c_int),
1816 };
1817
1818 parse_code(unsafe {
1819 zstd_sys::ZSTD_DCtx_setParameter(self.0.as_ptr(), param, value)
1820 })
1821 }
1822
1823 /// Performs a step of a streaming decompression operation.
1824 ///
1825 /// This will read some data from `input` and/or write some data to `output`.
1826 ///
1827 /// # Returns
1828 ///
1829 /// * `Ok(0)` if the current frame just finished decompressing successfully.
1830 /// * `Ok(hint)` with a hint for the "ideal" amount of input data to provide in the next call.
1831 /// Can be safely ignored.
1832 ///
1833 /// Wraps the `ZSTD_decompressStream()` function.
1834 pub fn decompress_stream<C: WriteBuf + ?Sized>(
1835 &mut self,
1836 output: &mut OutBuffer<'_, C>,
1837 input: &mut InBuffer<'_>,
1838 ) -> SafeResult {
1839 self.2.guard()?;
1840 self.3.streamed = true;
1841 let mut output = output.wrap();
1842 let mut input = input.wrap();
1843 let code = unsafe {
1844 zstd_sys::ZSTD_decompressStream(
1845 self.0.as_ptr(),
1846 ptr_mut(&mut output),
1847 ptr_mut(&mut input),
1848 )
1849 };
1850 let res = output.check(parse_code(code));
1851 self.2.record(input.check(res))
1852 }
1853
1854 /// Wraps the `ZSTD_DStreamInSize()` function.
1855 ///
1856 /// Returns a hint for the recommended size of the input buffer for decompression.
1857 pub fn in_size() -> usize {
1858 unsafe { zstd_sys::ZSTD_DStreamInSize() }
1859 }
1860
1861 /// Wraps the `ZSTD_DStreamOutSize()` function.
1862 ///
1863 /// Returns a hint for the recommended size of the output buffer for decompression.
1864 pub fn out_size() -> usize {
1865 unsafe { zstd_sys::ZSTD_DStreamOutSize() }
1866 }
1867
1868 /// Wraps the `ZSTD_sizeof_DCtx()` function.
1869 pub fn sizeof(&self) -> usize {
1870 unsafe { zstd_sys::ZSTD_sizeof_DCtx(self.0.as_ptr()) }
1871 }
1872
1873 /// Wraps the `ZSTD_decompressBlock()` function.
1874 ///
1875 /// # Safety
1876 ///
1877 /// The bytes written to `dst` become this context's history window, so `dst` must stay
1878 /// allocated and unmodified until the next call to `decompress_block` or `insert_block` on this
1879 /// context (or until this context is dropped), as the following block is decoded against it.
1880 #[cfg(feature = "experimental")]
1881 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
1882 pub unsafe fn decompress_block<C: WriteBuf + ?Sized>(
1883 &mut self,
1884 dst: &mut C,
1885 src: &[u8],
1886 ) -> SafeResult {
1887 self.3.streamed = true;
1888 unsafe {
1889 dst.write_from(|buffer, capacity| {
1890 parse_code(zstd_sys::ZSTD_decompressBlock(
1891 self.0.as_ptr(),
1892 buffer,
1893 capacity,
1894 ptr_void(src),
1895 src.len(),
1896 ))
1897 })
1898 }
1899 }
1900
1901 /// Wraps the `ZSTD_insertBlock()` function.
1902 ///
1903 /// # Safety
1904 ///
1905 /// `block` becomes this context's history window, so it must stay allocated and unmodified
1906 /// until the next call to `decompress_block` or `insert_block` on this context (or until this
1907 /// context is dropped), as the following block is decoded against it.
1908 #[cfg(feature = "experimental")]
1909 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
1910 pub unsafe fn insert_block(&mut self, block: &[u8]) -> usize {
1911 self.3.streamed = true;
1912 unsafe {
1913 zstd_sys::ZSTD_insertBlock(
1914 self.0.as_ptr(),
1915 ptr_void(block),
1916 block.len(),
1917 )
1918 }
1919 }
1920}
1921
1922impl Drop for DCtx<'_> {
1923 fn drop(&mut self) {
1924 unsafe {
1925 zstd_sys::ZSTD_freeDCtx(self.0.as_ptr());
1926 }
1927 }
1928}
1929
1930unsafe impl Send for DCtx<'_> {}
1931// Non thread-safe methods already take `&mut self`, so it's fine to implement Sync here.
1932unsafe impl Sync for DCtx<'_> {}
1933
1934/// Compression dictionary.
1935pub struct CDict<'a>(NonNull<zstd_sys::ZSTD_CDict>, PhantomData<&'a ()>);
1936
1937impl CDict<'static> {
1938 /// Prepare a dictionary to compress data.
1939 ///
1940 /// This will make it easier for compression contexts to load this dictionary.
1941 ///
1942 /// The dictionary content will be copied internally, and does not need to be kept around.
1943 ///
1944 /// # Panics
1945 ///
1946 /// If loading this dictionary failed.
1947 pub fn create(
1948 dict_buffer: &[u8],
1949 compression_level: CompressionLevel,
1950 ) -> Self {
1951 Self::try_create(dict_buffer, compression_level)
1952 .expect("zstd returned null pointer when creating dict")
1953 }
1954
1955 /// Prepare a dictionary to compress data.
1956 ///
1957 /// This will make it easier for compression contexts to load this dictionary.
1958 ///
1959 /// The dictionary content will be copied internally, and does not need to be kept around.
1960 pub fn try_create(
1961 dict_buffer: &[u8],
1962 compression_level: CompressionLevel,
1963 ) -> Option<Self> {
1964 Some(CDict(
1965 NonNull::new(unsafe {
1966 zstd_sys::ZSTD_createCDict(
1967 ptr_void(dict_buffer),
1968 dict_buffer.len(),
1969 compression_level,
1970 )
1971 })?,
1972 PhantomData,
1973 ))
1974 }
1975}
1976
1977impl<'a> CDict<'a> {
1978 #[cfg(feature = "experimental")]
1979 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
1980 pub fn create_by_reference(
1981 dict_buffer: &'a [u8],
1982 compression_level: CompressionLevel,
1983 ) -> Self {
1984 CDict(
1985 NonNull::new(unsafe {
1986 zstd_sys::ZSTD_createCDict_byReference(
1987 ptr_void(dict_buffer),
1988 dict_buffer.len(),
1989 compression_level,
1990 )
1991 })
1992 .expect("zstd returned null pointer"),
1993 PhantomData,
1994 )
1995 }
1996
1997 /// Returns the _current_ memory usage of this dictionary.
1998 ///
1999 /// Note that this may change over time.
2000 pub fn sizeof(&self) -> usize {
2001 unsafe { zstd_sys::ZSTD_sizeof_CDict(self.0.as_ptr()) }
2002 }
2003
2004 /// Returns the dictionary ID for this dict.
2005 ///
2006 /// Returns `None` if this dictionary is empty or invalid.
2007 pub fn get_dict_id(&self) -> Option<NonZeroU32> {
2008 NonZeroU32::new(unsafe {
2009 zstd_sys::ZSTD_getDictID_fromCDict(self.0.as_ptr()) as u32
2010 })
2011 }
2012}
2013
2014/// Wraps the `ZSTD_createCDict()` function.
2015pub fn create_cdict(
2016 dict_buffer: &[u8],
2017 compression_level: CompressionLevel,
2018) -> CDict<'static> {
2019 CDict::create(dict_buffer, compression_level)
2020}
2021
2022impl<'a> Drop for CDict<'a> {
2023 fn drop(&mut self) {
2024 unsafe {
2025 zstd_sys::ZSTD_freeCDict(self.0.as_ptr());
2026 }
2027 }
2028}
2029
2030unsafe impl<'a> Send for CDict<'a> {}
2031unsafe impl<'a> Sync for CDict<'a> {}
2032
2033/// Wraps the `ZSTD_compress_usingCDict()` function.
2034pub fn compress_using_cdict(
2035 cctx: &mut CCtx<'_>,
2036 dst: &mut [u8],
2037 src: &[u8],
2038 cdict: &CDict<'_>,
2039) -> SafeResult {
2040 cctx.compress_using_cdict(dst, src, cdict)
2041}
2042
2043/// A digested decompression dictionary.
2044pub struct DDict<'a>(NonNull<zstd_sys::ZSTD_DDict>, PhantomData<&'a ()>);
2045
2046impl DDict<'static> {
2047 pub fn create(dict_buffer: &[u8]) -> Self {
2048 Self::try_create(dict_buffer)
2049 .expect("zstd returned null pointer when creating dict")
2050 }
2051
2052 pub fn try_create(dict_buffer: &[u8]) -> Option<Self> {
2053 Some(DDict(
2054 NonNull::new(unsafe {
2055 zstd_sys::ZSTD_createDDict(
2056 ptr_void(dict_buffer),
2057 dict_buffer.len(),
2058 )
2059 })?,
2060 PhantomData,
2061 ))
2062 }
2063}
2064
2065impl<'a> DDict<'a> {
2066 pub fn sizeof(&self) -> usize {
2067 unsafe { zstd_sys::ZSTD_sizeof_DDict(self.0.as_ptr()) }
2068 }
2069
2070 /// Wraps the `ZSTD_createDDict_byReference()` function.
2071 ///
2072 /// The dictionary will keep referencing `dict_buffer`.
2073 #[cfg(feature = "experimental")]
2074 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2075 pub fn create_by_reference(dict_buffer: &'a [u8]) -> Self {
2076 DDict(
2077 NonNull::new(unsafe {
2078 zstd_sys::ZSTD_createDDict_byReference(
2079 ptr_void(dict_buffer),
2080 dict_buffer.len(),
2081 )
2082 })
2083 .expect("zstd returned null pointer"),
2084 PhantomData,
2085 )
2086 }
2087
2088 /// Returns the dictionary ID for this dict.
2089 ///
2090 /// Returns `None` if this dictionary is empty or invalid.
2091 pub fn get_dict_id(&self) -> Option<NonZeroU32> {
2092 NonZeroU32::new(unsafe {
2093 zstd_sys::ZSTD_getDictID_fromDDict(self.0.as_ptr()) as u32
2094 })
2095 }
2096}
2097
2098/// Wraps the `ZSTD_createDDict()` function.
2099///
2100/// It copies the dictionary internally, so the resulting `DDict` is `'static`.
2101pub fn create_ddict(dict_buffer: &[u8]) -> DDict<'static> {
2102 DDict::create(dict_buffer)
2103}
2104
2105impl<'a> Drop for DDict<'a> {
2106 fn drop(&mut self) {
2107 unsafe {
2108 zstd_sys::ZSTD_freeDDict(self.0.as_ptr());
2109 }
2110 }
2111}
2112
2113unsafe impl<'a> Send for DDict<'a> {}
2114unsafe impl<'a> Sync for DDict<'a> {}
2115
2116/// A shared thread pool for one or more compression contexts
2117#[cfg(all(feature = "experimental", feature = "zstdmt"))]
2118#[cfg_attr(
2119 feature = "doc-cfg",
2120 doc(cfg(all(feature = "experimental", feature = "zstdmt")))
2121)]
2122pub struct ThreadPool(NonNull<zstd_sys::ZSTD_threadPool>);
2123
2124#[cfg(all(feature = "experimental", feature = "zstdmt"))]
2125#[cfg_attr(
2126 feature = "doc-cfg",
2127 doc(cfg(all(feature = "experimental", feature = "zstdmt")))
2128)]
2129impl ThreadPool {
2130 /// Create a thread pool with the specified number of threads.
2131 ///
2132 /// # Panics
2133 ///
2134 /// If creating the thread pool failed.
2135 pub fn new(num_threads: usize) -> Self {
2136 Self::try_new(num_threads)
2137 .expect("zstd returned null pointer when creating thread pool")
2138 }
2139
2140 /// Create a thread pool with the specified number of threads.
2141 pub fn try_new(num_threads: usize) -> Option<Self> {
2142 Some(Self(NonNull::new(unsafe {
2143 zstd_sys::ZSTD_createThreadPool(num_threads)
2144 })?))
2145 }
2146}
2147
2148#[cfg(all(feature = "experimental", feature = "zstdmt"))]
2149#[cfg_attr(
2150 feature = "doc-cfg",
2151 doc(cfg(all(feature = "experimental", feature = "zstdmt")))
2152)]
2153impl Drop for ThreadPool {
2154 fn drop(&mut self) {
2155 unsafe {
2156 zstd_sys::ZSTD_freeThreadPool(self.0.as_ptr());
2157 }
2158 }
2159}
2160
2161#[cfg(all(feature = "experimental", feature = "zstdmt"))]
2162#[cfg_attr(
2163 feature = "doc-cfg",
2164 doc(cfg(all(feature = "experimental", feature = "zstdmt")))
2165)]
2166unsafe impl Send for ThreadPool {}
2167#[cfg(all(feature = "experimental", feature = "zstdmt"))]
2168#[cfg_attr(
2169 feature = "doc-cfg",
2170 doc(cfg(all(feature = "experimental", feature = "zstdmt")))
2171)]
2172unsafe impl Sync for ThreadPool {}
2173
2174/// Wraps the `ZSTD_decompress_usingDDict()` function.
2175pub fn decompress_using_ddict(
2176 dctx: &mut DCtx<'_>,
2177 dst: &mut [u8],
2178 src: &[u8],
2179 ddict: &DDict<'_>,
2180) -> SafeResult {
2181 dctx.decompress_using_ddict(dst, src, ddict)
2182}
2183
2184/// Compression stream.
2185///
2186/// Same as `CCtx`.
2187pub type CStream<'a> = CCtx<'a>;
2188
2189// CStream can't be shared across threads, so it does not implement Sync.
2190
2191/// Allocates a new `CStream`.
2192pub fn create_cstream<'a>() -> CStream<'a> {
2193 CCtx::create()
2194}
2195
2196/// Prepares an existing `CStream` for compression at the given level.
2197pub fn init_cstream(
2198 zcs: &mut CStream<'_>,
2199 compression_level: CompressionLevel,
2200) -> SafeResult {
2201 zcs.init(compression_level)
2202}
2203
2204#[derive(Debug)]
2205/// Wrapper around an input buffer.
2206///
2207/// Bytes will be read starting at `src[pos]`.
2208///
2209/// `pos` will be updated after reading.
2210///
2211/// # Invariant
2212///
2213/// `pos <= src.len()`
2214///
2215/// Both fields are public, so this is checked (and panics if it does not hold)
2216/// whenever the buffer is given to zstd.
2217pub struct InBuffer<'a> {
2218 pub src: &'a [u8],
2219 pub pos: usize,
2220}
2221
2222/// Describe a bytes container, like `Vec<u8>`.
2223///
2224/// Represents a contiguous segment of allocated memory, a prefix of which is initialized.
2225///
2226/// It allows starting from an uninitializes chunk of memory and writing to it, progressively
2227/// initializing it. No re-allocation typically occur after the initial creation.
2228///
2229/// The main implementors are:
2230/// * `Vec<u8>` and similar structures. These hold both a length (initialized data) and a capacity
2231/// (allocated memory).
2232///
2233/// Use `Vec::with_capacity` to create an empty `Vec` with non-zero capacity, and the length
2234/// field will be updated to cover the data written to it (as long as it fits in the given
2235/// capacity).
2236/// * `[u8]` and `[u8; N]`. These must start already-initialized, and will not be resized. It will
2237/// be up to the caller to only use the part that was written (as returned by the various writing
2238/// operations).
2239/// * `std::io::Cursor<T: WriteBuf>`. This will ignore data before the cursor's position, and
2240/// append data after that.
2241pub unsafe trait WriteBuf {
2242 /// Returns the valid data part of this container. Should only cover initialized data.
2243 fn as_slice(&self) -> &[u8];
2244
2245 /// Returns the full capacity of this container. May include uninitialized data.
2246 fn capacity(&self) -> usize;
2247
2248 /// Returns a pointer to the start of the data.
2249 fn as_mut_ptr(&mut self) -> *mut u8;
2250
2251 /// Indicates that the first `n` bytes of the container have been written.
2252 ///
2253 /// Safety: this should only be called if the `n` first bytes of this buffer have actually been
2254 /// initialized.
2255 unsafe fn filled_until(&mut self, n: usize);
2256
2257 /// Call the given closure using the pointer and capacity from `self`.
2258 ///
2259 /// Assumes the given function returns a parseable code, which if valid, represents how many
2260 /// bytes were written to `self`.
2261 ///
2262 /// The given closure must treat its first argument as pointing to potentially uninitialized
2263 /// memory, and should not read from it.
2264 ///
2265 /// In addition, it must have written at least `n` bytes contiguously from this pointer, where
2266 /// `n` is the returned value.
2267 unsafe fn write_from<F>(&mut self, f: F) -> SafeResult
2268 where
2269 F: FnOnce(*mut c_void, usize) -> SafeResult,
2270 {
2271 let capacity = self.capacity();
2272 let res = f(ptr_mut_void(self), capacity);
2273 if let Ok(n) = res {
2274 // Nothing can have been written past the end of the buffer; a
2275 // larger count would mark memory we do not own as initialized.
2276 assert!(n <= capacity, "zstd reported writing past the buffer");
2277 self.filled_until(n);
2278 }
2279 res
2280 }
2281}
2282
2283/// The position of a `Cursor`, as an index into the buffer it wraps.
2284///
2285/// `Cursor` stores the position as a `u64` and lets it be set anywhere, so on a
2286/// target where `usize` is narrower it can name an offset no buffer can hold.
2287/// Saturating leaves such a position out of range, where the bounds checks
2288/// below reject it; casting would wrap it around into a valid-looking offset
2289/// and quietly read or write the wrong part of the buffer.
2290#[cfg(feature = "std")]
2291fn cursor_position<T>(cursor: &std::io::Cursor<T>) -> usize {
2292 use core::convert::TryFrom;
2293
2294 usize::try_from(cursor.position()).unwrap_or(usize::MAX)
2295}
2296
2297#[cfg(feature = "std")]
2298#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "std")))]
2299unsafe impl<T> WriteBuf for std::io::Cursor<T>
2300where
2301 T: WriteBuf,
2302{
2303 fn as_slice(&self) -> &[u8] {
2304 // A cursor past the inner buffer's initialized part has nothing
2305 // initialized after it yet (see `filled_until` below).
2306 self.get_ref()
2307 .as_slice()
2308 .get(cursor_position(self)..)
2309 .unwrap_or(&[])
2310 }
2311
2312 fn capacity(&self) -> usize {
2313 self.get_ref()
2314 .capacity()
2315 .saturating_sub(cursor_position(self))
2316 }
2317
2318 fn as_mut_ptr(&mut self) -> *mut u8 {
2319 let start = cursor_position(self);
2320 assert!(start <= self.get_ref().capacity());
2321 // Safety: start is still in the same memory allocation
2322 unsafe { self.get_mut().as_mut_ptr().add(start) }
2323 }
2324
2325 unsafe fn filled_until(&mut self, n: usize) {
2326 // Here we assume data _before_ self.position() was already initialized.
2327 // Egh it's not actually guaranteed by Cursor? So let's guarantee it ourselves.
2328 // Since the cursor wraps another `WriteBuf`, we know how much data is initialized there.
2329 let position = cursor_position(self);
2330 let capacity = self.get_ref().capacity();
2331 if n == 0 && position > capacity {
2332 // Nothing was written, and nothing could have been: there is
2333 // no room at all after the cursor.
2334 return;
2335 }
2336 // Otherwise the caller wrote `n` bytes starting at `position`, so
2337 // `position` is inside the buffer. Checking it before the zero-fill
2338 // below keeps a position that could not be converted from running off
2339 // the end.
2340 //
2341 // Note that `n == 0` still truncates the data after the cursor, like
2342 // any other `n` does: an empty result must not leave a previous one
2343 // in place.
2344 assert!(position <= capacity);
2345 let initialized = self.get_ref().as_slice().len();
2346 if let Some(uninitialized) = position.checked_sub(initialized) {
2347 // Here, the cursor is further than the known-initialized part.
2348 // Cursor's solution is to pad with zeroes, so let's do the same.
2349 // We'll zero bytes from the end of valid data (as_slice().len()) to the cursor position.
2350
2351 // Safety:
2352 // * We checked `position <= self.get_ref().capacity()`
2353 // * This means that `position` is within (or one past) the nested
2354 // pointer's allocation.
2355 // * Finally, `initialized + uninitialized = position`, so the entire byte
2356 // range here is within the allocation
2357 unsafe {
2358 self.get_mut()
2359 .as_mut_ptr()
2360 .add(initialized)
2361 .write_bytes(0u8, uninitialized)
2362 };
2363 }
2364
2365 let start = position;
2366 assert!(start + n <= self.get_ref().capacity());
2367 self.get_mut().filled_until(start + n);
2368 }
2369}
2370
2371#[cfg(feature = "std")]
2372#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "std")))]
2373unsafe impl<'a> WriteBuf for &'a mut std::vec::Vec<u8> {
2374 fn as_slice(&self) -> &[u8] {
2375 std::vec::Vec::as_slice(self)
2376 }
2377
2378 fn capacity(&self) -> usize {
2379 std::vec::Vec::capacity(self)
2380 }
2381
2382 fn as_mut_ptr(&mut self) -> *mut u8 {
2383 std::vec::Vec::as_mut_ptr(self)
2384 }
2385
2386 unsafe fn filled_until(&mut self, n: usize) {
2387 std::vec::Vec::set_len(self, n)
2388 }
2389}
2390
2391#[cfg(feature = "std")]
2392#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "std")))]
2393unsafe impl WriteBuf for std::vec::Vec<u8> {
2394 fn as_slice(&self) -> &[u8] {
2395 &self[..]
2396 }
2397 fn capacity(&self) -> usize {
2398 self.capacity()
2399 }
2400 fn as_mut_ptr(&mut self) -> *mut u8 {
2401 self.as_mut_ptr()
2402 }
2403 unsafe fn filled_until(&mut self, n: usize) {
2404 self.set_len(n);
2405 }
2406}
2407
2408#[cfg(feature = "arrays")]
2409#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "arrays")))]
2410unsafe impl<const N: usize> WriteBuf for [u8; N] {
2411 fn as_slice(&self) -> &[u8] {
2412 self
2413 }
2414 fn capacity(&self) -> usize {
2415 self.len()
2416 }
2417
2418 fn as_mut_ptr(&mut self) -> *mut u8 {
2419 (&mut self[..]).as_mut_ptr()
2420 }
2421
2422 unsafe fn filled_until(&mut self, _n: usize) {
2423 // Assume the slice is already initialized
2424 }
2425}
2426
2427unsafe impl WriteBuf for [u8] {
2428 fn as_slice(&self) -> &[u8] {
2429 self
2430 }
2431 fn capacity(&self) -> usize {
2432 self.len()
2433 }
2434
2435 fn as_mut_ptr(&mut self) -> *mut u8 {
2436 self.as_mut_ptr()
2437 }
2438
2439 unsafe fn filled_until(&mut self, _n: usize) {
2440 // Assume the slice is already initialized
2441 }
2442}
2443
2444/*
2445// This is possible, but... why?
2446unsafe impl<'a> WriteBuf for OutBuffer<'a, [u8]> {
2447 fn as_slice(&self) -> &[u8] {
2448 self.dst
2449 }
2450 fn capacity(&self) -> usize {
2451 self.dst.len()
2452 }
2453 fn as_mut_ptr(&mut self) -> *mut u8 {
2454 self.dst.as_mut_ptr()
2455 }
2456 unsafe fn filled_until(&mut self, n: usize) {
2457 self.pos = n;
2458 }
2459}
2460*/
2461
2462#[derive(Debug)]
2463/// Wrapper around an output buffer.
2464///
2465/// `C` is usually either `[u8]` or `Vec<u8>`.
2466///
2467/// Bytes will be written starting at `dst[pos]`.
2468///
2469/// `pos` will be updated after writing.
2470///
2471/// # Invariant
2472///
2473/// `pos <= dst.capacity()`
2474pub struct OutBuffer<'a, C: WriteBuf + ?Sized> {
2475 dst: &'a mut C,
2476 pos: usize,
2477}
2478
2479/// Convenience method to get a mut pointer from a mut ref.
2480fn ptr_mut<B>(ptr_void: &mut B) -> *mut B {
2481 ptr_void as *mut B
2482}
2483
2484/// Interface between a C-level ZSTD_outBuffer and a rust-level `OutBuffer`.
2485///
2486/// Will update the parent buffer from the C buffer on drop.
2487struct OutBufferWrapper<'a, 'b, C: WriteBuf + ?Sized> {
2488 buf: zstd_sys::ZSTD_outBuffer,
2489 parent: &'a mut OutBuffer<'b, C>,
2490}
2491
2492impl<'a, 'b: 'a, C: WriteBuf + ?Sized> Deref for OutBufferWrapper<'a, 'b, C> {
2493 type Target = zstd_sys::ZSTD_outBuffer;
2494
2495 fn deref(&self) -> &Self::Target {
2496 &self.buf
2497 }
2498}
2499
2500impl<'a, 'b: 'a, C: WriteBuf + ?Sized> DerefMut
2501 for OutBufferWrapper<'a, 'b, C>
2502{
2503 fn deref_mut(&mut self) -> &mut Self::Target {
2504 &mut self.buf
2505 }
2506}
2507
2508impl<'a, C: WriteBuf + ?Sized> OutBuffer<'a, C> {
2509 /// Returns a new `OutBuffer` around the given slice.
2510 ///
2511 /// Starts with `pos = 0`.
2512 pub fn around(dst: &'a mut C) -> Self {
2513 OutBuffer { dst, pos: 0 }
2514 }
2515
2516 /// Returns a new `OutBuffer` around the given slice, starting at the given position.
2517 ///
2518 /// If `pos` is past the initialized part of `dst` (for example a `Vec`
2519 /// whose `len()` is smaller than `pos`), the gap is zero-filled, as a
2520 /// `Cursor` would do.
2521 ///
2522 /// # Panics
2523 ///
2524 /// If `pos > dst.capacity()`.
2525 pub fn around_pos(dst: &'a mut C, pos: usize) -> Self {
2526 if pos > dst.capacity() {
2527 panic!("Given position outside of the buffer bounds.");
2528 }
2529
2530 let initialized = dst.as_slice().len();
2531 if pos > initialized {
2532 // Writing to this buffer marks everything before `pos` as
2533 // initialized (see `set_pos`), so it has to be before we start.
2534 // Safety: `initialized..pos` lies within `capacity()`, which
2535 // `WriteBuf` promises is valid to write to.
2536 unsafe {
2537 dst.as_mut_ptr()
2538 .add(initialized)
2539 .write_bytes(0u8, pos - initialized);
2540 dst.filled_until(pos);
2541 }
2542 }
2543
2544 OutBuffer { dst, pos }
2545 }
2546
2547 /// Returns the current cursor position.
2548 ///
2549 /// Guaranteed to be <= self.capacity()
2550 pub fn pos(&self) -> usize {
2551 assert!(self.pos <= self.dst.capacity());
2552 self.pos
2553 }
2554
2555 /// Returns the capacity of the underlying buffer.
2556 pub fn capacity(&self) -> usize {
2557 self.dst.capacity()
2558 }
2559
2560 /// Sets the new cursor position.
2561 ///
2562 /// # Panics
2563 ///
2564 /// If `pos > self.dst.capacity()`.
2565 ///
2566 /// # Safety
2567 ///
2568 /// Data up to `pos` must have actually been written to.
2569 pub unsafe fn set_pos(&mut self, pos: usize) {
2570 if pos > self.dst.capacity() {
2571 panic!("Given position outside of the buffer bounds.");
2572 }
2573
2574 self.dst.filled_until(pos);
2575
2576 self.pos = pos;
2577 }
2578
2579 fn wrap<'b>(&'b mut self) -> OutBufferWrapper<'b, 'a, C> {
2580 // The capacity is the caller's to report (`WriteBuf`), and may have
2581 // shrunk since the position was set. zstd refuses a position past
2582 // the end before doing anything, and `set_pos()` would panic on it
2583 // once the call returned: do it first, while a compression context
2584 // still knows about the frame it has in progress. The capacity is
2585 // read once, so zstd gets the one that was checked.
2586 let capacity = self.dst.capacity();
2587 if self.pos > capacity {
2588 panic!("Given position outside of the buffer bounds.");
2589 }
2590
2591 OutBufferWrapper {
2592 buf: zstd_sys::ZSTD_outBuffer {
2593 dst: ptr_mut_void(self.dst),
2594 size: capacity,
2595 pos: self.pos,
2596 },
2597 parent: self,
2598 }
2599 }
2600
2601 /// Returns the part of this buffer that was written to.
2602 pub fn as_slice<'b>(&'b self) -> &'a [u8]
2603 where
2604 'b: 'a,
2605 {
2606 let pos = self.pos;
2607 &self.dst.as_slice()[..pos]
2608 }
2609
2610 /// Returns a pointer to the start of this buffer.
2611 pub fn as_mut_ptr(&mut self) -> *mut u8 {
2612 self.dst.as_mut_ptr()
2613 }
2614}
2615
2616impl<'a, 'b, C: WriteBuf + ?Sized> OutBufferWrapper<'a, 'b, C> {
2617 /// Passes `res` through, and forgets the position reported by zstd if it
2618 /// is an error, so the parent keeps the one from before the call.
2619 ///
2620 /// zstd.h makes no promise about `pos` after a failed call, and the legacy
2621 /// decoders report the whole output buffer as written when they fail; only
2622 /// a successful call vouches for the bytes up to `pos` being initialized.
2623 fn check(&mut self, res: SafeResult) -> SafeResult {
2624 if res.is_err() {
2625 self.buf.pos = self.parent.pos;
2626 }
2627 res
2628 }
2629}
2630
2631impl<'a, 'b, C: WriteBuf + ?Sized> Drop for OutBufferWrapper<'a, 'b, C> {
2632 fn drop(&mut self) {
2633 // Safe because `self.buf.pos` either comes from a successful call,
2634 // which guarantees that data until there has been written, or was put
2635 // back to the parent's position by `check()`.
2636 unsafe { self.parent.set_pos(self.buf.pos) };
2637 }
2638}
2639
2640struct InBufferWrapper<'a, 'b> {
2641 buf: zstd_sys::ZSTD_inBuffer,
2642 parent: &'a mut InBuffer<'b>,
2643}
2644
2645impl<'a, 'b: 'a> Deref for InBufferWrapper<'a, 'b> {
2646 type Target = zstd_sys::ZSTD_inBuffer;
2647
2648 fn deref(&self) -> &Self::Target {
2649 &self.buf
2650 }
2651}
2652
2653impl<'a, 'b: 'a> DerefMut for InBufferWrapper<'a, 'b> {
2654 fn deref_mut(&mut self) -> &mut Self::Target {
2655 &mut self.buf
2656 }
2657}
2658
2659impl<'a> InBuffer<'a> {
2660 /// Returns a new `InBuffer` around the given slice.
2661 ///
2662 /// Starts with `pos = 0`.
2663 pub fn around(src: &'a [u8]) -> Self {
2664 InBuffer { src, pos: 0 }
2665 }
2666
2667 /// Returns the current cursor position.
2668 pub fn pos(&self) -> usize {
2669 self.pos
2670 }
2671
2672 /// Sets the new cursor position.
2673 ///
2674 /// # Panics
2675 ///
2676 /// If `pos > self.src.len()`.
2677 pub fn set_pos(&mut self, pos: usize) {
2678 if pos > self.src.len() {
2679 panic!("Given position outside of the buffer bounds.");
2680 }
2681 self.pos = pos;
2682 }
2683
2684 fn wrap<'b>(&'b mut self) -> InBufferWrapper<'b, 'a> {
2685 // The fields are public, so `pos` may not have gone through `set_pos`.
2686 // Not all zstd functions check it before reading from `src + pos`.
2687 if self.pos > self.src.len() {
2688 panic!("Given position outside of the buffer bounds.");
2689 }
2690
2691 InBufferWrapper {
2692 buf: zstd_sys::ZSTD_inBuffer {
2693 src: ptr_void(self.src),
2694 size: self.src.len(),
2695 pos: self.pos,
2696 },
2697 parent: self,
2698 }
2699 }
2700}
2701
2702impl<'a, 'b> InBufferWrapper<'a, 'b> {
2703 /// Passes `res` through, and forgets the position reported by zstd if it
2704 /// is an error, so the parent keeps the one from before the call.
2705 ///
2706 /// See `OutBufferWrapper::check()`: a failed call consumed nothing usable,
2707 /// and the legacy decoders report the whole input as read.
2708 fn check(&mut self, res: SafeResult) -> SafeResult {
2709 if res.is_err() {
2710 self.buf.pos = self.parent.pos;
2711 }
2712 res
2713 }
2714}
2715
2716impl<'a, 'b> Drop for InBufferWrapper<'a, 'b> {
2717 fn drop(&mut self) {
2718 self.parent.set_pos(self.buf.pos);
2719 }
2720}
2721
2722/// A Decompression stream.
2723///
2724/// Same as `DCtx`.
2725pub type DStream<'a> = DCtx<'a>;
2726
2727// Some functions work on a "frame prefix".
2728// TODO: Define `struct FramePrefix(&[u8]);` and move these functions to it?
2729//
2730// Some other functions work on a dictionary (not CDict or DDict).
2731// Same thing?
2732
2733/// Wraps the `ZSTD_findFrameCompressedSize()` function.
2734///
2735/// `src` should contain at least an entire frame.
2736pub fn find_frame_compressed_size(src: &[u8]) -> SafeResult {
2737 let code = unsafe {
2738 zstd_sys::ZSTD_findFrameCompressedSize(ptr_void(src), src.len())
2739 };
2740 parse_code(code)
2741}
2742
2743/// Wraps the `ZSTD_getFrameContentSize()` function.
2744///
2745/// Args:
2746/// * `src`: A prefix of the compressed frame. It should at least include the frame header.
2747///
2748/// Returns:
2749/// * `Err(ContentSizeError)` if `src` is too small of a prefix, or if it appears corrupted.
2750/// * `Ok(None)` if the frame does not include a content size.
2751/// * `Ok(Some(content_size_in_bytes))` otherwise.
2752pub fn get_frame_content_size(
2753 src: &[u8],
2754) -> Result<Option<u64>, ContentSizeError> {
2755 parse_content_size(unsafe {
2756 zstd_sys::ZSTD_getFrameContentSize(ptr_void(src), src.len())
2757 })
2758}
2759
2760/// Wraps the `ZSTD_findDecompressedSize()` function.
2761///
2762/// `src` should be exactly a sequence of ZSTD frames.
2763#[cfg(feature = "experimental")]
2764#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2765pub fn find_decompressed_size(
2766 src: &[u8],
2767) -> Result<Option<u64>, ContentSizeError> {
2768 parse_content_size(unsafe {
2769 zstd_sys::ZSTD_findDecompressedSize(ptr_void(src), src.len())
2770 })
2771}
2772
2773/// Wraps the `ZSTD_isFrame()` function.
2774#[cfg(feature = "experimental")]
2775#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2776pub fn is_frame(buffer: &[u8]) -> bool {
2777 unsafe { zstd_sys::ZSTD_isFrame(ptr_void(buffer), buffer.len()) > 0 }
2778}
2779
2780/// Wraps the `ZSTD_getDictID_fromDict()` function.
2781///
2782/// Returns `None` if the dictionary is not a valid zstd dictionary.
2783pub fn get_dict_id_from_dict(dict: &[u8]) -> Option<NonZeroU32> {
2784 NonZeroU32::new(unsafe {
2785 zstd_sys::ZSTD_getDictID_fromDict(ptr_void(dict), dict.len()) as u32
2786 })
2787}
2788
2789/// Wraps the `ZSTD_getDictID_fromFrame()` function.
2790///
2791/// Returns `None` if the dictionary ID could not be decoded. This may happen if:
2792/// * The frame was not encoded with a dictionary.
2793/// * The frame intentionally did not include dictionary ID.
2794/// * The dictionary was non-conformant.
2795/// * `src` is too small and does not include the frame header.
2796/// * `src` is not a valid zstd frame prefix.
2797pub fn get_dict_id_from_frame(src: &[u8]) -> Option<NonZeroU32> {
2798 NonZeroU32::new(unsafe {
2799 zstd_sys::ZSTD_getDictID_fromFrame(ptr_void(src), src.len()) as u32
2800 })
2801}
2802
2803/// What kind of context reset should be applied.
2804pub enum ResetDirective {
2805 /// Only the session will be reset.
2806 ///
2807 /// All parameters will be preserved (including the dictionary).
2808 /// But any frame being processed will be dropped.
2809 ///
2810 /// It can be useful to start re-using a context after an error or when an
2811 /// ongoing compression is no longer needed.
2812 SessionOnly,
2813
2814 /// Only reset parameters (including dictionary or referenced prefix).
2815 ///
2816 /// All parameters will be reset to default values.
2817 ///
2818 /// This can only be done between sessions - no compression or decompression must be ongoing.
2819 Parameters,
2820
2821 /// Reset both the session and parameters.
2822 ///
2823 /// The result is similar to a newly created context.
2824 SessionAndParameters,
2825}
2826
2827impl ResetDirective {
2828 /// Does this drop a session in progress?
2829 ///
2830 /// Only a session reset brings a context back from the undefined state an
2831 /// error can leave it in - `Parameters` alone is refused while a session is
2832 /// open.
2833 fn resets_session(&self) -> bool {
2834 matches!(
2835 self,
2836 ResetDirective::SessionOnly | ResetDirective::SessionAndParameters
2837 )
2838 }
2839
2840 fn as_sys(self) -> zstd_sys::ZSTD_ResetDirective {
2841 match self {
2842 ResetDirective::SessionOnly => zstd_sys::ZSTD_ResetDirective::ZSTD_reset_session_only,
2843 ResetDirective::Parameters => zstd_sys::ZSTD_ResetDirective::ZSTD_reset_parameters,
2844 ResetDirective::SessionAndParameters => zstd_sys::ZSTD_ResetDirective::ZSTD_reset_session_and_parameters,
2845 }
2846 }
2847}
2848
2849#[cfg(feature = "experimental")]
2850#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2851#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2852#[repr(u32)]
2853pub enum FrameFormat {
2854 /// Regular zstd format.
2855 One = zstd_sys::ZSTD_format_e::ZSTD_f_zstd1 as u32,
2856
2857 /// Skip the 4 bytes identifying the content as zstd-compressed data.
2858 Magicless = zstd_sys::ZSTD_format_e::ZSTD_f_zstd1_magicless as u32,
2859}
2860
2861#[cfg(feature = "experimental")]
2862#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2863#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2864#[repr(u32)]
2865pub enum DictAttachPref {
2866 DefaultAttach =
2867 zstd_sys::ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach as u32,
2868 ForceAttach = zstd_sys::ZSTD_dictAttachPref_e::ZSTD_dictForceAttach as u32,
2869 ForceCopy = zstd_sys::ZSTD_dictAttachPref_e::ZSTD_dictForceCopy as u32,
2870 ForceLoad = zstd_sys::ZSTD_dictAttachPref_e::ZSTD_dictForceLoad as u32,
2871}
2872
2873#[cfg(feature = "experimental")]
2874#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2875#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2876#[repr(u32)]
2877pub enum ParamSwitch {
2878 Auto = zstd_sys::ZSTD_ParamSwitch_e::ZSTD_ps_auto as u32,
2879 Enable = zstd_sys::ZSTD_ParamSwitch_e::ZSTD_ps_enable as u32,
2880 Disable = zstd_sys::ZSTD_ParamSwitch_e::ZSTD_ps_disable as u32,
2881}
2882
2883/// A compression parameter.
2884#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2885#[non_exhaustive]
2886pub enum CParameter {
2887 #[cfg(feature = "experimental")]
2888 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2889 RSyncable(bool),
2890
2891 #[cfg(feature = "experimental")]
2892 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2893 Format(FrameFormat),
2894
2895 #[cfg(feature = "experimental")]
2896 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2897 ForceMaxWindow(bool),
2898
2899 #[cfg(feature = "experimental")]
2900 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2901 ForceAttachDict(DictAttachPref),
2902
2903 #[cfg(feature = "experimental")]
2904 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2905 LiteralCompressionMode(ParamSwitch),
2906
2907 #[cfg(feature = "experimental")]
2908 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2909 SrcSizeHint(u32),
2910
2911 #[cfg(feature = "experimental")]
2912 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2913 EnableDedicatedDictSearch(bool),
2914
2915 /// Whether zstd may keep referencing the input buffer instead of copying
2916 /// it.
2917 ///
2918 /// This requires the input to stay allocated and unmodified until the
2919 /// frame is complete, which a borrowed `InBuffer` cannot guarantee:
2920 /// `CCtx::set_parameter` refuses to enable it and returns an error.
2921 #[cfg(feature = "experimental")]
2922 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2923 StableInBuffer(bool),
2924
2925 #[cfg(feature = "experimental")]
2926 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2927 StableOutBuffer(bool),
2928
2929 #[cfg(feature = "experimental")]
2930 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2931 BlockDelimiters(bool),
2932
2933 #[cfg(feature = "experimental")]
2934 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2935 ValidateSequences(bool),
2936
2937 #[cfg(feature = "experimental")]
2938 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2939 UseBlockSplitter(ParamSwitch),
2940
2941 #[cfg(feature = "experimental")]
2942 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2943 UseRowMatchFinder(ParamSwitch),
2944
2945 #[cfg(feature = "experimental")]
2946 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2947 DeterministicRefPrefix(bool),
2948
2949 #[cfg(feature = "experimental")]
2950 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2951 PrefetchCDictTables(ParamSwitch),
2952
2953 #[cfg(feature = "experimental")]
2954 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2955 EnableSeqProducerFallback(bool),
2956
2957 #[cfg(feature = "experimental")]
2958 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2959 MaxBlockSize(u32),
2960
2961 #[cfg(feature = "experimental")]
2962 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2963 SearchForExternalRepcodes(ParamSwitch),
2964
2965 /// Target CBlock size.
2966 ///
2967 /// Tries to make compressed blocks fit in this size (not a guarantee, just a target).
2968 /// Useful to reduce end-to-end latency in low-bandwidth environments.
2969 ///
2970 /// No target when the value is 0.
2971 TargetCBlockSize(u32),
2972
2973 /// Compression level to use.
2974 ///
2975 /// Compression levels are global presets for the other compression parameters.
2976 CompressionLevel(CompressionLevel),
2977
2978 /// Maximum allowed back-reference distance.
2979 ///
2980 /// The actual distance is 2 power "this value".
2981 WindowLog(u32),
2982
2983 HashLog(u32),
2984
2985 ChainLog(u32),
2986
2987 SearchLog(u32),
2988
2989 MinMatch(u32),
2990
2991 TargetLength(u32),
2992
2993 Strategy(Strategy),
2994
2995 EnableLongDistanceMatching(bool),
2996
2997 LdmHashLog(u32),
2998
2999 LdmMinMatch(u32),
3000
3001 LdmBucketSizeLog(u32),
3002
3003 LdmHashRateLog(u32),
3004
3005 ContentSizeFlag(bool),
3006
3007 ChecksumFlag(bool),
3008
3009 DictIdFlag(bool),
3010
3011 /// How many threads will be spawned.
3012 ///
3013 /// With a default value of `0`, `compress_stream*` functions block until they complete.
3014 ///
3015 /// With any other value (including 1, a single compressing thread), these methods directly
3016 /// return, and the actual compression is done in the background (until a flush is requested).
3017 /// A context compressing that way from a borrowed dictionary or prefix
3018 /// must not be leaked, see [`CCtx`](CCtx#worker-threads-and-leaks).
3019 ///
3020 /// zstd clamps the value to its bounds instead of refusing it.
3021 ///
3022 /// Note: this will only work if the `zstdmt` feature is activated.
3023 NbWorkers(u32),
3024
3025 /// Size in bytes of a compression job.
3026 ///
3027 /// Does not have any effect when `NbWorkers` is set to 0.
3028 ///
3029 /// The default value of 0 finds the best job size based on the compression parameters.
3030 ///
3031 /// Note: this will only work if the `zstdmt` feature is activated.
3032 JobSize(u32),
3033
3034 /// Specifies how much overlap must be given to each worker.
3035 ///
3036 /// Possible values:
3037 ///
3038 /// * `0` (default value): automatic overlap based on compression strategy.
3039 /// * `1`: No overlap
3040 /// * `1 < n < 9`: Overlap a fraction of the window size, defined as `1/(2 ^ 9-n)`.
3041 /// * `9`: Full overlap (as long as the window)
3042 /// * `9 < m`: Will return an error.
3043 ///
3044 /// Note: this will only work if the `zstdmt` feature is activated.
3045 OverlapSizeLog(u32),
3046}
3047
3048/// A decompression parameter.
3049#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3050#[non_exhaustive]
3051pub enum DParameter {
3052 WindowLogMax(u32),
3053
3054 #[cfg(feature = "experimental")]
3055 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
3056 /// See `FrameFormat`.
3057 Format(FrameFormat),
3058
3059 #[cfg(feature = "experimental")]
3060 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
3061 StableOutBuffer(bool),
3062
3063 #[cfg(feature = "experimental")]
3064 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
3065 ForceIgnoreChecksum(bool),
3066
3067 #[cfg(feature = "experimental")]
3068 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
3069 RefMultipleDDicts(bool),
3070}
3071
3072/// Wraps the `ZDICT_trainFromBuffer()` function.
3073#[cfg(feature = "zdict_builder")]
3074#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "zdict_builder")))]
3075pub fn train_from_buffer<C: WriteBuf + ?Sized>(
3076 dict_buffer: &mut C,
3077 samples_buffer: &[u8],
3078 samples_sizes: &[usize],
3079) -> SafeResult {
3080 // A plain `sum()` wraps around when overflow checks are disabled, and
3081 // would accept sizes reaching far outside of `samples_buffer`.
3082 let total_size = samples_sizes
3083 .iter()
3084 .try_fold(0usize, |total, &size| total.checked_add(size));
3085 assert_eq!(
3086 Some(samples_buffer.len()),
3087 total_size,
3088 "sample sizes don't add up to the samples buffer length"
3089 );
3090
3091 unsafe {
3092 dict_buffer.write_from(|buffer, capacity| {
3093 parse_code(zstd_sys::ZDICT_trainFromBuffer(
3094 buffer,
3095 capacity,
3096 ptr_void(samples_buffer),
3097 samples_sizes.as_ptr(),
3098 samples_sizes.len() as u32,
3099 ))
3100 })
3101 }
3102}
3103
3104/// Wraps the `ZDICT_getDictID()` function.
3105#[cfg(feature = "zdict_builder")]
3106#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "zdict_builder")))]
3107pub fn get_dict_id(dict_buffer: &[u8]) -> Option<NonZeroU32> {
3108 NonZeroU32::new(unsafe {
3109 zstd_sys::ZDICT_getDictID(ptr_void(dict_buffer), dict_buffer.len())
3110 })
3111}
3112
3113/// Wraps the `ZSTD_getBlockSize()` function.
3114#[cfg(feature = "experimental")]
3115#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
3116pub fn get_block_size(cctx: &CCtx) -> usize {
3117 unsafe { zstd_sys::ZSTD_getBlockSize(cctx.0.as_ptr()) }
3118}
3119
3120/// Wraps the `ZSTD_decompressBound` function
3121#[cfg(feature = "experimental")]
3122#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
3123pub fn decompress_bound(data: &[u8]) -> Result<u64, ErrorCode> {
3124 let bound =
3125 unsafe { zstd_sys::ZSTD_decompressBound(ptr_void(data), data.len()) };
3126 if is_error(bound as usize) {
3127 Err(bound as usize)
3128 } else {
3129 Ok(bound)
3130 }
3131}
3132
3133/// Given a buffer of size `src_size`, returns the maximum number of sequences that can ge
3134/// generated.
3135#[cfg(feature = "experimental")]
3136#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
3137pub fn sequence_bound(src_size: usize) -> usize {
3138 // Safety: Just FFI.
3139 unsafe { zstd_sys::ZSTD_sequenceBound(src_size) }
3140}
3141
3142/// Returns the minimum extra space when output and input buffer overlap.
3143///
3144/// When using in-place decompression, the output buffer must be at least this much bigger (in
3145/// bytes) than the input buffer. The extra space must be at the front of the output buffer (the
3146/// input buffer must be at the end of the output buffer).
3147#[cfg(feature = "experimental")]
3148#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
3149pub fn decompression_margin(
3150 compressed_data: &[u8],
3151) -> Result<usize, ErrorCode> {
3152 parse_code(unsafe {
3153 zstd_sys::ZSTD_decompressionMargin(
3154 ptr_void(compressed_data),
3155 compressed_data.len(),
3156 )
3157 })
3158}