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, DecodeError, Encode, EncodeError};
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 Encode for CompressionType {
26    fn encode_into<W: Write>(&self, writer: &mut W) -> Result<(), EncodeError> {
27        match self {
28            Self::None => {
29                writer.write_u8(0)?;
30            }
31
32            #[cfg(feature = "lz4")]
33            Self::Lz4 => {
34                writer.write_u8(1)?;
35            }
36        }
37
38        Ok(())
39    }
40}
41
42impl Decode for CompressionType {
43    fn decode_from<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
44        let tag = reader.read_u8()?;
45
46        match tag {
47            0 => Ok(Self::None),
48
49            #[cfg(feature = "lz4")]
50            1 => Ok(Self::Lz4),
51
52            tag => Err(DecodeError::InvalidTag(("CompressionType", tag))),
53        }
54    }
55}
56
57impl std::fmt::Display for CompressionType {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        write!(
60            f,
61            "{}",
62            match self {
63                Self::None => "none",
64
65                #[cfg(feature = "lz4")]
66                Self::Lz4 => "lz4",
67            }
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}