comde/
com.rs

1//! Generic data structure compression framework.
2
3use std::io::{Read, Result, Seek, Write};
4
5pub struct ByteCount {
6    /// Bytes read from the reader, before being compressed.
7    pub read: u64,
8
9    /// Bytes written to the writer, after being compressed.
10    pub write: u64,
11}
12
13pub trait Compressor {
14    fn new() -> Self;
15
16    fn compress<W: Write + Seek, R: Read>(
17        &self,
18        writer: &mut W,
19        reader: &mut R,
20    ) -> Result<ByteCount>;
21
22    fn to_vec<V: Compress>(&self, data: V) -> Result<Vec<u8>> {
23        let mut writer = std::io::Cursor::new(Vec::with_capacity(128));
24        self.compress(&mut writer, &mut data.to_reader())?;
25        Ok(writer.into_inner())
26    }
27}
28
29pub trait Compress {
30    type Reader: Read;
31    fn to_reader(self) -> Self::Reader;
32}
33
34impl Compress for String {
35    type Reader = std::io::Cursor<String>;
36
37    fn to_reader(self) -> Self::Reader {
38        std::io::Cursor::new(self)
39    }
40}
41
42impl<'a> Compress for &'a str {
43    type Reader = std::io::Cursor<&'a str>;
44
45    fn to_reader(self) -> Self::Reader {
46        std::io::Cursor::new(self)
47    }
48}
49
50impl<'a> Compress for &'a Vec<u8> {
51    type Reader = std::io::Cursor<Self>;
52
53    fn to_reader(self) -> Self::Reader {
54        std::io::Cursor::new(self)
55    }
56}