Skip to main content

vortex_array/arrays/widen/compute/
cast.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Cast reductions for decimal and primitive [`Widen`] arrays.
5//!
6//! Same-scale decimal casts retarget the `Widen` when the child already fits the target. Primitive
7//! casts can retain a `Widen` for wider integer targets, after matching the child's signedness to the
8//! target. Both paths leave required conversions and nullability checks to the child's cast.
9
10use vortex_error::VortexResult;
11
12use crate::ArrayRef;
13use crate::array::ArrayView;
14use crate::arrays::Widen;
15use crate::arrays::widen::WidenArraySlotsExt;
16use crate::arrays::widen::compute::wrap_values;
17use crate::builtins::ArrayBuiltins;
18use crate::dtype::DType;
19use crate::dtype::DecimalDType;
20use crate::dtype::PType;
21use crate::scalar_fn::fns::cast::CastReduce;
22
23impl CastReduce for Widen {
24    fn cast(array: ArrayView<'_, Self>, dtype: &DType) -> VortexResult<Option<ArrayRef>> {
25        let values = array.values();
26
27        match values.dtype() {
28            DType::Decimal(values_dtype, _) => cast_decimal(values, *values_dtype, dtype),
29            DType::Primitive(values_ptype, _) => cast_primitive(values, *values_ptype, dtype),
30            _ => Ok(None),
31        }
32    }
33}
34
35fn cast_decimal(
36    values: &ArrayRef,
37    values_dtype: DecimalDType,
38    dtype: &DType,
39) -> VortexResult<Option<ArrayRef>> {
40    if let DType::Decimal(target_dtype, _) = dtype
41        && values_dtype.scale() == target_dtype.scale()
42        && values_dtype.canonical_values_type() < target_dtype.canonical_values_type()
43    {
44        // The child's declared precision proves that every value fits the target. Only nullability
45        // may still need a check, so leave the width conversion to Widen execution.
46        let values = values.cast(values.dtype().with_nullability(dtype.nullability()))?;
47
48        return wrap_values(values, dtype.clone()).map(Some);
49    }
50
51    // Rescaling, narrower targets, and primitive conversions still need the child's cast. The child
52    // has the parent's values, scale, and nulls, so these conversions preserve the logical result.
53    match dtype {
54        DType::Decimal(..) | DType::Primitive(..) => values.cast(dtype.clone()).map(Some),
55        _ => Ok(None),
56    }
57}
58
59fn cast_primitive(
60    values: &ArrayRef,
61    values_ptype: PType,
62    dtype: &DType,
63) -> VortexResult<Option<ArrayRef>> {
64    let DType::Primitive(target_ptype, nullability) = dtype else {
65        return Ok(None);
66    };
67
68    let cast_ptype = match values_ptype_for_cast(values_ptype, *target_ptype) {
69        Some(cast_ptype) if target_ptype.byte_width() > cast_ptype.byte_width() => cast_ptype,
70        // A float needs value conversion, and an integer target no wider than the converted child
71        // cannot retain a Widen. Casting directly also checks overflow and nullability.
72        _ => return values.cast(dtype.clone()).map(Some),
73    };
74
75    // Match the child's signedness and nullability to the target. If both already match, the cast
76    // returns the original child. Otherwise, it converts the child and checks negative values and
77    // nulls as needed. Widen handles the remaining width increase because every child value fits.
78    let values = values.cast(DType::Primitive(cast_ptype, *nullability))?;
79
80    wrap_values(values, dtype.clone()).map(Some)
81}
82
83/// Returns the type that the values take when the `Widen` is cast to the integer type `target`, or
84/// `None` for a float target.
85///
86/// The result has the signedness of `target`. An unsigned type fits a signed type only one width
87/// up, so unsigned values with a signed target widen one step. Signed values with an unsigned
88/// target keep their width, and the cast of the values rejects a negative value.
89fn values_ptype_for_cast(values: PType, target: PType) -> Option<PType> {
90    if target.is_float() {
91        return None;
92    }
93
94    let cast_ptype = match (values.is_signed_int(), target.is_signed_int()) {
95        // `validate_dtypes` keeps the values narrower than 64 bits.
96        (false, true) => match values {
97            PType::U8 => PType::I16,
98            PType::U16 => PType::I32,
99            _ => PType::I64,
100        },
101        (true, false) => values.to_unsigned(),
102        _ => values,
103    };
104
105    Some(cast_ptype)
106}