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/// The header of a frame, see [`get_frame_header()`].
48///
49/// `frameContentSize` is [`CONTENTSIZE_UNKNOWN`] when the header does not
50/// give it.
51pub use zstd_sys::ZSTD_FrameHeader as FrameHeader;
52
53/// Whether a frame is a regular zstd frame or a skippable one.
54pub use zstd_sys::ZSTD_FrameType_e as FrameType;
55
56/// Reset directive.
57// pub use zstd_sys::ZSTD_ResetDirective as ResetDirective;
58use core::ffi::{c_char, c_int, c_ulonglong, c_void};
59
60use core::marker::PhantomData;
61use core::num::{NonZeroU32, NonZeroU64};
62use core::ops::{Deref, DerefMut};
63use core::ptr::NonNull;
64use core::str;
65
66include!("constants.rs");
67
68#[cfg(feature = "experimental")]
69include!("constants_experimental.rs");
70
71#[cfg(feature = "seekable")]
72include!("constants_seekable.rs");
73
74/// Represents the compression level used by zstd.
75pub type CompressionLevel = i32;
76
77/// Represents a possible error from the zstd library.
78pub type ErrorCode = usize;
79
80/// Wrapper result around most zstd functions.
81///
82/// Either a success code (usually number of bytes written), or an error code.
83pub type SafeResult = Result<usize, ErrorCode>;
84
85/// The error code zstd itself returns when an allocation fails
86/// (`-ZSTD_error_memory_allocation` as a `size_t`), for the places where a
87/// context is allocated on the Rust side of a call.
88#[cfg(feature = "with-rust-allocator")]
89const MEMORY_ALLOCATION_ERROR: ErrorCode =
90    (zstd_sys::ZSTD_ErrorCode::ZSTD_error_memory_allocation as usize)
91        .wrapping_neg();
92
93/// The error code zstd itself returns for a parameter it does not support
94/// (`-ZSTD_error_parameter_unsupported` as a `size_t`), for the parameters
95/// that are refused on the Rust side of a call.
96#[cfg(any(feature = "experimental", not(feature = "zstdmt")))]
97const PARAMETER_UNSUPPORTED_ERROR: ErrorCode =
98    (zstd_sys::ZSTD_ErrorCode::ZSTD_error_parameter_unsupported as usize)
99        .wrapping_neg();
100
101/// The error code zstd itself returns for an operation the context is in no
102/// state to perform (`-ZSTD_error_stage_wrong` as a `size_t`), for the places
103/// where that has to be decided on the Rust side of a call.
104const STAGE_WRONG_ERROR: ErrorCode =
105    (zstd_sys::ZSTD_ErrorCode::ZSTD_error_stage_wrong as usize).wrapping_neg();
106
107/// The error code zstd returns for a dictionary that does not fit
108/// (`-ZSTD_error_dictionary_wrong`), for `CCtx::compress_with_*` on a context
109/// with a loaded dictionary, which they would lose.
110const DICTIONARY_WRONG_ERROR: ErrorCode =
111    (zstd_sys::ZSTD_ErrorCode::ZSTD_error_dictionary_wrong as usize)
112        .wrapping_neg();
113
114/// The error code `ZSTD_compress2()` returns when the destination is too
115/// small, leaving its frame in progress (`-ZSTD_error_dstSize_tooSmall`).
116const DST_SIZE_TOO_SMALL_ERROR: ErrorCode =
117    (zstd_sys::ZSTD_ErrorCode::ZSTD_error_dstSize_tooSmall as usize)
118        .wrapping_neg();
119
120/// The largest frame zstd compresses on the calling thread when its size is
121/// known (`ZSTDMT_JOBSIZE_MIN` in zstd 1.5; older versions used larger
122/// values, which only makes this cautious).
123const ZSTDMT_JOBSIZE_MIN: usize = 512 << 10;
124
125/// Indicates an error happened when parsing the frame content size.
126///
127/// The stream may be corrupted, or the given frame prefix was too small.
128#[derive(Debug)]
129pub struct ContentSizeError;
130
131impl core::fmt::Display for ContentSizeError {
132    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
133        f.write_str("Could not get content size")
134    }
135}
136
137/// Returns true if code represents error.
138fn is_error(code: usize) -> bool {
139    // Safety: Just FFI
140    unsafe { zstd_sys::ZSTD_isError(code) != 0 }
141}
142
143/// Parse the result code
144///
145/// Returns the number of bytes written if the code represents success,
146/// or the error message code otherwise.
147fn parse_code(code: usize) -> SafeResult {
148    if !is_error(code) {
149        Ok(code)
150    } else {
151        Err(code)
152    }
153}
154
155/// Parse a content size value.
156///
157/// zstd uses 2 special content size values to indicate either unknown size or parsing error.
158fn parse_content_size(
159    content_size: u64,
160) -> Result<Option<u64>, ContentSizeError> {
161    match content_size {
162        CONTENTSIZE_ERROR => Err(ContentSizeError),
163        CONTENTSIZE_UNKNOWN => Ok(None),
164        other => Ok(Some(other)),
165    }
166}
167
168fn ptr_void(src: &[u8]) -> *const c_void {
169    src.as_ptr() as *const c_void
170}
171
172fn ptr_mut_void(dst: &mut (impl WriteBuf + ?Sized)) -> *mut c_void {
173    dst.as_mut_ptr() as *mut c_void
174}
175
176/// Returns the ZSTD version.
177///
178/// Returns `major * 10_000 + minor * 100 + patch`.
179/// So 1.5.3 would be returned as `10_503`.
180pub fn version_number() -> u32 {
181    // Safety: Just FFI
182    unsafe { zstd_sys::ZSTD_versionNumber() as u32 }
183}
184
185/// Returns a string representation of the ZSTD version.
186///
187/// For example "1.5.3".
188pub fn version_string() -> &'static str {
189    // Safety: Assumes `ZSTD_versionString` returns a valid utf8 string.
190    unsafe { c_char_to_str(zstd_sys::ZSTD_versionString()) }
191}
192
193/// Returns the minimum (fastest) compression level supported.
194///
195/// This is likely going to be a _very_ large negative number.
196pub fn min_c_level() -> CompressionLevel {
197    // Safety: Just FFI
198    unsafe { zstd_sys::ZSTD_minCLevel() as CompressionLevel }
199}
200
201/// Returns the maximum (slowest) compression level supported.
202pub fn max_c_level() -> CompressionLevel {
203    // Safety: Just FFI
204    unsafe { zstd_sys::ZSTD_maxCLevel() as CompressionLevel }
205}
206
207/// Wraps the `ZSTD_compress` function.
208///
209/// This will try to compress `src` entirely and write the result to `dst`, returning the number of
210/// bytes written. If `dst` is too small to hold the compressed content, an error will be returned.
211///
212/// For streaming operations that don't require to store the entire input/output in memory, see
213/// `compress_stream`.
214pub fn compress<C: WriteBuf + ?Sized>(
215    dst: &mut C,
216    src: &[u8],
217    compression_level: CompressionLevel,
218) -> SafeResult {
219    // `ZSTD_compress` allocates its workspace with the C runtime's `malloc`.
220    // Route it through a context built on the Rust global allocator instead;
221    // `ZSTD_compressCCtx` on a fresh context is exactly what `ZSTD_compress`
222    // does internally.
223    #[cfg(feature = "with-rust-allocator")]
224    {
225        let mut cctx = CCtx::try_create().ok_or(MEMORY_ALLOCATION_ERROR)?;
226        cctx.compress(dst, src, compression_level)
227    }
228
229    // Safety: ZSTD_compress indeed returns how many bytes have been written.
230    #[cfg(not(feature = "with-rust-allocator"))]
231    unsafe {
232        dst.write_from(|buffer, capacity| {
233            parse_code(zstd_sys::ZSTD_compress(
234                buffer,
235                capacity,
236                ptr_void(src),
237                src.len(),
238                compression_level,
239            ))
240        })
241    }
242}
243
244/// Wraps the `ZSTD_decompress` function.
245///
246/// This is a one-step decompression (not streaming).
247///
248/// You will need to make sure `dst` is large enough to store all the decompressed content, or an
249/// error will be returned.
250///
251/// If decompression was a success, the number of bytes written will be returned.
252///
253/// Only that many bytes at the start of `dst` are meaningful: zstd may use the
254/// rest of `dst` as scratch space, so it can be overwritten even if it was
255/// zero-filled beforehand.
256///
257/// With a `Vec`, the output goes into its spare capacity, replacing anything
258/// already in it, and its length is then set to the number of bytes written.
259/// The `Vec` is never re-allocated, so create it with `Vec::with_capacity` (or
260/// `reserve`) for the full decompressed size: its capacity is what bounds the
261/// output.
262pub fn decompress<C: WriteBuf + ?Sized>(
263    dst: &mut C,
264    src: &[u8],
265) -> SafeResult {
266    // See `compress()`: keep the implicit context's allocations visible to
267    // the Rust global allocator.
268    #[cfg(feature = "with-rust-allocator")]
269    {
270        let mut dctx = DCtx::try_create().ok_or(MEMORY_ALLOCATION_ERROR)?;
271        dctx.decompress(dst, src)
272    }
273
274    // Safety: ZSTD_decompress indeed returns how many bytes have been written.
275    #[cfg(not(feature = "with-rust-allocator"))]
276    unsafe {
277        dst.write_from(|buffer, capacity| {
278            parse_code(zstd_sys::ZSTD_decompress(
279                buffer,
280                capacity,
281                ptr_void(src),
282                src.len(),
283            ))
284        })
285    }
286}
287
288/// Wraps the `ZSTD_getDecompressedSize` function.
289///
290/// Returns `None` if the size could not be found, or if the content is actually empty.
291#[deprecated(note = "Use get_frame_content_size instead.")]
292pub fn get_decompressed_size(src: &[u8]) -> Option<NonZeroU64> {
293    // Safety: Just FFI
294    NonZeroU64::new(unsafe {
295        zstd_sys::ZSTD_getDecompressedSize(ptr_void(src), src.len()) as u64
296    })
297}
298
299/// Maximum compressed size in worst case single-pass scenario
300pub fn compress_bound(src_size: usize) -> usize {
301    // Safety: Just FFI
302    unsafe { zstd_sys::ZSTD_compressBound(src_size) }
303}
304
305/// Remembers an error that may have left a context in a state zstd considers
306/// undefined.
307///
308/// zstd.h says of both `ZSTD_compressStream2()` and `ZSTD_decompressStream()`
309/// that "if an operation ends with an error, it may leave [the context] in an
310/// undefined state", and that calling them again on such a state is undefined
311/// behaviour - the context has to be reset first. So once a streaming
312/// operation fails, refuse to run another one until something resets the
313/// context, and hand the original error back instead.
314#[derive(Clone, Debug, Default)]
315struct Poison(Option<ErrorCode>);
316
317impl Poison {
318    /// Fails with the error that poisoned the context, if there was one.
319    fn guard(&self) -> Result<(), ErrorCode> {
320        match self.0 {
321            Some(code) => Err(code),
322            None => Ok(()),
323        }
324    }
325
326    /// Remembers `res` if it failed, and passes it through.
327    fn record(&mut self, res: SafeResult) -> SafeResult {
328        if let Err(code) = res {
329            self.0 = Some(code);
330        }
331        res
332    }
333
334    /// The context was reset, so it is usable again.
335    fn clear(&mut self) {
336        self.0 = None;
337    }
338}
339
340/// What a `CCtx` knows about its worker threads (`NbWorkers`), and about
341/// its block session.
342#[derive(Clone, Copy, Debug, Default)]
343struct Workers {
344    /// `NbWorkers` was ever set to a non-zero value, see `guard_own_tables`.
345    ever: bool,
346    /// The `NbWorkers` set with `set_parameter`, as zstd clamped it (0: none).
347    ///
348    /// Each frame gets these workers only if everything it reads is owned by
349    /// the context, see `CCtx::start_frame()`. A frame that
350    /// reads borrowed data runs on the calling thread instead: a context can
351    /// be leaked mid-frame, and its workers would then read the data after
352    /// the borrow ended.
353    count: u32,
354    /// `NbWorkers` is currently set to a non-zero value in zstd: `count`,
355    /// unless the frame in progress, or the last one, reads borrowed data.
356    requested: bool,
357    /// A borrowed prefix (`ref_prefix`) was referenced, and no frame has
358    /// started since to consume it.
359    prefix_borrowed: bool,
360    /// The dictionary referenced (`ref_cdict`) is only borrowed, or points
361    /// into bytes it only borrows (`CDict::create_by_reference`).
362    dict_borrowed: bool,
363    /// zstd holds a dictionary it loaded (`load_dictionary*`, or
364    /// `ref_dictionary`), which nothing could load again after
365    /// `compress_with_*` replaced it.
366    loaded: bool,
367    /// The `pending` frame reads borrowed data, so it runs on the calling
368    /// thread (or, for a one-shot call, is waited for before returning).
369    frame_borrows: bool,
370    /// A frame was started while `NbWorkers` was set, and is not finished.
371    ///
372    /// Its jobs may be running on the worker threads, reading the context's
373    /// dictionary and job table. zstd up to 1.5.7 does not wait for them when
374    /// the frame is abandoned: not on a session reset, not before a short
375    /// frame (which it compresses on the calling thread), and not before
376    /// freeing the dictionary when the context is freed. So the frame is
377    /// drained first, see `CCtx::drain()`.
378    pending: bool,
379    /// `ZSTD_e_end` was given for the `pending` frame. zstd then answers
380    /// `ZSTD_e_continue` by resetting the session without waiting for the
381    /// jobs, so that is refused here first.
382    ended: bool,
383    /// A `ZSTD_e_end` call took all of its input: zstd made the frame's last
384    /// job. It would hand any new input to a worker as a job after the last
385    /// one, which waits forever, so that is refused here first.
386    last: bool,
387    /// The size pledged for the next frame is short (see `short`).
388    pledged_short: bool,
389    /// The `pending` frame is known to be compressed on the calling thread:
390    /// its size is known (pledged, or given whole with `ZSTD_e_end`), and is
391    /// short (zstd hands out no jobs for a frame of at most
392    /// `ZSTDMT_JOBSIZE_MIN`).
393    short: bool,
394    /// The `pending` frame may have handed jobs to the worker threads: it
395    /// took some input, and is not `short`.
396    jobs: bool,
397    /// A job failed. zstd up to 1.5.7 can then keep a job it had prepared but
398    /// not handed to a worker yet (`jobReady`), after clearing it: the next
399    /// multithreaded frame hands that empty job to a worker, which crashes.
400    /// That stays in the context's multithreading state, which only freeing
401    /// the context frees, so no other multithreaded frame is started on it.
402    broken: bool,
403    /// `StableOutBuffer` is enabled. Draining needs an output buffer of its
404    /// own, which zstd then refuses, so it is not allowed with workers.
405    stable_out: bool,
406    /// `compress_block` started the frame zstd has open, as a block session,
407    /// and the session was not ended since (`CCtx::end_blocks()`, or a failed
408    /// block call), see `CCtx::start_blocks()`.
409    blocks: bool,
410}
411
412/// The `NbWorkers` zstd keeps when it accepts `value`: it clamps the value to
413/// its bounds rather than refusing it.
414fn accepted_workers(value: c_int) -> u32 {
415    // Safety: Just FFI
416    let bounds = unsafe {
417        zstd_sys::ZSTD_cParam_getBounds(
418            zstd_sys::ZSTD_cParameter::ZSTD_c_nbWorkers,
419        )
420    };
421    let upper = bounds.upperBound.max(0);
422    value.max(bounds.lowerBound).max(0).min(upper) as u32
423}
424
425/// Compression context
426///
427/// It is recommended to allocate a single context per thread and re-use it
428/// for many compression operations.
429///
430/// # Worker threads and leaks
431///
432/// With `CParameter::NbWorkers`, the jobs of a frame run on worker threads,
433/// which read the dictionary or prefix. Anything that abandons a frame in
434/// progress waits for them, dropping the context included (see
435/// [`CCtx::wait_for_workers()`]). A context that is leaked instead
436/// (`mem::forget`, `Box::leak`, a reference cycle) never waits, so the
437/// workers only ever read what the context owns, and leaks with it: a
438/// dictionary it copied ([`CCtx::load_dictionary()`]) or holds
439/// ([`CCtx::set_cdict()`], and [`CCtx::ref_cdict()`] with `alloc`), or a
440/// prefix it owns (`set_prefix()`).
441///
442/// A streaming frame that reads *borrowed* data is compressed on the calling
443/// thread instead, as with `NbWorkers(0)`. That is a prefix given to
444/// [`CCtx::ref_prefix()`], a dictionary made from borrowed bytes
445/// (`CDict::create_by_reference()`). The parameters that only apply to worker
446/// threads (`JobSize`, `OverlapSizeLog`, `RSyncable`) are still accepted, but
447/// have no effect on that frame: only [`CCtx::frame_workers()`] tells.
448///
449/// Worker threads need the `zstdmt` feature, which enables `alloc`: a build
450/// with worker threads always has the shared dictionary handles
451/// [`CCtx::ref_cdict()`] relies on. Without the feature, `NbWorkers` is
452/// refused, even when the linked zstd library has worker threads.
453///
454/// [`CCtx::compress2()`] and `compress_with_*()` never return with a frame
455/// that reads borrowed data still in progress, so they use the workers with
456/// borrowed data too. (The one-shot calls that take a compression level
457/// never use worker threads.)
458pub struct CCtx<'a>(
459    NonNull<zstd_sys::ZSTD_CCtx>,
460    PhantomData<&'a ()>,
461    Poison,
462    Workers,
463    Held,
464);
465
466/// What a `CCtx` keeps alive for zstd: the dictionary or prefix it
467/// references, when the context owns it rather than borrowing it. Dropped
468/// after `Drop for CCtx` waited for the workers, and leaked with the context.
469#[derive(Default)]
470struct Held {
471    /// The lifetime of the bytes it may point into is the context's `'a`
472    /// (or longer), see `CDict::erased()`.
473    cdict: Option<CDict<'static>>,
474    /// The dictionary zstd references, when the context has no handle to it
475    /// and only borrows it, for its `'a`: kept to reference it again after a
476    /// call that set it aside (`compress_with`).
477    borrowed_cdict: Option<NonNull<zstd_sys::ZSTD_CDict>>,
478    /// Never read: only kept until zstd no longer references its bytes.
479    #[cfg(feature = "alloc")]
480    #[allow(dead_code)]
481    prefix: Option<Owner>,
482}
483
484impl Held {
485    /// Only a dictionary (or nothing): one the context has a handle to, or
486    /// one it borrows.
487    fn with_cdict(
488        cdict: Option<CDict<'static>>,
489        borrowed_cdict: Option<NonNull<zstd_sys::ZSTD_CDict>>,
490    ) -> Self {
491        Held {
492            cdict,
493            borrowed_cdict,
494            #[cfg(feature = "alloc")]
495            prefix: None,
496        }
497    }
498
499    /// zstd's pointer to the dictionary, or null.
500    fn cdict_ptr(&self) -> *mut zstd_sys::ZSTD_CDict {
501        match (&self.cdict, self.borrowed_cdict) {
502            (Some(cdict), _) => cdict.as_ptr(),
503            (None, Some(cdict)) => cdict.as_ptr(),
504            (None, None) => core::ptr::null_mut(),
505        }
506    }
507}
508
509impl Default for CCtx<'_> {
510    fn default() -> Self {
511        CCtx::create()
512    }
513}
514
515impl<'a> CCtx<'a> {
516    /// Tries to create a new context.
517    ///
518    /// Returns `None` if zstd returns a NULL pointer - may happen if allocation fails.
519    ///
520    /// With the `with-rust-allocator` feature enabled, the context's internal
521    /// allocations go through Rust's global allocator instead of the C
522    /// runtime's `malloc`.
523    pub fn try_create() -> Option<Self> {
524        #[cfg(feature = "with-rust-allocator")]
525        // Safety: the callbacks satisfy zstd's allocation contract and remain
526        // valid for the lifetime of the context.
527        let context = unsafe {
528            zstd_sys::ZSTD_createCCtx_advanced(
529                crate::rust_allocator::RUST_GLOBAL_ALLOCATOR,
530            )
531        };
532        #[cfg(not(feature = "with-rust-allocator"))]
533        // Safety: zstd returns a newly owned context or null.
534        let context = unsafe { zstd_sys::ZSTD_createCCtx() };
535
536        Some(Self(
537            NonNull::new(context)?,
538            PhantomData,
539            Poison::default(),
540            Workers::default(),
541            Held::default(),
542        ))
543    }
544
545    /// Wrap `ZSTD_createCCtx`
546    ///
547    /// # Panics
548    ///
549    /// If zstd returns a NULL pointer.
550    pub fn create() -> Self {
551        Self::try_create()
552            .expect("zstd returned null pointer when creating new context")
553    }
554
555    /// Ends the session of a one-shot compression, and passes `res` through.
556    ///
557    /// zstd.h has these calls imply a reset, but most of them leave the stream
558    /// stage alone (and their source size behind as the pledged one), while
559    /// `ZSTD_compress2()` stays mid-frame when it fails. A later stream call
560    /// would then carry on from a state that still points at buffers and
561    /// dictionaries borrowed for that one call. So reset explicitly: the next
562    /// stream starts from scratch.
563    ///
564    /// Called as soon as zstd returns, inside the closure given to
565    /// `write_from`: that is the caller's code, which may panic afterwards.
566    fn finish_one_shot(&mut self, res: SafeResult) -> SafeResult {
567        self.reset(ResetDirective::SessionOnly).and(res)
568    }
569
570    /// Wraps the `ZSTD_compressCCtx()` function
571    pub fn compress<C: WriteBuf + ?Sized>(
572        &mut self,
573        dst: &mut C,
574        src: &[u8],
575        compression_level: CompressionLevel,
576    ) -> SafeResult {
577        self.end_blocks();
578        // The one-shot calls run on the calling thread, but end by resetting
579        // the session (see `finish_one_shot`), and overwrite the parameters a
580        // multithreaded frame left open was started with: wait for its jobs
581        // first. That is done inside the closure, with the call it is for:
582        // `write_from` is the caller's code, and when it panics before
583        // running the closure, the frame is still in progress, and known as
584        // such.
585        // Safety: ZSTD_compressCCtx returns how many bytes were written.
586        unsafe {
587            dst.write_from(|buffer, capacity| {
588                self.drain();
589                let res = parse_code(zstd_sys::ZSTD_compressCCtx(
590                    self.0.as_ptr(),
591                    buffer,
592                    capacity,
593                    ptr_void(src),
594                    src.len(),
595                    compression_level,
596                ));
597                self.finish_one_shot(res)
598            })
599        }
600    }
601
602    /// Compresses `src` into `dst` as one frame, with the parameters and the
603    /// dictionary or prefix set on this context.
604    ///
605    /// This uses the worker threads of `NbWorkers` even when the frame reads
606    /// borrowed data: it then returns only once the frame is done, or
607    /// abandoned (when `dst` is too small, after waiting for the workers).
608    /// Otherwise, as with `ZSTD_compress2()`, a frame that does not fit in
609    /// `dst` is left in progress until the session is reset.
610    ///
611    /// Wraps the `ZSTD_compress2()` function.
612    pub fn compress2<C: WriteBuf + ?Sized>(
613        &mut self,
614        dst: &mut C,
615        src: &[u8],
616    ) -> SafeResult {
617        self.end_blocks();
618        if self.3.count != 0 {
619            // Abandons the frame in progress, if any, waiting for its jobs.
620            // Waiting may find that one of them failed: `start_frame` checks
621            // `broken` after.
622            self.reset(ResetDirective::SessionOnly)?;
623            // This call never returns with a frame that reads borrowed data
624            // in progress (see below), so it may use the workers for it.
625            self.start_frame(true)?;
626        }
627        // What the call leaves behind is recorded as soon as zstd returns,
628        // inside the closure: `write_from` is the caller's code, and may
629        // panic after running it.
630        if !self.3.requested {
631            // Safety: ZSTD_compress2 returns how many bytes were written.
632            return unsafe {
633                dst.write_from(|buffer, capacity| {
634                    let res = parse_code(zstd_sys::ZSTD_compress2(
635                        self.0.as_ptr(),
636                        buffer,
637                        capacity,
638                        ptr_void(src),
639                        src.len(),
640                    ));
641                    // Unlike the others, this starts by resetting the
642                    // session, which drops the pledged size, and ends it when
643                    // it succeeds, having consumed the prefix, if any. When
644                    // it fails, it stays mid-frame: make streaming calls wait
645                    // for an explicit reset.
646                    self.3.pledged_short = false;
647                    self.3.prefix_borrowed &= res.is_err();
648                    self.2.clear();
649                    self.2.record(res)
650                })
651            };
652        }
653
654        // With worker threads, a frame this leaves in progress must be one
655        // that can be waited for later, see `drain()`. `ZSTD_compress2()`
656        // runs its frame with stable buffers, and zstd would then refuse any
657        // other buffer: do what it does, but with ordinary ones. That costs
658        // nothing to a multithreaded frame, which copies its input and output
659        // anyway. A short frame, compressed on the calling thread, goes
660        // straight to the destination when it can hold the whole frame, and
661        // through a copy otherwise.
662        //
663        // A frame that reads borrowed data must not be left in progress: its
664        // jobs would outlive the call, and the borrow with them if the
665        // context is then leaked. So when the destination is too small, the
666        // frame is waited for right away, before `write_from` runs any more
667        // of the caller's `WriteBuf` code.
668        // Safety: ZSTD_compressStream2 reports how many bytes it wrote in
669        // `output.pos`.
670        unsafe {
671            dst.write_from(|buffer, capacity| {
672                let mut output = zstd_sys::ZSTD_outBuffer {
673                    dst: buffer,
674                    size: capacity,
675                    pos: 0,
676                };
677                let mut input = zstd_sys::ZSTD_inBuffer {
678                    src: ptr_void(src),
679                    size: src.len(),
680                    pos: 0,
681                };
682                let raw = parse_code(zstd_sys::ZSTD_compressStream2(
683                    self.0.as_ptr(),
684                    &mut output,
685                    &mut input,
686                    zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
687                ));
688                self.track_frame(
689                    raw,
690                    zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
691                    src.len(),
692                    input.pos,
693                );
694                let res = match raw {
695                    Ok(0) => Ok(output.pos),
696                    Ok(_) => {
697                        if self.3.frame_borrows {
698                            // A job that fails here is recorded as `broken`.
699                            let _ = self.flush_to_scratch();
700                            // Nothing is left running: the frame is over,
701                            // but not its session, which `ZSTD_compress2()`
702                            // would also leave open.
703                            self.end_frame();
704                        }
705                        // Otherwise, as `ZSTD_compress2()`: the frame stays
706                        // in progress.
707                        Err(DST_SIZE_TOO_SMALL_ERROR)
708                    }
709                    Err(code) => Err(code),
710                };
711                self.2.record(res)
712            })
713        }
714    }
715
716    /// Wraps the `ZSTD_compress_usingDict()` function.
717    pub fn compress_using_dict<C: WriteBuf + ?Sized>(
718        &mut self,
719        dst: &mut C,
720        src: &[u8],
721        dict: &[u8],
722        compression_level: CompressionLevel,
723    ) -> SafeResult {
724        self.end_blocks();
725        // Safety: ZSTD_compress_usingDict returns how many bytes were written.
726        unsafe {
727            dst.write_from(|buffer, capacity| {
728                // See `compress()`.
729                self.drain();
730                let res = parse_code(zstd_sys::ZSTD_compress_usingDict(
731                    self.0.as_ptr(),
732                    buffer,
733                    capacity,
734                    ptr_void(src),
735                    src.len(),
736                    ptr_void(dict),
737                    dict.len(),
738                    compression_level,
739                ));
740                self.finish_one_shot(res)
741            })
742        }
743    }
744
745    /// Wraps the `ZSTD_compress_usingCDict()` function.
746    pub fn compress_using_cdict<C: WriteBuf + ?Sized>(
747        &mut self,
748        dst: &mut C,
749        src: &[u8],
750        cdict: &CDict<'_>,
751    ) -> SafeResult {
752        self.end_blocks();
753        // Safety: ZSTD_compress_usingCDict returns how many bytes were written.
754        unsafe {
755            dst.write_from(|buffer, capacity| {
756                // See `compress()`.
757                self.drain();
758                let res = parse_code(zstd_sys::ZSTD_compress_usingCDict(
759                    self.0.as_ptr(),
760                    buffer,
761                    capacity,
762                    ptr_void(src),
763                    src.len(),
764                    cdict.as_ptr(),
765                ));
766                self.finish_one_shot(res)
767            })
768        }
769    }
770
771    /// Compresses `src` into `dst` as one frame, with `cdict` for this call
772    /// only, and the other parameters set on this context.
773    ///
774    /// The dictionary is only borrowed, and nothing keeps it once this
775    /// returns: unlike [`CCtx::ref_cdict()`], this takes no handle (no
776    /// reference count to update), and leaves no dictionary alive in the
777    /// context. Like [`CCtx::compress2()`], and unlike
778    /// [`CCtx::compress_using_cdict()`], it uses the worker threads and the
779    /// context's parameters (a checksum, say).
780    ///
781    /// The dictionary the context referenced ([`CCtx::ref_cdict()`],
782    /// [`CCtx::set_cdict()`]) is referenced again afterwards; a prefix is
783    /// not. With a dictionary loaded with
784    /// [`CCtx::load_dictionary()`], which could not be loaded again, this
785    /// fails with a `dictionary_wrong` error: disable it first.
786    pub fn compress_with_cdict<C: WriteBuf + ?Sized>(
787        &mut self,
788        dst: &mut C,
789        src: &[u8],
790        cdict: &CDict<'_>,
791    ) -> SafeResult {
792        self.end_blocks();
793        // Safety: Just FFI. `compress_with` stops zstd referencing it.
794        self.compress_with(dst, src, false, |cctx| unsafe {
795            zstd_sys::ZSTD_CCtx_refCDict(cctx, cdict.as_ptr())
796        })
797    }
798
799    /// Compresses `src` into `dst` as one frame, with `prefix` as its
800    /// single-use dictionary, and the parameters set on this context.
801    ///
802    /// The prefix is only borrowed for this call. Like
803    /// [`CCtx::compress2()`], it uses the worker threads.
804    ///
805    /// The prefix stands in for the dictionary, and for the parameters a
806    /// prepared one decides: this frame gets the context's own (its
807    /// `CompressionLevel`, say), not the dictionary's.
808    ///
809    /// The dictionary the context referenced ([`CCtx::ref_cdict()`],
810    /// [`CCtx::set_cdict()`]) is referenced again afterwards; another
811    /// prefix is not. With a dictionary loaded with
812    /// [`CCtx::load_dictionary()`], which could not be loaded again, this
813    /// fails with a `dictionary_wrong` error: disable it first.
814    pub fn compress_with_prefix<C: WriteBuf + ?Sized>(
815        &mut self,
816        dst: &mut C,
817        src: &[u8],
818        prefix: &[u8],
819    ) -> SafeResult {
820        self.end_blocks();
821        // Safety: Just FFI. `compress_with` stops zstd referencing it.
822        self.compress_with(dst, src, true, |cctx| unsafe {
823            zstd_sys::ZSTD_CCtx_refPrefix(cctx, ptr_void(prefix), prefix.len())
824        })
825    }
826
827    /// `compress2()` with data that `refer` references for this call only
828    /// (a prefix when `prefix`, a dictionary otherwise).
829    ///
830    /// On every way out, panics included, the data is unreferenced before
831    /// its borrow ends: the frame is waited for, the session reset, and what
832    /// the context held referenced again (or nothing).
833    fn compress_with<C: WriteBuf + ?Sized>(
834        &mut self,
835        dst: &mut C,
836        src: &[u8],
837        prefix: bool,
838        refer: impl FnOnce(*mut zstd_sys::ZSTD_CCtx) -> usize,
839    ) -> SafeResult {
840        /// Puts the context back as it was, see `compress_with`.
841        struct Restore<'c, 'a> {
842            cctx: &'c mut CCtx<'a>,
843            /// What the context held. Its dictionary is given back, held or
844            /// borrowed; a prefix it owned is dropped after `drop()`, once
845            /// zstd no longer references it (its `Drop` may panic).
846            old: Held,
847        }
848        impl Drop for Restore<'_, '_> {
849            fn drop(&mut self) {
850                let cctx = &mut *self.cctx;
851                cctx.drain();
852                // Safety: Just FFI. Between frames, zstd takes both.
853                unsafe {
854                    zstd_sys::ZSTD_CCtx_reset(
855                        cctx.0.as_ptr(),
856                        zstd_sys::ZSTD_ResetDirective::ZSTD_reset_session_only,
857                    );
858                    // A dictionary the context only borrows is still
859                    // borrowed: for `'a`, which outlives the context.
860                    zstd_sys::ZSTD_CCtx_refCDict(
861                        cctx.0.as_ptr(),
862                        self.old.cdict_ptr(),
863                    );
864                }
865                cctx.2.clear();
866                cctx.3.pledged_short = false;
867                let old = Held::with_cdict(
868                    self.old.cdict.take(),
869                    self.old.borrowed_cdict.take(),
870                );
871                let borrowed = old.borrowed_cdict.is_some()
872                    || old.cdict.as_ref().map_or(false, CDict::borrows);
873                cctx.referenced(false, borrowed, false, old);
874            }
875        }
876
877        if self.3.loaded {
878            // Referencing anything else would drop it for good.
879            return Err(DICTIONARY_WRONG_ERROR);
880        }
881        // zstd only takes a new reference between frames.
882        self.reset(ResetDirective::SessionOnly)?;
883        let old = core::mem::take(&mut self.4);
884        let guard = Restore { cctx: self, old };
885        parse_code(refer(guard.cctx.0.as_ptr()))?;
886        guard
887            .cctx
888            .referenced(prefix, !prefix, false, Held::default());
889        guard.cctx.compress2(dst, src)
890    }
891
892    /// Initializes the context with the given compression level.
893    ///
894    /// This is equivalent to running:
895    /// * `reset()`
896    /// * `set_parameter(CompressionLevel, compression_level)`
897    ///
898    /// Abandons the current frame, if any. With worker threads, this first
899    /// waits for its jobs, see [`CCtx::wait_for_workers()`].
900    pub fn init(&mut self, compression_level: CompressionLevel) -> SafeResult {
901        self.end_blocks();
902        // This also resets the session and unloads the dictionary.
903        self.drain();
904        self.2.clear();
905        // zstd drops the pledged size.
906        self.3.pledged_short = false;
907        // Safety: Just FFI
908        let code = unsafe {
909            zstd_sys::ZSTD_initCStream(self.0.as_ptr(), compression_level)
910        };
911        let res = self.2.record(parse_code(code));
912        if res.is_ok() {
913            self.referenced(false, false, false, Held::default());
914        }
915        res
916    }
917
918    /// Wraps the `ZSTD_initCStream_srcSize()` function.
919    #[cfg(feature = "experimental")]
920    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
921    #[deprecated(
922        note = "Use reset, set_parameter, and set_pledged_src_size instead."
923    )]
924    pub fn init_src_size(
925        &mut self,
926        compression_level: CompressionLevel,
927        pledged_src_size: u64,
928    ) -> SafeResult {
929        self.end_blocks();
930        self.drain();
931        self.2.clear();
932        self.3.pledged_short = false;
933        // Safety: Just FFI
934        let code = unsafe {
935            zstd_sys::ZSTD_initCStream_srcSize(
936                self.0.as_ptr(),
937                compression_level as c_int,
938                pledged_src_size as c_ulonglong,
939            )
940        };
941        let res = parse_code(code);
942        if res.is_ok() {
943            // See `Workers::short`. Here, zstd takes 0 for an unknown size.
944            self.3.pledged_short = pledged_src_size != 0
945                && pledged_src_size <= ZSTDMT_JOBSIZE_MIN as u64;
946            self.referenced(false, false, false, Held::default());
947        }
948        res
949    }
950
951    /// Wraps the `ZSTD_initCStream_usingDict()` function.
952    #[cfg(feature = "experimental")]
953    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
954    #[deprecated(
955        note = "Use reset, set_parameter, and load_dictionary instead."
956    )]
957    pub fn init_using_dict(
958        &mut self,
959        dict: &[u8],
960        compression_level: CompressionLevel,
961    ) -> SafeResult {
962        self.end_blocks();
963        self.drain();
964        self.2.clear();
965        // zstd drops the pledged size.
966        self.3.pledged_short = false;
967        // Safety: Just FFI
968        let code = unsafe {
969            zstd_sys::ZSTD_initCStream_usingDict(
970                self.0.as_ptr(),
971                ptr_void(dict),
972                dict.len(),
973                compression_level,
974            )
975        };
976        let res = parse_code(code);
977        if res.is_ok() {
978            // The dictionary is copied.
979            self.referenced(false, false, !dict.is_empty(), Held::default());
980        }
981        res
982    }
983
984    /// Wraps the `ZSTD_initCStream_usingCDict()` function.
985    ///
986    /// With `alloc`, the context keeps its own handle to the dictionary, see
987    /// [`CCtx::ref_cdict()`].
988    #[cfg(all(
989        feature = "experimental",
990        feature = "alloc",
991        target_has_atomic = "ptr"
992    ))]
993    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
994    #[deprecated(note = "Use reset and ref_cdict instead.")]
995    pub fn init_using_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResult
996    where
997        'b: 'a, // What the dictionary points into outlives the stream.
998    {
999        self.end_blocks();
1000        self.init_with_cdict(cdict, Some(cdict.clone().erased()))
1001    }
1002
1003    /// Wraps the `ZSTD_initCStream_usingCDict()` function.
1004    ///
1005    /// Dictionary must outlive the context.
1006    ///
1007    /// ```compile_fail,E0515
1008    /// # #![allow(deprecated)]
1009    /// fn compressor() -> zstd_safe::CCtx<'static> {
1010    ///     let cdict = zstd_safe::CDict::create(b"dictionary", 3);
1011    ///     let mut cctx = zstd_safe::CCtx::create();
1012    ///     cctx.init_using_cdict(&cdict).unwrap();
1013    ///     cctx // `cdict` would be dropped while `cctx` still points at it.
1014    /// }
1015    /// ```
1016    #[cfg(all(
1017        feature = "experimental",
1018        not(all(feature = "alloc", target_has_atomic = "ptr"))
1019    ))]
1020    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
1021    #[deprecated(note = "Use reset and ref_cdict instead.")]
1022    pub fn init_using_cdict<'b>(&mut self, cdict: &'a CDict<'b>) -> SafeResult
1023    where
1024        'b: 'a, // Dictionary outlives the stream.
1025    {
1026        self.end_blocks();
1027        self.init_with_cdict(cdict, None)
1028    }
1029
1030    /// `init_using_cdict()`, keeping `held` (a handle to `cdict`, or `None`
1031    /// when it is only borrowed).
1032    #[cfg(feature = "experimental")]
1033    fn init_with_cdict(
1034        &mut self,
1035        cdict: &CDict<'_>,
1036        held: Option<CDict<'static>>,
1037    ) -> SafeResult {
1038        self.drain();
1039        self.2.clear();
1040        // zstd drops the pledged size.
1041        self.3.pledged_short = false;
1042        // Safety: Just FFI
1043        let code = unsafe {
1044            zstd_sys::ZSTD_initCStream_usingCDict(
1045                self.0.as_ptr(),
1046                cdict.as_ptr(),
1047            )
1048        };
1049        let res = self.2.record(parse_code(code));
1050        if res.is_ok() {
1051            self.hold_cdict(cdict.as_ptr(), held, cdict.borrows());
1052        }
1053        res
1054    }
1055
1056    /// Tries to load a dictionary.
1057    ///
1058    /// The dictionary content will be copied internally and does not need to be kept alive after
1059    /// calling this function.
1060    ///
1061    /// If you need to use the same dictionary for multiple contexts, it may be more efficient to
1062    /// create a `CDict` first, then loads that.
1063    ///
1064    /// The dictionary will apply to all compressed frames, until a new dictionary is set.
1065    ///
1066    /// Like zstd, this fails with a `stage_wrong` error while a frame is in
1067    /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
1068    pub fn load_dictionary(&mut self, dict: &[u8]) -> SafeResult {
1069        self.end_blocks();
1070        self.guard_workers()?;
1071        // Safety: Just FFI
1072        let res = parse_code(unsafe {
1073            zstd_sys::ZSTD_CCtx_loadDictionary(
1074                self.0.as_ptr(),
1075                ptr_void(dict),
1076                dict.len(),
1077            )
1078        });
1079        if res.is_ok() {
1080            // The dictionary is copied.
1081            self.referenced(false, false, !dict.is_empty(), Held::default());
1082        }
1083        res
1084    }
1085
1086    /// Loads a dictionary, read as `content_type`.
1087    ///
1088    /// Like [`CCtx::load_dictionary()`], which reads it as
1089    /// [`DictContentType::Auto`]: the dictionary is copied.
1090    ///
1091    /// Wraps the `ZSTD_CCtx_loadDictionary_advanced()` function.
1092    pub fn load_dictionary_advanced(
1093        &mut self,
1094        dict: &[u8],
1095        content_type: DictContentType,
1096    ) -> SafeResult {
1097        self.end_blocks();
1098        self.guard_workers()?;
1099        // Safety: Just FFI
1100        let res = parse_code(unsafe {
1101            zstd_sys::ZSTD_CCtx_loadDictionary_advanced(
1102                self.0.as_ptr(),
1103                ptr_void(dict),
1104                dict.len(),
1105                zstd_sys::ZSTD_dictLoadMethod_e::ZSTD_dlm_byCopy,
1106                content_type.c_type(),
1107            )
1108        });
1109        if res.is_ok() {
1110            self.referenced(false, false, !dict.is_empty(), Held::default());
1111        }
1112        res
1113    }
1114
1115    /// Loads a dictionary without copying it, read as `content_type`.
1116    ///
1117    /// The dictionary applies to all compressed frames, until a new one is
1118    /// set. It is only borrowed: with worker threads, a streaming frame that
1119    /// reads it runs on the calling thread, as with
1120    /// [`CCtx::ref_prefix()`], see [`CCtx`](CCtx#worker-threads-and-leaks).
1121    /// As with [`CCtx::load_dictionary()`], `compress_with_*()` refuses
1122    /// to replace it, with a `dictionary_wrong` error.
1123    ///
1124    /// Like zstd, this fails with a `stage_wrong` error while a frame is in
1125    /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
1126    ///
1127    /// Wraps the `ZSTD_CCtx_loadDictionary_advanced()` function.
1128    pub fn ref_dictionary<'b>(
1129        &mut self,
1130        dict: &'b [u8],
1131        content_type: DictContentType,
1132    ) -> SafeResult
1133    where
1134        'b: 'a,
1135    {
1136        self.end_blocks();
1137        self.guard_workers()?;
1138        // Safety: Just FFI. `dict` outlives the context.
1139        let res = parse_code(unsafe {
1140            zstd_sys::ZSTD_CCtx_loadDictionary_advanced(
1141                self.0.as_ptr(),
1142                ptr_void(dict),
1143                dict.len(),
1144                zstd_sys::ZSTD_dictLoadMethod_e::ZSTD_dlm_byRef,
1145                content_type.c_type(),
1146            )
1147        });
1148        if res.is_ok() {
1149            // An empty dictionary references nothing.
1150            let loaded = !dict.is_empty();
1151            self.referenced(false, loaded, loaded, Held::default());
1152        }
1153        res
1154    }
1155
1156    /// References a prepared dictionary for the next frames.
1157    ///
1158    /// The context keeps its own handle to it, so the dictionary itself is
1159    /// not borrowed: it can come from a cache, a `static` or a local, and be
1160    /// dropped before the context. Only the bytes a dictionary made with
1161    /// `CDict::create_by_reference()` points into must outlive the
1162    /// context.
1163    ///
1164    /// Frames with it may use worker threads, unless it points into such
1165    /// borrowed bytes: a streaming frame then runs on the calling thread,
1166    /// see [`CCtx`](CCtx#worker-threads-and-leaks).
1167    ///
1168    /// The dictionary decides the compression parameters (its level, say);
1169    /// the others stay the context's.
1170    ///
1171    /// Like zstd, this fails with a `stage_wrong` error while a frame is in
1172    /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
1173    ///
1174    /// Wraps the `ZSTD_CCtx_refCDict()` function.
1175    #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
1176    pub fn ref_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResult
1177    where
1178        'b: 'a,
1179    {
1180        self.end_blocks();
1181        self.set_cdict(cdict.clone())
1182    }
1183
1184    /// References a prepared dictionary for the next frames, borrowing it.
1185    ///
1186    /// Without `alloc`, or on a target without pointer-sized atomics, a
1187    /// dictionary cannot be shared otherwise. Such a build normally has no
1188    /// worker threads (the `zstdmt` feature enables `alloc`); if it does, a
1189    /// streaming frame that reads a borrowed dictionary runs on the calling
1190    /// thread, see [`CCtx`](CCtx#worker-threads-and-leaks).
1191    /// [`CCtx::set_cdict()`] moves the dictionary into the context instead.
1192    ///
1193    /// Like zstd, this fails with a `stage_wrong` error while a frame is in
1194    /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
1195    ///
1196    /// The dictionary has to outlive the context:
1197    ///
1198    /// ```compile_fail,E0505
1199    /// let cdict = zstd_safe::CDict::create(b"a dictionary", 3);
1200    /// let mut cctx = zstd_safe::CCtx::create();
1201    /// cctx.ref_cdict(&cdict).unwrap();
1202    /// drop(cdict);
1203    /// let mut frame = [0u8; 64];
1204    /// cctx.compress2(&mut frame[..], b"some data").unwrap();
1205    /// ```
1206    ///
1207    /// Wraps the `ZSTD_CCtx_refCDict()` function.
1208    #[cfg(not(all(feature = "alloc", target_has_atomic = "ptr")))]
1209    pub fn ref_cdict<'b>(&mut self, cdict: &'a CDict<'b>) -> SafeResult
1210    where
1211        'b: 'a,
1212    {
1213        self.end_blocks();
1214        self.refer_cdict(cdict.as_ptr(), None, true)
1215    }
1216
1217    /// References a prepared dictionary for the next frames, moving it into
1218    /// the context.
1219    ///
1220    /// The dictionary is dropped if this fails (while a frame is in
1221    /// progress, say). See [`CCtx::ref_cdict()`].
1222    pub fn set_cdict<'b>(&mut self, cdict: CDict<'b>) -> SafeResult
1223    where
1224        'b: 'a,
1225    {
1226        self.end_blocks();
1227        let borrows = cdict.borrows();
1228        self.refer_cdict(cdict.as_ptr(), Some(cdict.erased()), borrows)
1229    }
1230
1231    /// `ref_cdict()` with zstd's pointer to the dictionary, keeping `held`
1232    /// (a handle to it, or `None` when the dictionary itself is only
1233    /// borrowed) once zstd accepted it. See `hold_cdict()` for `borrows`.
1234    fn refer_cdict(
1235        &mut self,
1236        cdict: *mut zstd_sys::ZSTD_CDict,
1237        held: Option<CDict<'static>>,
1238        borrows: bool,
1239    ) -> SafeResult {
1240        self.guard_workers()?;
1241        // Safety: Just FFI
1242        let res = parse_code(unsafe {
1243            zstd_sys::ZSTD_CCtx_refCDict(self.0.as_ptr(), cdict)
1244        });
1245        if res.is_ok() {
1246            self.hold_cdict(cdict, held, borrows);
1247        }
1248        res
1249    }
1250
1251    /// Records that zstd now references a dictionary, which `held` is a
1252    /// handle to, if the context has one.
1253    ///
1254    /// `borrows` is whether a frame that reads it reads borrowed data: the
1255    /// dictionary itself, without a handle, or the bytes it points into.
1256    fn hold_cdict(
1257        &mut self,
1258        cdict: *mut zstd_sys::ZSTD_CDict,
1259        held: Option<CDict<'static>>,
1260        borrows: bool,
1261    ) {
1262        let borrowed_cdict = match held {
1263            Some(_) => None,
1264            None => NonNull::new(cdict),
1265        };
1266        let borrowed = borrows || borrowed_cdict.is_some();
1267        let held = Held::with_cdict(held, borrowed_cdict);
1268        self.referenced(false, borrowed, false, held);
1269    }
1270
1271    /// Return to "no-dictionary" mode.
1272    ///
1273    /// This will disable any dictionary/prefix previously registered for future frames.
1274    ///
1275    /// Like zstd, this fails with a `stage_wrong` error while a frame is in
1276    /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
1277    pub fn disable_dictionary(&mut self) -> SafeResult {
1278        self.end_blocks();
1279        self.guard_workers()?;
1280        // Safety: Just FFI
1281        let res = parse_code(unsafe {
1282            zstd_sys::ZSTD_CCtx_loadDictionary(
1283                self.0.as_ptr(),
1284                core::ptr::null(),
1285                0,
1286            )
1287        });
1288        if res.is_ok() {
1289            self.referenced(false, false, false, Held::default());
1290        }
1291        res
1292    }
1293
1294    /// Use some prefix as single-use dictionary for the next compressed frame.
1295    ///
1296    /// Just like a dictionary, decompression will need to be given the same prefix.
1297    ///
1298    /// This is best used if the "prefix" looks like the data to be compressed.
1299    ///
1300    /// The prefix is only borrowed: with worker threads, a streaming frame
1301    /// that reads it runs on the calling thread, and the parameters that
1302    /// need workers (`RSyncable`, say) have no effect on it, see
1303    /// [`CCtx`](CCtx#worker-threads-and-leaks). `set_prefix()` takes a
1304    /// prefix the context owns, which can use them.
1305    ///
1306    /// Like zstd, this fails with a `stage_wrong` error while a frame is in
1307    /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
1308    pub fn ref_prefix<'b>(&mut self, prefix: &'b [u8]) -> SafeResult
1309    where
1310        'b: 'a,
1311    {
1312        self.end_blocks();
1313        self.guard_workers()?;
1314        // Safety: Just FFI
1315        let res = parse_code(unsafe {
1316            zstd_sys::ZSTD_CCtx_refPrefix(
1317                self.0.as_ptr(),
1318                ptr_void(prefix),
1319                prefix.len(),
1320            )
1321        });
1322        if res.is_ok() {
1323            // An empty prefix references nothing.
1324            self.referenced(!prefix.is_empty(), false, false, Held::default());
1325        }
1326        res
1327    }
1328
1329    /// Uses a prefix as single-use dictionary for the next compressed frame,
1330    /// owning it.
1331    ///
1332    /// `prefix` gives the bytes without copying them: a `Vec<u8>`, an
1333    /// `Arc<[u8]>` or `Arc<Vec<u8>>`, a memory map, a `bytes::Bytes`, a
1334    /// `&'static [u8]`... The context keeps it for as long as zstd may read
1335    /// it, so a frame that reads it may use worker threads, unlike with
1336    /// [`CCtx::ref_prefix()`].
1337    ///
1338    /// It is dropped when something takes its place or unloads it: another
1339    /// dictionary or prefix, a reset of the parameters, one of the `init*`
1340    /// methods, or a call to [`CCtx::compress_with_cdict()`] or
1341    /// [`CCtx::compress_with_prefix()`]. Not when a frame is done with it:
1342    /// zstd uses a prefix for one frame only, but the context does not
1343    /// track which.
1344    ///
1345    /// Like zstd, this fails with a `stage_wrong` error while a frame is in
1346    /// progress: reset the session first (see [`CCtx::wait_for_workers()`]).
1347    #[cfg(feature = "alloc")]
1348    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "alloc")))]
1349    pub fn set_prefix<P>(&mut self, prefix: P) -> SafeResult
1350    where
1351        P: core::ops::Deref + Send + Sync + 'static,
1352        P::Target: AsRef<[u8]>,
1353    {
1354        self.end_blocks();
1355        self.guard_workers()?;
1356        let (owner, ptr, len) = Owner::new(prefix);
1357        // Safety: Just FFI. The context owns the bytes from here on, and
1358        // keeps them until zstd no longer references them.
1359        let res = parse_code(unsafe {
1360            zstd_sys::ZSTD_CCtx_refPrefix(self.0.as_ptr(), ptr.cast(), len)
1361        });
1362        if res.is_ok() {
1363            let held = Held {
1364                cdict: None,
1365                borrowed_cdict: None,
1366                prefix: Some(owner),
1367            };
1368            self.referenced(false, false, false, held);
1369        }
1370        res
1371    }
1372
1373    /// Performs a step of a streaming compression operation.
1374    ///
1375    /// This will read some data from `input` and/or write some data to `output`.
1376    ///
1377    /// # Returns
1378    ///
1379    /// A hint for the "ideal" amount of input data to provide in the next call.
1380    ///
1381    /// This hint is only for performance purposes.
1382    ///
1383    /// Wraps the `ZSTD_compressStream()` function.
1384    pub fn compress_stream<C: WriteBuf + ?Sized>(
1385        &mut self,
1386        output: &mut OutBuffer<'_, C>,
1387        input: &mut InBuffer<'_>,
1388    ) -> SafeResult {
1389        use zstd_sys::ZSTD_EndDirective::ZSTD_e_continue;
1390        self.end_blocks();
1391        self.2.guard()?;
1392        if let Some(res) =
1393            self.before_stream(input.pos == input.src.len(), ZSTD_e_continue)
1394        {
1395            // Any input is welcome.
1396            return res.map(|_| Self::in_size());
1397        }
1398        let remaining = input.src.len().saturating_sub(input.pos);
1399        let mut output = output.wrap();
1400        let mut input = input.wrap();
1401        // Safety: Just FFI
1402        let code = unsafe {
1403            zstd_sys::ZSTD_compressStream(
1404                self.0.as_ptr(),
1405                ptr_mut(&mut output),
1406                ptr_mut(&mut input),
1407            )
1408        };
1409        let taken = input.buf.pos.saturating_sub(input.parent.pos);
1410        let res = output.check(parse_code(code));
1411        let res = self.2.record(input.check(res));
1412        self.track_frame(res, ZSTD_e_continue, remaining, taken);
1413        res
1414    }
1415
1416    /// Performs a step of a streaming compression operation.
1417    ///
1418    /// This will read some data from `input` and/or write some data to `output`.
1419    ///
1420    /// The `end_op` directive can be used to specify what to do after: nothing special, flush
1421    /// internal buffers, or end the frame.
1422    ///
1423    /// # Returns
1424    ///
1425    /// An lower bound for the amount of data that still needs to be flushed out.
1426    ///
1427    /// This is useful when flushing or ending the frame: you need to keep calling this function
1428    /// until it returns 0.
1429    ///
1430    /// Wraps the `ZSTD_compressStream2()` function.
1431    pub fn compress_stream2<C: WriteBuf + ?Sized>(
1432        &mut self,
1433        output: &mut OutBuffer<'_, C>,
1434        input: &mut InBuffer<'_>,
1435        end_op: zstd_sys::ZSTD_EndDirective,
1436    ) -> SafeResult {
1437        self.end_blocks();
1438        self.2.guard()?;
1439        if let Some(res) =
1440            self.before_stream(input.pos == input.src.len(), end_op)
1441        {
1442            return res;
1443        }
1444        let remaining = input.src.len().saturating_sub(input.pos);
1445        let mut output = output.wrap();
1446        let mut input = input.wrap();
1447        // Safety: Just FFI
1448        let code = unsafe {
1449            zstd_sys::ZSTD_compressStream2(
1450                self.0.as_ptr(),
1451                ptr_mut(&mut output),
1452                ptr_mut(&mut input),
1453                end_op,
1454            )
1455        };
1456        let taken = input.buf.pos.saturating_sub(input.parent.pos);
1457        let res = output.check(parse_code(code));
1458        let res = self.2.record(input.check(res));
1459        self.track_frame(res, end_op, remaining, taken);
1460        res
1461    }
1462
1463    /// Flush any intermediate buffer.
1464    ///
1465    /// To fully flush, you should keep calling this function until it returns `Ok(0)`.
1466    ///
1467    /// Wraps the `ZSTD_flushStream()` function.
1468    pub fn flush_stream<C: WriteBuf + ?Sized>(
1469        &mut self,
1470        output: &mut OutBuffer<'_, C>,
1471    ) -> SafeResult {
1472        use zstd_sys::ZSTD_EndDirective::ZSTD_e_flush;
1473        self.end_blocks();
1474        self.2.guard()?;
1475        if let Some(res) = self.before_stream(true, ZSTD_e_flush) {
1476            return res;
1477        }
1478        let mut output = output.wrap();
1479        // Safety: Just FFI
1480        let code = unsafe {
1481            zstd_sys::ZSTD_flushStream(self.0.as_ptr(), ptr_mut(&mut output))
1482        };
1483        let res = self.2.record(output.check(parse_code(code)));
1484        self.track_frame(res, ZSTD_e_flush, 0, 0);
1485        res
1486    }
1487
1488    /// Ends the stream.
1489    ///
1490    /// You should keep calling this function until it returns `Ok(0)`.
1491    ///
1492    /// Wraps the `ZSTD_endStream()` function.
1493    pub fn end_stream<C: WriteBuf + ?Sized>(
1494        &mut self,
1495        output: &mut OutBuffer<'_, C>,
1496    ) -> SafeResult {
1497        use zstd_sys::ZSTD_EndDirective::ZSTD_e_end;
1498        self.end_blocks();
1499        self.2.guard()?;
1500        if let Some(res) = self.before_stream(true, ZSTD_e_end) {
1501            return res;
1502        }
1503        let mut output = output.wrap();
1504        // Safety: Just FFI
1505        let code = unsafe {
1506            zstd_sys::ZSTD_endStream(self.0.as_ptr(), ptr_mut(&mut output))
1507        };
1508        let res = self.2.record(output.check(parse_code(code)));
1509        self.track_frame(res, ZSTD_e_end, 0, 0);
1510        res
1511    }
1512
1513    /// Ends the block session, if any, see `Workers::blocks`.
1514    ///
1515    /// Called first by every `&mut self` method but `compress_block`, which
1516    /// documents that its blocks may be gone once another one runs, and by
1517    /// `compress_block` when it fails. Their frame is abandoned, so that
1518    /// nothing carries it on.
1519    #[inline]
1520    fn end_blocks(&mut self) {
1521        if self.3.blocks {
1522            self.end_blocks_now();
1523        }
1524    }
1525
1526    #[cold]
1527    #[inline(never)]
1528    fn end_blocks_now(&mut self) {
1529        self.3.blocks = false;
1530        // Safety: Just FFI. A block session runs on the calling thread, with
1531        // no pledged size, and nothing in it is recorded as poison: resetting
1532        // its session leaves nothing else to update.
1533        unsafe {
1534            zstd_sys::ZSTD_CCtx_reset(
1535                self.0.as_ptr(),
1536                zstd_sys::ZSTD_ResetDirective::ZSTD_reset_session_only,
1537            );
1538        }
1539    }
1540
1541    /// Decides whether a streaming call may reach zstd, see `Workers`.
1542    ///
1543    /// Returns what the call should return instead when it may not.
1544    ///
1545    /// Without `NbWorkers`, this is one test, inlined in every streaming
1546    /// call: the rest is kept out of line.
1547    #[inline]
1548    fn before_stream(
1549        &mut self,
1550        no_input: bool,
1551        end_op: zstd_sys::ZSTD_EndDirective,
1552    ) -> Option<SafeResult> {
1553        if self.3.count == 0 {
1554            return None;
1555        }
1556        self.before_stream_with_workers(no_input, end_op)
1557    }
1558
1559    /// `before_stream()` while `NbWorkers` is set.
1560    #[inline(never)]
1561    fn before_stream_with_workers(
1562        &mut self,
1563        no_input: bool,
1564        end_op: zstd_sys::ZSTD_EndDirective,
1565    ) -> Option<SafeResult> {
1566        use zstd_sys::ZSTD_EndDirective::{ZSTD_e_continue, ZSTD_e_end};
1567        if !self.3.pending {
1568            // This call starts a frame. A streaming frame can be left in
1569            // progress, so it only gets the workers without borrowed data.
1570            if let Err(code) = self.start_frame(false) {
1571                return Some(Err(code));
1572            }
1573        }
1574        if !self.3.requested {
1575            return None;
1576        }
1577        if self.3.pending {
1578            if (self.3.ended && end_op == ZSTD_e_continue)
1579                || (self.3.last && !no_input)
1580            {
1581                return Some(Err(STAGE_WRONG_ERROR));
1582            }
1583        } else if no_input && end_op != ZSTD_e_end {
1584            // Starting a frame with nothing in it. If it was then ended,
1585            // zstd up to 1.5.7 would hand an empty job to a worker, which its
1586            // own wait on errors (`ZSTDMT_waitForAllJobsCompleted`) takes for
1587            // done before the worker even starts. `drain()` does wait for it,
1588            // so this is only a safeguard: wait for some input, nothing would
1589            // have been written yet anyway. (A frame that starts with
1590            // `ZSTD_e_end` takes the size of its input, so an empty one is
1591            // compressed on the calling thread.)
1592            return Some(Ok(0));
1593        }
1594        None
1595    }
1596
1597    /// Gives the frame about to start the workers it may use, see
1598    /// `Workers::count`.
1599    ///
1600    /// `blocking` is for a call that returns only once its frame is done:
1601    /// that frame may use the workers even when it reads borrowed data.
1602    /// Only called while `NbWorkers` is set and no frame is in progress, when
1603    /// zstd still takes a new `nbWorkers`.
1604    fn start_frame(&mut self, blocking: bool) -> Result<(), ErrorCode> {
1605        let borrows = self.3.prefix_borrowed || self.3.dict_borrowed;
1606        let workers = blocking || !borrows;
1607        if workers && self.3.broken {
1608            // See `Workers::broken`.
1609            return Err(STAGE_WRONG_ERROR);
1610        }
1611        if workers != self.3.requested {
1612            let value = if workers { self.3.count } else { 0 };
1613            // Safety: Just FFI
1614            parse_code(unsafe {
1615                zstd_sys::ZSTD_CCtx_setParameter(
1616                    self.0.as_ptr(),
1617                    zstd_sys::ZSTD_cParameter::ZSTD_c_nbWorkers,
1618                    value as c_int,
1619                )
1620            })?;
1621            self.3.requested = workers;
1622        }
1623        self.3.frame_borrows = borrows;
1624        Ok(())
1625    }
1626
1627    /// Records what a streaming call left open, see `Workers`.
1628    ///
1629    /// `given` is how much input the call was given, and `taken` how much of
1630    /// it zstd took.
1631    ///
1632    /// Inlined like `before_stream()`, with the work for `NbWorkers` out of
1633    /// line.
1634    #[inline]
1635    fn track_frame(
1636        &mut self,
1637        res: SafeResult,
1638        end_op: zstd_sys::ZSTD_EndDirective,
1639        given: usize,
1640        taken: usize,
1641    ) {
1642        // zstd started a frame by now, which consumed the prefix, if any. (A
1643        // failed call may not have: the prefix then stays counted.)
1644        self.3.prefix_borrowed &= res.is_err();
1645        // A pledged size is for the frame this call started or continued.
1646        let pledged_short = core::mem::take(&mut self.3.pledged_short);
1647        if self.3.count != 0 {
1648            self.track_frame_with_workers(
1649                res,
1650                end_op,
1651                given,
1652                taken,
1653                pledged_short,
1654            );
1655        }
1656    }
1657
1658    /// `track_frame()` while `NbWorkers` is set.
1659    #[inline(never)]
1660    fn track_frame_with_workers(
1661        &mut self,
1662        res: SafeResult,
1663        end_op: zstd_sys::ZSTD_EndDirective,
1664        given: usize,
1665        taken: usize,
1666        pledged_short: bool,
1667    ) {
1668        use zstd_sys::ZSTD_EndDirective::ZSTD_e_end;
1669        // From here on, frames are tracked even when they run on the calling
1670        // thread: `NbWorkers` may only change between frames.
1671        if !self.3.pending {
1672            // This call started the frame. Given whole, its size is the
1673            // input's, whatever was pledged.
1674            self.3.short = if end_op == ZSTD_e_end {
1675                given <= ZSTDMT_JOBSIZE_MIN
1676            } else {
1677                pledged_short
1678            };
1679        }
1680        self.3.jobs |= self.3.requested && taken > 0 && !self.3.short;
1681        match res {
1682            Ok(0) if end_op == ZSTD_e_end => self.end_frame(),
1683            // A frame on the calling thread is over as soon as its end is
1684            // flushed out, whatever the directive of that call (a frame on
1685            // the workers waits for another `ZSTD_e_end`). Ask zstd, rather
1686            // than guess what a call that ended the frame left to do.
1687            Ok(_)
1688                if self.3.ended
1689                    && end_op != ZSTD_e_end
1690                    && self.between_frames() =>
1691            {
1692                self.end_frame()
1693            }
1694            Ok(_) => {
1695                self.3.pending = true;
1696                if end_op == ZSTD_e_end {
1697                    self.3.ended = true;
1698                    self.3.last |= taken == given;
1699                }
1700            }
1701            // When a job failed, zstd waited for the others and reset the
1702            // session (refused directives never get that far, nor does an
1703            // output position past the buffer's end, which zstd would refuse
1704            // while jobs are running: see `OutBuffer::wrap()`).
1705            // Otherwise, there are no jobs. Either way, nothing is left to
1706            // wait for.
1707            Err(_) => {
1708                self.3.broken |= self.3.jobs;
1709                self.end_frame();
1710            }
1711        }
1712    }
1713
1714    /// Whether zstd is between two frames, while `NbWorkers` is set.
1715    ///
1716    /// zstd refuses a new `nbWorkers` while a frame is in progress, before
1717    /// looking at anything else, and takes the one it already has otherwise.
1718    fn between_frames(&mut self) -> bool {
1719        let workers = if self.3.requested { self.3.count } else { 0 };
1720        // Safety: Just FFI
1721        let code = unsafe {
1722            zstd_sys::ZSTD_CCtx_setParameter(
1723                self.0.as_ptr(),
1724                zstd_sys::ZSTD_cParameter::ZSTD_c_nbWorkers,
1725                workers as c_int,
1726            )
1727        };
1728        parse_code(code).is_ok()
1729    }
1730
1731    /// Records that no frame is in progress anymore.
1732    fn end_frame(&mut self) {
1733        self.3.pending = false;
1734        self.3.ended = false;
1735        self.3.last = false;
1736        self.3.short = false;
1737        self.3.jobs = false;
1738        self.3.frame_borrows = false;
1739    }
1740
1741    /// Waits for the jobs of the frame in progress, if any, so that it can
1742    /// be abandoned.
1743    ///
1744    /// Asking zstd to flush everything waits for every job to be done and
1745    /// its output flushed (here to a scratch buffer, and thrown away). This
1746    /// also hands a worker the job zstd prepared but could not hand out yet.
1747    /// That compresses what was left in zstd's input buffer as one more
1748    /// job: wasted work, but bounded by one job. Starting a new frame would
1749    /// avoid it, but zstd up to 1.5.7 can then hand that prepared job out
1750    /// after clearing it, and a worker crashes.
1751    fn drain(&mut self) {
1752        if !self.3.pending {
1753            return;
1754        }
1755        // A frame on the calling thread has no jobs to wait for.
1756        if self.3.requested {
1757            let _ = self.flush_to_scratch();
1758        }
1759        self.end_frame();
1760    }
1761
1762    /// Flushes the frame in progress to a scratch buffer, throwing the output
1763    /// away, until every job is done. See `drain()`.
1764    fn flush_to_scratch(&mut self) -> Result<(), ErrorCode> {
1765        let mut scratch = [0u8; 4096];
1766        loop {
1767            let mut output = zstd_sys::ZSTD_outBuffer {
1768                dst: ptr_mut_void(&mut scratch[..]),
1769                size: scratch.len(),
1770                pos: 0,
1771            };
1772            let mut input = zstd_sys::ZSTD_inBuffer {
1773                src: ptr_void(&[]),
1774                size: 0,
1775                pos: 0,
1776            };
1777            // Safety: Just FFI, with buffers that live through the call.
1778            let code = unsafe {
1779                zstd_sys::ZSTD_compressStream2(
1780                    self.0.as_ptr(),
1781                    &mut output,
1782                    &mut input,
1783                    zstd_sys::ZSTD_EndDirective::ZSTD_e_flush,
1784                )
1785            };
1786            match parse_code(code) {
1787                Ok(0) => return Ok(()),
1788                Ok(_) => continue,
1789                // A job failed: see `track_frame`.
1790                Err(code) => {
1791                    self.3.broken |= self.3.jobs;
1792                    return Err(code);
1793                }
1794            }
1795        }
1796    }
1797
1798    /// Fails while a frame is in progress (zstd refuses these calls then).
1799    ///
1800    /// zstd up to 1.5.7 would also take them after the session was reset
1801    /// while worker threads were still running jobs, freeing what they read:
1802    /// every reset here waits for them first, and this keeps the error the
1803    /// same whatever the library does.
1804    fn guard_workers(&self) -> Result<(), ErrorCode> {
1805        if self.3.pending {
1806            return Err(STAGE_WRONG_ERROR);
1807        }
1808        Ok(())
1809    }
1810
1811    /// Records a change to the dictionary or prefix the next frames read,
1812    /// once zstd accepted it. Any of them replaces the previous one.
1813    ///
1814    /// `loaded` is for a dictionary zstd copied, and `held` is what the
1815    /// context now keeps alive for zstd (nothing, for borrowed or copied
1816    /// data).
1817    ///
1818    /// Drops what the context held before, if anything: zstd no longer
1819    /// references it, and resets what pointed into it before its next frame
1820    /// reads anything (`ZSTD_reset_matchState`). zstd only takes such a
1821    /// change between frames.
1822    ///
1823    /// That drop comes last, once everything describes the new state: it
1824    /// runs the `Drop` of whoever owned a prefix or a dictionary's bytes,
1825    /// which is the caller's code and may panic.
1826    fn referenced(
1827        &mut self,
1828        prefix_borrowed: bool,
1829        dict_borrowed: bool,
1830        loaded: bool,
1831        held: Held,
1832    ) {
1833        self.3.prefix_borrowed = prefix_borrowed;
1834        self.3.dict_borrowed = dict_borrowed;
1835        self.3.loaded = loaded;
1836        let old = core::mem::replace(&mut self.4, held);
1837        drop(old);
1838    }
1839
1840    /// How many worker threads the frame in progress uses, or the next frame
1841    /// will use if none is in progress.
1842    ///
1843    /// This is the `NbWorkers` set with [`CCtx::set_parameter()`], as zstd
1844    /// clamped it to its bounds, unless that frame reads borrowed data (a
1845    /// prefix given to [`CCtx::ref_prefix()`], say): a streaming frame then
1846    /// runs on the calling thread, see
1847    /// [`CCtx`](CCtx#worker-threads-and-leaks). `compress2()` always may
1848    /// use the workers.
1849    ///
1850    /// zstd itself compresses a frame it knows to be short (512 KiB at
1851    /// most) on the calling thread, which this does not tell.
1852    pub fn frame_workers(&self) -> u32 {
1853        let workers = if self.3.pending {
1854            self.3.requested
1855        } else {
1856            !(self.3.prefix_borrowed || self.3.dict_borrowed)
1857        };
1858        if workers {
1859            self.3.count
1860        } else {
1861            0
1862        }
1863    }
1864
1865    /// Abandons the current frame, if any, and waits for the worker threads
1866    /// to be done with it.
1867    ///
1868    /// With `CParameter::NbWorkers`, the jobs of a frame run on worker
1869    /// threads, reading the dictionary. Anything that abandons a frame in
1870    /// progress waits for them first: a session reset (and `init()`, which
1871    /// implies one), a one-shot compression, and dropping the context. This
1872    /// is the same as `reset(SessionOnly)`. Waiting first compresses what was
1873    /// left of the frame's input as one more job, and throws the result away.
1874    ///
1875    /// After a job failed on a worker thread (for instance because the frame
1876    /// was given more than its pledged size), the context refuses any
1877    /// frame that would use the workers while `NbWorkers` is set (a
1878    /// streaming frame that reads borrowed data does not), and setting
1879    /// it again (with a `stage_wrong` error): zstd up to 1.5.7 can leave a
1880    /// cleared job behind that the next multithreaded frame would hand to a
1881    /// worker, which crashes. Create a new context then, or set `NbWorkers`
1882    /// to 0.
1883    ///
1884    /// Once a `ZSTD_e_end` call took all of its input, a frame takes no more:
1885    /// that is refused with a `stage_wrong` error too, instead of the worker
1886    /// threads waiting forever for a job after the last one.
1887    pub fn wait_for_workers(&mut self) -> SafeResult {
1888        self.end_blocks();
1889        self.reset(ResetDirective::SessionOnly)
1890    }
1891
1892    /// Returns the size currently used by this context.
1893    ///
1894    /// This may change over time.
1895    pub fn sizeof(&self) -> usize {
1896        // Safety: Just FFI
1897        unsafe { zstd_sys::ZSTD_sizeof_CCtx(self.0.as_ptr()) }
1898    }
1899
1900    /// Resets the state of the context.
1901    ///
1902    /// Depending on the reset mode, it can reset the session, the parameters, or both.
1903    ///
1904    /// Resetting the session abandons the frame in progress, if any: with
1905    /// worker threads, this first waits for its jobs, see
1906    /// [`CCtx::wait_for_workers()`]. Like zstd, resetting only the parameters
1907    /// fails with a `stage_wrong` error while a frame is in progress.
1908    ///
1909    /// Wraps the `ZSTD_CCtx_reset()` function.
1910    pub fn reset(&mut self, reset: ResetDirective) -> SafeResult {
1911        self.end_blocks();
1912        if reset.resets_session() {
1913            self.drain();
1914        } else {
1915            self.guard_workers()?;
1916        }
1917        // Safety: Just FFI
1918        let res = parse_code(unsafe {
1919            zstd_sys::ZSTD_CCtx_reset(self.0.as_ptr(), reset.as_sys())
1920        });
1921        if res.is_ok() && reset.resets_session() {
1922            self.2.clear();
1923            self.3.pledged_short = false;
1924        }
1925        if res.is_ok() && !matches!(reset, ResetDirective::SessionOnly) {
1926            self.3.count = 0;
1927            self.3.requested = false;
1928            self.3.stable_out = false;
1929            // Resetting the parameters also unloads the dictionary.
1930            self.referenced(false, false, false, Held::default());
1931        }
1932        res
1933    }
1934
1935    /// Sets a compression parameter.
1936    ///
1937    /// Some of these parameters need to be set during de-compression as well.
1938    ///
1939    /// Like zstd, changing `NbWorkers` fails with a `stage_wrong` error while
1940    /// a frame is in progress, and so does setting it to a non-zero value
1941    /// after a multithreaded call failed (see [`CCtx::wait_for_workers()`]).
1942    /// `NbWorkers` and `StableOutBuffer` cannot be used together.
1943    ///
1944    /// Without the `zstdmt` feature, a non-zero `NbWorkers` fails with a
1945    /// `parameter_unsupported` error, as it does in a zstd library built
1946    /// without worker threads, even when the linked library has them.
1947    pub fn set_parameter(&mut self, param: CParameter) -> SafeResult {
1948        self.end_blocks();
1949        match param {
1950            CParameter::NbWorkers(workers) => {
1951                // What a zstd built without worker threads answers. A system
1952                // library may have them: they stay off without the feature,
1953                // which is what makes the shared dictionary handles available
1954                // (see `CCtx::ref_cdict()`).
1955                #[cfg(not(feature = "zstdmt"))]
1956                if workers != 0 {
1957                    return Err(PARAMETER_UNSUPPORTED_ERROR);
1958                }
1959                // zstd would resize the job table the old jobs still use.
1960                self.guard_workers()?;
1961                // What zstd will make of the value, see `accepted_workers`.
1962                if accepted_workers(workers as c_int) != 0 {
1963                    if self.3.broken {
1964                        return Err(STAGE_WRONG_ERROR);
1965                    }
1966                    #[cfg(feature = "experimental")]
1967                    if self.3.stable_out {
1968                        return Err(PARAMETER_UNSUPPORTED_ERROR);
1969                    }
1970                }
1971            }
1972            // Waiting for the workers needs an output buffer of its own.
1973            #[cfg(feature = "experimental")]
1974            CParameter::StableOutBuffer(true) if self.3.count != 0 => {
1975                return Err(PARAMETER_UNSUPPORTED_ERROR);
1976            }
1977            _ => (),
1978        }
1979        // TODO: Until bindgen properly generates a binding for this, we'll need to do it here.
1980
1981        #[cfg(feature = "experimental")]
1982        use zstd_sys::ZSTD_cParameter::{
1983            ZSTD_c_experimentalParam1 as ZSTD_c_rsyncable,
1984            ZSTD_c_experimentalParam10 as ZSTD_c_stableOutBuffer,
1985            ZSTD_c_experimentalParam11 as ZSTD_c_blockDelimiters,
1986            ZSTD_c_experimentalParam12 as ZSTD_c_validateSequences,
1987            ZSTD_c_experimentalParam13 as ZSTD_c_useBlockSplitter,
1988            ZSTD_c_experimentalParam14 as ZSTD_c_useRowMatchFinder,
1989            ZSTD_c_experimentalParam15 as ZSTD_c_deterministicRefPrefix,
1990            ZSTD_c_experimentalParam16 as ZSTD_c_prefetchCDictTables,
1991            ZSTD_c_experimentalParam17 as ZSTD_c_enableSeqProducerFallback,
1992            ZSTD_c_experimentalParam18 as ZSTD_c_maxBlockSize,
1993            ZSTD_c_experimentalParam19 as ZSTD_c_searchForExternalRepcodes,
1994            ZSTD_c_experimentalParam2 as ZSTD_c_format,
1995            ZSTD_c_experimentalParam3 as ZSTD_c_forceMaxWindow,
1996            ZSTD_c_experimentalParam4 as ZSTD_c_forceAttachDict,
1997            ZSTD_c_experimentalParam5 as ZSTD_c_literalCompressionMode,
1998            ZSTD_c_experimentalParam7 as ZSTD_c_srcSizeHint,
1999            ZSTD_c_experimentalParam8 as ZSTD_c_enableDedicatedDictSearch,
2000            ZSTD_c_experimentalParam9 as ZSTD_c_stableInBuffer,
2001        };
2002
2003        use zstd_sys::ZSTD_cParameter::*;
2004        use CParameter::*;
2005
2006        let (param, value) = match param {
2007            #[cfg(feature = "experimental")]
2008            RSyncable(rsyncable) => (ZSTD_c_rsyncable, rsyncable as c_int),
2009            #[cfg(feature = "experimental")]
2010            Format(format) => (ZSTD_c_format, format as c_int),
2011            #[cfg(feature = "experimental")]
2012            ForceMaxWindow(force) => (ZSTD_c_forceMaxWindow, force as c_int),
2013            #[cfg(feature = "experimental")]
2014            ForceAttachDict(force) => (ZSTD_c_forceAttachDict, force as c_int),
2015            #[cfg(feature = "experimental")]
2016            LiteralCompressionMode(mode) => {
2017                (ZSTD_c_literalCompressionMode, mode as c_int)
2018            }
2019            #[cfg(feature = "experimental")]
2020            SrcSizeHint(value) => (ZSTD_c_srcSizeHint, value as c_int),
2021            #[cfg(feature = "experimental")]
2022            EnableDedicatedDictSearch(enable) => {
2023                (ZSTD_c_enableDedicatedDictSearch, enable as c_int)
2024            }
2025            // In stable mode zstd keeps reading from the `InBuffer` of one
2026            // call during `flush_stream`/`end_stream`, but the slice is only
2027            // borrowed for that one call: the safe API cannot uphold this.
2028            #[cfg(feature = "experimental")]
2029            StableInBuffer(true) => return Err(PARAMETER_UNSUPPORTED_ERROR),
2030            #[cfg(feature = "experimental")]
2031            StableInBuffer(false) => (ZSTD_c_stableInBuffer, 0),
2032            #[cfg(feature = "experimental")]
2033            StableOutBuffer(stable) => {
2034                (ZSTD_c_stableOutBuffer, stable as c_int)
2035            }
2036            #[cfg(feature = "experimental")]
2037            BlockDelimiters(value) => (ZSTD_c_blockDelimiters, value as c_int),
2038            #[cfg(feature = "experimental")]
2039            ValidateSequences(validate) => {
2040                (ZSTD_c_validateSequences, validate as c_int)
2041            }
2042            #[cfg(feature = "experimental")]
2043            UseBlockSplitter(split) => {
2044                (ZSTD_c_useBlockSplitter, split as c_int)
2045            }
2046            #[cfg(feature = "experimental")]
2047            UseRowMatchFinder(mode) => {
2048                (ZSTD_c_useRowMatchFinder, mode as c_int)
2049            }
2050            #[cfg(feature = "experimental")]
2051            DeterministicRefPrefix(deterministic) => {
2052                (ZSTD_c_deterministicRefPrefix, deterministic as c_int)
2053            }
2054            #[cfg(feature = "experimental")]
2055            PrefetchCDictTables(prefetch) => {
2056                (ZSTD_c_prefetchCDictTables, prefetch as c_int)
2057            }
2058            #[cfg(feature = "experimental")]
2059            EnableSeqProducerFallback(enable) => {
2060                (ZSTD_c_enableSeqProducerFallback, enable as c_int)
2061            }
2062            #[cfg(feature = "experimental")]
2063            MaxBlockSize(value) => (ZSTD_c_maxBlockSize, value as c_int),
2064            #[cfg(feature = "experimental")]
2065            SearchForExternalRepcodes(value) => {
2066                (ZSTD_c_searchForExternalRepcodes, value as c_int)
2067            }
2068            TargetCBlockSize(value) => {
2069                (ZSTD_c_targetCBlockSize, value as c_int)
2070            }
2071            CompressionLevel(level) => (ZSTD_c_compressionLevel, level),
2072            WindowLog(value) => (ZSTD_c_windowLog, value as c_int),
2073            HashLog(value) => (ZSTD_c_hashLog, value as c_int),
2074            ChainLog(value) => (ZSTD_c_chainLog, value as c_int),
2075            SearchLog(value) => (ZSTD_c_searchLog, value as c_int),
2076            MinMatch(value) => (ZSTD_c_minMatch, value as c_int),
2077            TargetLength(value) => (ZSTD_c_targetLength, value as c_int),
2078            Strategy(strategy) => (ZSTD_c_strategy, strategy as c_int),
2079            EnableLongDistanceMatching(flag) => {
2080                (ZSTD_c_enableLongDistanceMatching, flag as c_int)
2081            }
2082            LdmHashLog(value) => (ZSTD_c_ldmHashLog, value as c_int),
2083            LdmMinMatch(value) => (ZSTD_c_ldmMinMatch, value as c_int),
2084            LdmBucketSizeLog(value) => {
2085                (ZSTD_c_ldmBucketSizeLog, value as c_int)
2086            }
2087            LdmHashRateLog(value) => (ZSTD_c_ldmHashRateLog, value as c_int),
2088            ContentSizeFlag(flag) => (ZSTD_c_contentSizeFlag, flag as c_int),
2089            ChecksumFlag(flag) => (ZSTD_c_checksumFlag, flag as c_int),
2090            DictIdFlag(flag) => (ZSTD_c_dictIDFlag, flag as c_int),
2091
2092            NbWorkers(value) => (ZSTD_c_nbWorkers, value as c_int),
2093
2094            JobSize(value) => (ZSTD_c_jobSize, value as c_int),
2095
2096            OverlapSizeLog(value) => (ZSTD_c_overlapLog, value as c_int),
2097        };
2098
2099        // Safety: Just FFI
2100        let res = parse_code(unsafe {
2101            zstd_sys::ZSTD_CCtx_setParameter(self.0.as_ptr(), param, value)
2102        });
2103        if res.is_ok() && matches!(param, ZSTD_c_nbWorkers) {
2104            let count = accepted_workers(value);
2105            self.3.count = count;
2106            self.3.requested = count != 0;
2107            self.3.ever |= count != 0;
2108        }
2109        #[cfg(feature = "experimental")]
2110        if res.is_ok() && matches!(param, ZSTD_c_stableOutBuffer) {
2111            self.3.stable_out = value != 0;
2112        }
2113        res
2114    }
2115
2116    /// Guarantee that the input size will be this value.
2117    ///
2118    /// If given `None`, assumes the size is unknown.
2119    ///
2120    /// Unless explicitly disabled, this will cause the size to be written in the compressed frame
2121    /// header.
2122    ///
2123    /// If the actual data given to compress has a different size, an error will be returned.
2124    pub fn set_pledged_src_size(
2125        &mut self,
2126        pledged_src_size: Option<u64>,
2127    ) -> SafeResult {
2128        self.end_blocks();
2129        // Safety: Just FFI
2130        let res = parse_code(unsafe {
2131            zstd_sys::ZSTD_CCtx_setPledgedSrcSize(
2132                self.0.as_ptr(),
2133                pledged_src_size.unwrap_or(CONTENTSIZE_UNKNOWN) as c_ulonglong,
2134            )
2135        });
2136        if res.is_ok() {
2137            // See `Workers::short`.
2138            self.3.pledged_short = matches!(
2139                pledged_src_size,
2140                Some(size) if size <= ZSTDMT_JOBSIZE_MIN as u64
2141            );
2142        }
2143        res
2144    }
2145
2146    /// Starts a block session, unless `compress_block` already did and no
2147    /// other method ran since, see `Workers::blocks`.
2148    ///
2149    /// zstd carries a block on from whatever frame the context has open,
2150    /// which may read what another call only borrowed: the source of a
2151    /// one-shot or streaming call that failed mid-frame, a dictionary zstd
2152    /// freed since. A frame with a pledged size also gets tables sized for
2153    /// it, while zstd takes blocks as large as the window. So start a frame
2154    /// of unknown size from scratch, the way a streaming call does.
2155    #[cfg(feature = "experimental")]
2156    fn start_blocks(&mut self) -> Result<(), ErrorCode> {
2157        use zstd_sys::ZSTD_EndDirective::ZSTD_e_continue;
2158        if self.3.blocks {
2159            return Ok(());
2160        }
2161        self.reset(ResetDirective::SessionOnly)?;
2162        // Nothing is written: a frame's header waits for its first block.
2163        let mut scratch = [0u8; 16];
2164        self.compress_stream2(
2165            &mut OutBuffer::around(&mut scratch[..]),
2166            &mut InBuffer::around(&[]),
2167            ZSTD_e_continue,
2168        )?;
2169        self.3.blocks = true;
2170        Ok(())
2171    }
2172
2173    /// Fails if the tables of this context may not be the ones its applied
2174    /// parameters describe.
2175    ///
2176    /// Starting a multi-threaded frame overwrites the applied parameters with
2177    /// those of the workers, but leaves the context's own stage and workspace
2178    /// as the last single-threaded frame left them. If that frame was
2179    /// abandoned before its first block, zstd still accepts the calls that
2180    /// work on this context directly, and overruns a workspace that was sized
2181    /// for other parameters. The applied parameters cannot be queried, so
2182    /// refuse these calls as soon as a multi-threaded frame could have been
2183    /// started.
2184    #[cfg(feature = "experimental")]
2185    fn guard_own_tables(&self) -> Result<(), ErrorCode> {
2186        if self.3.ever {
2187            return Err(STAGE_WRONG_ERROR);
2188        }
2189        Ok(())
2190    }
2191
2192    /// Wraps the `ZSTD_getBlockSize()` function.
2193    ///
2194    /// This is the largest block `compress_block` takes in the frame the
2195    /// context has open. Before a block session started, that frame may not
2196    /// be the session's: a larger block is then refused with a `srcSize_wrong`
2197    /// error. Starting a streaming frame first gives the session's size, as
2198    /// the session starts with the same parameters.
2199    #[cfg(feature = "experimental")]
2200    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2201    #[deprecated(
2202        note = "The block API is deprecated; use the normal compression API instead."
2203    )]
2204    pub fn get_block_size(&self) -> usize {
2205        // Safety: Just FFI
2206        unsafe { zstd_sys::ZSTD_getBlockSize(self.0.as_ptr()) }
2207    }
2208
2209    /// Wraps the `ZSTD_compressBlock()` function.
2210    ///
2211    /// The blocks of a session are compressed against each other, and
2212    /// against the context's dictionary or prefix. The first call starts the
2213    /// session, with the parameters set on this context: it abandons the
2214    /// frame in progress, if any, and the pledged source size with it. Any
2215    /// other method of this context that takes `&mut self` ends the session,
2216    /// and the next call starts a new one, from an empty history. The decoder
2217    /// has to start a new session at the same points (see
2218    /// [`DCtx::decompress_block()`]).
2219    ///
2220    /// A call that fails ends the session too, and poisons the context, as a
2221    /// failed streaming call does: block and streaming calls then return that
2222    /// error until the context is reset ([`CCtx::reset()`]).
2223    ///
2224    /// Returns an error once `NbWorkers` was set to a non-zero value on this
2225    /// context.
2226    ///
2227    /// # Safety
2228    ///
2229    /// `src` becomes this context's history window, so it must stay allocated and unmodified until
2230    /// the session ends: until this call fails, or a call to another method of this context that
2231    /// takes `&mut self` returns (or until this context is dropped), as the following blocks are
2232    /// compressed against it.
2233    #[cfg(feature = "experimental")]
2234    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2235    #[deprecated(
2236        note = "The block API is deprecated; use compress_stream2 instead."
2237    )]
2238    pub unsafe fn compress_block<C: WriteBuf + ?Sized>(
2239        &mut self,
2240        dst: &mut C,
2241        src: &[u8],
2242    ) -> SafeResult {
2243        self.2.guard()?;
2244        self.guard_own_tables()?;
2245        self.start_blocks()?;
2246        // Safety: ZSTD_compressBlock returns the number of bytes written.
2247        unsafe {
2248            dst.write_from(|buffer, capacity| {
2249                let res = parse_code(zstd_sys::ZSTD_compressBlock(
2250                    self.0.as_ptr(),
2251                    buffer,
2252                    capacity,
2253                    ptr_void(src),
2254                    src.len(),
2255                ));
2256                // zstd makes no promise about the state a failed call leaves
2257                // behind: end the session, and its frame with it, and refuse
2258                // to carry on until the caller resets the context, which
2259                // tells them to restart the decoder's session too.
2260                if res.is_err() {
2261                    self.end_blocks_now();
2262                }
2263                self.2.record(res)
2264            })
2265        }
2266    }
2267
2268    /// Returns the recommended input buffer size.
2269    ///
2270    /// Using this size may result in minor performance boost.
2271    pub fn in_size() -> usize {
2272        // Safety: Just FFI
2273        unsafe { zstd_sys::ZSTD_CStreamInSize() }
2274    }
2275
2276    /// Returns the recommended output buffer size.
2277    ///
2278    /// Using this may result in minor performance boost.
2279    pub fn out_size() -> usize {
2280        // Safety: Just FFI
2281        unsafe { zstd_sys::ZSTD_CStreamOutSize() }
2282    }
2283
2284    /// Use a shared thread pool for this context.
2285    ///
2286    /// Thread pool must outlive the context.
2287    #[cfg(all(feature = "experimental", feature = "zstdmt"))]
2288    #[cfg_attr(
2289        feature = "doc-cfg",
2290        doc(cfg(all(feature = "experimental", feature = "zstdmt")))
2291    )]
2292    pub fn ref_thread_pool<'b>(&mut self, pool: &'b ThreadPool) -> SafeResult
2293    where
2294        'b: 'a,
2295    {
2296        self.end_blocks();
2297        parse_code(unsafe {
2298            zstd_sys::ZSTD_CCtx_refThreadPool(self.0.as_ptr(), pool.0.as_ptr())
2299        })
2300    }
2301
2302    /// Return to using a private thread pool for this context.
2303    #[cfg(all(feature = "experimental", feature = "zstdmt"))]
2304    #[cfg_attr(
2305        feature = "doc-cfg",
2306        doc(cfg(all(feature = "experimental", feature = "zstdmt")))
2307    )]
2308    pub fn disable_thread_pool(&mut self) -> SafeResult {
2309        self.end_blocks();
2310        parse_code(unsafe {
2311            zstd_sys::ZSTD_CCtx_refThreadPool(
2312                self.0.as_ptr(),
2313                core::ptr::null_mut(),
2314            )
2315        })
2316    }
2317
2318    #[cfg(feature = "experimental")]
2319    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2320    pub fn get_frame_progression(&self) -> FrameProgression {
2321        // Safety: Just FFI
2322        unsafe { zstd_sys::ZSTD_getFrameProgression(self.0.as_ptr()) }
2323    }
2324}
2325
2326impl<'a> Drop for CCtx<'a> {
2327    fn drop(&mut self) {
2328        // zstd up to 1.5.7 frees the dictionary before it stops the worker
2329        // threads, and does not stop a shared pool's at all: wait for the
2330        // jobs of the frame in progress first.
2331        self.drain();
2332        // Safety: Just FFI
2333        unsafe {
2334            zstd_sys::ZSTD_freeCCtx(self.0.as_ptr());
2335        }
2336    }
2337}
2338
2339// Safety: the context is a plain heap allocation this handle owns; zstd keeps
2340// no thread-local state for it, so it can be moved between threads.
2341unsafe impl Send for CCtx<'_> {}
2342// Safety: every method that mutates the context takes `&mut self`, so a shared
2343// `&CCtx` only ever reads. There is no interior mutability to race on.
2344unsafe impl Sync for CCtx<'_> {}
2345
2346/// Converts a zstd-owned C string to a `str`.
2347///
2348/// # Safety
2349///
2350/// `text` must point to a nul-terminated C string that lives for the rest of
2351/// the program - which is what the zstd functions this is used with return,
2352/// as they hand back pointers to static string literals.
2353unsafe fn c_char_to_str(text: *const c_char) -> &'static str {
2354    // Safety: guaranteed by the caller, see above.
2355    core::ffi::CStr::from_ptr(text)
2356        .to_str()
2357        .expect("bad error message from zstd")
2358}
2359
2360/// Returns the error string associated with an error code.
2361pub fn get_error_name(code: usize) -> &'static str {
2362    unsafe {
2363        // Safety: assumes ZSTD returns a well-formed utf8 string.
2364        let name = zstd_sys::ZSTD_getErrorName(code);
2365        c_char_to_str(name)
2366    }
2367}
2368
2369/// Returns whether `code` is an error of the given kind.
2370///
2371/// The kinds are those of `zstd_sys::ZSTD_ErrorCode`, listed in
2372/// `zstd_errors.h`.
2373///
2374/// This goes from `kind` to a code rather than the other way around, so it
2375/// works whatever the version of the linked libzstd: a code these bindings
2376/// don't know is just not equal to any `kind`.
2377///
2378/// ```
2379/// use zstd_safe::zstd_sys::ZSTD_ErrorCode;
2380///
2381/// let mut small = [0u8; 4];
2382/// let code = zstd_safe::compress(&mut small[..], &[42u8; 1000], 3).unwrap_err();
2383/// assert!(zstd_safe::is_error_kind(code, ZSTD_ErrorCode::ZSTD_error_dstSize_tooSmall));
2384/// ```
2385pub fn is_error_kind(code: ErrorCode, kind: zstd_sys::ZSTD_ErrorCode) -> bool {
2386    // Error codes are the negated error values, as a `size_t`.
2387    is_error(code) && code == (kind as usize).wrapping_neg()
2388}
2389
2390/// A Decompression Context.
2391///
2392/// The lifetime references the potential dictionary used for this context.
2393///
2394/// If no dictionary was used, it will most likely be `'static`.
2395///
2396/// Same as `DStream`.
2397pub struct DCtx<'a>(
2398    NonNull<zstd_sys::ZSTD_DCtx>,
2399    PhantomData<&'a ()>,
2400    Poison,
2401    DState,
2402);
2403
2404/// What a `DCtx` remembers about its own use.
2405#[derive(Clone, Copy, Debug, Default)]
2406struct DState {
2407    /// A streaming (or block) call ran since the session was last reset, so
2408    /// a stream may be open, see `finish_one_shot`.
2409    streamed: bool,
2410    /// The last call that decoded anything was a block call, which started
2411    /// or carried on a block session and did not fail, and the session was
2412    /// not reset since, see `DCtx::start_blocks()`.
2413    blocks: bool,
2414}
2415
2416impl Default for DCtx<'_> {
2417    fn default() -> Self {
2418        DCtx::create()
2419    }
2420}
2421
2422impl<'a> DCtx<'a> {
2423    /// Try to create a new decompression context.
2424    ///
2425    /// Returns `None` if the operation failed (for example, not enough memory).
2426    ///
2427    /// With the `with-rust-allocator` feature enabled, the context's internal
2428    /// allocations go through Rust's global allocator instead of the C
2429    /// runtime's `malloc`.
2430    pub fn try_create() -> Option<Self> {
2431        #[cfg(feature = "with-rust-allocator")]
2432        // Safety: the callbacks satisfy zstd's allocation contract and remain
2433        // valid for the lifetime of the context.
2434        let context = unsafe {
2435            zstd_sys::ZSTD_createDCtx_advanced(
2436                crate::rust_allocator::RUST_GLOBAL_ALLOCATOR,
2437            )
2438        };
2439        #[cfg(not(feature = "with-rust-allocator"))]
2440        // Safety: zstd returns a newly owned context or null.
2441        let context = unsafe { zstd_sys::ZSTD_createDCtx() };
2442
2443        Some(Self(
2444            NonNull::new(context)?,
2445            PhantomData,
2446            Poison::default(),
2447            DState::default(),
2448        ))
2449    }
2450
2451    /// Creates a new decoding context.
2452    ///
2453    /// # Panics
2454    ///
2455    /// If the context creation fails.
2456    pub fn create() -> Self {
2457        Self::try_create()
2458            .expect("zstd returned null pointer when creating new context")
2459    }
2460
2461    /// Ends the session of a one-shot decompression, and passes `res` through.
2462    ///
2463    /// zstd.h has these calls imply a reset, but they leave the stream stage
2464    /// alone. A stream they interrupted would then carry on from a state that
2465    /// still points at buffers and dictionaries borrowed for that one call. So
2466    /// reset explicitly: the next stream starts from scratch.
2467    ///
2468    /// Only an open stream can carry on, though: a new one starts by setting
2469    /// everything up again from the context's own dictionary. So when no
2470    /// streaming call ran since the last reset, there is nothing to end, and
2471    /// skipping the reset saves a call per frame - which shows on tiny ones.
2472    ///
2473    /// Only the check is inlined: it runs once per frame.
2474    ///
2475    /// Called as soon as zstd returns, inside the closure given to
2476    /// `write_from`: that is the caller's code, which may panic afterwards.
2477    #[inline]
2478    fn finish_one_shot(&mut self, res: SafeResult) -> SafeResult {
2479        self.3.blocks = false;
2480        if self.3.streamed || self.2.guard().is_err() {
2481            self.reset_after_one_shot(res)
2482        } else {
2483            res
2484        }
2485    }
2486
2487    #[cold]
2488    #[inline(never)]
2489    fn reset_after_one_shot(&mut self, res: SafeResult) -> SafeResult {
2490        self.reset(ResetDirective::SessionOnly).and(res)
2491    }
2492
2493    /// Fully decompress the given frame.
2494    ///
2495    /// This decompress an entire frame in-memory. If you can have enough memory to store both the
2496    /// input and output buffer, then it may be faster that streaming decompression.
2497    ///
2498    /// Only as many bytes as returned at the start of `dst` are meaningful:
2499    /// zstd may overwrite the rest. A `Vec` avoids this, see
2500    /// [`crate::decompress()`]: it is never re-allocated, so create it with
2501    /// `Vec::with_capacity` for the full decompressed size.
2502    ///
2503    /// Wraps the `ZSTD_decompressDCtx()` function.
2504    pub fn decompress<C: WriteBuf + ?Sized>(
2505        &mut self,
2506        dst: &mut C,
2507        src: &[u8],
2508    ) -> SafeResult {
2509        unsafe {
2510            dst.write_from(|buffer, capacity| {
2511                let res = parse_code(zstd_sys::ZSTD_decompressDCtx(
2512                    self.0.as_ptr(),
2513                    buffer,
2514                    capacity,
2515                    ptr_void(src),
2516                    src.len(),
2517                ));
2518                self.finish_one_shot(res)
2519            })
2520        }
2521    }
2522
2523    /// Fully decompress the given frame using a dictionary.
2524    ///
2525    /// Dictionary must be identical to the one used during compression.
2526    ///
2527    /// If you plan on using the same dictionary multiple times, it is faster to create a `DDict`
2528    /// first and use `decompress_using_ddict`.
2529    ///
2530    /// Only as many bytes as returned at the start of `dst` are meaningful:
2531    /// zstd may overwrite the rest. A `Vec` avoids this, see
2532    /// [`crate::decompress()`]: it is never re-allocated, so create it with
2533    /// `Vec::with_capacity` for the full decompressed size.
2534    ///
2535    /// Wraps `ZSTD_decompress_usingDict`
2536    pub fn decompress_using_dict<C: WriteBuf + ?Sized>(
2537        &mut self,
2538        dst: &mut C,
2539        src: &[u8],
2540        dict: &[u8],
2541    ) -> SafeResult {
2542        unsafe {
2543            dst.write_from(|buffer, capacity| {
2544                let res = parse_code(zstd_sys::ZSTD_decompress_usingDict(
2545                    self.0.as_ptr(),
2546                    buffer,
2547                    capacity,
2548                    ptr_void(src),
2549                    src.len(),
2550                    ptr_void(dict),
2551                    dict.len(),
2552                ));
2553                self.finish_one_shot(res)
2554            })
2555        }
2556    }
2557
2558    /// Fully decompress the given frame using a dictionary.
2559    ///
2560    /// Dictionary must be identical to the one used during compression.
2561    ///
2562    /// Only as many bytes as returned at the start of `dst` are meaningful:
2563    /// zstd may overwrite the rest. A `Vec` avoids this, see
2564    /// [`crate::decompress()`]: it is never re-allocated, so create it with
2565    /// `Vec::with_capacity` for the full decompressed size.
2566    ///
2567    /// Wraps the `ZSTD_decompress_usingDDict()` function.
2568    pub fn decompress_using_ddict<C: WriteBuf + ?Sized>(
2569        &mut self,
2570        dst: &mut C,
2571        src: &[u8],
2572        ddict: &DDict<'_>,
2573    ) -> SafeResult {
2574        unsafe {
2575            dst.write_from(|buffer, capacity| {
2576                let res = parse_code(zstd_sys::ZSTD_decompress_usingDDict(
2577                    self.0.as_ptr(),
2578                    buffer,
2579                    capacity,
2580                    ptr_void(src),
2581                    src.len(),
2582                    ddict.0.as_ptr(),
2583                ));
2584                self.finish_one_shot(res)
2585            })
2586        }
2587    }
2588
2589    /// Initializes an existing `DStream` for decompression.
2590    ///
2591    /// This is equivalent to calling:
2592    /// * `reset(SessionOnly)`
2593    /// * `disable_dictionary()`
2594    ///
2595    /// Wraps the `ZSTD_initCStream()` function.
2596    pub fn init(&mut self) -> SafeResult {
2597        self.2.clear();
2598        let code = unsafe { zstd_sys::ZSTD_initDStream(self.0.as_ptr()) };
2599        self.2.record(parse_code(code))
2600    }
2601
2602    /// Wraps the `ZSTD_initDStream_usingDict()` function.
2603    #[cfg(feature = "experimental")]
2604    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2605    #[deprecated(note = "Use reset and load_dictionary instead.")]
2606    pub fn init_using_dict(&mut self, dict: &[u8]) -> SafeResult {
2607        self.2.clear();
2608        let code = unsafe {
2609            zstd_sys::ZSTD_initDStream_usingDict(
2610                self.0.as_ptr(),
2611                ptr_void(dict),
2612                dict.len(),
2613            )
2614        };
2615        parse_code(code)
2616    }
2617
2618    /// Wraps the `ZSTD_initDStream_usingDDict()` function.
2619    ///
2620    /// Dictionary must outlive the context.
2621    ///
2622    /// ```compile_fail,E0515
2623    /// # #![allow(deprecated)]
2624    /// fn decompressor() -> zstd_safe::DCtx<'static> {
2625    ///     let ddict = zstd_safe::DDict::create(b"dictionary");
2626    ///     let mut dctx = zstd_safe::DCtx::create();
2627    ///     dctx.init_using_ddict(&ddict).unwrap();
2628    ///     dctx // `ddict` would be dropped while `dctx` still points at it.
2629    /// }
2630    /// ```
2631    #[cfg(feature = "experimental")]
2632    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2633    #[deprecated(note = "Use reset and ref_ddict instead.")]
2634    pub fn init_using_ddict<'b>(&mut self, ddict: &'a DDict<'b>) -> SafeResult
2635    where
2636        'b: 'a,
2637    {
2638        self.2.clear();
2639        // Safety: Just FFI
2640        let code = unsafe {
2641            zstd_sys::ZSTD_initDStream_usingDDict(
2642                self.0.as_ptr(),
2643                ddict.0.as_ptr(),
2644            )
2645        };
2646        self.2.record(parse_code(code))
2647    }
2648
2649    /// Resets the state of the context.
2650    ///
2651    /// Depending on the reset mode, it can reset the session, the parameters, or both.
2652    ///
2653    /// Wraps the `ZSTD_DCtx_reset()` function.
2654    pub fn reset(&mut self, reset: ResetDirective) -> SafeResult {
2655        let res = parse_code(unsafe {
2656            zstd_sys::ZSTD_DCtx_reset(self.0.as_ptr(), reset.as_sys())
2657        });
2658        if res.is_ok() && reset.resets_session() {
2659            self.2.clear();
2660            self.3.streamed = false;
2661            // So that a decoder can start a new block session where its
2662            // encoder did (`CCtx::compress_block`).
2663            self.3.blocks = false;
2664        }
2665        res
2666    }
2667
2668    /// Loads a dictionary.
2669    ///
2670    /// This will let this context decompress frames that were compressed using this dictionary.
2671    ///
2672    /// The dictionary content will be copied internally and does not need to be kept alive after
2673    /// calling this function.
2674    ///
2675    /// If you need to use the same dictionary for multiple contexts, it may be more efficient to
2676    /// create a `DDict` first, then loads that.
2677    ///
2678    /// The dictionary will apply to all future frames, until a new dictionary is set.
2679    pub fn load_dictionary(&mut self, dict: &[u8]) -> SafeResult {
2680        parse_code(unsafe {
2681            zstd_sys::ZSTD_DCtx_loadDictionary(
2682                self.0.as_ptr(),
2683                ptr_void(dict),
2684                dict.len(),
2685            )
2686        })
2687    }
2688
2689    /// Loads a dictionary, read as `content_type`.
2690    ///
2691    /// Like [`DCtx::load_dictionary()`], which reads it as
2692    /// [`DictContentType::Auto`]: the dictionary is copied.
2693    ///
2694    /// Wraps the `ZSTD_DCtx_loadDictionary_advanced()` function.
2695    pub fn load_dictionary_advanced(
2696        &mut self,
2697        dict: &[u8],
2698        content_type: DictContentType,
2699    ) -> SafeResult {
2700        // Safety: Just FFI
2701        parse_code(unsafe {
2702            zstd_sys::ZSTD_DCtx_loadDictionary_advanced(
2703                self.0.as_ptr(),
2704                ptr_void(dict),
2705                dict.len(),
2706                zstd_sys::ZSTD_dictLoadMethod_e::ZSTD_dlm_byCopy,
2707                content_type.c_type(),
2708            )
2709        })
2710    }
2711
2712    /// Loads a dictionary without copying it, read as `content_type`.
2713    ///
2714    /// The dictionary applies to all future frames, until a new one is set.
2715    ///
2716    /// Wraps the `ZSTD_DCtx_loadDictionary_advanced()` function.
2717    pub fn ref_dictionary<'b>(
2718        &mut self,
2719        dict: &'b [u8],
2720        content_type: DictContentType,
2721    ) -> SafeResult
2722    where
2723        'b: 'a,
2724    {
2725        // Safety: Just FFI. `dict` outlives the context.
2726        parse_code(unsafe {
2727            zstd_sys::ZSTD_DCtx_loadDictionary_advanced(
2728                self.0.as_ptr(),
2729                ptr_void(dict),
2730                dict.len(),
2731                zstd_sys::ZSTD_dictLoadMethod_e::ZSTD_dlm_byRef,
2732                content_type.c_type(),
2733            )
2734        })
2735    }
2736
2737    /// Return to "no-dictionary" mode.
2738    ///
2739    /// This will disable any dictionary/prefix previously registered for future frames.
2740    pub fn disable_dictionary(&mut self) -> SafeResult {
2741        parse_code(unsafe {
2742            zstd_sys::ZSTD_DCtx_loadDictionary(
2743                self.0.as_ptr(),
2744                core::ptr::null(),
2745                0,
2746            )
2747        })
2748    }
2749
2750    /// References a dictionary.
2751    ///
2752    /// This will let this context decompress frames compressed with the same dictionary.
2753    ///
2754    /// It will apply to all frames decompressed by this context (until a new dictionary is set).
2755    ///
2756    /// Wraps the `ZSTD_DCtx_refDDict()` function.
2757    ///
2758    /// Dictionary must outlive the context.
2759    pub fn ref_ddict<'b>(&mut self, ddict: &'a DDict<'b>) -> SafeResult
2760    where
2761        'b: 'a,
2762    {
2763        parse_code(unsafe {
2764            zstd_sys::ZSTD_DCtx_refDDict(self.0.as_ptr(), ddict.0.as_ptr())
2765        })
2766    }
2767
2768    /// Use some prefix as single-use dictionary for the next frame.
2769    ///
2770    /// Just like a dictionary, this only works if compression was done with the same prefix.
2771    ///
2772    /// But unlike a dictionary, this only applies to the next frame.
2773    ///
2774    /// Wraps the `ZSTD_DCtx_refPrefix()` function.
2775    pub fn ref_prefix<'b>(&mut self, prefix: &'b [u8]) -> SafeResult
2776    where
2777        'b: 'a,
2778    {
2779        parse_code(unsafe {
2780            zstd_sys::ZSTD_DCtx_refPrefix(
2781                self.0.as_ptr(),
2782                ptr_void(prefix),
2783                prefix.len(),
2784            )
2785        })
2786    }
2787
2788    /// Sets a decompression parameter.
2789    pub fn set_parameter(&mut self, param: DParameter) -> SafeResult {
2790        #[cfg(feature = "experimental")]
2791        use zstd_sys::ZSTD_dParameter::{
2792            ZSTD_d_experimentalParam1 as ZSTD_d_format,
2793            ZSTD_d_experimentalParam2 as ZSTD_d_stableOutBuffer,
2794            ZSTD_d_experimentalParam3 as ZSTD_d_forceIgnoreChecksum,
2795            ZSTD_d_experimentalParam4 as ZSTD_d_refMultipleDDicts,
2796        };
2797
2798        use zstd_sys::ZSTD_dParameter::*;
2799        use DParameter::*;
2800
2801        let (param, value) = match param {
2802            #[cfg(feature = "experimental")]
2803            Format(format) => (ZSTD_d_format, format as c_int),
2804            #[cfg(feature = "experimental")]
2805            StableOutBuffer(stable) => {
2806                (ZSTD_d_stableOutBuffer, stable as c_int)
2807            }
2808            #[cfg(feature = "experimental")]
2809            ForceIgnoreChecksum(force) => {
2810                (ZSTD_d_forceIgnoreChecksum, force as c_int)
2811            }
2812            #[cfg(feature = "experimental")]
2813            RefMultipleDDicts(value) => {
2814                (ZSTD_d_refMultipleDDicts, value as c_int)
2815            }
2816
2817            WindowLogMax(value) => (ZSTD_d_windowLogMax, value as c_int),
2818        };
2819
2820        parse_code(unsafe {
2821            zstd_sys::ZSTD_DCtx_setParameter(self.0.as_ptr(), param, value)
2822        })
2823    }
2824
2825    /// Performs a step of a streaming decompression operation.
2826    ///
2827    /// This will read some data from `input` and/or write some data to `output`.
2828    ///
2829    /// # Returns
2830    ///
2831    /// * `Ok(0)` if the current frame just finished decompressing successfully.
2832    /// * `Ok(hint)` with a hint for the "ideal" amount of input data to provide in the next call.
2833    ///   Can be safely ignored.
2834    ///
2835    /// Wraps the `ZSTD_decompressStream()` function.
2836    pub fn decompress_stream<C: WriteBuf + ?Sized>(
2837        &mut self,
2838        output: &mut OutBuffer<'_, C>,
2839        input: &mut InBuffer<'_>,
2840    ) -> SafeResult {
2841        self.2.guard()?;
2842        self.3.streamed = true;
2843        self.3.blocks = false;
2844        let mut output = output.wrap();
2845        let mut input = input.wrap();
2846        let code = unsafe {
2847            zstd_sys::ZSTD_decompressStream(
2848                self.0.as_ptr(),
2849                ptr_mut(&mut output),
2850                ptr_mut(&mut input),
2851            )
2852        };
2853        let res = output.check(parse_code(code));
2854        self.2.record(input.check(res))
2855    }
2856
2857    /// Wraps the `ZSTD_DStreamInSize()` function.
2858    ///
2859    /// Returns a hint for the recommended size of the input buffer for decompression.
2860    pub fn in_size() -> usize {
2861        unsafe { zstd_sys::ZSTD_DStreamInSize() }
2862    }
2863
2864    /// Wraps the `ZSTD_DStreamOutSize()` function.
2865    ///
2866    /// Returns a hint for the recommended size of the output buffer for decompression.
2867    pub fn out_size() -> usize {
2868        unsafe { zstd_sys::ZSTD_DStreamOutSize() }
2869    }
2870
2871    /// Wraps the `ZSTD_sizeof_DCtx()` function.
2872    pub fn sizeof(&self) -> usize {
2873        unsafe { zstd_sys::ZSTD_sizeof_DCtx(self.0.as_ptr()) }
2874    }
2875
2876    /// Starts a block session, unless the last call that decoded anything
2877    /// was a block call, which already did.
2878    ///
2879    /// A frame leaves its history window behind, in buffers and dictionaries
2880    /// the call that decoded it may only have borrowed (and, with a
2881    /// `DDict`, the entropy tables too), and a new context starts with none
2882    /// set up at all. `ZSTD_decompressBlock()` would carry on from that, so
2883    /// start from an empty history first, as zstd.h asks. That also ends the
2884    /// stream in progress, if any: the next streaming call starts a new one.
2885    #[cfg(feature = "experimental")]
2886    fn start_blocks(&mut self) {
2887        if !self.3.blocks {
2888            // Safety: Just FFI. Both only reset fields, and cannot fail. The
2889            // poison is left alone: only `reset` clears it (`insert_block`
2890            // cannot report it, the next `decompress_block` does).
2891            unsafe {
2892                zstd_sys::ZSTD_DCtx_reset(
2893                    self.0.as_ptr(),
2894                    zstd_sys::ZSTD_ResetDirective::ZSTD_reset_session_only,
2895                );
2896                zstd_sys::ZSTD_decompressBegin(self.0.as_ptr());
2897            }
2898            self.3.blocks = true;
2899        }
2900        self.3.streamed = true;
2901    }
2902
2903    /// Wraps the `ZSTD_decompressBlock()` function.
2904    ///
2905    /// The first block call (`decompress_block` or `insert_block`) on this
2906    /// context, or the first one after any other decoding call (a one-shot
2907    /// call, or `decompress_stream`) or a session reset (`reset`), starts a
2908    /// new block session, with an empty history: blocks are only decoded
2909    /// against the blocks of the same session, which has to start where the
2910    /// encoder's did (see [`CCtx::compress_block()`]). Starting one abandons
2911    /// the stream in progress, if any.
2912    ///
2913    /// A call that fails ends the session too, and poisons the context, as a
2914    /// failed streaming call does: block and streaming calls then return that
2915    /// error until the context is reset ([`DCtx::reset()`]).
2916    ///
2917    /// To decode blocks against a raw-content dictionary, start the session
2918    /// with `insert_block(dictionary)`.
2919    ///
2920    /// # Safety
2921    ///
2922    /// The bytes written to `dst` become this context's history window, so `dst` must stay
2923    /// allocated and unmodified until the block session ends (see above), or until this context is
2924    /// dropped, as the following blocks of the session are decoded against it.
2925    #[cfg(feature = "experimental")]
2926    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2927    #[deprecated(
2928        note = "The block API is deprecated; use decompress_stream instead."
2929    )]
2930    pub unsafe fn decompress_block<C: WriteBuf + ?Sized>(
2931        &mut self,
2932        dst: &mut C,
2933        src: &[u8],
2934    ) -> SafeResult {
2935        self.2.guard()?;
2936        self.start_blocks();
2937        unsafe {
2938            dst.write_from(|buffer, capacity| {
2939                let res = parse_code(zstd_sys::ZSTD_decompressBlock(
2940                    self.0.as_ptr(),
2941                    buffer,
2942                    capacity,
2943                    ptr_void(src),
2944                    src.len(),
2945                ));
2946                // zstd makes no promise about the state a failed call leaves
2947                // behind: refuse to carry on until the caller resets the
2948                // context, which starts a new session.
2949                if res.is_err() {
2950                    self.3.blocks = false;
2951                }
2952                self.2.record(res)
2953            })
2954        }
2955    }
2956
2957    /// Wraps the `ZSTD_insertBlock()` function.
2958    ///
2959    /// Like `decompress_block`, this may start a new block session. It
2960    /// returns no error, so it does not report a poisoned context either:
2961    /// the next `decompress_block` does.
2962    ///
2963    /// # Safety
2964    ///
2965    /// `block` becomes this context's history window, so it must stay allocated and unmodified
2966    /// until the block session ends (see `decompress_block`), or until this context is dropped, as
2967    /// the following blocks of the session are decoded against it.
2968    #[cfg(feature = "experimental")]
2969    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
2970    #[deprecated(
2971        note = "The block API is deprecated; use decompress_stream instead."
2972    )]
2973    pub unsafe fn insert_block(&mut self, block: &[u8]) -> usize {
2974        self.start_blocks();
2975        unsafe {
2976            zstd_sys::ZSTD_insertBlock(
2977                self.0.as_ptr(),
2978                ptr_void(block),
2979                block.len(),
2980            )
2981        }
2982    }
2983}
2984
2985impl Drop for DCtx<'_> {
2986    fn drop(&mut self) {
2987        unsafe {
2988            zstd_sys::ZSTD_freeDCtx(self.0.as_ptr());
2989        }
2990    }
2991}
2992
2993// Safety: as for `CCtx` - an owned heap allocation with no thread-local state.
2994unsafe impl Send for DCtx<'_> {}
2995// Non thread-safe methods already take `&mut self`, so it's fine to implement Sync here.
2996// Safety: as for `CCtx` - the mutating methods all take `&mut self`.
2997unsafe impl Sync for DCtx<'_> {}
2998
2999/// Owns bytes that zstd points into, without copying them: a `Vec<u8>`, an
3000/// `Arc<[u8]>`, a memory map...
3001///
3002/// Kept as a raw pointer rather than a `Box`: the bytes may live inside the
3003/// owner, and moving a `Box` would assert unique access to memory zstd still
3004/// points into. The owner goes to its final place on the heap before its
3005/// bytes are taken, and is not touched again until it is dropped.
3006#[cfg(feature = "alloc")]
3007struct Owner(NonNull<dyn Send + Sync>);
3008
3009#[cfg(feature = "alloc")]
3010impl Owner {
3011    /// Moves `owner` to the heap, and returns it with its bytes.
3012    ///
3013    /// The bytes stay valid until the `Owner` is dropped.
3014    fn new<P>(owner: P) -> (Self, *const u8, usize)
3015    where
3016        P: core::ops::Deref + Send + Sync + 'static,
3017        P::Target: AsRef<[u8]>,
3018    {
3019        let owner: *mut P =
3020            alloc::boxed::Box::into_raw(alloc::boxed::Box::new(owner));
3021        // Safety: `owner` is valid, and only ever read from now on.
3022        let bytes: &[u8] = unsafe { (**owner).as_ref() };
3023        let (ptr, len) = (bytes.as_ptr(), bytes.len());
3024        let owner: *mut (dyn Send + Sync) = owner;
3025        // Safety: from a `Box`, so not null.
3026        (Owner(unsafe { NonNull::new_unchecked(owner) }), ptr, len)
3027    }
3028}
3029
3030#[cfg(feature = "alloc")]
3031impl Drop for Owner {
3032    fn drop(&mut self) {
3033        // Safety: made by `Box::into_raw`, and only read since.
3034        drop(unsafe { alloc::boxed::Box::from_raw(self.0.as_ptr()) });
3035    }
3036}
3037
3038// Safety: the owner is `Send + Sync`; this only reads it, then drops it.
3039#[cfg(feature = "alloc")]
3040unsafe impl Send for Owner {}
3041#[cfg(feature = "alloc")]
3042unsafe impl Sync for Owner {}
3043
3044// The owner is never called into after a panic, only dropped: a context or
3045// a dictionary that holds one stays as unwind-safe as it was without.
3046#[cfg(feature = "alloc")]
3047impl core::panic::UnwindSafe for Owner {}
3048#[cfg(feature = "alloc")]
3049impl core::panic::RefUnwindSafe for Owner {}
3050
3051/// Compression dictionary.
3052///
3053/// A digested dictionary, cheap to share: with the `alloc` feature (on targets
3054/// with pointer-sized atomics), it is a reference-counted handle, and cloning
3055/// it shares the same digested tables. A context referencing it
3056/// ([`CCtx::ref_cdict()`]) keeps its own handle, so the dictionary lives as
3057/// long as any context uses it, leaked ones included. Without `alloc`, it has
3058/// a single owner: move it into a context ([`CCtx::set_cdict()`]) or borrow
3059/// it.
3060///
3061/// The bytes it was made from are copied ([`CDict::create()`]), owned by the
3062/// dictionary (`CDict::create_by_reference_owned()`), or borrowed for `'a`
3063/// (`CDict::create_by_reference()`). With worker threads, a streaming frame
3064/// that reads borrowed bytes runs on the calling thread, see
3065/// [`CCtx`](CCtx#worker-threads-and-leaks).
3066///
3067/// With `with-rust-allocator`, prepared dictionaries retain fixed compression
3068/// parameters rather than adapting them to later input sizes. This can change
3069/// compression ratio, speed, and memory usage compared with the C allocator.
3070pub struct CDict<'a>(CDictHandle, Borrow<'a>);
3071
3072/// The borrow of the bytes a [`CDict`] may point into.
3073///
3074/// Its `Drop` does nothing, but tells the borrow checker what the one of
3075/// `CDict<'a>` itself did before it was a handle: the bytes must still be
3076/// alive when the dictionary is dropped.
3077struct Borrow<'a>(PhantomData<&'a ()>);
3078
3079impl Drop for Borrow<'_> {
3080    fn drop(&mut self) {}
3081}
3082
3083#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
3084type CDictHandle = alloc::sync::Arc<CDictInner>;
3085#[cfg(not(all(feature = "alloc", target_has_atomic = "ptr")))]
3086type CDictHandle = CDictInner;
3087
3088/// What a [`CDict`] handle points to.
3089struct CDictInner {
3090    ptr: NonNull<zstd_sys::ZSTD_CDict>,
3091    /// The dictionary points into bytes it only borrows
3092    /// (`CDict::create_by_reference()`), for the `'a` of its handles.
3093    borrows: bool,
3094    /// Owns the bytes a dictionary made by reference points into, see
3095    /// `CDict::try_create_by_reference_owned()`. Dropped after the
3096    /// dictionary is freed.
3097    #[cfg(feature = "alloc")]
3098    #[allow(dead_code)] // Only kept alive.
3099    owner: Option<Owner>,
3100}
3101
3102impl Drop for CDictInner {
3103    fn drop(&mut self) {
3104        // The dictionary first: it may point into the owner.
3105        // Safety: this is the last handle to it.
3106        unsafe {
3107            zstd_sys::ZSTD_freeCDict(self.ptr.as_ptr());
3108        }
3109        // Then `owner`, as a field.
3110    }
3111}
3112
3113// Safety: a digested dictionary is immutable once built. zstd.h: "ZSTD_CDict
3114// can be created once and shared by multiple threads concurrently, since its
3115// usage is read-only". The owner is `Send + Sync`, and is only dropped.
3116unsafe impl Send for CDictInner {}
3117unsafe impl Sync for CDictInner {}
3118
3119#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
3120impl Clone for CDict<'_> {
3121    /// Returns another handle to the same digested dictionary.
3122    fn clone(&self) -> Self {
3123        CDict(self.0.clone(), Borrow(PhantomData))
3124    }
3125}
3126
3127impl<'a> CDict<'a> {
3128    /// `borrows`: the dictionary points into bytes borrowed for `'a`.
3129    fn from_raw(
3130        ptr: *mut zstd_sys::ZSTD_CDict,
3131        borrows: bool,
3132    ) -> Option<Self> {
3133        let inner = CDictInner {
3134            ptr: NonNull::new(ptr)?,
3135            borrows,
3136            #[cfg(feature = "alloc")]
3137            owner: None,
3138        };
3139        // Without `alloc`, the handle is the dictionary itself.
3140        #[allow(clippy::useless_conversion)]
3141        let handle = inner.into();
3142        Some(CDict(handle, Borrow(PhantomData)))
3143    }
3144
3145    fn as_ptr(&self) -> *mut zstd_sys::ZSTD_CDict {
3146        self.0.ptr.as_ptr()
3147    }
3148
3149    /// Whether the dictionary points into bytes it only borrows.
3150    fn borrows(&self) -> bool {
3151        self.0.borrows
3152    }
3153
3154    /// Forgets the lifetime of the bytes the dictionary may point into, for
3155    /// a context to hold it: a `CCtx<'b>` only takes a dictionary whose
3156    /// `'a` outlives its own `'b`, which it stands for from then on.
3157    fn erased(self) -> CDict<'static> {
3158        CDict(self.0, Borrow(PhantomData))
3159    }
3160}
3161
3162impl CDict<'static> {
3163    /// Prepare a dictionary to compress data.
3164    ///
3165    /// This will make it easier for compression contexts to load this dictionary.
3166    ///
3167    /// The dictionary content will be copied internally, and does not need to be kept around.
3168    ///
3169    /// # Panics
3170    ///
3171    /// If loading this dictionary failed.
3172    pub fn create(
3173        dict_buffer: &[u8],
3174        compression_level: CompressionLevel,
3175    ) -> Self {
3176        Self::try_create(dict_buffer, compression_level)
3177            .expect("zstd returned null pointer when creating dict")
3178    }
3179
3180    /// Prepare a dictionary to compress data.
3181    ///
3182    /// This will make it easier for compression contexts to load this dictionary.
3183    ///
3184    /// The dictionary content will be copied internally, and does not need to be kept around.
3185    pub fn try_create(
3186        dict_buffer: &[u8],
3187        compression_level: CompressionLevel,
3188    ) -> Option<Self> {
3189        #[cfg(feature = "with-rust-allocator")]
3190        let ptr = unsafe {
3191            rust_allocator::create_cdict(
3192                dict_buffer,
3193                compression_level,
3194                zstd_sys::ZSTD_dictLoadMethod_e::ZSTD_dlm_byCopy,
3195            )
3196        };
3197        #[cfg(not(feature = "with-rust-allocator"))]
3198        let ptr = unsafe {
3199            zstd_sys::ZSTD_createCDict(
3200                ptr_void(dict_buffer),
3201                dict_buffer.len(),
3202                compression_level,
3203            )
3204        };
3205        Self::from_raw(ptr, false)
3206    }
3207
3208    /// Prepare a dictionary to compress data, referencing the bytes `owner`
3209    /// gives, which the dictionary then owns.
3210    ///
3211    /// # Panics
3212    ///
3213    /// If loading this dictionary failed. See
3214    /// [`CDict::try_create_by_reference_owned`].
3215    #[cfg(all(feature = "experimental", feature = "alloc"))]
3216    #[cfg_attr(
3217        feature = "doc-cfg",
3218        doc(cfg(all(feature = "experimental", feature = "alloc")))
3219    )]
3220    pub fn create_by_reference_owned<P>(
3221        owner: P,
3222        compression_level: CompressionLevel,
3223    ) -> Self
3224    where
3225        P: core::ops::Deref + Send + Sync + 'static,
3226        P::Target: AsRef<[u8]>,
3227    {
3228        Self::try_create_by_reference_owned(owner, compression_level)
3229            .expect("zstd returned null pointer")
3230    }
3231
3232    /// Prepare a dictionary to compress data, referencing the bytes `owner`
3233    /// gives, which the dictionary then owns.
3234    ///
3235    /// The bytes are not copied: `owner` can be a `Vec<u8>`, an `Arc<[u8]>`,
3236    /// an `Arc<Vec<u8>>`, a memory map, a `bytes::Bytes`, a
3237    /// `&'static [u8]`... It is dropped with the last handle to the
3238    /// dictionary.
3239    ///
3240    /// Returns `None` if zstd could not load the dictionary.
3241    #[cfg(all(feature = "experimental", feature = "alloc"))]
3242    #[cfg_attr(
3243        feature = "doc-cfg",
3244        doc(cfg(all(feature = "experimental", feature = "alloc")))
3245    )]
3246    pub fn try_create_by_reference_owned<P>(
3247        owner: P,
3248        compression_level: CompressionLevel,
3249    ) -> Option<Self>
3250    where
3251        P: core::ops::Deref + Send + Sync + 'static,
3252        P::Target: AsRef<[u8]>,
3253    {
3254        let (owner, ptr, len) = Owner::new(owner);
3255        // Safety: the dictionary owns the bytes from here on (below), and
3256        // frees itself before them.
3257        let ptr = unsafe {
3258            Self::by_reference(
3259                core::slice::from_raw_parts(ptr, len),
3260                compression_level,
3261            )
3262        };
3263        let inner = CDictInner {
3264            ptr: NonNull::new(ptr)?,
3265            borrows: false,
3266            owner: Some(owner),
3267        };
3268        Some(CDict(inner.into(), Borrow(PhantomData)))
3269    }
3270}
3271
3272impl<'a> CDict<'a> {
3273    /// Digests `dict_buffer` by reference.
3274    ///
3275    /// # Safety
3276    ///
3277    /// `dict_buffer` must stay valid and unchanged until the dictionary is
3278    /// freed.
3279    #[cfg(feature = "experimental")]
3280    unsafe fn by_reference(
3281        dict_buffer: &[u8],
3282        compression_level: CompressionLevel,
3283    ) -> *mut zstd_sys::ZSTD_CDict {
3284        #[cfg(feature = "with-rust-allocator")]
3285        let ptr = rust_allocator::create_cdict(
3286            dict_buffer,
3287            compression_level,
3288            zstd_sys::ZSTD_dictLoadMethod_e::ZSTD_dlm_byRef,
3289        );
3290        #[cfg(not(feature = "with-rust-allocator"))]
3291        let ptr = zstd_sys::ZSTD_createCDict_byReference(
3292            ptr_void(dict_buffer),
3293            dict_buffer.len(),
3294            compression_level,
3295        );
3296        ptr
3297    }
3298
3299    /// Prepare a dictionary to compress data, referencing `dict_buffer`.
3300    ///
3301    /// The bytes must outlive the dictionary:
3302    ///
3303    /// ```compile_fail,E0597
3304    /// let cdict;
3305    /// let bytes = vec![0u8; 16];
3306    /// cdict = zstd_safe::CDict::create_by_reference(&bytes, 3);
3307    /// ```
3308    ///
3309    /// # Panics
3310    ///
3311    /// If loading this dictionary failed. See [`CDict::try_create_by_reference`].
3312    #[cfg(feature = "experimental")]
3313    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
3314    pub fn create_by_reference(
3315        dict_buffer: &'a [u8],
3316        compression_level: CompressionLevel,
3317    ) -> Self {
3318        Self::try_create_by_reference(dict_buffer, compression_level)
3319            .expect("zstd returned null pointer")
3320    }
3321
3322    /// Prepare a dictionary to compress data, referencing `dict_buffer`.
3323    ///
3324    /// The bytes are not copied, and are borrowed for as long as the
3325    /// dictionary is used. With worker threads (`CParameter::NbWorkers`), a
3326    /// streaming frame that reads such a dictionary runs on the calling
3327    /// thread, see [`CCtx`](CCtx#worker-threads-and-leaks): a context can be
3328    /// leaked mid-frame, and the borrow would end under its workers.
3329    ///
3330    /// `CDict::try_create_by_reference_owned()` makes a dictionary that
3331    /// keeps the workers, from bytes with an owner (a `Vec`, an
3332    /// `Arc<[u8]>`, a memory map) or `'static` ones (`include_bytes!`,
3333    /// say): nothing tells this method that a `&'a [u8]` is `'static`.
3334    ///
3335    /// Returns `None` if zstd could not load the dictionary, for instance
3336    /// because it starts with the dictionary magic number but its header is
3337    /// corrupt.
3338    #[cfg(feature = "experimental")]
3339    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
3340    pub fn try_create_by_reference(
3341        dict_buffer: &'a [u8],
3342        compression_level: CompressionLevel,
3343    ) -> Option<Self> {
3344        // Safety: the bytes are borrowed for `'a`, as the dictionary is.
3345        let ptr =
3346            unsafe { Self::by_reference(dict_buffer, compression_level) };
3347        Self::from_raw(ptr, true)
3348    }
3349
3350    /// Returns the _current_ memory usage of this dictionary.
3351    ///
3352    /// Note that this may change over time.
3353    pub fn sizeof(&self) -> usize {
3354        unsafe { zstd_sys::ZSTD_sizeof_CDict(self.as_ptr()) }
3355    }
3356
3357    /// Returns the dictionary ID for this dict.
3358    ///
3359    /// Returns `None` if this dictionary is empty or invalid.
3360    pub fn get_dict_id(&self) -> Option<NonZeroU32> {
3361        NonZeroU32::new(unsafe {
3362            zstd_sys::ZSTD_getDictID_fromCDict(self.as_ptr()) as u32
3363        })
3364    }
3365}
3366
3367/// Wraps the `ZSTD_createCDict()` function.
3368pub fn create_cdict(
3369    dict_buffer: &[u8],
3370    compression_level: CompressionLevel,
3371) -> CDict<'static> {
3372    CDict::create(dict_buffer, compression_level)
3373}
3374
3375/// Wraps the `ZSTD_compress_usingCDict()` function.
3376pub fn compress_using_cdict(
3377    cctx: &mut CCtx<'_>,
3378    dst: &mut [u8],
3379    src: &[u8],
3380    cdict: &CDict<'_>,
3381) -> SafeResult {
3382    cctx.compress_using_cdict(dst, src, cdict)
3383}
3384
3385/// A digested decompression dictionary.
3386pub struct DDict<'a>(NonNull<zstd_sys::ZSTD_DDict>, PhantomData<&'a ()>);
3387
3388impl DDict<'static> {
3389    /// Prepare a dictionary to decompress data.
3390    ///
3391    /// The dictionary content will be copied internally, and does not need to be kept around.
3392    ///
3393    /// # Panics
3394    ///
3395    /// If loading this dictionary failed. See [`DDict::try_create`].
3396    pub fn create(dict_buffer: &[u8]) -> Self {
3397        Self::try_create(dict_buffer)
3398            .expect("zstd returned null pointer when creating dict")
3399    }
3400
3401    /// Prepare a dictionary to decompress data.
3402    ///
3403    /// The dictionary content will be copied internally, and does not need to be kept around.
3404    /// Returns `None` if zstd could not load the dictionary, for instance because it starts
3405    /// with the dictionary magic number but its header is corrupt.
3406    pub fn try_create(dict_buffer: &[u8]) -> Option<Self> {
3407        #[cfg(feature = "with-rust-allocator")]
3408        let ptr = unsafe {
3409            rust_allocator::create_ddict(
3410                dict_buffer,
3411                zstd_sys::ZSTD_dictLoadMethod_e::ZSTD_dlm_byCopy,
3412            )
3413        };
3414        #[cfg(not(feature = "with-rust-allocator"))]
3415        let ptr = unsafe {
3416            zstd_sys::ZSTD_createDDict(
3417                ptr_void(dict_buffer),
3418                dict_buffer.len(),
3419            )
3420        };
3421        Some(DDict(NonNull::new(ptr)?, PhantomData))
3422    }
3423}
3424
3425impl<'a> DDict<'a> {
3426    pub fn sizeof(&self) -> usize {
3427        unsafe { zstd_sys::ZSTD_sizeof_DDict(self.0.as_ptr()) }
3428    }
3429
3430    /// Wraps the `ZSTD_createDDict_byReference()` function.
3431    ///
3432    /// The dictionary will keep referencing `dict_buffer`.
3433    ///
3434    /// # Panics
3435    ///
3436    /// If loading this dictionary failed. See [`DDict::try_create_by_reference`].
3437    pub fn create_by_reference(dict_buffer: &'a [u8]) -> Self {
3438        Self::try_create_by_reference(dict_buffer)
3439            .expect("zstd returned null pointer")
3440    }
3441
3442    /// Wraps the `ZSTD_createDDict_byReference()` function.
3443    ///
3444    /// The dictionary will keep referencing `dict_buffer`. Returns `None` if
3445    /// zstd could not load the dictionary, for instance because it starts with
3446    /// the dictionary magic number but its header is corrupt.
3447    pub fn try_create_by_reference(dict_buffer: &'a [u8]) -> Option<Self> {
3448        #[cfg(feature = "with-rust-allocator")]
3449        let ptr = unsafe {
3450            rust_allocator::create_ddict(
3451                dict_buffer,
3452                zstd_sys::ZSTD_dictLoadMethod_e::ZSTD_dlm_byRef,
3453            )
3454        };
3455        #[cfg(not(feature = "with-rust-allocator"))]
3456        let ptr = unsafe {
3457            zstd_sys::ZSTD_createDDict_byReference(
3458                ptr_void(dict_buffer),
3459                dict_buffer.len(),
3460            )
3461        };
3462        Some(DDict(NonNull::new(ptr)?, PhantomData))
3463    }
3464
3465    /// Returns the dictionary ID for this dict.
3466    ///
3467    /// Returns `None` if this dictionary is empty or invalid.
3468    pub fn get_dict_id(&self) -> Option<NonZeroU32> {
3469        NonZeroU32::new(unsafe {
3470            zstd_sys::ZSTD_getDictID_fromDDict(self.0.as_ptr()) as u32
3471        })
3472    }
3473}
3474
3475/// Wraps the `ZSTD_createDDict()` function.
3476///
3477/// It copies the dictionary internally, so the resulting `DDict` is `'static`.
3478pub fn create_ddict(dict_buffer: &[u8]) -> DDict<'static> {
3479    DDict::create(dict_buffer)
3480}
3481
3482impl<'a> Drop for DDict<'a> {
3483    fn drop(&mut self) {
3484        unsafe {
3485            zstd_sys::ZSTD_freeDDict(self.0.as_ptr());
3486        }
3487    }
3488}
3489
3490// Safety: like `CDict`, a digested dictionary is only read once built - the
3491// contexts referencing it never write to it.
3492unsafe impl<'a> Send for DDict<'a> {}
3493unsafe impl<'a> Sync for DDict<'a> {}
3494
3495/// A shared thread pool for one or more compression contexts
3496#[cfg(all(feature = "experimental", feature = "zstdmt"))]
3497#[cfg_attr(
3498    feature = "doc-cfg",
3499    doc(cfg(all(feature = "experimental", feature = "zstdmt")))
3500)]
3501pub struct ThreadPool(NonNull<zstd_sys::ZSTD_threadPool>);
3502
3503#[cfg(all(feature = "experimental", feature = "zstdmt"))]
3504#[cfg_attr(
3505    feature = "doc-cfg",
3506    doc(cfg(all(feature = "experimental", feature = "zstdmt")))
3507)]
3508impl ThreadPool {
3509    /// Create a thread pool with the specified number of threads.
3510    ///
3511    /// # Panics
3512    ///
3513    /// If creating the thread pool failed.
3514    pub fn new(num_threads: usize) -> Self {
3515        Self::try_new(num_threads)
3516            .expect("zstd returned null pointer when creating thread pool")
3517    }
3518
3519    /// Create a thread pool with the specified number of threads.
3520    pub fn try_new(num_threads: usize) -> Option<Self> {
3521        Some(Self(NonNull::new(unsafe {
3522            zstd_sys::ZSTD_createThreadPool(num_threads)
3523        })?))
3524    }
3525}
3526
3527#[cfg(all(feature = "experimental", feature = "zstdmt"))]
3528#[cfg_attr(
3529    feature = "doc-cfg",
3530    doc(cfg(all(feature = "experimental", feature = "zstdmt")))
3531)]
3532impl Drop for ThreadPool {
3533    fn drop(&mut self) {
3534        unsafe {
3535            zstd_sys::ZSTD_freeThreadPool(self.0.as_ptr());
3536        }
3537    }
3538}
3539
3540#[cfg(all(feature = "experimental", feature = "zstdmt"))]
3541#[cfg_attr(
3542    feature = "doc-cfg",
3543    doc(cfg(all(feature = "experimental", feature = "zstdmt")))
3544)]
3545// Safety: the pool owns its worker threads and the queue guarding them; none
3546// of that is tied to the thread that created it.
3547unsafe impl Send for ThreadPool {}
3548#[cfg(all(feature = "experimental", feature = "zstdmt"))]
3549#[cfg_attr(
3550    feature = "doc-cfg",
3551    doc(cfg(all(feature = "experimental", feature = "zstdmt")))
3552)]
3553// Safety: sharing is what the pool is for - zstd.h offers these functions to
3554// "share a thread pool among multiple compression contexts" - and its work
3555// queue is guarded by an internal mutex.
3556unsafe impl Sync for ThreadPool {}
3557
3558/// Wraps the `ZSTD_decompress_usingDDict()` function.
3559///
3560/// Only as many bytes as returned at the start of `dst` are meaningful: zstd
3561/// may overwrite the rest.
3562pub fn decompress_using_ddict(
3563    dctx: &mut DCtx<'_>,
3564    dst: &mut [u8],
3565    src: &[u8],
3566    ddict: &DDict<'_>,
3567) -> SafeResult {
3568    dctx.decompress_using_ddict(dst, src, ddict)
3569}
3570
3571/// Compression stream.
3572///
3573/// Same as `CCtx`.
3574pub type CStream<'a> = CCtx<'a>;
3575
3576// `CStream` is an alias for `CCtx`, and shares its `Send` and `Sync` impls.
3577
3578/// Allocates a new `CStream`.
3579pub fn create_cstream<'a>() -> CStream<'a> {
3580    CCtx::create()
3581}
3582
3583/// Prepares an existing `CStream` for compression at the given level.
3584pub fn init_cstream(
3585    zcs: &mut CStream<'_>,
3586    compression_level: CompressionLevel,
3587) -> SafeResult {
3588    zcs.init(compression_level)
3589}
3590
3591#[derive(Debug)]
3592/// Wrapper around an input buffer.
3593///
3594/// Bytes will be read starting at `src[pos]`.
3595///
3596/// `pos` will be updated after reading.
3597///
3598/// # Invariant
3599///
3600/// `pos <= src.len()`
3601///
3602/// Both fields are public, so this is checked (and panics if it does not hold)
3603/// whenever the buffer is given to zstd.
3604pub struct InBuffer<'a> {
3605    pub src: &'a [u8],
3606    pub pos: usize,
3607}
3608
3609/// Describe a bytes container, like `Vec<u8>`.
3610///
3611/// Represents a contiguous segment of allocated memory, a prefix of which is initialized.
3612///
3613/// It allows starting from an uninitializes chunk of memory and writing to it, progressively
3614/// initializing it. No re-allocation typically occur after the initial creation.
3615///
3616/// The main implementors are:
3617/// * `Vec<u8>` and similar structures. These hold both a length (initialized data) and a capacity
3618///   (allocated memory).
3619///
3620///   Use `Vec::with_capacity` to create an empty `Vec` with non-zero capacity, and the length
3621///   field will be updated to cover the data written to it (as long as it fits in the given
3622///   capacity).
3623/// * `[u8]` and `[u8; N]`. These must start already-initialized, and will not be resized. It will
3624///   be up to the caller to only use the part that was written (as returned by the various writing
3625///   operations).
3626/// * `std::io::Cursor<T: WriteBuf>`. This will ignore data before the cursor's position, and
3627///   append data after that.
3628///
3629/// # Safety
3630///
3631/// An implementation has to keep four promises, because the zstd functions
3632/// this is handed to write straight through the pointer:
3633///
3634/// * `as_mut_ptr()` points at a buffer that is valid to write `capacity()`
3635///   bytes to.
3636/// * `as_slice()` covers only initialized bytes - never any of the capacity
3637///   that has not been written yet.
3638/// * `filled_until(n)` is what marks the first `n` bytes as initialized, so
3639///   after it returns, `as_slice()` must cover them.
3640/// * `capacity()` and the pointer `as_mut_ptr()` returns may change between
3641///   uses (a `Vec` grows when pushed to), but not while the buffer is
3642///   mutably borrowed by the code writing to it through this trait (an
3643///   `OutBuffer`, a call taking `&mut` of it): calling this trait's methods,
3644///   in any order, changes neither (`filled_until()` only changes what
3645///   `as_slice()` covers).
3646pub unsafe trait WriteBuf {
3647    /// Returns the valid data part of this container. Should only cover initialized data.
3648    fn as_slice(&self) -> &[u8];
3649
3650    /// Returns the full capacity of this container. May include uninitialized data.
3651    fn capacity(&self) -> usize;
3652
3653    /// Returns a pointer to the start of the data.
3654    fn as_mut_ptr(&mut self) -> *mut u8;
3655
3656    /// Indicates that the first `n` bytes of the container have been written.
3657    ///
3658    /// # Safety
3659    ///
3660    /// The first `n` bytes of this buffer must actually have been initialized.
3661    unsafe fn filled_until(&mut self, n: usize);
3662
3663    /// Call the given closure using the pointer and capacity from `self`.
3664    ///
3665    /// The closure returns a parseable code which, if valid, is how many bytes
3666    /// it wrote to `self`.
3667    ///
3668    /// # Safety
3669    ///
3670    /// The closure must treat its first argument as pointing to potentially
3671    /// uninitialized memory, and must not read from it. It must have written
3672    /// at least `n` bytes contiguously from that pointer, where `n` is the
3673    /// value it returns.
3674    unsafe fn write_from<F>(&mut self, f: F) -> SafeResult
3675    where
3676        F: FnOnce(*mut c_void, usize) -> SafeResult,
3677    {
3678        let capacity = self.capacity();
3679        let res = f(ptr_mut_void(self), capacity);
3680        if let Ok(n) = res {
3681            // Nothing can have been written past the end of the buffer; a
3682            // larger count would mark memory we do not own as initialized.
3683            assert!(n <= capacity, "zstd reported writing past the buffer");
3684            self.filled_until(n);
3685        }
3686        res
3687    }
3688}
3689
3690/// The position of a `Cursor`, as an index into the buffer it wraps.
3691///
3692/// `Cursor` stores the position as a `u64` and lets it be set anywhere, so on a
3693/// target where `usize` is narrower it can name an offset no buffer can hold.
3694/// Saturating leaves such a position out of range, where the bounds checks
3695/// below reject it; casting would wrap it around into a valid-looking offset
3696/// and quietly read or write the wrong part of the buffer.
3697#[cfg(feature = "std")]
3698fn cursor_position<T>(cursor: &std::io::Cursor<T>) -> usize {
3699    use core::convert::TryFrom;
3700
3701    usize::try_from(cursor.position()).unwrap_or(usize::MAX)
3702}
3703
3704#[cfg(feature = "std")]
3705#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "std")))]
3706unsafe impl<T> WriteBuf for std::io::Cursor<T>
3707where
3708    T: WriteBuf,
3709{
3710    fn as_slice(&self) -> &[u8] {
3711        // A cursor past the inner buffer's initialized part has nothing
3712        // initialized after it yet (see `filled_until` below).
3713        self.get_ref()
3714            .as_slice()
3715            .get(cursor_position(self)..)
3716            .unwrap_or(&[])
3717    }
3718
3719    fn capacity(&self) -> usize {
3720        self.get_ref()
3721            .capacity()
3722            .saturating_sub(cursor_position(self))
3723    }
3724
3725    fn as_mut_ptr(&mut self) -> *mut u8 {
3726        let start = cursor_position(self);
3727        assert!(start <= self.get_ref().capacity());
3728        // Safety: start is still in the same memory allocation
3729        unsafe { self.get_mut().as_mut_ptr().add(start) }
3730    }
3731
3732    unsafe fn filled_until(&mut self, n: usize) {
3733        // Here we assume data _before_ self.position() was already initialized.
3734        // Egh it's not actually guaranteed by Cursor? So let's guarantee it ourselves.
3735        // Since the cursor wraps another `WriteBuf`, we know how much data is initialized there.
3736        let position = cursor_position(self);
3737        let capacity = self.get_ref().capacity();
3738        if n == 0 && position > capacity {
3739            // Nothing was written, and nothing could have been: there is
3740            // no room at all after the cursor.
3741            return;
3742        }
3743        // Otherwise the caller wrote `n` bytes starting at `position`, so
3744        // `position` is inside the buffer. Checking it before the zero-fill
3745        // below keeps a position that could not be converted from running off
3746        // the end.
3747        //
3748        // Note that `n == 0` still truncates the data after the cursor, like
3749        // any other `n` does: an empty result must not leave a previous one
3750        // in place.
3751        assert!(position <= capacity);
3752        let initialized = self.get_ref().as_slice().len();
3753        if let Some(uninitialized) = position.checked_sub(initialized) {
3754            // Here, the cursor is further than the known-initialized part.
3755            // Cursor's solution is to pad with zeroes, so let's do the same.
3756            // We'll zero bytes from the end of valid data (as_slice().len()) to the cursor position.
3757
3758            // Safety:
3759            // * We checked `position <= self.get_ref().capacity()`
3760            // * This means that `position` is within (or one past) the nested
3761            //   pointer's allocation.
3762            // * Finally, `initialized + uninitialized = position`, so the entire byte
3763            //   range here is within the allocation
3764            unsafe {
3765                self.get_mut()
3766                    .as_mut_ptr()
3767                    .add(initialized)
3768                    .write_bytes(0u8, uninitialized)
3769            };
3770        }
3771
3772        let start = position;
3773        assert!(start + n <= self.get_ref().capacity());
3774        self.get_mut().filled_until(start + n);
3775    }
3776}
3777
3778#[cfg(feature = "alloc")]
3779#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "alloc")))]
3780unsafe impl WriteBuf for &mut alloc::vec::Vec<u8> {
3781    fn as_slice(&self) -> &[u8] {
3782        alloc::vec::Vec::as_slice(self)
3783    }
3784
3785    fn capacity(&self) -> usize {
3786        alloc::vec::Vec::capacity(self)
3787    }
3788
3789    fn as_mut_ptr(&mut self) -> *mut u8 {
3790        alloc::vec::Vec::as_mut_ptr(self)
3791    }
3792
3793    unsafe fn filled_until(&mut self, n: usize) {
3794        alloc::vec::Vec::set_len(self, n)
3795    }
3796}
3797
3798#[cfg(feature = "alloc")]
3799#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "alloc")))]
3800unsafe impl WriteBuf for alloc::vec::Vec<u8> {
3801    fn as_slice(&self) -> &[u8] {
3802        &self[..]
3803    }
3804    fn capacity(&self) -> usize {
3805        self.capacity()
3806    }
3807    fn as_mut_ptr(&mut self) -> *mut u8 {
3808        self.as_mut_ptr()
3809    }
3810    unsafe fn filled_until(&mut self, n: usize) {
3811        self.set_len(n);
3812    }
3813}
3814
3815#[cfg(feature = "arrays")]
3816#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "arrays")))]
3817unsafe impl<const N: usize> WriteBuf for [u8; N] {
3818    fn as_slice(&self) -> &[u8] {
3819        self
3820    }
3821    fn capacity(&self) -> usize {
3822        self.len()
3823    }
3824
3825    fn as_mut_ptr(&mut self) -> *mut u8 {
3826        self[..].as_mut_ptr()
3827    }
3828
3829    unsafe fn filled_until(&mut self, _n: usize) {
3830        // Assume the slice is already initialized
3831    }
3832}
3833
3834unsafe impl WriteBuf for [u8] {
3835    fn as_slice(&self) -> &[u8] {
3836        self
3837    }
3838    fn capacity(&self) -> usize {
3839        self.len()
3840    }
3841
3842    fn as_mut_ptr(&mut self) -> *mut u8 {
3843        self.as_mut_ptr()
3844    }
3845
3846    unsafe fn filled_until(&mut self, _n: usize) {
3847        // Assume the slice is already initialized
3848    }
3849}
3850
3851/*
3852// This is possible, but... why?
3853unsafe impl<'a> WriteBuf for OutBuffer<'a, [u8]> {
3854    fn as_slice(&self) -> &[u8] {
3855        self.dst
3856    }
3857    fn capacity(&self) -> usize {
3858        self.dst.len()
3859    }
3860    fn as_mut_ptr(&mut self) -> *mut u8 {
3861        self.dst.as_mut_ptr()
3862    }
3863    unsafe fn filled_until(&mut self, n: usize) {
3864        self.pos = n;
3865    }
3866}
3867*/
3868
3869#[derive(Debug)]
3870/// Wrapper around an output buffer.
3871///
3872/// `C` is usually either `[u8]` or `Vec<u8>`.
3873///
3874/// Bytes will be written starting at `dst[pos]`.
3875///
3876/// `pos` will be updated after writing.
3877///
3878/// # Invariant
3879///
3880/// `pos <= dst.capacity()`
3881pub struct OutBuffer<'a, C: WriteBuf + ?Sized> {
3882    dst: &'a mut C,
3883    pos: usize,
3884}
3885
3886/// Convenience method to get a mut pointer from a mut ref.
3887fn ptr_mut<B>(ptr_void: &mut B) -> *mut B {
3888    ptr_void as *mut B
3889}
3890
3891/// Interface between a C-level ZSTD_outBuffer and a rust-level `OutBuffer`.
3892///
3893/// Will update the parent buffer from the C buffer on drop.
3894struct OutBufferWrapper<'a, 'b, C: WriteBuf + ?Sized> {
3895    buf: zstd_sys::ZSTD_outBuffer,
3896    parent: &'a mut OutBuffer<'b, C>,
3897}
3898
3899impl<'a, 'b: 'a, C: WriteBuf + ?Sized> Deref for OutBufferWrapper<'a, 'b, C> {
3900    type Target = zstd_sys::ZSTD_outBuffer;
3901
3902    fn deref(&self) -> &Self::Target {
3903        &self.buf
3904    }
3905}
3906
3907impl<'a, 'b: 'a, C: WriteBuf + ?Sized> DerefMut
3908    for OutBufferWrapper<'a, 'b, C>
3909{
3910    fn deref_mut(&mut self) -> &mut Self::Target {
3911        &mut self.buf
3912    }
3913}
3914
3915impl<'a, C: WriteBuf + ?Sized> OutBuffer<'a, C> {
3916    /// Returns a new `OutBuffer` around the given slice.
3917    ///
3918    /// Starts with `pos = 0`.
3919    pub fn around(dst: &'a mut C) -> Self {
3920        OutBuffer { dst, pos: 0 }
3921    }
3922
3923    /// Returns a new `OutBuffer` around the given slice, starting at the given position.
3924    ///
3925    /// If `pos` is past the initialized part of `dst` (for example a `Vec`
3926    /// whose `len()` is smaller than `pos`), the gap is zero-filled, as a
3927    /// `Cursor` would do.
3928    ///
3929    /// # Panics
3930    ///
3931    /// If `pos > dst.capacity()`.
3932    pub fn around_pos(dst: &'a mut C, pos: usize) -> Self {
3933        if pos > dst.capacity() {
3934            panic!("Given position outside of the buffer bounds.");
3935        }
3936
3937        let initialized = dst.as_slice().len();
3938        if pos > initialized {
3939            // Writing to this buffer marks everything before `pos` as
3940            // initialized (see `set_pos`), so it has to be before we start.
3941            // Safety: `initialized..pos` lies within `capacity()`, which
3942            // `WriteBuf` promises is valid to write to.
3943            unsafe {
3944                dst.as_mut_ptr()
3945                    .add(initialized)
3946                    .write_bytes(0u8, pos - initialized);
3947                dst.filled_until(pos);
3948            }
3949        }
3950
3951        OutBuffer { dst, pos }
3952    }
3953
3954    /// Returns the current cursor position.
3955    ///
3956    /// Guaranteed to be <= self.capacity()
3957    pub fn pos(&self) -> usize {
3958        assert!(self.pos <= self.dst.capacity());
3959        self.pos
3960    }
3961
3962    /// Returns the capacity of the underlying buffer.
3963    pub fn capacity(&self) -> usize {
3964        self.dst.capacity()
3965    }
3966
3967    /// Sets the new cursor position.
3968    ///
3969    /// # Panics
3970    ///
3971    /// If `pos > self.dst.capacity()`.
3972    ///
3973    /// # Safety
3974    ///
3975    /// Data up to `pos` must have actually been written to.
3976    pub unsafe fn set_pos(&mut self, pos: usize) {
3977        if pos > self.dst.capacity() {
3978            panic!("Given position outside of the buffer bounds.");
3979        }
3980
3981        self.dst.filled_until(pos);
3982
3983        self.pos = pos;
3984    }
3985
3986    fn wrap<'b>(&'b mut self) -> OutBufferWrapper<'b, 'a, C> {
3987        // `WriteBuf` promises the capacity does not shrink under us, but
3988        // checking costs nothing. zstd refuses a position past the end before
3989        // doing anything, and `set_pos()` would panic on it once the call
3990        // returned: do it first, while a compression context still knows
3991        // about the frame it has in progress. zstd is given the capacity that
3992        // was checked, not a second reading of it.
3993        let capacity = self.dst.capacity();
3994        if self.pos > capacity {
3995            panic!("Given position outside of the buffer bounds.");
3996        }
3997
3998        OutBufferWrapper {
3999            buf: zstd_sys::ZSTD_outBuffer {
4000                dst: ptr_mut_void(self.dst),
4001                size: capacity,
4002                pos: self.pos,
4003            },
4004            parent: self,
4005        }
4006    }
4007
4008    /// Returns the part of this buffer that was written to.
4009    pub fn as_slice<'b>(&'b self) -> &'a [u8]
4010    where
4011        'b: 'a,
4012    {
4013        let pos = self.pos;
4014        &self.dst.as_slice()[..pos]
4015    }
4016
4017    /// Returns a pointer to the start of this buffer.
4018    pub fn as_mut_ptr(&mut self) -> *mut u8 {
4019        self.dst.as_mut_ptr()
4020    }
4021}
4022
4023impl<'a, 'b, C: WriteBuf + ?Sized> OutBufferWrapper<'a, 'b, C> {
4024    /// Passes `res` through, and forgets the position reported by zstd if it
4025    /// is an error, so the parent keeps the one from before the call.
4026    ///
4027    /// zstd.h makes no promise about `pos` after a failed call, and the legacy
4028    /// decoders report the whole output buffer as written when they fail; only
4029    /// a successful call vouches for the bytes up to `pos` being initialized.
4030    fn check(&mut self, res: SafeResult) -> SafeResult {
4031        if res.is_err() {
4032            self.buf.pos = self.parent.pos;
4033        }
4034        res
4035    }
4036}
4037
4038impl<'a, 'b, C: WriteBuf + ?Sized> Drop for OutBufferWrapper<'a, 'b, C> {
4039    fn drop(&mut self) {
4040        // Safe because `self.buf.pos` either comes from a successful call,
4041        // which guarantees that data until there has been written, or was put
4042        // back to the parent's position by `check()`.
4043        unsafe { self.parent.set_pos(self.buf.pos) };
4044    }
4045}
4046
4047struct InBufferWrapper<'a, 'b> {
4048    buf: zstd_sys::ZSTD_inBuffer,
4049    parent: &'a mut InBuffer<'b>,
4050}
4051
4052impl<'a, 'b: 'a> Deref for InBufferWrapper<'a, 'b> {
4053    type Target = zstd_sys::ZSTD_inBuffer;
4054
4055    fn deref(&self) -> &Self::Target {
4056        &self.buf
4057    }
4058}
4059
4060impl<'a, 'b: 'a> DerefMut for InBufferWrapper<'a, 'b> {
4061    fn deref_mut(&mut self) -> &mut Self::Target {
4062        &mut self.buf
4063    }
4064}
4065
4066impl<'a> InBuffer<'a> {
4067    /// Returns a new `InBuffer` around the given slice.
4068    ///
4069    /// Starts with `pos = 0`.
4070    pub fn around(src: &'a [u8]) -> Self {
4071        InBuffer { src, pos: 0 }
4072    }
4073
4074    /// Returns the current cursor position.
4075    pub fn pos(&self) -> usize {
4076        self.pos
4077    }
4078
4079    /// Sets the new cursor position.
4080    ///
4081    /// # Panics
4082    ///
4083    /// If `pos > self.src.len()`.
4084    pub fn set_pos(&mut self, pos: usize) {
4085        if pos > self.src.len() {
4086            panic!("Given position outside of the buffer bounds.");
4087        }
4088        self.pos = pos;
4089    }
4090
4091    fn wrap<'b>(&'b mut self) -> InBufferWrapper<'b, 'a> {
4092        // The fields are public, so `pos` may not have gone through `set_pos`.
4093        // Not all zstd functions check it before reading from `src + pos`.
4094        if self.pos > self.src.len() {
4095            panic!("Given position outside of the buffer bounds.");
4096        }
4097
4098        InBufferWrapper {
4099            buf: zstd_sys::ZSTD_inBuffer {
4100                src: ptr_void(self.src),
4101                size: self.src.len(),
4102                pos: self.pos,
4103            },
4104            parent: self,
4105        }
4106    }
4107}
4108
4109impl<'a, 'b> InBufferWrapper<'a, 'b> {
4110    /// Passes `res` through, and forgets the position reported by zstd if it
4111    /// is an error, so the parent keeps the one from before the call.
4112    ///
4113    /// See `OutBufferWrapper::check()`: a failed call consumed nothing usable,
4114    /// and the legacy decoders report the whole input as read.
4115    fn check(&mut self, res: SafeResult) -> SafeResult {
4116        if res.is_err() {
4117            self.buf.pos = self.parent.pos;
4118        }
4119        res
4120    }
4121}
4122
4123impl<'a, 'b> Drop for InBufferWrapper<'a, 'b> {
4124    fn drop(&mut self) {
4125        self.parent.set_pos(self.buf.pos);
4126    }
4127}
4128
4129/// A Decompression stream.
4130///
4131/// Same as `DCtx`.
4132pub type DStream<'a> = DCtx<'a>;
4133
4134// Some functions work on a "frame prefix".
4135// TODO: Define `struct FramePrefix(&[u8]);` and move these functions to it?
4136//
4137// Some other functions work on a dictionary (not CDict or DDict).
4138// Same thing?
4139
4140/// Wraps the `ZSTD_findFrameCompressedSize()` function.
4141///
4142/// `src` should contain at least an entire frame.
4143pub fn find_frame_compressed_size(src: &[u8]) -> SafeResult {
4144    let code = unsafe {
4145        zstd_sys::ZSTD_findFrameCompressedSize(ptr_void(src), src.len())
4146    };
4147    parse_code(code)
4148}
4149
4150/// Wraps the `ZSTD_getFrameContentSize()` function.
4151///
4152/// Args:
4153/// * `src`: A prefix of the compressed frame. It should at least include the frame header.
4154///
4155/// Returns:
4156/// * `Err(ContentSizeError)` if `src` is too small of a prefix, or if it appears corrupted.
4157/// * `Ok(None)` if the frame does not include a content size.
4158/// * `Ok(Some(content_size_in_bytes))` otherwise.
4159pub fn get_frame_content_size(
4160    src: &[u8],
4161) -> Result<Option<u64>, ContentSizeError> {
4162    parse_content_size(unsafe {
4163        zstd_sys::ZSTD_getFrameContentSize(ptr_void(src), src.len())
4164    })
4165}
4166
4167/// What [`get_frame_header()`] found at the start of `src`.
4168#[derive(Copy, Clone, Debug)]
4169pub enum FrameHeaderStatus {
4170    /// The whole header was in `src`.
4171    Complete(FrameHeader),
4172    /// `src` ends before the header does: decoding it needs `src_size`
4173    /// bytes of the frame (in total, not in addition to `src`).
4174    Incomplete { src_size: usize },
4175}
4176
4177/// Wraps the `ZSTD_getFrameHeader()` function.
4178///
4179/// `src` is the start of a frame: a regular zstd frame, or a skippable one.
4180/// For a skippable frame, `frameContentSize` is the size of its content, and
4181/// `dictID` its magic variant (0 to 15).
4182///
4183/// Fails if `src` does not start with a valid frame header.
4184pub fn get_frame_header(src: &[u8]) -> Result<FrameHeaderStatus, ErrorCode> {
4185    let mut header = core::mem::MaybeUninit::<FrameHeader>::uninit();
4186    // Safety: Just FFI. zstd only reads `src`, and only writes `header`.
4187    let code = unsafe {
4188        zstd_sys::ZSTD_getFrameHeader(
4189            header.as_mut_ptr(),
4190            ptr_void(src),
4191            src.len(),
4192        )
4193    };
4194    // Safety: zstd filled the header if it returned 0.
4195    parse_frame_header(code, || unsafe { header.assume_init() })
4196}
4197
4198/// Wraps the `ZSTD_getFrameHeader_advanced()` function.
4199///
4200/// Like [`get_frame_header()`], for a frame written in `format`. A
4201/// magicless frame cannot be a skippable frame.
4202#[cfg(feature = "experimental")]
4203#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4204pub fn get_frame_header_advanced(
4205    src: &[u8],
4206    format: FrameFormat,
4207) -> Result<FrameHeaderStatus, ErrorCode> {
4208    let mut header = core::mem::MaybeUninit::<FrameHeader>::uninit();
4209    // Safety: Just FFI. zstd only reads `src`, and only writes `header`.
4210    let code = unsafe {
4211        zstd_sys::ZSTD_getFrameHeader_advanced(
4212            header.as_mut_ptr(),
4213            ptr_void(src),
4214            src.len(),
4215            format.c_format(),
4216        )
4217    };
4218    // Safety: zstd filled the header if it returned 0.
4219    parse_frame_header(code, || unsafe { header.assume_init() })
4220}
4221
4222/// Reads the code `ZSTD_getFrameHeader*()` returned; `header` gives the
4223/// header it filled, and is only called when it did.
4224fn parse_frame_header(
4225    code: usize,
4226    header: impl FnOnce() -> FrameHeader,
4227) -> Result<FrameHeaderStatus, ErrorCode> {
4228    Ok(match parse_code(code)? {
4229        0 => FrameHeaderStatus::Complete(header()),
4230        src_size => FrameHeaderStatus::Incomplete { src_size },
4231    })
4232}
4233
4234/// Wraps the `ZSTD_findDecompressedSize()` function.
4235///
4236/// `src` should be exactly a sequence of ZSTD frames.
4237#[cfg(feature = "experimental")]
4238#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4239pub fn find_decompressed_size(
4240    src: &[u8],
4241) -> Result<Option<u64>, ContentSizeError> {
4242    parse_content_size(unsafe {
4243        zstd_sys::ZSTD_findDecompressedSize(ptr_void(src), src.len())
4244    })
4245}
4246
4247/// Wraps the `ZSTD_isFrame()` function.
4248#[cfg(feature = "experimental")]
4249#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4250pub fn is_frame(buffer: &[u8]) -> bool {
4251    unsafe { zstd_sys::ZSTD_isFrame(ptr_void(buffer), buffer.len()) > 0 }
4252}
4253
4254/// Wraps the `ZSTD_getDictID_fromDict()` function.
4255///
4256/// Returns `None` if the dictionary is not a valid zstd dictionary.
4257pub fn get_dict_id_from_dict(dict: &[u8]) -> Option<NonZeroU32> {
4258    NonZeroU32::new(unsafe {
4259        zstd_sys::ZSTD_getDictID_fromDict(ptr_void(dict), dict.len()) as u32
4260    })
4261}
4262
4263/// Wraps the `ZSTD_getDictID_fromFrame()` function.
4264///
4265/// Returns `None` if the dictionary ID could not be decoded. This may happen if:
4266/// * The frame was not encoded with a dictionary.
4267/// * The frame intentionally did not include dictionary ID.
4268/// * The dictionary was non-conformant.
4269/// * `src` is too small and does not include the frame header.
4270/// * `src` is not a valid zstd frame prefix.
4271pub fn get_dict_id_from_frame(src: &[u8]) -> Option<NonZeroU32> {
4272    NonZeroU32::new(unsafe {
4273        zstd_sys::ZSTD_getDictID_fromFrame(ptr_void(src), src.len()) as u32
4274    })
4275}
4276
4277/// What kind of context reset should be applied.
4278#[derive(Copy, Clone, Debug, PartialEq, Eq)]
4279pub enum ResetDirective {
4280    /// Only the session will be reset.
4281    ///
4282    /// All parameters will be preserved (including the dictionary).
4283    /// But any frame being processed will be dropped.
4284    ///
4285    /// It can be useful to start re-using a context after an error or when an
4286    /// ongoing compression is no longer needed.
4287    SessionOnly,
4288
4289    /// Only reset parameters (including dictionary or referenced prefix).
4290    ///
4291    /// All parameters will be reset to default values.
4292    ///
4293    /// This can only be done between sessions - no compression or decompression must be ongoing.
4294    Parameters,
4295
4296    /// Reset both the session and parameters.
4297    ///
4298    /// The result is similar to a newly created context.
4299    SessionAndParameters,
4300}
4301
4302impl ResetDirective {
4303    /// Does this drop a session in progress?
4304    ///
4305    /// Only a session reset brings a context back from the undefined state an
4306    /// error can leave it in - `Parameters` alone is refused while a session is
4307    /// open.
4308    fn resets_session(self) -> bool {
4309        matches!(
4310            self,
4311            ResetDirective::SessionOnly | ResetDirective::SessionAndParameters
4312        )
4313    }
4314
4315    fn as_sys(self) -> zstd_sys::ZSTD_ResetDirective {
4316        match self {
4317            ResetDirective::SessionOnly => zstd_sys::ZSTD_ResetDirective::ZSTD_reset_session_only,
4318            ResetDirective::Parameters => zstd_sys::ZSTD_ResetDirective::ZSTD_reset_parameters,
4319            ResetDirective::SessionAndParameters => zstd_sys::ZSTD_ResetDirective::ZSTD_reset_session_and_parameters,
4320        }
4321    }
4322}
4323
4324#[cfg(feature = "experimental")]
4325#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4326#[derive(Copy, Clone, Debug, PartialEq, Eq)]
4327#[repr(u32)]
4328pub enum FrameFormat {
4329    /// Regular zstd format.
4330    One = zstd_sys::ZSTD_format_e::ZSTD_f_zstd1 as u32,
4331
4332    /// Skip the 4 bytes identifying the content as zstd-compressed data.
4333    Magicless = zstd_sys::ZSTD_format_e::ZSTD_f_zstd1_magicless as u32,
4334}
4335
4336#[cfg(feature = "experimental")]
4337impl FrameFormat {
4338    fn c_format(self) -> zstd_sys::ZSTD_format_e {
4339        match self {
4340            FrameFormat::One => zstd_sys::ZSTD_format_e::ZSTD_f_zstd1,
4341            FrameFormat::Magicless => {
4342                zstd_sys::ZSTD_format_e::ZSTD_f_zstd1_magicless
4343            }
4344        }
4345    }
4346}
4347
4348/// How zstd reads the bytes of a dictionary.
4349#[derive(Copy, Clone, Debug, PartialEq, Eq)]
4350pub enum DictContentType {
4351    /// A dictionary in zstd's format if the bytes start with its magic
4352    /// number, raw content otherwise.
4353    Auto,
4354
4355    /// Raw content, even if the bytes start with the dictionary magic
4356    /// number.
4357    RawContent,
4358
4359    /// A dictionary in zstd's format: anything else is an error.
4360    FullDict,
4361}
4362
4363impl DictContentType {
4364    fn c_type(self) -> zstd_sys::ZSTD_dictContentType_e {
4365        use zstd_sys::ZSTD_dictContentType_e::*;
4366        match self {
4367            DictContentType::Auto => ZSTD_dct_auto,
4368            DictContentType::RawContent => ZSTD_dct_rawContent,
4369            DictContentType::FullDict => ZSTD_dct_fullDict,
4370        }
4371    }
4372}
4373
4374#[cfg(feature = "experimental")]
4375#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4376#[derive(Copy, Clone, Debug, PartialEq, Eq)]
4377#[repr(u32)]
4378pub enum DictAttachPref {
4379    DefaultAttach =
4380        zstd_sys::ZSTD_dictAttachPref_e::ZSTD_dictDefaultAttach as u32,
4381    ForceAttach = zstd_sys::ZSTD_dictAttachPref_e::ZSTD_dictForceAttach as u32,
4382    ForceCopy = zstd_sys::ZSTD_dictAttachPref_e::ZSTD_dictForceCopy as u32,
4383    ForceLoad = zstd_sys::ZSTD_dictAttachPref_e::ZSTD_dictForceLoad as u32,
4384}
4385
4386#[cfg(feature = "experimental")]
4387#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4388#[derive(Copy, Clone, Debug, PartialEq, Eq)]
4389#[repr(u32)]
4390pub enum ParamSwitch {
4391    Auto = zstd_sys::ZSTD_ParamSwitch_e::ZSTD_ps_auto as u32,
4392    Enable = zstd_sys::ZSTD_ParamSwitch_e::ZSTD_ps_enable as u32,
4393    Disable = zstd_sys::ZSTD_ParamSwitch_e::ZSTD_ps_disable as u32,
4394}
4395
4396/// A compression parameter.
4397#[derive(Copy, Clone, Debug, PartialEq, Eq)]
4398#[non_exhaustive]
4399pub enum CParameter {
4400    /// Makes the compressed output friendly to `rsync`.
4401    ///
4402    /// Only frames compressed with worker threads are: this has no effect
4403    /// with `NbWorkers(0)`, or on a frame that runs on the calling thread
4404    /// (see `NbWorkers`).
4405    #[cfg(feature = "experimental")]
4406    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4407    RSyncable(bool),
4408
4409    #[cfg(feature = "experimental")]
4410    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4411    Format(FrameFormat),
4412
4413    #[cfg(feature = "experimental")]
4414    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4415    ForceMaxWindow(bool),
4416
4417    #[cfg(feature = "experimental")]
4418    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4419    ForceAttachDict(DictAttachPref),
4420
4421    #[cfg(feature = "experimental")]
4422    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4423    LiteralCompressionMode(ParamSwitch),
4424
4425    #[cfg(feature = "experimental")]
4426    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4427    SrcSizeHint(u32),
4428
4429    #[cfg(feature = "experimental")]
4430    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4431    EnableDedicatedDictSearch(bool),
4432
4433    /// Whether zstd may keep referencing the input buffer instead of copying
4434    /// it.
4435    ///
4436    /// This requires the input to stay allocated and unmodified until the
4437    /// frame is complete, which a borrowed `InBuffer` cannot guarantee:
4438    /// `CCtx::set_parameter` refuses to enable it and returns an error.
4439    #[cfg(feature = "experimental")]
4440    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4441    StableInBuffer(bool),
4442
4443    #[cfg(feature = "experimental")]
4444    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4445    StableOutBuffer(bool),
4446
4447    #[cfg(feature = "experimental")]
4448    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4449    BlockDelimiters(bool),
4450
4451    #[cfg(feature = "experimental")]
4452    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4453    ValidateSequences(bool),
4454
4455    #[cfg(feature = "experimental")]
4456    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4457    UseBlockSplitter(ParamSwitch),
4458
4459    #[cfg(feature = "experimental")]
4460    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4461    UseRowMatchFinder(ParamSwitch),
4462
4463    #[cfg(feature = "experimental")]
4464    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4465    DeterministicRefPrefix(bool),
4466
4467    #[cfg(feature = "experimental")]
4468    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4469    PrefetchCDictTables(ParamSwitch),
4470
4471    #[cfg(feature = "experimental")]
4472    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4473    EnableSeqProducerFallback(bool),
4474
4475    #[cfg(feature = "experimental")]
4476    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4477    MaxBlockSize(u32),
4478
4479    #[cfg(feature = "experimental")]
4480    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4481    SearchForExternalRepcodes(ParamSwitch),
4482
4483    /// Target CBlock size.
4484    ///
4485    /// Tries to make compressed blocks fit in this size (not a guarantee, just a target).
4486    /// Useful to reduce end-to-end latency in low-bandwidth environments.
4487    ///
4488    /// No target when the value is 0.
4489    TargetCBlockSize(u32),
4490
4491    /// Compression level to use.
4492    ///
4493    /// Compression levels are global presets for the other compression parameters.
4494    CompressionLevel(CompressionLevel),
4495
4496    /// Maximum allowed back-reference distance.
4497    ///
4498    /// The actual distance is 2 power "this value".
4499    WindowLog(u32),
4500
4501    HashLog(u32),
4502
4503    ChainLog(u32),
4504
4505    SearchLog(u32),
4506
4507    MinMatch(u32),
4508
4509    TargetLength(u32),
4510
4511    Strategy(Strategy),
4512
4513    EnableLongDistanceMatching(bool),
4514
4515    LdmHashLog(u32),
4516
4517    LdmMinMatch(u32),
4518
4519    LdmBucketSizeLog(u32),
4520
4521    LdmHashRateLog(u32),
4522
4523    ContentSizeFlag(bool),
4524
4525    ChecksumFlag(bool),
4526
4527    DictIdFlag(bool),
4528
4529    /// How many threads will be spawned.
4530    ///
4531    /// With a default value of `0`, `compress_stream*` functions block until they complete.
4532    ///
4533    /// With any other value (including 1, a single compressing thread), these methods directly
4534    /// return, and the actual compression is done in the background (until a flush is requested).
4535    ///
4536    /// zstd clamps the value to its bounds instead of refusing it. A
4537    /// streaming frame that reads a borrowed dictionary or prefix is
4538    /// compressed on the calling thread whatever this is set to, and
4539    /// `JobSize`, `OverlapSizeLog` and `RSyncable` then have no effect on
4540    /// it, see [`CCtx`](CCtx#worker-threads-and-leaks).
4541    /// [`CCtx::frame_workers()`] returns what a frame gets.
4542    ///
4543    /// Note: this needs the `zstdmt` feature. Without it, any value other
4544    /// than `0` is refused with a `parameter_unsupported` error.
4545    NbWorkers(u32),
4546
4547    /// Size in bytes of a compression job.
4548    ///
4549    /// Does not have any effect when `NbWorkers` is set to 0, or on a frame
4550    /// that runs on the calling thread (see `NbWorkers`).
4551    ///
4552    /// The default value of 0 finds the best job size based on the compression parameters.
4553    ///
4554    /// Note: this will only work if the `zstdmt` feature is activated.
4555    JobSize(u32),
4556
4557    /// Specifies how much overlap must be given to each worker.
4558    ///
4559    /// Possible values:
4560    ///
4561    /// * `0` (default value): automatic overlap based on compression strategy.
4562    /// * `1`: No overlap
4563    /// * `1 < n < 9`: Overlap a fraction of the window size, defined as `1/(2 ^ 9-n)`.
4564    /// * `9`: Full overlap (as long as the window)
4565    /// * `9 < m`: Will return an error.
4566    ///
4567    /// Note: this will only work if the `zstdmt` feature is activated.
4568    OverlapSizeLog(u32),
4569}
4570
4571/// A decompression parameter.
4572#[derive(Copy, Clone, Debug, PartialEq, Eq)]
4573#[non_exhaustive]
4574pub enum DParameter {
4575    WindowLogMax(u32),
4576
4577    #[cfg(feature = "experimental")]
4578    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4579    /// See `FrameFormat`.
4580    Format(FrameFormat),
4581
4582    #[cfg(feature = "experimental")]
4583    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4584    StableOutBuffer(bool),
4585
4586    #[cfg(feature = "experimental")]
4587    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4588    ForceIgnoreChecksum(bool),
4589
4590    #[cfg(feature = "experimental")]
4591    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4592    RefMultipleDDicts(bool),
4593}
4594
4595/// Wraps the `ZDICT_trainFromBuffer()` function.
4596#[cfg(feature = "zdict_builder")]
4597#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "zdict_builder")))]
4598pub fn train_from_buffer<C: WriteBuf + ?Sized>(
4599    dict_buffer: &mut C,
4600    samples_buffer: &[u8],
4601    samples_sizes: &[usize],
4602) -> SafeResult {
4603    // A plain `sum()` wraps around when overflow checks are disabled, and
4604    // would accept sizes reaching far outside of `samples_buffer`.
4605    let total_size = samples_sizes
4606        .iter()
4607        .try_fold(0usize, |total, &size| total.checked_add(size));
4608    assert_eq!(
4609        Some(samples_buffer.len()),
4610        total_size,
4611        "sample sizes don't add up to the samples buffer length"
4612    );
4613
4614    unsafe {
4615        dict_buffer.write_from(|buffer, capacity| {
4616            parse_code(zstd_sys::ZDICT_trainFromBuffer(
4617                buffer,
4618                capacity,
4619                ptr_void(samples_buffer),
4620                samples_sizes.as_ptr(),
4621                samples_sizes.len() as u32,
4622            ))
4623        })
4624    }
4625}
4626
4627/// Wraps the `ZDICT_getDictID()` function.
4628#[cfg(feature = "zdict_builder")]
4629#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "zdict_builder")))]
4630pub fn get_dict_id(dict_buffer: &[u8]) -> Option<NonZeroU32> {
4631    NonZeroU32::new(unsafe {
4632        zstd_sys::ZDICT_getDictID(ptr_void(dict_buffer), dict_buffer.len())
4633    })
4634}
4635
4636/// Wraps the `ZSTD_getBlockSize()` function.
4637#[cfg(feature = "experimental")]
4638#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4639#[deprecated(
4640    note = "The block API is deprecated; use the normal compression API instead."
4641)]
4642pub fn get_block_size(cctx: &CCtx) -> usize {
4643    unsafe { zstd_sys::ZSTD_getBlockSize(cctx.0.as_ptr()) }
4644}
4645
4646/// Wraps the `ZSTD_decompressBound` function
4647#[cfg(feature = "experimental")]
4648#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4649pub fn decompress_bound(data: &[u8]) -> Result<u64, ErrorCode> {
4650    let bound =
4651        unsafe { zstd_sys::ZSTD_decompressBound(ptr_void(data), data.len()) };
4652    if is_error(bound as usize) {
4653        Err(bound as usize)
4654    } else {
4655        Ok(bound)
4656    }
4657}
4658
4659/// Given a buffer of size `src_size`, returns the maximum number of sequences that can ge
4660/// generated.
4661#[cfg(feature = "experimental")]
4662#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4663pub fn sequence_bound(src_size: usize) -> usize {
4664    // Safety: Just FFI.
4665    unsafe { zstd_sys::ZSTD_sequenceBound(src_size) }
4666}
4667
4668/// Returns the minimum extra space when output and input buffer overlap.
4669///
4670/// When using in-place decompression, the output buffer must be at least this much bigger (in
4671/// bytes) than the input buffer. The extra space must be at the front of the output buffer (the
4672/// input buffer must be at the end of the output buffer).
4673#[cfg(feature = "experimental")]
4674#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
4675pub fn decompression_margin(
4676    compressed_data: &[u8],
4677) -> Result<usize, ErrorCode> {
4678    parse_code(unsafe {
4679        zstd_sys::ZSTD_decompressionMargin(
4680            ptr_void(compressed_data),
4681            compressed_data.len(),
4682        )
4683    })
4684}