use prost::Message;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure_eq;
use vortex_error::vortex_err;
use super::DecimalMetadata;
use crate::ArrayParts;
use crate::array::Array;
use crate::arrays::Decimal;
use crate::arrays::decimal::DecimalData;
use crate::arrays::fixed_width::vtable as fixed_width;
use crate::buffer::BufferHandle;
use crate::dtype::DType;
use crate::dtype::DecimalDType;
use crate::dtype::DecimalType;
use crate::serde::ArrayChildren;
use crate::validity::Validity;
pub(super) struct StoredDecimal {
pub(super) decimal_dtype: DecimalDType,
pub(super) values_type: DecimalType,
pub(super) values: BufferHandle,
pub(super) validity: Validity,
}
impl StoredDecimal {
pub(super) fn deserialize(
dtype: &DType,
len: usize,
metadata: &[u8],
buffers: &[BufferHandle],
children: &dyn ArrayChildren,
) -> VortexResult<Self> {
let Some(&decimal_dtype) = dtype.as_decimal_opt() else {
vortex_bail!("Decimal node requires a decimal dtype, got {dtype}");
};
let values_type = DecimalMetadata::decode(metadata)?.get_values_type()?;
let values = fixed_width::single_buffer(buffers)?;
let byte_len = len.checked_mul(values_type.byte_width()).ok_or_else(|| {
vortex_err!(
"Decimal node of {values_type} values must have a byte length that fits in usize, \
got length {len}"
)
})?;
vortex_ensure_eq!(
values.len(),
byte_len,
"Decimal buffer must have the byte length of {len} {values_type} values",
);
DecimalData::validate(&values, values_type)?;
let validity = fixed_width::deserialize_validity(dtype.nullability(), len, children)?;
Ok(Self {
decimal_dtype,
values_type,
values,
validity,
})
}
pub(super) fn is_legacy(&self) -> bool {
self.values_type != self.decimal_dtype.canonical_values_type()
}
pub(super) fn into_array_parts(self) -> ArrayParts<Decimal> {
debug_assert!(
!self.is_legacy(),
"Decimal array parts require the canonical width, got a legacy node"
);
Array::<Decimal>::decimal_parts(self.values, self.decimal_dtype, self.validity)
}
}