use std::fmt::Display;
use std::fmt::Formatter;
use smallvec::smallvec;
use vortex_buffer::Alignment;
use vortex_buffer::BitBufferMut;
use vortex_buffer::Buffer;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_ensure;
use vortex_error::vortex_ensure_eq;
use vortex_error::vortex_panic;
use crate::ArrayRef;
use crate::ArraySlots;
use crate::ExecutionCtx;
use crate::IntoArray;
use crate::array::Array;
use crate::array::ArrayParts;
use crate::array::TypedArrayRef;
use crate::array::child_to_validity;
use crate::array::validity_to_child;
use crate::array_slots;
use crate::arrays::Decimal;
use crate::arrays::DecimalArray;
use crate::arrays::PrimitiveArray;
use crate::arrays::decimal::cast_value_in_precision;
use crate::arrays::decimal::check_precision;
use crate::arrays::decimal::precision_bounds;
use crate::arrays::primitive::PrimitiveArrayExt;
use crate::buffer::BufferHandle;
use crate::dtype::DType;
use crate::dtype::DecimalDType;
use crate::dtype::DecimalType;
use crate::dtype::IntegerPType;
use crate::dtype::NativeDecimalType;
use crate::dtype::Nullability;
use crate::match_each_decimal_value_type;
use crate::match_each_unsigned_integer_ptype;
use crate::patches::Patches;
use crate::validity::Validity;
#[array_slots(Decimal)]
pub struct DecimalSlots {
#[slot(0)]
pub validity_child: Option<ArrayRef>,
}
#[derive(Clone, Debug)]
pub struct DecimalData {
pub(super) decimal_dtype: DecimalDType,
pub(super) values: BufferHandle,
}
impl Display for DecimalData {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"decimal_dtype: {}, values_type: {}",
self.decimal_dtype,
self.values_type()
)
}
}
pub struct DecimalDataParts {
pub decimal_dtype: DecimalDType,
pub values: BufferHandle,
pub values_type: DecimalType,
pub validity: Validity,
}
pub trait DecimalArrayExt: TypedArrayRef<Decimal> {
fn decimal_dtype(&self) -> DecimalDType {
match self.dtype() {
DType::Decimal(decimal_dtype, _) => *decimal_dtype,
_ => unreachable!("DecimalArrayExt requires a decimal dtype"),
}
}
fn nullability(&self) -> Nullability {
match self.dtype() {
DType::Decimal(_, nullability) => *nullability,
_ => unreachable!("DecimalArrayExt requires a decimal dtype"),
}
}
fn validity(&self) -> Validity {
child_to_validity(self.validity_child(), self.nullability())
}
fn values_type(&self) -> DecimalType {
DecimalData::values_type(self)
}
fn precision(&self) -> u8 {
self.decimal_dtype().precision()
}
fn scale(&self) -> i8 {
self.decimal_dtype().scale()
}
fn buffer_handle(&self) -> &BufferHandle {
&self.values
}
fn buffer<T: NativeDecimalType>(&self) -> Buffer<T> {
DecimalData::buffer::<T>(self)
}
}
impl<T: TypedArrayRef<Decimal>> DecimalArrayExt for T {}
impl DecimalData {
fn make_slots(validity: &Validity, len: usize) -> ArraySlots {
smallvec![validity_to_child(validity, len)]
}
pub(super) fn validate_width(
values_type: DecimalType,
decimal_dtype: DecimalDType,
) -> VortexResult<()> {
let canonical = decimal_dtype.canonical_values_type();
vortex_ensure_eq!(
values_type,
canonical,
"{decimal_dtype} requires {canonical} values, got {values_type}",
);
Ok(())
}
pub(crate) fn validate(buffer: &BufferHandle, values_type: DecimalType) -> VortexResult<()> {
let byte_width = values_type.byte_width();
vortex_ensure!(
buffer.len().is_multiple_of(byte_width),
"decimal buffer size {} is not divisible by element width {}",
buffer.len(),
byte_width,
);
match_each_decimal_value_type!(values_type, |D| {
vortex_ensure!(
buffer.is_aligned_to(Alignment::of::<D>()),
"decimal buffer alignment {:?} is invalid for values type {:?}",
buffer.alignment(),
D::DECIMAL_TYPE,
);
Ok::<(), vortex_error::VortexError>(())
})?;
Ok(())
}
pub fn len(&self) -> usize {
self.values.len() / self.values_type().byte_width()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn buffer_handle(&self) -> &BufferHandle {
&self.values
}
pub fn buffer<T: NativeDecimalType>(&self) -> Buffer<T> {
if self.values_type() != T::DECIMAL_TYPE {
vortex_panic!(
"Cannot extract Buffer<{:?}> for DecimalArray with values_type {:?}",
T::DECIMAL_TYPE,
self.values_type(),
);
}
Buffer::<T>::from_byte_buffer(self.values.as_host().clone())
}
pub fn values_type(&self) -> DecimalType {
self.decimal_dtype.canonical_values_type()
}
pub fn decimal_dtype(&self) -> DecimalDType {
self.decimal_dtype
}
pub fn precision(&self) -> u8 {
self.decimal_dtype.precision()
}
pub fn scale(&self) -> i8 {
self.decimal_dtype.scale()
}
}
impl Array<Decimal> {
pub fn into_data_parts(self) -> DecimalDataParts {
let validity = DecimalArrayExt::validity(&self);
let decimal_dtype = DecimalArrayExt::decimal_dtype(&self);
let data = self.into_data();
DecimalDataParts {
decimal_dtype,
values: data.values,
values_type: decimal_dtype.canonical_values_type(),
validity,
}
}
}
impl Array<Decimal> {
pub fn new<T: NativeDecimalType>(
buffer: Buffer<T>,
decimal_dtype: DecimalDType,
validity: Validity,
ctx: &mut ExecutionCtx,
) -> Self {
Self::try_new(buffer, decimal_dtype, validity, ctx)
.vortex_expect("DecimalArray construction failed")
}
pub unsafe fn new_unchecked<T: NativeDecimalType>(
buffer: Buffer<T>,
decimal_dtype: DecimalDType,
validity: Validity,
) -> Self {
let values = BufferHandle::new_host(buffer.into_byte_buffer());
unsafe { Self::new_unchecked_handle(values, T::DECIMAL_TYPE, decimal_dtype, validity) }
}
pub fn try_new<T: NativeDecimalType>(
buffer: Buffer<T>,
decimal_dtype: DecimalDType,
validity: Validity,
ctx: &mut ExecutionCtx,
) -> VortexResult<Self> {
let values = BufferHandle::new_host(buffer.into_byte_buffer());
Self::try_new_handle(values, T::DECIMAL_TYPE, decimal_dtype, validity, ctx)
}
#[expect(
clippy::same_name_method,
reason = "intentionally named from_iter like Iterator::from_iter"
)]
pub fn from_iter<T: NativeDecimalType, I: IntoIterator<Item = T>>(
iter: I,
decimal_dtype: DecimalDType,
) -> Self {
let values_type = decimal_dtype.canonical_values_type();
let values = collect_decimal_values(iter.into_iter(), decimal_dtype);
unsafe {
Self::new_unchecked_handle(values, values_type, decimal_dtype, Validity::NonNullable)
}
}
pub fn from_option_iter<T: NativeDecimalType, I: IntoIterator<Item = Option<T>>>(
iter: I,
decimal_dtype: DecimalDType,
) -> Self {
let iter = iter.into_iter();
let mut validity = BitBufferMut::with_capacity(iter.size_hint().0);
let values_type = decimal_dtype.canonical_values_type();
let values = collect_decimal_values(
iter.map(|value| {
validity.append(value.is_some());
value.unwrap_or_default()
}),
decimal_dtype,
);
let validity = Validity::from(validity.freeze());
unsafe { Self::new_unchecked_handle(values, values_type, decimal_dtype, validity) }
}
pub fn new_handle(
values: BufferHandle,
values_type: DecimalType,
decimal_dtype: DecimalDType,
validity: Validity,
ctx: &mut ExecutionCtx,
) -> Self {
Self::try_new_handle(values, values_type, decimal_dtype, validity, ctx)
.vortex_expect("DecimalArray construction failed")
}
pub fn try_new_handle(
values: BufferHandle,
values_type: DecimalType,
decimal_dtype: DecimalDType,
validity: Validity,
ctx: &mut ExecutionCtx,
) -> VortexResult<Self> {
let array =
Self::try_new_handle_from_trusted_values(values, values_type, decimal_dtype, validity)?;
let validity = array.validity()?;
if array.buffer_handle().is_on_host() && validity.as_array().is_none_or(ArrayRef::is_host) {
let mask = validity.execute_mask(array.len(), ctx)?;
match_each_decimal_value_type!(values_type, |T| {
check_precision(array.buffer::<T>().as_slice(), &mask, decimal_dtype)
})?;
}
Ok(array)
}
pub fn try_new_handle_from_trusted_values(
values: BufferHandle,
values_type: DecimalType,
decimal_dtype: DecimalDType,
validity: Validity,
) -> VortexResult<Self> {
DecimalData::validate_width(values_type, decimal_dtype)?;
let parts = Self::decimal_parts(values, decimal_dtype, validity);
Array::try_from_parts(parts)
}
pub unsafe fn new_unchecked_handle(
values: BufferHandle,
values_type: DecimalType,
decimal_dtype: DecimalDType,
validity: Validity,
) -> Self {
DecimalData::validate_width(values_type, decimal_dtype)
.unwrap_or_else(|error| vortex_panic!(error));
let parts = Self::decimal_parts(values, decimal_dtype, validity);
unsafe { Array::from_parts_unchecked(parts) }
}
pub(super) fn decimal_parts(
values: BufferHandle,
decimal_dtype: DecimalDType,
validity: Validity,
) -> ArrayParts<Decimal> {
let dtype = DType::Decimal(decimal_dtype, validity.nullability());
let len = values.len() / decimal_dtype.canonical_values_type().byte_width();
let slots = DecimalData::make_slots(&validity, len);
let data = DecimalData {
decimal_dtype,
values,
};
ArrayParts::new(Decimal, dtype, len, data, slots)
}
pub fn patch(self, patches: &Patches, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
vortex_ensure!(
self.dtype().eq_ignore_nullability(patches.values().dtype()),
"Decimal patch values have dtype {}, expected {}",
patches.values().dtype(),
self.dtype(),
);
let patch_indices = patches.indices().clone().execute::<PrimitiveArray>(ctx)?;
let patch_values = patches.values().clone().execute::<DecimalArray>(ctx)?;
let decimal_dtype = self.decimal_dtype();
let validity = self.validity()?.patch(
self.len(),
patches.offset(),
&patch_indices.clone().into_array(),
&patch_values.validity()?,
ctx,
)?;
let indices = patch_indices.reinterpret_cast(patch_indices.ptype().to_unsigned());
match_each_unsigned_integer_ptype!(indices.ptype(), |I| {
match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |T| {
self.patch_typed(
indices.as_slice::<I>(),
patches.offset(),
&patch_values.buffer::<T>(),
validity,
)
})
})
}
fn patch_typed<I: IntegerPType, T: NativeDecimalType>(
self,
indices: &[I],
offset: usize,
patch_values: &[T],
validity: Validity,
) -> VortexResult<Self> {
let decimal_dtype = self.decimal_dtype();
let bytes = self.into_data().values.unwrap_host();
let mut values = Buffer::<T>::from_byte_buffer(bytes).into_mut();
for (index, value) in itertools::zip_eq(indices, patch_values) {
values[index.as_() - offset] = *value;
}
Self::try_new_handle_from_trusted_values(
BufferHandle::new_host(values.freeze().into_byte_buffer()),
T::DECIMAL_TYPE,
decimal_dtype,
validity,
)
}
}
fn collect_decimal_values<T: NativeDecimalType>(
iter: impl Iterator<Item = T>,
decimal_dtype: DecimalDType,
) -> BufferHandle {
match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |D| {
let bounds = precision_bounds::<D>(decimal_dtype);
let values = Buffer::<D>::from_iter(
iter.map(|value| cast_value_in_precision(value, decimal_dtype, &bounds)),
);
BufferHandle::new_host(values.into_byte_buffer())
})
}