Skip to main content

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