Skip to main content

zu_encoding/
lib.rs

1//! Lightweight columnar encodings.
2//!
3//! Every encoding has a format-stable id (`docs/04-storage-zu1-format.md` ยง3)
4//! and must decode at 1 GB/s/core or better with at most 64 KiB of scratch.
5//! Encoder and decoder implementations land in M0; this crate starts with the
6//! stable id table so downstream crates can reference it.
7
8pub mod alp;
9pub mod alp_rd;
10pub mod bitpack;
11pub mod bool_bitpack;
12mod counts;
13pub mod delta;
14pub mod delta_patch;
15pub mod dict;
16pub mod for_bitpack;
17pub mod frequency;
18pub mod fsst;
19pub mod patch;
20pub mod rle;
21pub mod segment;
22pub mod validity;
23pub mod zstd_leaf;
24
25use zu_common::ZuError;
26
27/// Format-stable encoding identifiers. Never renumber.
28#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29#[repr(u8)]
30pub enum EncodingId {
31    Plain = 0,
32    Constant = 1,
33    Rle = 2,
34    Dict = 3,
35    ForBitPack = 4,
36    DeltaBitPack = 5,
37    Alp = 6,
38    AlpRd = 7,
39    Fsst = 8,
40    BoolBitpack = 9,
41    Frequency = 10,
42    Zstd = 11,
43    DeltaPatch = 12,
44}
45
46impl TryFrom<u8> for EncodingId {
47    type Error = ZuError;
48
49    fn try_from(v: u8) -> Result<Self, ZuError> {
50        Ok(match v {
51            0 => Self::Plain,
52            1 => Self::Constant,
53            2 => Self::Rle,
54            3 => Self::Dict,
55            4 => Self::ForBitPack,
56            5 => Self::DeltaBitPack,
57            6 => Self::Alp,
58            7 => Self::AlpRd,
59            8 => Self::Fsst,
60            9 => Self::BoolBitpack,
61            10 => Self::Frequency,
62            11 => Self::Zstd,
63            12 => Self::DeltaPatch,
64            other => {
65                return Err(ZuError::Unsupported {
66                    what: "encoding",
67                    id: u32::from(other),
68                });
69            }
70        })
71    }
72}
73
74/// Bits required to represent `max` with frame-of-reference packing.
75#[inline]
76pub fn bits_needed(max: u64) -> u32 {
77    64 - max.leading_zeros()
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    #[test]
85    fn encoding_id_roundtrip() {
86        for raw in 0u8..=12 {
87            let id = EncodingId::try_from(raw).unwrap();
88            assert_eq!(id as u8, raw);
89        }
90        assert!(EncodingId::try_from(13).is_err());
91    }
92
93    #[test]
94    fn bits() {
95        assert_eq!(bits_needed(0), 0);
96        assert_eq!(bits_needed(1), 1);
97        assert_eq!(bits_needed(255), 8);
98        assert_eq!(bits_needed(256), 9);
99        assert_eq!(bits_needed(u64::MAX), 64);
100    }
101}