Skip to main content

vortex_array/arrays/widen/compute/
compare.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_buffer::BitBuffer;
5use vortex_error::VortexExpect;
6use vortex_error::VortexResult;
7
8use crate::ArrayRef;
9use crate::ExecutionCtx;
10use crate::IntoArray;
11use crate::array::ArrayView;
12use crate::arrays::BoolArray;
13use crate::arrays::ConstantArray;
14use crate::arrays::Widen;
15use crate::arrays::widen::WidenArraySlotsExt;
16use crate::arrays::widen::compute::constant_fits_values;
17use crate::arrays::widen::compute::constant_in_values_dtype;
18use crate::arrays::widen::compute::ptype_holding_both_values;
19use crate::builtins::ArrayBuiltins;
20use crate::dtype::DType;
21use crate::dtype::DecimalDType;
22use crate::scalar::Scalar;
23use crate::scalar_fn::builtin::compare::CompareKernel;
24use crate::scalar_fn::builtin::operators::CompareOperator;
25
26impl CompareKernel for Widen {
27    fn compare(
28        lhs: ArrayView<'_, Self>,
29        rhs: &ArrayRef,
30        operator: CompareOperator,
31        ctx: &mut ExecutionCtx,
32    ) -> VortexResult<Option<ArrayRef>> {
33        if !lhs.dtype().eq_ignore_nullability(rhs.dtype()) {
34            return Ok(None);
35        }
36
37        if let Some(rhs) = rhs.as_opt::<Widen>() {
38            return compare_narrow_values(lhs, rhs, operator);
39        }
40
41        // `CompareExecuteAdaptor` answers a null constant before it calls this kernel.
42        let Some(constant) = rhs.as_constant() else {
43            return Ok(None);
44        };
45        let values = lhs.values();
46        let Some(fits) = constant_fits_values(constant, values.dtype()) else {
47            return Ok(None);
48        };
49        if !fits {
50            return compare_out_of_range(lhs, constant, operator, ctx).map(Some);
51        }
52
53        let constant = constant_in_values_dtype(constant, values, lhs.len())?;
54
55        values.compare(constant, operator).map(Some)
56    }
57}
58
59/// Compares the values of two `Widen` arrays at the wider of the two value types.
60///
61/// Decimal values with the same scale compare at the larger of the two child precisions, which
62/// holds every value of both children.
63fn compare_narrow_values(
64    lhs: ArrayView<'_, Widen>,
65    rhs: ArrayView<'_, Widen>,
66    operator: CompareOperator,
67) -> VortexResult<Option<ArrayRef>> {
68    let lhs_values = lhs.values();
69    let rhs_values = rhs.values();
70
71    let dtype = match (lhs_values.dtype(), rhs_values.dtype()) {
72        (DType::Primitive(..), DType::Primitive(..)) => {
73            let Some(ptype) = ptype_holding_both_values(lhs, rhs) else {
74                return Ok(None);
75            };
76
77            DType::from(ptype)
78        }
79        (DType::Decimal(lhs_dtype, _), DType::Decimal(rhs_dtype, _))
80            if lhs_dtype.scale() == rhs_dtype.scale() =>
81        {
82            DType::Decimal(
83                DecimalDType::new(
84                    lhs_dtype.precision().max(rhs_dtype.precision()),
85                    lhs_dtype.scale(),
86                ),
87                lhs_values.dtype().nullability(),
88            )
89        }
90        _ => return Ok(None),
91    };
92    let lhs_values = lhs_values.cast(dtype.with_nullability(lhs_values.dtype().nullability()))?;
93    let rhs_values = rhs_values.cast(dtype.with_nullability(rhs_values.dtype().nullability()))?;
94
95    lhs_values.compare(rhs_values, operator).map(Some)
96}
97
98/// Answers a compare of `lhs` with a valid `constant` outside the range of its values.
99///
100/// Every value is on the same side of the constant, so every valid row has the same answer, and the
101/// result takes the validity of the values. Without nulls, the result is a [`ConstantArray`], so
102/// that later steps such as a filter keep their constant fast paths.
103fn compare_out_of_range(
104    lhs: ArrayView<'_, Widen>,
105    constant: &Scalar,
106    operator: CompareOperator,
107    ctx: &mut ExecutionCtx,
108) -> VortexResult<ArrayRef> {
109    // The range of the values holds zero, so the constant is below the range exactly when it is
110    // below zero. An unsigned constant outside the range is always above it.
111    let zero = Scalar::zero_value(constant.dtype());
112    let below = constant
113        .partial_cmp(&zero)
114        .vortex_expect("a scalar compares with the zero of its own dtype")
115        .is_lt();
116    let answer = match operator {
117        CompareOperator::Eq => false,
118        CompareOperator::NotEq => true,
119        CompareOperator::Lt | CompareOperator::Lte => !below,
120        CompareOperator::Gt | CompareOperator::Gte => below,
121    };
122
123    let validity = lhs
124        .values()
125        .validity()?
126        .union_nullability(constant.dtype().nullability());
127    if validity.definitely_no_nulls() {
128        let answer = Scalar::bool(answer, validity.nullability());
129        return Ok(ConstantArray::new(answer, lhs.len()).into_array());
130    }
131
132    let bits = BitBuffer::full_in(answer, lhs.len(), ctx.allocator().clone());
133    Ok(BoolArray::try_new(bits, validity)?.into_array())
134}