use std::ops::RangeInclusive;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_ensure;
use crate::ArrayRef;
use crate::ExecutionCtx;
use crate::IntoArray;
use crate::aggregate_fn::NumericalAggregateOpts;
use crate::aggregate_fn::fns::min_max::MinMaxResult;
use crate::aggregate_fn::fns::min_max::min_max;
use crate::arrays::PrimitiveArray;
use crate::arrays::WidenArray;
use crate::arrays::widen::compute::wrap_values;
use crate::builtins::ArrayBuiltins;
use crate::dtype::DType;
use crate::dtype::PType;
use crate::scalar::PValue;
impl WidenArray {
pub fn encode(array: PrimitiveArray, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
let dtype = array.dtype().clone();
wrap_values(narrow_values(array, ctx)?.into_array(), dtype)
}
#[deprecated(
note = "Changes the dtype. Each caller must decide whether it needs a Widen (#10733)"
)]
pub fn encode_values(
array: PrimitiveArray,
ctx: &mut ExecutionCtx,
) -> VortexResult<PrimitiveArray> {
if !array.ptype().is_int() {
return Ok(array);
}
narrow_values(array, ctx)
}
}
fn narrow_values(array: PrimitiveArray, ctx: &mut ExecutionCtx) -> VortexResult<PrimitiveArray> {
let ptype = array.ptype();
vortex_ensure!(ptype.is_int(), "Widen requires integer values, got {ptype}");
if ptype.byte_width() == 1 {
return Ok(array);
}
let bounds = match min_max(array.as_ref(), ctx, NumericalAggregateOpts::default())? {
Some(bounds) => integer_extrema(bounds),
None => 0..=0,
};
let Some(stored_ptype) = smallest_integer_ptype(bounds, ptype.is_signed_int())
.filter(|stored_ptype| stored_ptype.byte_width() < ptype.byte_width())
else {
return Ok(array);
};
let stored_dtype = DType::Primitive(stored_ptype, array.dtype().nullability());
array
.into_array()
.cast(stored_dtype)?
.execute::<PrimitiveArray>(ctx)
}
pub(in crate::arrays::widen) fn integer_extrema(bounds: MinMaxResult) -> RangeInclusive<i128> {
let [min, max] = [bounds.min, bounds.max].map(|bound| {
bound
.as_primitive()
.pvalue()
.and_then(PValue::as_i128)
.vortex_expect("min_max of an integer array returns non-null integer extrema")
});
min..=max
}
pub(in crate::arrays::widen) fn smallest_integer_ptype(
bounds: RangeInclusive<i128>,
signed: bool,
) -> Option<PType> {
let (min, max) = bounds.into_inner();
if signed {
let min_ptype = PType::min_signed_ptype_for_value(i64::try_from(min).ok()?);
let max_ptype = PType::min_signed_ptype_for_value(i64::try_from(max).ok()?);
Some(min_ptype.max_signed_ptype(max_ptype))
} else {
let min_ptype = PType::min_unsigned_ptype_for_value(u64::try_from(min).ok()?);
let max_ptype = PType::min_unsigned_ptype_for_value(u64::try_from(max).ok()?);
Some(min_ptype.max_unsigned_ptype(max_ptype))
}
}