use bytes::bytes_dict_builder;
use decimal::decimal_dict_builder;
use primitive::primitive_dict_builder;
use vortex_buffer::BufferAllocatorRef;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_panic;
use crate::ArrayRef;
use crate::ExecutionCtx;
use crate::IntoArray;
use crate::arrays::DictArray;
use crate::arrays::PrimitiveArray;
use crate::arrays::primitive::PrimitiveArrayExt;
use crate::builtins::ArrayBuiltins;
use crate::dtype::DType;
use crate::dtype::Nullability;
use crate::dtype::PType;
use crate::match_each_decimal_value_type;
use crate::match_each_native_ptype;
mod bytes;
mod decimal;
mod primitive;
mod values;
#[derive(Clone)]
pub struct DictConstraints {
pub max_bytes: usize,
pub max_len: usize,
}
pub const UNCONSTRAINED: DictConstraints = DictConstraints {
max_bytes: usize::MAX,
max_len: usize::MAX,
};
pub const fn codes_ptype_for_max_len(max_len: u64) -> PType {
match max_len {
len if len <= 1 << u8::BITS => PType::U8,
len if len <= 1 << u16::BITS => PType::U16,
len if len <= 1 << u32::BITS => PType::U32,
_ => PType::U64,
}
}
pub trait DictEncoder: Send {
fn encode(&mut self, array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<PrimitiveArray>;
fn reset(&mut self) -> ArrayRef;
fn codes_ptype(&self) -> PType;
}
#[deprecated(note = "use `dict_encoder_in` with an explicit allocator")]
pub fn dict_encoder(array: &ArrayRef, constraints: &DictConstraints) -> Box<dyn DictEncoder> {
dict_encoder_in(
array,
constraints,
BufferAllocatorRef::statically_allocated(),
)
}
pub fn dict_encoder_in(
array: &ArrayRef,
constraints: &DictConstraints,
allocator: BufferAllocatorRef,
) -> Box<dyn DictEncoder> {
match array.dtype() {
DType::Primitive(ptype, nullability) => match_each_native_ptype!(*ptype, |P| {
primitive_dict_builder::<P>(*nullability, constraints, allocator)
}),
DType::Utf8(_) | DType::Binary(_) => {
bytes_dict_builder(array.dtype().clone(), constraints, allocator)
}
DType::Decimal(decimal_dtype, nullability) => {
match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |D| {
decimal_dict_builder::<D>(*decimal_dtype, *nullability, constraints, allocator)
})
}
dtype => {
vortex_panic!(
"Can only dictionary encode primitive, decimal or binary arrays, got {dtype}"
)
}
}
}
pub fn dict_encode_with_constraints(
array: &ArrayRef,
constraints: &DictConstraints,
ctx: &mut ExecutionCtx,
) -> VortexResult<DictArray> {
let constraints = DictConstraints {
max_bytes: constraints.max_bytes,
max_len: constraints.max_len.min(array.len().max(1)),
};
let mut encoder = dict_encoder_in(array, &constraints, ctx.allocator().clone());
let codes = encoder.encode(array, ctx)?;
let values = encoder.reset();
let codes = narrow_codes(codes, values.len(), ctx)?;
unsafe {
Ok(DictArray::new_unchecked(codes.into_array(), values).set_all_values_referenced(true))
}
}
fn narrow_codes(
codes: PrimitiveArray,
dict_len: usize,
ctx: &mut ExecutionCtx,
) -> VortexResult<PrimitiveArray> {
let ptype = codes_ptype_for_max_len(dict_len as u64);
if codes.ptype() == ptype {
return Ok(codes);
}
codes
.as_ref()
.cast(DType::Primitive(ptype, Nullability::NonNullable))?
.execute::<PrimitiveArray>(ctx)
}
pub fn dict_encode(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<DictArray> {
let dict_array = dict_encode_with_constraints(array, &UNCONSTRAINED, ctx)?;
if dict_array.len() != array.len() {
vortex_bail!(
"must have encoded all {} elements, but only encoded {}",
array.len(),
dict_array.len(),
);
}
Ok(dict_array)
}
#[cfg(test)]
mod tests {
use std::sync::LazyLock;
use rstest::rstest;
use vortex_error::VortexResult;
use vortex_session::VortexSession;
use super::dict_encode;
use crate::IntoArray;
use crate::VortexSessionExecute;
use crate::arrays::PrimitiveArray;
use crate::arrays::dict::DictArraySlotsExt;
use crate::arrays::primitive::PrimitiveArrayExt;
static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
#[rstest]
#[case::empty(0)]
#[case::single(1)]
#[case::fills_u8(256)]
#[case::overflows_u8(257)]
#[case::fills_u16(65_536)]
#[case::overflows_u16(65_537)]
fn codes_are_as_narrow_as_a_scan_makes_them(#[case] distinct: u32) -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let array = PrimitiveArray::from_iter((0..distinct).chain(0..distinct)).into_array();
let codes = dict_encode(&array, &mut ctx)?
.codes()
.clone()
.execute::<PrimitiveArray>(&mut ctx)?;
assert_eq!(codes.ptype(), codes.narrow(&mut ctx)?.ptype());
Ok(())
}
}