#[cfg(feature = "gzip")]
pub mod gzip;
#[cfg(any(feature = "lz4", feature = "lz4-hc"))]
pub mod lz4;
#[cfg(feature = "snappy")]
pub mod snappy;
#[cfg(feature = "zstd")]
pub mod zstd;
pub mod error;
pub use self::error::{CompressionError, CompressionErrorKind};
pub type Result<T> = core::result::Result<T, CompressionError>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i16)]
#[non_exhaustive]
pub enum Compression {
None = 0,
Gzip = 1,
Snappy = 2,
Lz4 = 3,
Zstd = 4,
}
impl Compression {
pub const fn from_attributes(attributes: i16) -> Result<Self> {
match attributes & 0x07 {
0 => Ok(Self::None),
1 => Ok(Self::Gzip),
2 => Ok(Self::Snappy),
3 => Ok(Self::Lz4),
4 => Ok(Self::Zstd),
n => Err(CompressionError::new(
Self::None,
CompressionErrorKind::UnknownCodec(n),
)),
}
}
pub fn compress(self, payload: &[u8]) -> Result<Vec<u8>> {
self.compress_with_level(payload, None)
}
pub fn compress_with_level(self, payload: &[u8], level: Option<i32>) -> Result<Vec<u8>> {
match self {
Self::None => {
let _ = level;
Ok(payload.to_vec())
},
#[cfg(feature = "gzip")]
Self::Gzip => gzip::compress_with_level(payload, level),
#[cfg(feature = "snappy")]
Self::Snappy => snappy::compress_with_level(payload, level),
#[cfg(any(feature = "lz4", feature = "lz4-hc"))]
Self::Lz4 => lz4::compress_with_level(payload, level),
#[cfg(feature = "zstd")]
Self::Zstd => zstd::compress_with_level(payload, level),
#[cfg(not(feature = "gzip"))]
Self::Gzip => Err(CompressionError::new(
self,
CompressionErrorKind::CodecDisabled,
)),
#[cfg(not(feature = "snappy"))]
Self::Snappy => Err(CompressionError::new(
self,
CompressionErrorKind::CodecDisabled,
)),
#[cfg(not(any(feature = "lz4", feature = "lz4-hc")))]
Self::Lz4 => Err(CompressionError::new(
self,
CompressionErrorKind::CodecDisabled,
)),
#[cfg(not(feature = "zstd"))]
Self::Zstd => Err(CompressionError::new(
self,
CompressionErrorKind::CodecDisabled,
)),
}
}
pub fn decompress(self, payload: &[u8]) -> Result<Vec<u8>> {
match self {
Self::None => Ok(payload.to_vec()),
#[cfg(feature = "gzip")]
Self::Gzip => gzip::decompress(payload),
#[cfg(feature = "snappy")]
Self::Snappy => snappy::decompress(payload),
#[cfg(any(feature = "lz4", feature = "lz4-hc"))]
Self::Lz4 => lz4::decompress(payload),
#[cfg(feature = "zstd")]
Self::Zstd => zstd::decompress(payload),
#[cfg(not(feature = "gzip"))]
Self::Gzip => Err(CompressionError::new(
self,
CompressionErrorKind::CodecDisabled,
)),
#[cfg(not(feature = "snappy"))]
Self::Snappy => Err(CompressionError::new(
self,
CompressionErrorKind::CodecDisabled,
)),
#[cfg(not(any(feature = "lz4", feature = "lz4-hc")))]
Self::Lz4 => Err(CompressionError::new(
self,
CompressionErrorKind::CodecDisabled,
)),
#[cfg(not(feature = "zstd"))]
Self::Zstd => Err(CompressionError::new(
self,
CompressionErrorKind::CodecDisabled,
)),
}
}
}