zstd/bulk/mod.rs
1//! Compress and decompress data in bulk.
2//!
3//! These methods process all the input data at once.
4//! It is therefore best used with relatively small blocks
5//! (like small network packets).
6
7mod compressor;
8mod decompressor;
9
10#[cfg(test)]
11mod tests;
12
13pub use self::compressor::Compressor;
14pub use self::decompressor::Decompressor;
15
16use std::io;
17
18/// Compresses a single block of data to the given destination buffer.
19///
20/// Returns the number of bytes written, or an error if something happened
21/// (for instance if the destination buffer was too small).
22///
23/// [`crate::compress_bound()`] says how large the destination might need to
24/// be. Passing a `Vec` instead of a slice works too, and then it is the
25/// `Vec`'s *capacity* that bounds the output - so `reserve` what you need
26/// rather than `resize`, since the bytes do not have to be initialized.
27///
28/// A level of `0` uses zstd's default (currently `3`).
29pub fn compress_to_buffer(
30 source: &[u8],
31 destination: &mut [u8],
32 level: i32,
33) -> io::Result<usize> {
34 Compressor::new(level)?.compress_to_buffer(source, destination)
35}
36
37/// Compresses a block of data and returns the compressed result.
38///
39/// A level of `0` uses zstd's default (currently `3`).
40pub fn compress(data: &[u8], level: i32) -> io::Result<Vec<u8>> {
41 Compressor::new(level)?.compress(data)
42}
43
44/// Decompress a single block of data to the given destination buffer.
45///
46/// Returns the number of bytes written, or an error if something happened
47/// (for instance if the destination buffer was too small).
48///
49/// [`crate::decompressed_size()`] says how big the result will be, when the
50/// frame records it - there is no need to store the size alongside the data
51/// yourself. Passing a `Vec` instead of a slice works too, and then it is the
52/// `Vec`'s *capacity* that bounds the output, so `reserve` what you need
53/// rather than `resize`.
54pub fn decompress_to_buffer(
55 source: &[u8],
56 destination: &mut [u8],
57) -> io::Result<usize> {
58 Decompressor::new()?.decompress_to_buffer(source, destination)
59}
60
61/// Decompresses a block of data and returns the decompressed result.
62///
63/// The decompressed data should be at most `capacity` bytes, or an error will
64/// be returned - so `capacity` is the most you are willing to allocate for
65/// this, not a guess that has to be right. When the frame records its size,
66/// only that much is allocated however large a `capacity` you allow.
67///
68/// [`crate::decompressed_size()`] gives you that size up front, if you would
69/// rather decide for yourself.
70pub fn decompress(data: &[u8], capacity: usize) -> io::Result<Vec<u8>> {
71 Decompressor::new()?.decompress(data, capacity)
72}