Skip to main content

vortex_array/builders/dict/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use bytes::bytes_dict_builder;
5use decimal::decimal_dict_builder;
6use primitive::primitive_dict_builder;
7use vortex_buffer::BufferAllocatorRef;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10use vortex_error::vortex_panic;
11
12use crate::ArrayRef;
13use crate::ExecutionCtx;
14use crate::IntoArray;
15use crate::arrays::DictArray;
16use crate::arrays::PrimitiveArray;
17use crate::arrays::primitive::PrimitiveArrayExt;
18use crate::builtins::ArrayBuiltins;
19use crate::dtype::DType;
20use crate::dtype::Nullability;
21use crate::dtype::PType;
22use crate::match_each_decimal_value_type;
23use crate::match_each_native_ptype;
24
25mod bytes;
26mod decimal;
27mod primitive;
28mod values;
29
30#[derive(Clone)]
31pub struct DictConstraints {
32    /// Limits the encoded storage for dictionary values.
33    pub max_bytes: usize,
34    /// Limits the number of dictionary values.
35    pub max_len: usize,
36}
37
38pub const UNCONSTRAINED: DictConstraints = DictConstraints {
39    max_bytes: usize::MAX,
40    max_len: usize::MAX,
41};
42
43/// Returns the narrowest unsigned code type that can index `max_len` dictionary values.
44///
45/// Codes count from zero, so a code type indexes one more value than its maximum: `u8` codes
46/// index up to 256 values.
47pub const fn codes_ptype_for_max_len(max_len: u64) -> PType {
48    match max_len {
49        len if len <= 1 << u8::BITS => PType::U8,
50        len if len <= 1 << u16::BITS => PType::U16,
51        len if len <= 1 << u32::BITS => PType::U32,
52        _ => PType::U64,
53    }
54}
55
56pub trait DictEncoder: Send {
57    /// Assign dictionary codes to the given input array.
58    fn encode(&mut self, array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<PrimitiveArray>;
59
60    /// Clear the encoder state to make it ready for a new round of decoding.
61    fn reset(&mut self) -> ArrayRef;
62
63    /// Returns the PType of the codes this encoder produces.
64    fn codes_ptype(&self) -> PType;
65}
66
67/// Create a dictionary encoder using the default allocator.
68#[deprecated(note = "use `dict_encoder_in` with an explicit allocator")]
69pub fn dict_encoder(array: &ArrayRef, constraints: &DictConstraints) -> Box<dyn DictEncoder> {
70    dict_encoder_in(
71        array,
72        constraints,
73        BufferAllocatorRef::statically_allocated(),
74    )
75}
76
77/// Create a dictionary encoder using `allocator`.
78pub fn dict_encoder_in(
79    array: &ArrayRef,
80    constraints: &DictConstraints,
81    allocator: BufferAllocatorRef,
82) -> Box<dyn DictEncoder> {
83    // Choose by dtype: the encoders execute an input that is not already canonical, such as a
84    // lazy slice.
85    match array.dtype() {
86        DType::Primitive(ptype, nullability) => match_each_native_ptype!(*ptype, |P| {
87            primitive_dict_builder::<P>(*nullability, constraints, allocator)
88        }),
89        DType::Utf8(_) | DType::Binary(_) => {
90            bytes_dict_builder(array.dtype().clone(), constraints, allocator)
91        }
92        DType::Decimal(decimal_dtype, nullability) => {
93            match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |D| {
94                decimal_dict_builder::<D>(*decimal_dtype, *nullability, constraints, allocator)
95            })
96        }
97        dtype => {
98            vortex_panic!(
99                "Can only dictionary encode primitive, decimal or binary arrays, got {dtype}"
100            )
101        }
102    }
103}
104
105/// Encode an array as a `DictArray` subject to the given constraints.
106///
107/// The codes use the narrowest unsigned integer type that can address the dictionary, so callers
108/// have nothing left to narrow.
109///
110/// Vortex encoders must always produce unsigned integer codes; signed codes are only accepted for external compatibility.
111pub fn dict_encode_with_constraints(
112    array: &ArrayRef,
113    constraints: &DictConstraints,
114    ctx: &mut ExecutionCtx,
115) -> VortexResult<DictArray> {
116    // Every row contributes at most one dictionary entry, so the array bounds the dictionary
117    // length whatever the caller asked for. Encoders pick their code width up front from this
118    // bound, so tightening it keeps a one-shot encode from writing `u64` codes for a dictionary
119    // that cannot hold more than a handful of entries.
120    let constraints = DictConstraints {
121        max_bytes: constraints.max_bytes,
122        max_len: constraints.max_len.min(array.len().max(1)),
123    };
124    let mut encoder = dict_encoder_in(array, &constraints, ctx.allocator().clone());
125    let codes = encoder.encode(array, ctx)?;
126    let values = encoder.reset();
127    let codes = narrow_codes(codes, values.len(), ctx)?;
128    // SAFETY: The encoding process will produce a value set of codes and values
129    // All values in the dictionary are guaranteed to be referenced by at least one code
130    // since we build the dictionary from the codes we observe during encoding
131    unsafe {
132        Ok(DictArray::new_unchecked(codes.into_array(), values).set_all_values_referenced(true))
133    }
134}
135
136/// Narrow codes addressing a `dict_len`-entry dictionary to the smallest type that can hold them.
137///
138/// Encoders hand out consecutive codes and only ever add an entry they immediately use, so the
139/// largest code is `dict_len - 1`. That makes the narrowest code type known without the scan
140/// [`PrimitiveArrayExt::narrow`] would otherwise run over the codes.
141fn narrow_codes(
142    codes: PrimitiveArray,
143    dict_len: usize,
144    ctx: &mut ExecutionCtx,
145) -> VortexResult<PrimitiveArray> {
146    let ptype = codes_ptype_for_max_len(dict_len as u64);
147    if codes.ptype() == ptype {
148        return Ok(codes);
149    }
150    codes
151        .as_ref()
152        .cast(DType::Primitive(ptype, Nullability::NonNullable))?
153        .execute::<PrimitiveArray>(ctx)
154}
155
156pub fn dict_encode(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<DictArray> {
157    let dict_array = dict_encode_with_constraints(array, &UNCONSTRAINED, ctx)?;
158    if dict_array.len() != array.len() {
159        vortex_bail!(
160            "must have encoded all {} elements, but only encoded {}",
161            array.len(),
162            dict_array.len(),
163        );
164    }
165    Ok(dict_array)
166}
167
168#[cfg(test)]
169mod tests {
170    use std::sync::LazyLock;
171
172    use rstest::rstest;
173    use vortex_error::VortexResult;
174    use vortex_session::VortexSession;
175
176    use super::dict_encode;
177    use crate::IntoArray;
178    use crate::VortexSessionExecute;
179    use crate::arrays::PrimitiveArray;
180    use crate::arrays::dict::DictArraySlotsExt;
181    use crate::arrays::primitive::PrimitiveArrayExt;
182
183    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
184
185    /// `narrow_codes` picks the code type from the dictionary length instead of scanning the
186    /// codes, so it must land on the same type a scan would at every width boundary.
187    #[rstest]
188    #[case::empty(0)]
189    #[case::single(1)]
190    #[case::fills_u8(256)]
191    #[case::overflows_u8(257)]
192    #[case::fills_u16(65_536)]
193    #[case::overflows_u16(65_537)]
194    fn codes_are_as_narrow_as_a_scan_makes_them(#[case] distinct: u32) -> VortexResult<()> {
195        let mut ctx = SESSION.create_execution_ctx();
196        let array = PrimitiveArray::from_iter((0..distinct).chain(0..distinct)).into_array();
197
198        let codes = dict_encode(&array, &mut ctx)?
199            .codes()
200            .clone()
201            .execute::<PrimitiveArray>(&mut ctx)?;
202
203        assert_eq!(codes.ptype(), codes.narrow(&mut ctx)?.ptype());
204        Ok(())
205    }
206}