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
use std::ops;

use zopfli::{self, Format, Options};

use crate::error::*;

pub enum Compressed {
    Gz(Vec<u8>),
    Xz(Vec<u8>),
}

impl ops::Deref for Compressed {
    type Target = Vec<u8>;

    fn deref(&self) -> &Self::Target {
        match self {
            Self::Gz(data) |
            Self::Xz(data) => &data,
        }
    }
}

/// Compresses data using the [native Rust implementation of Zopfli](https://github.com/carols10cents/zopfli).
pub fn gz(data: &[u8]) -> CDResult<Vec<u8>> {
    // Compressed data is typically half to a third the original size
    let mut compressed = Vec::with_capacity(data.len() >> 1);
    zopfli::compress(&Options::default(), &Format::Gzip, data, &mut compressed)?;

    Ok(compressed)
}

/// Compresses data using the xz2 library
#[cfg(feature = "lzma")]
pub fn xz_or_gz(data: &[u8], fast: bool) -> CDResult<Compressed> {
    use std::io::Read;
    use xz2::bufread::XzEncoder;

    // Compressed data is typically half to a third the original size
    let mut compressed = Vec::with_capacity(data.len() >> 1);
    // Compression level 6 is a good trade off between size and [ridiculously] long compression time
    XzEncoder::new(data, if fast { 1 } else { 6 }).read_to_end(&mut compressed)?;
    compressed.shrink_to_fit();

    Ok(Compressed::Xz(compressed))
}

#[cfg(not(feature = "lzma"))]
pub fn xz_or_gz(data: &[u8], _fast: bool) -> CDResult<Compressed> {
    gz(data).map(Compressed::Gz)
}