use vortex_error::{vortex_bail, vortex_err, VortexError, VortexResult};
use crate::encoding::Encoding;
use crate::stats::{ArrayStatistics, Stat};
use crate::{ArrayDType, ArrayData, IntoArrayData, IntoCanonical};
pub trait TakeFn<Array> {
fn take(&self, array: &Array, indices: &ArrayData) -> VortexResult<ArrayData>;
unsafe fn take_unchecked(&self, array: &Array, indices: &ArrayData) -> VortexResult<ArrayData> {
self.take(array, indices)
}
}
impl<E: Encoding> TakeFn<ArrayData> for E
where
E: TakeFn<E::Array>,
for<'a> &'a E::Array: TryFrom<&'a ArrayData, Error = VortexError>,
{
fn take(&self, array: &ArrayData, indices: &ArrayData) -> VortexResult<ArrayData> {
let array_ref = <&E::Array>::try_from(array)?;
let encoding = array
.encoding()
.as_any()
.downcast_ref::<E>()
.ok_or_else(|| vortex_err!("Mismatched encoding"))?;
TakeFn::take(encoding, array_ref, indices)
}
}
pub fn take(
array: impl AsRef<ArrayData>,
indices: impl AsRef<ArrayData>,
) -> VortexResult<ArrayData> {
let array = array.as_ref();
let indices = indices.as_ref();
if !indices.dtype().is_int() || indices.dtype().is_nullable() {
vortex_bail!(
"Take indices must be a non-nullable integer type, got {}",
indices.dtype()
);
}
let checked_indices = indices
.statistics()
.get_as::<usize>(Stat::Max)
.is_some_and(|max| max < array.len());
let taken = take_impl(array, indices, checked_indices)?;
debug_assert_eq!(
taken.len(),
indices.len(),
"Take length mismatch {}",
array.encoding().id()
);
debug_assert_eq!(
array.dtype(),
taken.dtype(),
"Take dtype mismatch {}",
array.encoding().id()
);
Ok(taken)
}
fn take_impl(
array: &ArrayData,
indices: &ArrayData,
checked_indices: bool,
) -> VortexResult<ArrayData> {
if let Some(take_fn) = array.encoding().take_fn() {
let result = if checked_indices {
unsafe { take_fn.take_unchecked(array, indices) }
} else {
take_fn.take(array, indices)
}?;
if array.dtype() != result.dtype() {
vortex_bail!(
"TakeFn {} changed array dtype from {} to {}",
array.encoding().id(),
array.dtype(),
result.dtype()
);
}
return Ok(result);
}
log::debug!("No take implementation found for {}", array.encoding().id());
let canonical = array.clone().into_canonical()?.into_array();
let canonical_take_fn = canonical
.encoding()
.take_fn()
.ok_or_else(|| vortex_err!(NotImplemented: "take", canonical.encoding().id()))?;
if checked_indices {
unsafe { canonical_take_fn.take_unchecked(&canonical, indices) }
} else {
canonical_take_fn.take(&canonical, indices)
}
}