mina_tree/ondisk/
compression.rs

1pub enum MaybeCompressed<'a> {
2    Compressed(Box<[u8]>),
3    No(&'a [u8]),
4}
5
6impl AsRef<[u8]> for MaybeCompressed<'_> {
7    fn as_ref(&self) -> &[u8] {
8        match self {
9            MaybeCompressed::Compressed(c) => c,
10            MaybeCompressed::No(b) => b,
11        }
12    }
13}
14
15impl MaybeCompressed<'_> {
16    pub fn is_compressed(&self) -> bool {
17        matches!(self, Self::Compressed(_))
18    }
19}
20
21#[cfg(feature = "compression")]
22pub fn compress(bytes: &[u8]) -> std::io::Result<MaybeCompressed<'_>> {
23    let compressed = {
24        let mut result = Vec::<u8>::with_capacity(bytes.len());
25        zstd::stream::copy_encode(bytes, &mut result, zstd::DEFAULT_COMPRESSION_LEVEL)?;
26        result
27    };
28
29    if compressed.len() >= bytes.len() {
30        Ok(MaybeCompressed::No(bytes))
31    } else {
32        Ok(MaybeCompressed::Compressed(compressed.into()))
33    }
34}
35
36#[cfg(not(feature = "compression"))]
37pub fn compress(bytes: &[u8]) -> std::io::Result<MaybeCompressed<'_>> {
38    Ok(MaybeCompressed::No(bytes))
39}
40
41#[cfg(feature = "compression")]
42pub fn decompress(bytes: &[u8], is_compressed: bool) -> std::io::Result<Box<[u8]>> {
43    if is_compressed {
44        let mut result = Vec::with_capacity(bytes.len() * 2);
45        zstd::stream::copy_decode(bytes, &mut result)?;
46        Ok(result.into())
47    } else {
48        Ok(bytes.into())
49    }
50}
51
52#[cfg(not(feature = "compression"))]
53pub fn decompress(bytes: &[u8], _is_compressed: bool) -> std::io::Result<Box<[u8]>> {
54    Ok(bytes.into())
55}