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