byte_size/
engine.rs

1use bimap::BiHashMap;
2use crate::builder::Builder;
3use crate::iterator::CodeIterator;
4use crate::error::Result;
5use crate::ir::CodeType;
6
7///Used to compress and decompress
8///
9/// Can only be created with the [Builder] struct via [Builder::engine]
10pub struct Engine {
11    pub (crate) custom_spaces: bool,
12    pub (crate) custom_map: BiHashMap<& 'static [u8], usize>,
13    pub (crate) lengths: Vec<usize>,
14}
15
16impl Engine {
17
18    ///Compress the string using the builder options
19    pub fn compress(&self, string: & str) -> Vec<u8> {
20        let mut res = Vec::new();
21
22        for code in CodeIterator::new(string, &self) {
23            code.serialize_into(& mut res, &self);
24        }
25
26        res
27    }
28
29    ///Tries to decompress the byte slice.
30    ///
31    /// If successful, the decompressed string is returned. Otherwise a [Result] is returned.
32    pub fn decompress(&self, mut bytes: & [u8]) -> Result<String> {
33        let mut string = String::new();
34
35        while !bytes.is_empty() {
36            let code = CodeType::deserialize_from(& mut bytes, &self)?;
37
38            code.add_to_string(& mut string, &self)?;
39        }
40
41        Ok(string)
42    }
43
44}
45
46///Convenience function to compress a string using the [Builder::default] options
47pub fn compress(string: &str) -> Vec<u8> {
48    Builder::default().engine().compress(string)
49}
50
51///Convenience function to decompress a byte slice using the [Builder::default] options
52pub fn decompress(bytes: & [u8]) -> Result<String> {
53    Builder::default().engine().decompress(bytes)
54}