lindera_compress/
lib.rs

1use std::io::Write;
2
3use flate2::{
4    write::{DeflateEncoder, GzEncoder, ZlibEncoder},
5    Compression,
6};
7pub use lindera_decompress::{Algorithm, CompressedData};
8
9#[allow(dead_code)]
10fn algorithm_compression_ratio_estimation() -> f64 {
11    unimplemented!()
12}
13
14pub fn compress(data: &[u8], algorithm: Algorithm) -> anyhow::Result<CompressedData> {
15    match algorithm {
16        Algorithm::Deflate => {
17            let mut e = DeflateEncoder::new(Vec::new(), Compression::default());
18            e.write_all(data)?;
19
20            Ok(CompressedData::new(algorithm, e.finish()?))
21        }
22        Algorithm::Zlib => {
23            let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
24            e.write_all(data)?;
25
26            Ok(CompressedData::new(algorithm, e.finish()?))
27        }
28        Algorithm::Gzip => {
29            let mut e = GzEncoder::new(Vec::new(), Compression::default());
30            e.write_all(data)?;
31            Ok(CompressedData::new(algorithm, e.finish()?))
32        }
33        Algorithm::Raw => Ok(CompressedData::new(algorithm, data.to_vec())),
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40    use lindera_decompress::decompress;
41    use rand::prelude::*;
42
43    #[test]
44    fn compress_decompress() {
45        let mut rng = rand::thread_rng();
46        let mut buf = Vec::new();
47
48        for _i in 0..10000 {
49            buf.push(rng.gen())
50        }
51        for _i in 0..10000 {
52            buf.push(0)
53        }
54
55        let compress_data = compress(&buf, Algorithm::Deflate).unwrap();
56
57        let data = decompress(compress_data).unwrap();
58
59        assert_eq!(&buf, &data);
60    }
61}