Skip to main content

vortex_array/arrays/widen/compute/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Operations that run on the values of a [`Widen`] instead of on a widened copy.
5//!
6//! An operation runs on the values only where it gives the canonical result. Decoding a value is a
7//! strictly increasing, one-to-one map that keeps validity, so comparisons, sortedness, constancy
8//! and extrema carry over from the values, and every value in a result widens exactly to the
9//! logical dtype.
10//!
11//! Most of these operations decide from dtypes and constants alone. The arithmetic kernel also
12//! needs the min and max of each operand, which come from cached statistics or from one scan of the
13//! operand. That scan is the one hidden cost in this module.
14//!
15//! [`AggregateFnSession::default`] registers the aggregate kernel, not the `Widen` encoding's
16//! `initialize`, because the kernel session runs `initialize` on a temporary session and drops its
17//! aggregate registry.
18//!
19//! [`AggregateFnSession::default`]: crate::aggregate_fn::session::AggregateFnSession::default
20
21pub(crate) mod aggregate;
22mod cast;
23mod compare;
24mod fill_null;
25mod filter;
26mod mask;
27pub(crate) mod numeric;
28pub(crate) mod rules;
29mod slice;
30mod take;
31
32use vortex_error::VortexExpect;
33use vortex_error::VortexResult;
34
35use crate::ArrayRef;
36use crate::IntoArray;
37use crate::array::ArrayView;
38use crate::arrays::ConstantArray;
39use crate::arrays::Widen;
40use crate::arrays::WidenArray;
41use crate::arrays::widen::WidenArraySlotsExt;
42use crate::arrays::widen::encode::smallest_integer_ptype;
43use crate::builtins::ArrayBuiltins;
44use crate::dtype::DType;
45use crate::dtype::PType;
46use crate::scalar::PValue;
47use crate::scalar::Scalar;
48
49/// Returns `values` when it has `dtype`, and a `Widen` of `dtype` over `values` otherwise.
50///
51/// `dtype` **must** have the nullability of `values`, because the values hold the validity of the
52/// `Widen`. A mask, a fill null or a take with nullable indices can change the nullability of the
53/// values, so those callers take the nullability of the result.
54pub fn wrap_values(values: ArrayRef, dtype: DType) -> VortexResult<ArrayRef> {
55    if values.dtype() == &dtype {
56        return Ok(values);
57    }
58
59    Ok(WidenArray::try_new(values, dtype)?.into_array())
60}
61
62/// Returns the type that the values of `array` widen to so that they also hold `scalar`: the type
63/// of the values, or the smallest wider type of the logical signedness that holds `scalar`.
64///
65/// A null `scalar` keeps the type of the values. Returns `None` when `scalar` does not have the
66/// logical dtype, or when the values or the logical dtype is not an integer (a decimal `Widen`).
67pub fn ptype_holding_values_and_scalar(
68    array: ArrayView<'_, Widen>,
69    scalar: &Scalar,
70) -> Option<PType> {
71    let (DType::Primitive(values_ptype, _), DType::Primitive(logical_ptype, _)) =
72        (array.values().dtype(), array.dtype())
73    else {
74        return None;
75    };
76    if !scalar.dtype().eq_ignore_nullability(array.dtype()) {
77        return None;
78    }
79    if scalar.is_null() {
80        return Some(*values_ptype);
81    }
82
83    let value = scalar
84        .as_primitive()
85        .pvalue()
86        .and_then(PValue::as_i128)
87        .vortex_expect("the non-null scalar has the Widen's integer dtype");
88    let scalar_ptype = smallest_integer_ptype(value..=value, logical_ptype.is_signed_int())?;
89
90    if scalar_ptype.byte_width() > values_ptype.byte_width() {
91        Some(scalar_ptype)
92    } else {
93        Some(*values_ptype)
94    }
95}
96
97/// Casts the integer array `array` to `ptype`, keeping its nullability.
98pub fn cast_keeping_nullability(array: &ArrayRef, ptype: PType) -> VortexResult<ArrayRef> {
99    array.cast(DType::Primitive(ptype, array.dtype().nullability()))
100}
101
102/// Returns whether the dtype range of `values` holds `constant`.
103///
104/// Integers must have the same signedness, and decimals must have the same scale. Returns `None`
105/// for null constants, unsupported dtypes, or incompatible constants.
106pub fn constant_fits_values(constant: &Scalar, values: &DType) -> Option<bool> {
107    match (values, constant.dtype()) {
108        (DType::Decimal(values_dtype, _), DType::Decimal(constant_dtype, _))
109            if values_dtype.scale() == constant_dtype.scale() =>
110        {
111            let value = constant.as_decimal().decimal_value()?;
112
113            Some(value.fits_in_precision(*values_dtype))
114        }
115        (DType::Primitive(values_ptype, _), DType::Primitive(constant_ptype, _))
116            if values_ptype.is_int()
117                && constant_ptype.is_int()
118                && values_ptype.is_signed_int() == constant_ptype.is_signed_int() =>
119        {
120            // `PValue` compares through `i64` or `u64`, so the signedness must match.
121            let value = constant.as_primitive().pvalue()?;
122
123            Some(
124                PValue::min_value(*values_ptype) <= value
125                    && value <= PValue::max_value(*values_ptype),
126            )
127        }
128        _ => None,
129    }
130}
131
132/// Returns the wider of the value types of two [`Widen`] arrays, or `None` when a value type is
133/// not primitive.
134///
135/// The logical dtypes **must** have the same signedness. The value types then have that signedness
136/// too, so the wider one holds every value of the narrower one.
137pub fn ptype_holding_both_values(
138    lhs: ArrayView<'_, Widen>,
139    rhs: ArrayView<'_, Widen>,
140) -> Option<PType> {
141    let (DType::Primitive(lhs_ptype, _), DType::Primitive(rhs_ptype, _)) =
142        (lhs.values().dtype(), rhs.values().dtype())
143    else {
144        return None;
145    };
146
147    if lhs_ptype.is_signed_int() {
148        Some(lhs_ptype.max_signed_ptype(*rhs_ptype))
149    } else {
150        Some(lhs_ptype.max_unsigned_ptype(*rhs_ptype))
151    }
152}
153
154/// Returns `constant`, which **must** fit the type of `values`, as a constant array of that type
155/// with the nullability of `constant`.
156pub fn constant_in_values_dtype(
157    constant: &Scalar,
158    values: &ArrayRef,
159    len: usize,
160) -> VortexResult<ArrayRef> {
161    let dtype = values
162        .dtype()
163        .with_nullability(constant.dtype().nullability());
164
165    Ok(ConstantArray::new(constant.cast(&dtype)?, len).into_array())
166}