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::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,
len: usize,
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,
len,
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) -> VortexResult<ArrayParts<Decimal>> {
let dtype = DType::Decimal(self.decimal_dtype, self.validity.nullability());
let slots = DecimalData::make_slots(&self.validity, self.len);
let data = DecimalData::try_new_handle(self.values, self.values_type, self.decimal_dtype)?;
Ok(ArrayParts::new(Decimal, dtype, self.len, data, slots))
}
}