Skip to main content

fwob_v2/
codec.rs

1use crate::{Result, V2Error};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4#[repr(u8)]
5pub enum Codec {
6    None = 0,
7    Zstd = 1,
8    Lz4 = 2,
9}
10
11impl Codec {
12    pub fn from_id(id: u8) -> Result<Self> {
13        match id {
14            0 => Ok(Self::None),
15            1 => Ok(Self::Zstd),
16            2 => Ok(Self::Lz4),
17            other => Err(V2Error::UnsupportedCodec(other)),
18        }
19    }
20
21    pub fn compress(self, input: &[u8]) -> Result<Vec<u8>> {
22        self.compress_with_zstd_level(input, 3)
23    }
24
25    pub fn compress_with_zstd_level(self, input: &[u8], zstd_level: i32) -> Result<Vec<u8>> {
26        Ok(match self {
27            Self::None => input.to_vec(),
28            Self::Zstd => zstd::bulk::compress(input, zstd_level)?,
29            Self::Lz4 => lz4_flex::compress_prepend_size(input),
30        })
31    }
32
33    pub fn decompress(self, input: &[u8], expected_len: usize) -> Result<Vec<u8>> {
34        let out = match self {
35            Self::None => input.to_vec(),
36            Self::Zstd => zstd::bulk::decompress(input, expected_len)?,
37            Self::Lz4 => {
38                lz4_flex::decompress_size_prepended(input).map_err(|_| V2Error::ChecksumMismatch)?
39            }
40        };
41        if out.len() != expected_len {
42            return Err(V2Error::ChecksumMismatch);
43        }
44        Ok(out)
45    }
46}