rusty_leveldb/
compressor.rs

1/// Custom compression method
2///
3/// ```
4/// # use rusty_leveldb::{Compressor, CompressorId};
5///
6/// #[derive(Debug, Clone, Copy, Default)]
7/// pub struct CustomCompressor;
8///
9/// impl CompressorId for CustomCompressor {
10///     // a unique id to identify what compressor should DB use
11///     const ID: u8 = 42;
12/// }
13///
14/// impl Compressor for CustomCompressor {
15///     fn encode(&self, block: Vec<u8>) -> rusty_leveldb::Result<Vec<u8>> {
16///         // Do something
17///         Ok(block)
18///     }
19///
20///     fn decode(&self, block: Vec<u8>) -> rusty_leveldb::Result<Vec<u8>> {
21///         // Do something
22///         Ok(block)
23///     }
24/// }
25/// ```
26///
27/// See [crate::CompressorList] for usage
28pub trait Compressor {
29    fn encode(&self, block: Vec<u8>) -> crate::Result<Vec<u8>>;
30
31    fn decode(&self, block: Vec<u8>) -> crate::Result<Vec<u8>>;
32}
33
34/// Set default compressor id
35pub trait CompressorId {
36    const ID: u8;
37}
38
39/// A compressor that do **Nothing**
40///
41/// It default id is `0`
42#[derive(Debug, Clone, Copy, Default)]
43pub struct NoneCompressor;
44
45impl CompressorId for NoneCompressor {
46    const ID: u8 = 0;
47}
48
49impl Compressor for NoneCompressor {
50    fn encode(&self, block: Vec<u8>) -> crate::Result<Vec<u8>> {
51        Ok(block)
52    }
53
54    fn decode(&self, block: Vec<u8>) -> crate::Result<Vec<u8>> {
55        Ok(block)
56    }
57}
58
59/// A compressor that compress data with Google's Snappy
60///
61/// It default id is `1`
62#[derive(Debug, Clone, Copy, Default)]
63pub struct SnappyCompressor;
64
65impl CompressorId for SnappyCompressor {
66    const ID: u8 = 1;
67}
68
69impl Compressor for SnappyCompressor {
70    fn encode(&self, block: Vec<u8>) -> crate::Result<Vec<u8>> {
71        Ok(snap::raw::Encoder::new().compress_vec(&block)?)
72    }
73
74    fn decode(&self, block: Vec<u8>) -> crate::Result<Vec<u8>> {
75        Ok(snap::raw::Decoder::new().decompress_vec(&block)?)
76    }
77}