Skip to main content

zstd/stream/
mod.rs

1//! Compress and decompress Zstd streams.
2//!
3//! Zstd streams are the main way to compress and decompress data.
4//! They are compatible with the `zstd` command-line tool.
5//!
6//! This module provides both `Read` and `Write` interfaces to compressing and
7//! decompressing.
8
9pub mod read;
10pub mod write;
11
12mod functions;
13pub mod zio;
14
15#[cfg(test)]
16mod tests;
17
18pub mod raw;
19
20pub use self::functions::{
21    compress_file, compress_file_into, compress_sized, compress_sized_into,
22    copy_decode, copy_encode, decode_all, decompressed_size, encode_all,
23};
24pub use self::read::Decoder;
25pub use self::write::{AutoFinishEncoder, Encoder};
26
27#[doc(hidden)]
28#[macro_export]
29/// Common functions for the decoder, both in read and write mode.
30macro_rules! decoder_parameters {
31    () => {
32        /// Sets the maximum back-reference distance.
33        ///
34        /// The actual maximum distance is going to be `2^log_distance`.
35        ///
36        /// This will need to at least match the value set when compressing.
37        pub fn window_log_max(&mut self, log_distance: u32) -> io::Result<()> {
38            self.set_parameter(zstd_safe::DParameter::WindowLogMax(
39                log_distance,
40            ))
41        }
42
43        #[cfg(feature = "experimental")]
44        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
45        /// Enables or disabled expecting the 4-byte magic header
46        ///
47        /// Only available with the `experimental` feature.
48        ///
49        /// This will need to match the settings used when compressing.
50        pub fn include_magicbytes(
51            &mut self,
52            include_magicbytes: bool,
53        ) -> io::Result<()> {
54            self.set_parameter(zstd_safe::DParameter::Format(
55                if include_magicbytes {
56                    zstd_safe::FrameFormat::One
57                } else {
58                    zstd_safe::FrameFormat::Magicless
59                },
60            ))
61        }
62    };
63}
64
65#[doc(hidden)]
66#[macro_export]
67/// Common functions for the decoder, both in read and write mode.
68macro_rules! decoder_common {
69    ($readwrite:ident) => {
70        /// Sets a decompression parameter on the decompression stream.
71        pub fn set_parameter(
72            &mut self,
73            parameter: zstd_safe::DParameter,
74        ) -> io::Result<()> {
75            self.$readwrite.operation_mut().set_parameter(parameter)
76        }
77
78        $crate::decoder_parameters!();
79    };
80}
81
82#[doc(hidden)]
83#[macro_export]
84/// Parameter-setters for the encoder. Relies on a `set_parameter` method.
85macro_rules! encoder_parameters {
86    () => {
87        /// Controls whether zstd should include a content checksum at the end
88        /// of each frame.
89        pub fn include_checksum(
90            &mut self,
91            include_checksum: bool,
92        ) -> io::Result<()> {
93            self.set_parameter(zstd_safe::CParameter::ChecksumFlag(
94                include_checksum,
95            ))
96        }
97
98        /// Enables multithreaded compression
99        ///
100        /// * If `n_workers == 0` (default), then multithreaded will be
101        ///   disabled.
102        /// * If `n_workers >= 1`, then compression will be done in separate
103        ///   threads.
104        ///
105        /// So even `n_workers = 1` may increase performance by separating
106        /// IO and compression.
107        ///
108        /// Note: This is only available if the `zstdmt` cargo feature is activated.
109        #[cfg(feature = "zstdmt")]
110        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "zstdmt")))]
111        pub fn multithread(&mut self, n_workers: u32) -> io::Result<()> {
112            self.set_parameter(zstd_safe::CParameter::NbWorkers(n_workers))
113        }
114
115        /// Enables or disables storing of the dict id.
116        ///
117        /// Defaults to true. If false, the behaviour of decoding with a wrong
118        /// dictionary is undefined.
119        pub fn include_dictid(
120            &mut self,
121            include_dictid: bool,
122        ) -> io::Result<()> {
123            self.set_parameter(zstd_safe::CParameter::DictIdFlag(
124                include_dictid,
125            ))
126        }
127
128        /// Enables or disabled storing of the contentsize.
129        ///
130        /// Note that this only has an effect if the size is given with `set_pledged_src_size`.
131        pub fn include_contentsize(
132            &mut self,
133            include_contentsize: bool,
134        ) -> io::Result<()> {
135            self.set_parameter(zstd_safe::CParameter::ContentSizeFlag(
136                include_contentsize,
137            ))
138        }
139        /// Enables or disables long-distance matching
140        pub fn long_distance_matching(
141            &mut self,
142            long_distance_matching: bool,
143        ) -> io::Result<()> {
144            self.set_parameter(
145                zstd_safe::CParameter::EnableLongDistanceMatching(
146                    long_distance_matching,
147                ),
148            )
149        }
150
151        /// Sets the target size for compressed blocks.
152        ///
153        /// A lower block size may result in slightly lower speed (~2%) and compression ratio
154        /// (~0.1%), but may decrease end-to-end latency in low-bandwidth environments (time to
155        /// first decompressed byte).
156        ///
157        /// No value, or a value of zero, results in no constraint for the block sizes.
158        pub fn set_target_cblock_size(
159            &mut self,
160            target_size: Option<u32>,
161        ) -> io::Result<()> {
162            self.set_parameter(zstd_safe::CParameter::TargetCBlockSize(
163                target_size.unwrap_or(0),
164            ))
165        }
166
167        /// Sets the maximum back-reference distance.
168        ///
169        /// The actual maximum distance is going to be `2^log_distance`.
170        ///
171        /// Note that decompression will need to use at least the same setting.
172        pub fn window_log(&mut self, log_distance: u32) -> io::Result<()> {
173            self.set_parameter(zstd_safe::CParameter::WindowLog(log_distance))
174        }
175
176        #[cfg(feature = "experimental")]
177        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
178        /// Enables or disable the magic bytes at the beginning of each frame.
179        ///
180        /// If disabled, include_magicbytes must also be called on the decoder.
181        ///
182        /// Only available with the `experimental` feature.
183        ///
184        /// Note that decompression will need to use the same setting.
185        pub fn include_magicbytes(
186            &mut self,
187            include_magicbytes: bool,
188        ) -> io::Result<()> {
189            self.set_parameter(zstd_safe::CParameter::Format(
190                if include_magicbytes {
191                    zstd_safe::FrameFormat::One
192                } else {
193                    zstd_safe::FrameFormat::Magicless
194                },
195            ))
196        }
197    };
198}
199
200#[doc(hidden)]
201#[macro_export]
202/// Common functions for the encoder, both in read and write mode.
203macro_rules! encoder_common {
204    ($readwrite:ident) => {
205        /// Sets the given zstd compression parameter.
206        pub fn set_parameter(
207            &mut self,
208            parameter: zstd_safe::CParameter,
209        ) -> io::Result<()> {
210            self.$readwrite.operation_mut().set_parameter(parameter)
211        }
212
213        /// Sets the expected size of the input.
214        ///
215        /// This affects the compression effectiveness.
216        ///
217        /// It is an error to give an incorrect size (an error will be returned when closing the
218        /// stream if the size does not match what was pledged).
219        ///
220        /// Giving a `None` size means the size is unknown (this is the default).
221        pub fn set_pledged_src_size(
222            &mut self,
223            size: Option<u64>,
224        ) -> io::Result<()> {
225            self.$readwrite.operation_mut().set_pledged_src_size(size)
226        }
227
228        $crate::encoder_parameters!();
229    };
230}