use std::cell::OnceCell;
use std::hash::Hash;
use std::mem;
use rustc_hash::FxBuildHasher;
use vortex_buffer::Alignment;
use vortex_buffer::BitBuffer;
use vortex_buffer::BitBufferMut;
use vortex_buffer::Buffer;
use vortex_buffer::BufferAllocatorRef;
use vortex_buffer::BufferMut;
use vortex_error::VortexExpect;
use vortex_error::vortex_panic;
use vortex_mask::Mask;
use vortex_utils::aliases::hash_map::Entry;
use vortex_utils::aliases::hash_map::HashMap;
use crate::dtype::UnsignedPType;
pub(super) struct ValuesDict<K, V, Code> {
lookup: HashMap<K, Code, FxBuildHasher>,
null_code: OnceCell<Code>,
values: BufferMut<V>,
values_nulls: BitBufferMut,
max_dict_len: usize,
allocator: BufferAllocatorRef,
}
impl<K, V, Code> ValuesDict<K, V, Code>
where
K: Hash + Eq,
V: Copy + Default,
Code: UnsignedPType,
{
pub(super) fn new_in(max_dict_len: usize, allocator: BufferAllocatorRef) -> Self {
Self {
lookup: HashMap::with_hasher(FxBuildHasher),
null_code: OnceCell::new(),
values: BufferMut::empty_aligned_in(Alignment::of::<V>(), allocator.clone()),
values_nulls: BitBufferMut::empty_in(allocator.clone()),
max_dict_len,
allocator,
}
}
pub(super) fn encode(
&mut self,
values: &[V],
mask: &Mask,
key: impl Fn(V) -> K,
) -> BufferMut<Code> {
let mut codes = BufferMut::<Code>::with_capacity_in(values.len(), self.allocator.clone());
if values.is_empty() {
return codes;
}
match mask {
Mask::AllTrue(_) => {
for &value in values {
let Some(code) = self.encode_value(key(value), value) else {
break;
};
unsafe { codes.push_unchecked(code) }
}
}
Mask::AllFalse(_) => {
if let Some(code) = self.encode_null() {
unsafe { codes.push_n_unchecked(code, values.len()) }
}
}
Mask::Values(v) => {
for (&value, valid) in values.iter().zip(v.bit_buffer()) {
let code = if valid {
self.encode_value(key(value), value)
} else {
self.encode_null()
};
let Some(code) = code else {
break;
};
unsafe { codes.push_unchecked(code) }
}
}
}
codes
}
pub(super) fn reset(&mut self) -> (Buffer<V>, BitBuffer) {
self.lookup.clear();
self.null_code = OnceCell::new();
let values = mem::replace(
&mut self.values,
BufferMut::empty_aligned_in(Alignment::of::<V>(), self.allocator.clone()),
);
let nulls = mem::replace(
&mut self.values_nulls,
BitBufferMut::empty_in(self.allocator.clone()),
);
(values.freeze(), nulls.freeze())
}
fn encode_value(&mut self, key: K, value: V) -> Option<Code> {
match self.lookup.entry(key) {
Entry::Occupied(o) => Some(*o.get()),
Entry::Vacant(vac) => {
if is_full(&self.values, self.max_dict_len) {
return None;
}
let next_code = next_code(&self.values);
self.values.push(value);
self.values_nulls.append_true();
Some(*vac.insert(next_code))
}
}
}
fn encode_null(&mut self) -> Option<Code> {
if let Some(code) = self.null_code.get() {
return Some(*code);
}
if is_full(&self.values, self.max_dict_len) {
return None;
}
let code = next_code(&self.values);
self.values.push(V::default());
self.values_nulls.append_false();
self.null_code
.set(code)
.ok()
.vortex_expect("null code is initialized once");
Some(code)
}
}
fn is_full<V>(values: &BufferMut<V>, max_dict_len: usize) -> bool {
!values.is_empty() && values.len() >= max_dict_len
}
fn next_code<V, Code: UnsignedPType>(values: &BufferMut<V>) -> Code {
Code::from_usize(values.len())
.unwrap_or_else(|| vortex_panic!("{} has to fit into {}", values.len(), Code::PTYPE))
}