use num_traits::AsPrimitive;
use vortex_buffer::Buffer;
use vortex_buffer::BufferAllocatorRef;
use vortex_buffer::BufferMut;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use vortex_error::vortex_ensure_eq;
use super::super::Interleave;
use super::super::InterleaveArrayExt;
use crate::array::Array;
use crate::arrays::Primitive;
use crate::match_each_unsigned_integer_ptype;
pub(super) struct Source<T> {
data: Buffer<T>,
len: usize,
row_mask: usize,
}
impl<T: Copy> Source<T> {
pub(super) fn constant(payload: T, len: usize, allocator: &BufferAllocatorRef) -> Self {
Self {
data: Buffer::full_in(payload, 1, allocator.clone()),
len,
row_mask: 0,
}
}
pub(super) fn decoded(data: Buffer<T>) -> Self {
Self {
len: data.len(),
data,
row_mask: usize::MAX,
}
}
}
pub(super) fn gather<T: Copy>(
array: &Array<Interleave>,
sources: &[Source<T>],
allocator: &BufferAllocatorRef,
) -> VortexResult<Buffer<T>> {
let branches = array.array_indices().as_::<Primitive>();
let rows = array.row_indices().as_::<Primitive>();
match_each_unsigned_integer_ptype!(branches.ptype(), |A| {
match_each_unsigned_integer_ptype!(rows.ptype(), |R| {
gather_rows(
sources,
branches.as_slice::<A>(),
rows.as_slice::<R>(),
allocator,
)
})
})
}
fn gather_rows<T, A, R>(
sources: &[Source<T>],
branches: &[A],
rows: &[R],
allocator: &BufferAllocatorRef,
) -> VortexResult<Buffer<T>>
where
T: Copy,
A: AsPrimitive<usize>,
R: AsPrimitive<usize>,
{
vortex_ensure_eq!(
rows.len(),
branches.len(),
"interleave row_indices length does not match array_indices length",
);
let len = branches.len();
let mut output = BufferMut::with_capacity_in(len, allocator.clone());
let slots = &mut output.spare_capacity_mut()[..len];
for ((slot, branch), row) in slots.iter_mut().zip(branches).zip(rows) {
let Some(source) = sources.get((*branch).as_()) else {
vortex_bail!("interleave array index out of bounds");
};
let row = (*row).as_();
vortex_ensure!(row < source.len, "interleave row index out of bounds");
slot.write(source.data[row & source.row_mask]);
}
unsafe { output.set_len(len) };
Ok(output.freeze())
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use vortex_buffer::buffer;
use vortex_error::VortexResult;
use super::Source;
use super::gather_rows;
use crate::memory::BufferAllocatorRef;
#[rstest]
#[case::array_index(2, 0, "array index out of bounds")]
#[case::constant_row_index(0, 1, "row index out of bounds")]
#[case::decoded_row_index(1, 1, "row index out of bounds")]
fn rejects_out_of_bounds_selectors(
#[case] branch: u8,
#[case] row: u8,
#[case] message: &str,
) -> VortexResult<()> {
let allocator = BufferAllocatorRef::statically_allocated();
let sources = [
Source::constant(1u32, 1, &allocator),
Source::decoded(buffer![2u32]),
];
let error = gather_rows(&sources, &[branch], &[row], &allocator)
.expect_err("every case names a value or a row that does not exist");
assert!(error.to_string().contains(message), "{error}");
Ok(())
}
}