Skip to main content

lsm_tree/
compression.rs

1// Copyright (c) 2024-present, fjall-rs
2// This source code is licensed under both the Apache 2.0 and MIT License
3// (found in the LICENSE-* files in the repository)
4
5use crate::coding::{Decode, Encode};
6use byteorder::{ReadBytesExt, WriteBytesExt};
7use std::io::{Read, Write};
8
9/// Compression algorithm to use
10#[derive(Copy, Clone, Debug, Eq, PartialEq)]
11pub enum CompressionType {
12    /// No compression
13    ///
14    /// Not recommended.
15    None,
16
17    /// LZ4 compression
18    ///
19    /// Recommended for use cases with a focus
20    /// on speed over compression ratio.
21    #[cfg(feature = "lz4")]
22    Lz4,
23}
24
25impl std::fmt::Display for CompressionType {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        write!(
28            f,
29            "{}",
30            match self {
31                Self::None => "none",
32
33                #[cfg(feature = "lz4")]
34                Self::Lz4 => "lz4",
35            }
36        )
37    }
38}
39
40impl Encode for CompressionType {
41    fn encode_into<W: Write>(&self, writer: &mut W) -> Result<(), crate::Error> {
42        match self {
43            Self::None => {
44                writer.write_u8(0)?;
45            }
46
47            #[cfg(feature = "lz4")]
48            Self::Lz4 => {
49                writer.write_u8(1)?;
50            }
51        }
52
53        Ok(())
54    }
55}
56
57impl Decode for CompressionType {
58    fn decode_from<R: Read>(reader: &mut R) -> Result<Self, crate::Error> {
59        let tag = reader.read_u8()?;
60
61        match tag {
62            0 => Ok(Self::None),
63
64            #[cfg(feature = "lz4")]
65            1 => Ok(Self::Lz4),
66
67            tag => Err(crate::Error::InvalidTag(("CompressionType", tag))),
68        }
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use test_log::test;
76
77    #[test]
78    fn compression_serialize_none() {
79        let serialized = CompressionType::None.encode_into_vec();
80        assert_eq!(1, serialized.len());
81    }
82
83    #[cfg(feature = "lz4")]
84    mod lz4 {
85        use super::*;
86        use test_log::test;
87
88        #[test]
89        fn compression_serialize_none() {
90            let serialized = CompressionType::Lz4.encode_into_vec();
91            assert_eq!(1, serialized.len());
92        }
93    }
94}