Skip to main content

crabka_compression/
codec_type.rs

1//! `CompressionType` enum mapping to Kafka's record-batch attribute bits.
2
3/// Codec identifier matching the lowest three bits of Kafka's record-batch
4/// attribute byte.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6#[repr(u8)]
7#[non_exhaustive]
8pub enum CompressionType {
9    None = 0,
10    Gzip = 1,
11    Snappy = 2,
12    Lz4 = 3,
13    Zstd = 4,
14}
15
16impl CompressionType {
17    /// Decode the lowest three bits of a Kafka record-batch attribute byte.
18    /// Returns `None` for codec ids outside `0..=4`.
19    #[must_use]
20    pub fn from_attribute_bits(b: u8) -> Option<Self> {
21        match b & 0b0000_0111 {
22            0 => Some(Self::None),
23            1 => Some(Self::Gzip),
24            2 => Some(Self::Snappy),
25            3 => Some(Self::Lz4),
26            4 => Some(Self::Zstd),
27            _ => None,
28        }
29    }
30
31    /// Encode this codec into the lowest three bits of an attribute byte.
32    #[must_use]
33    pub fn as_attribute_bits(self) -> u8 {
34        self as u8
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use assert2::assert;
42
43    #[test]
44    fn attribute_bits_roundtrip() {
45        for ct in [
46            CompressionType::None,
47            CompressionType::Gzip,
48            CompressionType::Snappy,
49            CompressionType::Lz4,
50            CompressionType::Zstd,
51        ] {
52            assert!(CompressionType::from_attribute_bits(ct.as_attribute_bits()) == Some(ct));
53        }
54    }
55
56    #[test]
57    fn attribute_bits_mask() {
58        // Only the low 3 bits define the codec; upper bits are other flags.
59        assert!(
60            CompressionType::from_attribute_bits(0b1111_1000 | 0b0000_0001)
61                == Some(CompressionType::Gzip)
62        );
63    }
64
65    #[test]
66    fn attribute_bits_unknown() {
67        assert!(CompressionType::from_attribute_bits(5) == None);
68        assert!(CompressionType::from_attribute_bits(7) == None);
69    }
70}