vortex_array/builders/dict/
mod.rs1use 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 pub max_bytes: usize,
34 pub max_len: usize,
36}
37
38pub const UNCONSTRAINED: DictConstraints = DictConstraints {
39 max_bytes: usize::MAX,
40 max_len: usize::MAX,
41};
42
43pub 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 fn encode(&mut self, array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<PrimitiveArray>;
59
60 fn reset(&mut self) -> ArrayRef;
62
63 fn codes_ptype(&self) -> PType;
65}
66
67#[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
77pub fn dict_encoder_in(
79 array: &ArrayRef,
80 constraints: &DictConstraints,
81 allocator: BufferAllocatorRef,
82) -> Box<dyn DictEncoder> {
83 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
105pub fn dict_encode_with_constraints(
112 array: &ArrayRef,
113 constraints: &DictConstraints,
114 ctx: &mut ExecutionCtx,
115) -> VortexResult<DictArray> {
116 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 unsafe {
132 Ok(DictArray::new_unchecked(codes.into_array(), values).set_all_values_referenced(true))
133 }
134}
135
136fn 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 #[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}