use std::any::Any;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use crate::ArrayRef;
use crate::ExecutionCtx;
use crate::IntoArray;
use crate::arrays::ChunkedArray;
use crate::arrays::ConstantArray;
use crate::arrays::VariantArray;
use crate::arrays::variant::VariantArraySlotsExt;
use crate::builders::ArrayBuilder;
use crate::builtins::ArrayBuiltins;
use crate::canonical::Canonical;
use crate::dtype::DType;
use crate::dtype::Nullability;
use crate::scalar::Scalar;
pub trait VariantStorageBuilder: Send + 'static {
fn as_any_mut(&mut self) -> &mut dyn Any;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn finish(self: Box<Self>) -> VortexResult<ArrayRef>;
}
enum CorePart {
Chunk(ArrayRef),
Storage(Box<dyn VariantStorageBuilder>),
Run(Scalar, usize),
}
impl CorePart {
fn len(&self) -> usize {
match self {
CorePart::Chunk(chunk) => chunk.len(),
CorePart::Storage(storage) => storage.len(),
CorePart::Run(_, len) => *len,
}
}
fn finish(self) -> VortexResult<ArrayRef> {
match self {
CorePart::Chunk(chunk) => Ok(chunk),
CorePart::Storage(storage) => storage.finish(),
CorePart::Run(scalar, len) => Ok(ConstantArray::new(scalar, len).into_array()),
}
}
}
enum ShreddedPart {
Array(ArrayRef),
Unshredded(usize),
}
pub struct VariantBuilder {
dtype: DType,
core: Vec<CorePart>,
finished_len: usize,
shredded: Vec<ShreddedPart>,
shredded_len: usize,
in_core: bool,
}
impl VariantBuilder {
pub fn new(nullability: Nullability) -> Self {
Self {
dtype: DType::Variant(nullability),
core: Vec::new(),
finished_len: 0,
shredded: Vec::new(),
shredded_len: 0,
in_core: false,
}
}
pub fn append_variant_array(
&mut self,
array: &VariantArray,
ctx: &mut ExecutionCtx,
) -> VortexResult<()> {
self.check_dtype(array.dtype())?;
if array.is_empty() {
return Ok(());
}
if self.in_core {
let chunk = if array.shredded().is_some() {
array.clone().into_array()
} else {
array.core_storage().clone()
};
self.push(CorePart::Chunk(chunk));
return Ok(());
}
if let Some(shredded) = array.shredded() {
if let Some(ShreddedPart::Array(first)) = self
.shredded
.iter()
.find(|part| matches!(part, ShreddedPart::Array(_)))
{
vortex_ensure!(
first.dtype().eq_ignore_nullability(shredded.dtype()),
"cannot build a Variant from Variants shredded as {} and as {}",
first.dtype(),
shredded.dtype()
);
}
self.pad_shredded(self.len());
self.shredded_len += shredded.len();
self.shredded.push(ShreddedPart::Array(shredded.clone()));
}
self.in_core = true;
let appended = array.core_storage().append_to_builder(self, ctx);
self.in_core = false;
appended
}
pub fn append_storage<B: VariantStorageBuilder>(
&mut self,
dtype: &DType,
new: impl FnOnce(&DType) -> B,
append: impl FnOnce(&mut B) -> VortexResult<()>,
) -> VortexResult<()> {
self.check_dtype(dtype)?;
let reuse = match self.core.last_mut() {
Some(CorePart::Storage(storage)) => storage.as_any_mut().is::<B>(),
_ => false,
};
if !reuse {
self.push(CorePart::Storage(Box::new(new(&self.dtype))));
}
let Some(CorePart::Storage(storage)) = self.core.last_mut() else {
vortex_bail!("the Variant storage builder was just installed");
};
let Some(storage) = storage.as_any_mut().downcast_mut::<B>() else {
vortex_bail!("the Variant storage builder has the type it was installed as");
};
append(storage)
}
pub fn append_n_scalars(&mut self, scalar: &Scalar, n: usize) -> VortexResult<()> {
self.check_dtype(scalar.dtype())?;
if n == 0 {
return Ok(());
}
let scalar = if scalar.dtype() == &self.dtype {
scalar.clone()
} else {
scalar.cast(&self.dtype)?
};
if let Some(CorePart::Run(run, len)) = self.core.last_mut()
&& *run == scalar
{
*len += n;
return Ok(());
}
self.push(CorePart::Run(scalar, n));
Ok(())
}
pub fn finish_into_variant(&mut self) -> VortexResult<VariantArray> {
let len = self.len();
let shredded = self.finish_shredded(len)?;
let mut chunks = std::mem::take(&mut self.core)
.into_iter()
.map(CorePart::finish)
.collect::<VortexResult<Vec<_>>>()?;
self.finished_len = 0;
let core = match chunks.len() {
1 => chunks.remove(0),
_ => ChunkedArray::try_new(chunks, self.dtype.clone())?.into_array(),
};
VariantArray::try_new(core, shredded)
}
fn check_dtype(&self, dtype: &DType) -> VortexResult<()> {
vortex_ensure!(
dtype.is_variant() && (self.dtype.is_nullable() || !dtype.is_nullable()),
"cannot append {dtype} to a builder of {}",
self.dtype
);
Ok(())
}
fn push(&mut self, part: CorePart) {
if part.len() == 0 && !matches!(part, CorePart::Storage(_)) {
return;
}
self.finished_len += self.core.last().map_or(0, CorePart::len);
self.core.push(part);
}
fn pad_shredded(&mut self, len: usize) {
if len > self.shredded_len {
self.shredded
.push(ShreddedPart::Unshredded(len - self.shredded_len));
self.shredded_len = len;
}
}
fn finish_shredded(&mut self, len: usize) -> VortexResult<Option<ArrayRef>> {
let Some(dtype) = self.shredded.iter().find_map(|part| match part {
ShreddedPart::Array(array) => Some(array.dtype().clone()),
ShreddedPart::Unshredded(_) => None,
}) else {
self.shredded.clear();
self.shredded_len = 0;
return Ok(None);
};
self.pad_shredded(len);
let parts = std::mem::take(&mut self.shredded);
self.shredded_len = 0;
let nullable = parts.iter().any(|part| match part {
ShreddedPart::Array(array) => array.dtype().is_nullable(),
ShreddedPart::Unshredded(_) => true,
});
let dtype = if nullable { dtype.as_nullable() } else { dtype };
let mut chunks = parts
.into_iter()
.map(|part| match part {
ShreddedPart::Array(array) => {
vortex_ensure!(
array.dtype().eq_ignore_nullability(&dtype),
"cannot build a Variant from Variants shredded as {dtype} and as {}",
array.dtype()
);
if array.dtype() == &dtype {
Ok(array)
} else {
array.cast(dtype.clone())
}
}
ShreddedPart::Unshredded(len) => {
Ok(ConstantArray::new(Scalar::null(dtype.clone()), len).into_array())
}
})
.collect::<VortexResult<Vec<_>>>()?;
if chunks.len() == 1 {
return Ok(chunks.pop());
}
Ok(Some(ChunkedArray::try_new(chunks, dtype)?.into_array()))
}
}
impl ArrayBuilder for VariantBuilder {
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn dtype(&self) -> &DType {
&self.dtype
}
fn len(&self) -> usize {
self.finished_len + self.core.last().map_or(0, CorePart::len)
}
fn append_zeros(&mut self, n: usize) {
let zero = Scalar::zero_value(&self.dtype);
self.append_n_scalars(&zero, n)
.vortex_expect("the zero value of the builder's dtype can be appended");
}
unsafe fn append_nulls_unchecked(&mut self, n: usize) {
let null = Scalar::null(self.dtype.clone());
self.append_n_scalars(&null, n)
.vortex_expect("a null of the builder's dtype can be appended");
}
fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
self.append_n_scalars(scalar, 1)
}
fn reserve_exact(&mut self, _additional: usize) {}
fn reserve_chunks(&mut self, additional: usize) {
self.core.reserve(additional);
self.shredded.reserve(additional);
}
fn finish(&mut self) -> ArrayRef {
self.finish_into_variant()
.vortex_expect("the appended Variants finish into one")
.into_array()
}
fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
Canonical::Variant(
self.finish_into_variant()
.vortex_expect("the appended Variants finish into one"),
)
}
}
#[cfg(test)]
mod tests {
use std::sync::LazyLock;
use vortex_error::VortexResult;
use vortex_error::vortex_err;
use vortex_session::VortexSession;
use super::*;
use crate::VortexSessionExecute;
use crate::arrays::Chunked;
use crate::arrays::Constant;
use crate::arrays::PrimitiveArray;
use crate::arrays::chunked::ChunkedArrayExt;
use crate::assert_arrays_eq;
use crate::builders::builder_with_capacity_in;
use crate::memory::BufferAllocatorRef;
static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
fn variant(value: i32) -> Scalar {
Scalar::variant(Scalar::primitive(value, Nullability::NonNullable))
}
fn values(array: &VariantArray) -> VortexResult<Vec<Option<i32>>> {
let mut ctx = SESSION.create_execution_ctx();
(0..array.len())
.map(|idx| {
let scalar = array.execute_scalar(idx, &mut ctx)?;
Ok(scalar
.as_variant()
.value()
.and_then(|value| value.as_primitive().as_::<i32>()))
})
.collect()
}
#[test]
fn dispatches_on_the_variant_dtype() {
let builder = builder_with_capacity_in(
&DType::Variant(Nullability::Nullable),
4,
BufferAllocatorRef::static_ref(),
);
assert!(builder.as_any().is::<VariantBuilder>());
}
#[test]
fn appends_scalars_as_runs() -> VortexResult<()> {
let mut builder = VariantBuilder::new(Nullability::Nullable);
builder.append_scalar(&variant(1))?;
builder.append_scalar(&variant(1))?;
builder.append_nulls(2);
builder.append_scalar(&variant(2))?;
let array = builder.finish_into_variant()?;
assert_eq!(values(&array)?, [Some(1), Some(1), None, None, Some(2)]);
let core = array.core_storage().as_::<Chunked>();
assert_eq!(core.nchunks(), 3);
assert!(core.iter_chunks().all(|chunk| chunk.is::<Constant>()));
Ok(())
}
#[test]
fn pads_the_shredded_child() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let shredded = VariantArray::try_new(
ConstantArray::new(variant(1), 2).into_array(),
Some(PrimitiveArray::from_iter([10i32, 20]).into_array()),
)?;
let mut builder = VariantBuilder::new(Nullability::NonNullable);
builder.append_scalar(&variant(3))?;
builder.append_variant_array(&shredded, &mut ctx)?;
builder.append_scalar(&variant(4))?;
let array = builder.finish_into_variant()?;
assert_eq!(values(&array)?, [Some(3), Some(10), Some(20), Some(4)]);
let shredded = array
.shredded()
.ok_or_else(|| vortex_err!("expected a shredded child"))?;
assert_arrays_eq!(
shredded,
PrimitiveArray::from_option_iter([None, Some(10i32), Some(20), None]),
&mut ctx
);
Ok(())
}
#[test]
fn concatenates_the_shredded_children() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let mut builder = VariantBuilder::new(Nullability::NonNullable);
for (values, shredded) in [(vec![1, 2], vec![10i32, 20]), (vec![3], vec![30])] {
let core = ChunkedArray::try_new(
values
.into_iter()
.map(|value| ConstantArray::new(variant(value), 1).into_array()),
DType::Variant(Nullability::NonNullable),
)?;
let array = VariantArray::try_new(
core.into_array(),
Some(PrimitiveArray::from_iter(shredded).into_array()),
)?;
builder.append_variant_array(&array, &mut ctx)?;
}
let array = builder.finish_into_variant()?;
assert_eq!(values(&array)?, [Some(10), Some(20), Some(30)]);
let shredded = array
.shredded()
.ok_or_else(|| vortex_err!("expected a shredded child"))?;
assert_arrays_eq!(
shredded,
PrimitiveArray::from_iter([10i32, 20, 30]),
&mut ctx
);
Ok(())
}
#[test]
fn rejects_shredded_children_of_different_dtypes() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let shredded = |value: i32, typed: ArrayRef| {
VariantArray::try_new(
ConstantArray::new(variant(value), 1).into_array(),
Some(typed),
)
};
let mut builder = VariantBuilder::new(Nullability::NonNullable);
builder.append_variant_array(
&shredded(1, PrimitiveArray::from_iter([10i32]).into_array())?,
&mut ctx,
)?;
let err = builder
.append_variant_array(
&shredded(2, PrimitiveArray::from_iter([20i64]).into_array())?,
&mut ctx,
)
.and_then(|()| builder.finish_into_variant().map(|_| ()))
.unwrap_err();
assert!(
err.to_string()
.contains("cannot build a Variant from Variants shredded as")
);
Ok(())
}
#[test]
fn rejects_nullable_variants_in_a_non_nullable_builder() {
let mut builder = VariantBuilder::new(Nullability::NonNullable);
let null = Scalar::null(DType::Variant(Nullability::Nullable));
assert!(builder.append_scalar(&null).is_err());
}
#[test]
fn finishes_empty() -> VortexResult<()> {
let array = VariantBuilder::new(Nullability::Nullable).finish_into_variant()?;
assert!(array.is_empty());
assert!(array.shredded().is_none());
Ok(())
}
}