zstd 0.14.4

Binding for the zstd compression library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Train a dictionary from various sources.
//!
//! A dictionary can help improve the compression of small files.
//! The dictionary must be present during decompression,
//! but can be shared across multiple "similar" files.
//!
//! Creating a dictionary using the `zstd` C library,
//! using the `zstd` command-line interface, using this library,
//! or using the `train` binary provided, should give the same result,
//! and are therefore completely compatible.
//!
//! To use, see [`Encoder::with_dictionary`] or [`Decoder::with_dictionary`].
//!
//! [`Encoder::with_dictionary`]: ../struct.Encoder.html#method.with_dictionary
//! [`Decoder::with_dictionary`]: ../struct.Decoder.html#method.with_dictionary

#[cfg(feature = "zdict_builder")]
use std::io::{self, Read};

pub use zstd_safe::{CDict, DDict};

/// Prepared dictionary for compression
///
/// A dictionary can include its own copy of the data (if it is `'static`), or it can merely point
/// to a separate buffer (if it has another lifetime).
pub struct EncoderDictionary<'a> {
    cdict: CDict<'a>,
}

/// The error for a dictionary zstd could not load.
fn invalid_dictionary() -> std::io::Error {
    std::io::Error::new(
        std::io::ErrorKind::InvalidData,
        "zstd could not load the dictionary",
    )
}

impl EncoderDictionary<'static> {
    /// Creates a prepared dictionary for compression.
    ///
    /// This will copy the dictionary internally.
    ///
    /// # Panics
    ///
    /// If zstd cannot load the dictionary - for instance, it starts with the
    /// dictionary magic number but its header is corrupt. Use
    /// [`EncoderDictionary::try_copy`] for a dictionary you did not make
    /// yourself.
    pub fn copy(dictionary: &[u8], level: i32) -> Self {
        Self::try_copy(dictionary, level)
            .expect("zstd returned null pointer when creating dict")
    }

    /// Creates a prepared dictionary for compression, or an error if zstd
    /// cannot load it.
    ///
    /// This will copy the dictionary internally.
    pub fn try_copy(dictionary: &[u8], level: i32) -> std::io::Result<Self> {
        let cdict = zstd_safe::CDict::try_create(dictionary, level)
            .ok_or_else(invalid_dictionary)?;
        Ok(Self { cdict })
    }
}

impl<'a> EncoderDictionary<'a> {
    #[cfg(feature = "experimental")]
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
    /// Create prepared dictionary for compression
    ///
    /// A level of `0` uses zstd's default (currently `3`).
    ///
    /// Only available with the `experimental` feature. Use `EncoderDictionary::copy` otherwise.
    ///
    /// # Panics
    ///
    /// If zstd cannot load the dictionary. Use [`EncoderDictionary::try_new`]
    /// for a dictionary you did not make yourself.
    pub fn new(dictionary: &'a [u8], level: i32) -> Self {
        Self::try_new(dictionary, level).expect("zstd returned null pointer")
    }

    #[cfg(feature = "experimental")]
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
    /// Create prepared dictionary for compression, or an error if zstd cannot
    /// load it.
    ///
    /// Only available with the `experimental` feature. Use
    /// `EncoderDictionary::try_copy` otherwise.
    pub fn try_new(dictionary: &'a [u8], level: i32) -> std::io::Result<Self> {
        let cdict =
            zstd_safe::CDict::try_create_by_reference(dictionary, level)
                .ok_or_else(invalid_dictionary)?;
        Ok(Self { cdict })
    }

    /// Returns reference to `CDict` inner object
    pub fn as_cdict(&self) -> &CDict<'a> {
        &self.cdict
    }
}

/// Prepared dictionary for decompression
pub struct DecoderDictionary<'a> {
    ddict: DDict<'a>,
}

impl DecoderDictionary<'static> {
    /// Create a prepared dictionary for decompression.
    ///
    /// This will copy the dictionary internally.
    ///
    /// # Panics
    ///
    /// If zstd cannot load the dictionary - for instance, it starts with the
    /// dictionary magic number but its header is corrupt. Use
    /// [`DecoderDictionary::try_copy`] for a dictionary you did not make
    /// yourself.
    pub fn copy(dictionary: &[u8]) -> Self {
        Self::try_copy(dictionary)
            .expect("zstd returned null pointer when creating dict")
    }

    /// Create a prepared dictionary for decompression, or an error if zstd
    /// cannot load it.
    ///
    /// This will copy the dictionary internally.
    pub fn try_copy(dictionary: &[u8]) -> std::io::Result<Self> {
        let ddict = zstd_safe::DDict::try_create(dictionary)
            .ok_or_else(invalid_dictionary)?;
        Ok(Self { ddict })
    }
}

impl<'a> DecoderDictionary<'a> {
    #[cfg(feature = "experimental")]
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
    /// Create prepared dictionary for decompression
    ///
    /// Only available with the `experimental` feature. Use `DecoderDictionary::copy` otherwise.
    ///
    /// # Panics
    ///
    /// If zstd cannot load the dictionary. Use [`DecoderDictionary::try_new`]
    /// for a dictionary you did not make yourself.
    pub fn new(dict: &'a [u8]) -> Self {
        Self::try_new(dict).expect("zstd returned null pointer")
    }

    #[cfg(feature = "experimental")]
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
    /// Create prepared dictionary for decompression, or an error if zstd
    /// cannot load it.
    ///
    /// Only available with the `experimental` feature. Use
    /// `DecoderDictionary::try_copy` otherwise.
    pub fn try_new(dict: &'a [u8]) -> std::io::Result<Self> {
        let ddict = zstd_safe::DDict::try_create_by_reference(dict)
            .ok_or_else(invalid_dictionary)?;
        Ok(Self { ddict })
    }

    /// Returns reference to `DDict` inner object
    pub fn as_ddict(&self) -> &DDict<'a> {
        &self.ddict
    }
}

/// Train a dictionary from a big continuous chunk of data, with all samples
/// contiguous in memory.
///
/// This is the most efficient way to train a dictionary,
/// since this is directly fed into `zstd`.
///
/// * `sample_data` is the concatenation of all sample data.
/// * `sample_sizes` is the size of each sample in `sample_data`.
///   The sum of all `sample_sizes` should equal the length of `sample_data`.
/// * `max_size` is the maximum size of the dictionary to generate. A buffer of
///   that size is allocated up front, for zstd to write the dictionary into.
///
/// The result is the dictionary data. You can, for example, feed it to [`CDict::create`].
#[cfg(feature = "zdict_builder")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "zdict_builder")))]
pub fn from_continuous(
    sample_data: &[u8],
    sample_sizes: &[usize],
    max_size: usize,
) -> io::Result<Vec<u8>> {
    use crate::map_error_code;

    // Complain if the lengths don't add up to the entire data.
    // Add them with overflow detection: a wrapping sum would accept sizes
    // reaching far outside of `sample_data`.
    let total_size = sample_sizes
        .iter()
        .try_fold(0usize, |total, &size| total.checked_add(size));
    if total_size != Some(sample_data.len()) {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            "sample sizes don't add up".to_string(),
        ));
    }

    let mut result = crate::vec_with_capacity(max_size)?;
    zstd_safe::train_from_buffer(&mut result, sample_data, sample_sizes)
        .map_err(map_error_code)?;
    Ok(result)
}

/// Train a dictionary from multiple samples.
///
/// The samples will internally be copied to a single continuous buffer,
/// so make sure you have enough memory available.
///
/// If you need to stretch your system's limits,
/// [`from_continuous`] directly uses the given slice.
///
/// [`from_continuous`]: ./fn.from_continuous.html
///
/// * `samples` is a list of individual samples to train on.
/// * `max_size` is the maximum size of the dictionary to generate. A buffer of
///   that size is allocated up front, for zstd to write the dictionary into.
///
/// The result is the dictionary data. You can, for example, feed it to [`CDict::create`].
#[cfg(feature = "zdict_builder")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "zdict_builder")))]
pub fn from_samples<S: AsRef<[u8]>>(
    samples: &[S],
    max_size: usize,
) -> io::Result<Vec<u8>> {
    // Pre-allocate the entire required size. The samples may overlap (the
    // same slice given several times), so their total can exceed memory.
    let total_length = samples
        .iter()
        .try_fold(0usize, |total, sample| {
            total.checked_add(sample.as_ref().len())
        })
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::OutOfMemory,
                "the samples are too large to copy together",
            )
        })?;

    let mut data = crate::vec_with_capacity(total_length)?;

    // Copy every sample to a big chunk of memory
    data.extend(samples.iter().flat_map(|s| s.as_ref()).cloned());

    let sizes: Vec<_> = samples.iter().map(|s| s.as_ref().len()).collect();

    from_continuous(&data, &sizes, max_size)
}

/// Train a dictionary from multiple samples.
///
/// Unlike [`from_samples`], this does not require having a list of all samples.
/// It also allows running into an error when iterating through the samples.
///
/// They will still be copied to a continuous array and fed to [`from_continuous`].
///
/// * `samples` is an iterator of individual samples to train on.
/// * `max_size` is the maximum size of the dictionary to generate.
///
/// The result is the dictionary data. You can, for example, feed it to [`CDict::create`].
///
/// # Examples
///
/// ```rust,no_run
/// // Train from a couple of json files.
/// let dict_buffer = zstd::dict::from_sample_iterator(
///     ["file_a.json", "file_b.json"]
///         .into_iter()
///         .map(|filename| std::fs::File::open(filename)),
///     10_000,  // 10kB dictionary
/// ).unwrap();
/// ```
///
/// ```rust,no_run
/// use std::io::BufRead as _;
/// // Treat each line from stdin as a separate sample.
/// let dict_buffer = zstd::dict::from_sample_iterator(
///     std::io::stdin().lock().lines().map(|line: std::io::Result<String>| {
///         // Transform each line into a `Cursor<Vec<u8>>` so they implement Read.
///         line.map(String::into_bytes)
///             .map(std::io::Cursor::new)
///     }),
///     10_000,  // 10kB dictionary
/// ).unwrap();
/// ```
#[cfg(feature = "zdict_builder")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "zdict_builder")))]
pub fn from_sample_iterator<I, R>(
    samples: I,
    max_size: usize,
) -> io::Result<Vec<u8>>
where
    I: IntoIterator<Item = io::Result<R>>,
    R: Read,
{
    let mut data = Vec::new();
    let mut sizes = Vec::new();

    for sample in samples {
        let mut sample = sample?;
        let len = sample.read_to_end(&mut data)?;
        sizes.push(len);
    }

    from_continuous(&data, &sizes, max_size)
}

/// Train a dict from a list of files.
///
/// * `filenames` is an iterator of files to load. Each file will be treated as an individual
///   sample.
/// * `max_size` is the maximum size of the dictionary to generate.
///
/// The result is the dictionary data. You can, for example, feed it to [`CDict::create`].
#[cfg(feature = "zdict_builder")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "zdict_builder")))]
pub fn from_files<I, P>(filenames: I, max_size: usize) -> io::Result<Vec<u8>>
where
    P: AsRef<std::path::Path>,
    I: IntoIterator<Item = P>,
{
    from_sample_iterator(
        filenames
            .into_iter()
            .map(|filename| std::fs::File::open(filename)),
        max_size,
    )
}

#[cfg(test)]
#[cfg(feature = "zdict_builder")]
mod tests {
    use std::fs;
    use std::io;
    use std::io::Read;

    use walkdir;

    #[test]
    fn test_dict_training() {
        // Train a dictionary
        let paths: Vec<_> = walkdir::WalkDir::new("src")
            .into_iter()
            .map(|entry| entry.unwrap())
            .map(|entry| entry.into_path())
            .filter(|path| path.to_str().unwrap().ends_with(".rs"))
            .collect();

        let dict = super::from_files(&paths, 4000).unwrap();

        for path in paths {
            let mut buffer = Vec::new();
            let mut file = fs::File::open(path).unwrap();
            let mut content = Vec::new();
            file.read_to_end(&mut content).unwrap();
            io::copy(
                &mut &content[..],
                &mut crate::stream::Encoder::with_dictionary(
                    &mut buffer,
                    1,
                    &dict,
                )
                .unwrap()
                .auto_finish(),
            )
            .unwrap();

            let mut result = Vec::new();
            io::copy(
                &mut crate::stream::Decoder::with_dictionary(
                    &buffer[..],
                    &dict[..],
                )
                .unwrap(),
                &mut result,
            )
            .unwrap();

            assert_eq!(&content, &result);
        }
    }

    #[test]
    fn test_from_continuous_overflowing_sizes() {
        // These sizes only add up to the data length by wrapping around.
        let data = [0u8; 100];
        let sizes = [usize::MAX - 99, 200];
        assert!(super::from_continuous(&data, &sizes, 4000).is_err());
    }

    #[test]
    fn test_impossible_max_size() {
        use std::io::ErrorKind::OutOfMemory;

        // A dictionary buffer that cannot be allocated is an error, not an
        // abort or a panic.
        let error = super::from_continuous(&[], &[], usize::MAX).unwrap_err();
        assert_eq!(error.kind(), OutOfMemory);
        let error = super::from_samples::<&[u8]>(&[], usize::MAX).unwrap_err();
        assert_eq!(error.kind(), OutOfMemory);
    }
}