vortex_btrblocks/integer/
dictionary.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Dictionary compressor that reuses the unique values in the `IntegerStats`.
5
6use vortex_array::IntoArray;
7use vortex_array::arrays::DictArray;
8use vortex_array::arrays::PrimitiveArray;
9use vortex_array::validity::Validity;
10use vortex_array::vtable::ValidityHelper;
11use vortex_buffer::Buffer;
12
13use crate::integer::IntegerStats;
14use crate::integer::stats::ErasedStats;
15
16macro_rules! typed_encode {
17    ($stats:ident, $typed:ident, $validity:ident, $typ:ty) => {{
18        let values: Buffer<$typ> = $typed.distinct_values.keys().map(|x| x.0).collect();
19
20        let max_code = values.len();
21        let codes = if max_code <= u8::MAX as usize {
22            let buf =
23                <DictEncoder as Encode<$typ, u8>>::encode(&values, $stats.src.as_slice::<$typ>());
24            PrimitiveArray::new(buf, $validity.clone()).into_array()
25        } else if max_code <= u16::MAX as usize {
26            let buf =
27                <DictEncoder as Encode<$typ, u16>>::encode(&values, $stats.src.as_slice::<$typ>());
28            PrimitiveArray::new(buf, $validity.clone()).into_array()
29        } else {
30            let buf =
31                <DictEncoder as Encode<$typ, u32>>::encode(&values, $stats.src.as_slice::<$typ>());
32            PrimitiveArray::new(buf, $validity.clone()).into_array()
33        };
34
35        let values_validity = match $validity {
36            Validity::NonNullable => Validity::NonNullable,
37            _ => Validity::AllValid,
38        };
39
40        let values = PrimitiveArray::new(values, values_validity).into_array();
41        // SAFETY: invariants enforced in DictEncoder
42        unsafe { DictArray::new_unchecked(codes, values).set_all_values_referenced(true) }
43    }};
44}
45
46/// Compresses an integer array into a dictionary arrays according to attached stats.
47#[expect(
48    clippy::cognitive_complexity,
49    reason = "complexity from match on all integer types"
50)]
51pub fn dictionary_encode(stats: &IntegerStats) -> DictArray {
52    // We need to preserve the nullability somehow from the original
53    let src_validity = stats.src.validity();
54
55    match &stats.typed {
56        ErasedStats::U8(typed) => typed_encode!(stats, typed, src_validity, u8),
57        ErasedStats::U16(typed) => typed_encode!(stats, typed, src_validity, u16),
58        ErasedStats::U32(typed) => typed_encode!(stats, typed, src_validity, u32),
59        ErasedStats::U64(typed) => typed_encode!(stats, typed, src_validity, u64),
60        ErasedStats::I8(typed) => typed_encode!(stats, typed, src_validity, i8),
61        ErasedStats::I16(typed) => typed_encode!(stats, typed, src_validity, i16),
62        ErasedStats::I32(typed) => typed_encode!(stats, typed, src_validity, i32),
63        ErasedStats::I64(typed) => typed_encode!(stats, typed, src_validity, i64),
64    }
65}
66
67struct DictEncoder;
68
69trait Encode<T, I> {
70    /// Using the distinct value set, turn the values into a set of codes.
71    fn encode(distinct: &[T], values: &[T]) -> Buffer<I>;
72}
73
74macro_rules! impl_encode {
75    ($typ:ty) => { impl_encode!($typ, u8, u16, u32); };
76    ($typ:ty, $($ityp:ty),+) => {
77        $(
78        impl Encode<$typ, $ityp> for DictEncoder {
79            #[allow(clippy::cast_possible_truncation)]
80            fn encode(distinct: &[$typ], values: &[$typ]) -> Buffer<$ityp> {
81                let mut codes =
82                    vortex_utils::aliases::hash_map::HashMap::<$typ, $ityp>::with_capacity(
83                        distinct.len(),
84                    );
85                for (code, &value) in distinct.iter().enumerate() {
86                    codes.insert(value, code as $ityp);
87                }
88
89                let mut output = vortex_buffer::BufferMut::with_capacity(values.len());
90                for value in values {
91                    // Any code lookups which fail are for nulls, so their value
92                    // does not matter.
93                    // SAFETY: we have exactly sized output to be as large as values.
94                    unsafe { output.push_unchecked(codes.get(value).copied().unwrap_or_default()) };
95                }
96
97                return output.freeze();
98            }
99        }
100        )*
101    };
102}
103
104impl_encode!(u8);
105impl_encode!(u16);
106impl_encode!(u32);
107impl_encode!(u64);
108impl_encode!(i8);
109impl_encode!(i16);
110impl_encode!(i32);
111impl_encode!(i64);
112
113#[cfg(test)]
114mod tests {
115    use vortex_array::Array;
116    use vortex_array::IntoArray;
117    use vortex_array::arrays::BoolArray;
118    use vortex_array::arrays::PrimitiveArray;
119    use vortex_array::assert_arrays_eq;
120    use vortex_array::validity::Validity;
121    use vortex_buffer::buffer;
122
123    use crate::CompressorStats;
124    use crate::integer::IntegerStats;
125    use crate::integer::dictionary::dictionary_encode;
126
127    #[test]
128    fn test_dict_encode_integer_stats() {
129        // Create an array that has some nulls
130        let data = buffer![100i32, 200, 100, 0, 100];
131        let validity =
132            Validity::Array(BoolArray::from_iter([true, true, true, false, true]).into_array());
133        let array = PrimitiveArray::new(data, validity);
134
135        let stats = IntegerStats::generate(&array);
136        let dict_array = dictionary_encode(&stats);
137        assert_eq!(dict_array.values().len(), 2);
138        assert_eq!(dict_array.codes().len(), 5);
139
140        let undict = dict_array;
141
142        // We just use code zero, but it doesn't really matter.
143        // We can just shove a whole validity buffer in there instead.
144        let expected = PrimitiveArray::new(
145            buffer![100i32, 200, 100, 100, 100],
146            Validity::Array(BoolArray::from_iter([true, true, true, false, true]).into_array()),
147        )
148        .into_array();
149        assert_arrays_eq!(undict.as_ref(), expected.as_ref());
150    }
151}