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