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,
}
}
}
pub fn gz(data: &[u8]) -> CDResult<Vec<u8>> {
let mut compressed = Vec::with_capacity(data.len() >> 1);
zopfli::compress(&Options::default(), &Format::Gzip, data, &mut compressed)?;
Ok(compressed)
}
#[cfg(feature = "lzma")]
pub fn xz_or_gz(data: &[u8], fast: bool) -> CDResult<Compressed> {
use std::io::Read;
use xz2::bufread::XzEncoder;
let mut compressed = Vec::with_capacity(data.len() >> 1);
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)
}