use std::hash::Hasher;
use itertools::Itertools;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use vortex_error::vortex_ensure_eq;
use vortex_error::vortex_panic;
use vortex_session::registry::CachedId;
use crate::ArrayEq;
use crate::ArrayHash;
use crate::ArrayRef;
use crate::Canonical;
use crate::EqMode;
use crate::ExecutionCtx;
use crate::ExecutionResult;
use crate::IntoArray;
use crate::array::Array;
use crate::array::ArrayId;
use crate::array::ArrayParts;
use crate::array::ArrayView;
use crate::array::VTable;
use crate::array::with_empty_buffers;
use crate::arrays::FixedSizeList;
use crate::arrays::Struct;
use crate::arrays::Variant;
use crate::arrays::chunked::ChunkedArrayExt;
use crate::arrays::chunked::ChunkedData;
use crate::arrays::chunked::array::ChunkedSlots;
use crate::arrays::chunked::compute::rules::RULES;
use crate::arrays::chunked::vtable::canonical::ListChunks;
use crate::arrays::chunked::vtable::canonical::swizzle;
use crate::arrays::chunked::vtable::canonical::swizzle_fixed_size_list;
use crate::arrays::chunked::vtable::canonical::swizzle_list;
use crate::arrays::chunked::vtable::canonical::swizzle_struct;
use crate::arrays::chunked::vtable::canonical::swizzle_variant;
use crate::buffer::BufferHandle;
use crate::builders::ArrayBuilder;
use crate::dtype::DType;
use crate::dtype::Nullability;
use crate::dtype::PType;
mod canonical;
mod operations;
mod plugin;
mod validity;
pub type ChunkedArray = Array<Chunked>;
#[derive(Clone, Debug)]
pub struct Chunked;
impl ArrayHash for ChunkedData {
fn array_hash<H: Hasher>(&self, _state: &mut H, _accuracy: EqMode) {
}
}
impl ArrayEq for ChunkedData {
fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool {
true
}
}
impl VTable for Chunked {
type TypedArrayData = ChunkedData;
type OperationsVTable = Self;
type ValidityVTable = Self;
fn id(&self) -> ArrayId {
static ID: CachedId = CachedId::new("vortex.chunked");
*ID
}
fn validate(
&self,
data: &ChunkedData,
dtype: &DType,
len: usize,
slots: &[Option<ArrayRef>],
) -> VortexResult<()> {
vortex_ensure!(
!slots.is_empty(),
"ChunkedArray must have at least a chunk offsets slot"
);
let chunk_offsets = slots[ChunkedSlots::CHUNK_OFFSETS]
.as_ref()
.vortex_expect("validated chunk offsets slot");
vortex_ensure_eq!(
chunk_offsets.dtype(),
&DType::Primitive(PType::U64, Nullability::NonNullable),
"ChunkedArray chunk offsets must be non-nullable u64",
);
vortex_ensure_eq!(
chunk_offsets.len(),
data.chunk_offsets.len(),
"ChunkedArray chunk offsets slot length does not match cached offsets length",
);
vortex_ensure_eq!(
data.chunk_offsets.len(),
slots.len() - ChunkedSlots::CHUNKS_OFFSET + 1,
"ChunkedArray must have one more chunk offset than chunks",
);
vortex_ensure_eq!(
data.chunk_offsets
.last()
.copied()
.vortex_expect("chunked arrays always have a leading 0 offset"),
len,
"ChunkedArray length does not match outer length",
);
for (idx, (start, end)) in data
.chunk_offsets
.iter()
.copied()
.tuple_windows()
.enumerate()
{
let chunk = slots[ChunkedSlots::CHUNKS_OFFSET + idx]
.as_ref()
.vortex_expect("validated chunk slot");
vortex_ensure_eq!(
chunk.dtype(),
dtype,
"ChunkedArray chunk dtype does not match outer dtype",
);
vortex_ensure_eq!(
chunk.len(),
end - start,
"ChunkedArray chunk {idx} len does not match offsets span",
);
}
Ok(())
}
fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
0
}
fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
vortex_panic!("ChunkedArray buffer index {idx} out of bounds")
}
fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
vortex_panic!("ChunkedArray buffer_name index {idx} out of bounds")
}
fn with_buffers(
&self,
array: ArrayView<'_, Self>,
buffers: &[BufferHandle],
) -> VortexResult<ArrayParts<Self>> {
with_empty_buffers(self, array, buffers)
}
fn append_to_builder(
array: ArrayView<'_, Self>,
builder: &mut dyn ArrayBuilder,
ctx: &mut ExecutionCtx,
) -> VortexResult<()> {
builder.reserve_chunks(array.nchunks());
for chunk in array.iter_chunks() {
chunk.append_to_builder(builder, ctx)?;
}
Ok(())
}
fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
match idx {
ChunkedSlots::CHUNK_OFFSETS => "chunk_offsets".to_string(),
n => format!("chunks[{}]", n - ChunkedSlots::CHUNKS_OFFSET),
}
}
fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
match array.dtype() {
DType::Union(..) => {
vortex_bail!(
"TODO(connor)[Union]: canonicalize chunked Union arrays by packing type IDs \
and every sparse child along identical chunk boundaries"
)
}
DType::FixedSizeList(..) => swizzle::<FixedSizeList>(array, swizzle_fixed_size_list),
DType::Struct(..) => swizzle::<Struct>(array, swizzle_struct),
DType::List(..) => swizzle::<ListChunks>(array, |array| swizzle_list(array, ctx)),
DType::Variant(..) => swizzle::<Variant>(array, |array| swizzle_variant(array, ctx)),
_ => {
let slot_idx = array.next_child_slot.max(ChunkedSlots::CHUNKS_OFFSET);
if slot_idx < array.slots().len() {
Ok(ExecutionResult::append_child(
array.with_next_child_slot(slot_idx + 1),
slot_idx,
))
} else if slot_idx == ChunkedSlots::CHUNKS_OFFSET {
Ok(ExecutionResult::done(
Canonical::empty(array.dtype()).into_array(),
))
} else {
Ok(ExecutionResult::done_into_builder(array))
}
}
}
}
fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
Ok(match array.nchunks() {
0 if matches!(array.dtype(), DType::Variant(_)) => None,
0 => Some(Canonical::empty(array.dtype()).into_array()),
1 => Some(array.chunk(0).clone()),
_ => return RULES.evaluate(array),
})
}
}