Skip to main content

vortex_array/aggregate_fn/fns/min_max/
decimal.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use itertools::Itertools;
5use vortex_error::VortexResult;
6use vortex_mask::Mask;
7
8use super::MinMaxPartial;
9use super::MinMaxResult;
10use crate::ExecutionCtx;
11use crate::aggregate_fn::AggregateArgs;
12use crate::aggregate_fn::NumericalAggregateOpts;
13use crate::arrays::DecimalArray;
14use crate::dtype::NativeDecimalType;
15use crate::dtype::Nullability::NonNullable;
16use crate::match_each_decimal_value_type;
17use crate::scalar::DecimalValue;
18use crate::scalar::Scalar;
19
20pub(super) fn accumulate_decimal(
21    args: AggregateArgs<'_, NumericalAggregateOpts>,
22    partial: &mut MinMaxPartial,
23    array: &DecimalArray,
24    ctx: &mut ExecutionCtx,
25) -> VortexResult<()> {
26    match_each_decimal_value_type!(array.values_type(), |T| {
27        let local = compute_min_max_with_validity::<T>(array, ctx)?;
28        partial.merge(args, local)
29    })
30}
31
32fn compute_min_max_with_validity<D>(
33    array: &DecimalArray,
34    ctx: &mut ExecutionCtx,
35) -> VortexResult<Option<MinMaxResult>>
36where
37    D: Into<DecimalValue> + NativeDecimalType,
38{
39    let validity = array
40        .as_ref()
41        .validity()?
42        .execute_mask(array.as_ref().len(), ctx)?;
43    if matches!(&validity, Mask::AllFalse(_)) {
44        return Ok(None);
45    }
46
47    let decimal_dtype = array.decimal_dtype();
48
49    let Some((min, max)) = valid_range(array.buffer::<D>().as_slice(), &validity) else {
50        return Ok(None);
51    };
52
53    let min_scalar = Scalar::try_decimal(min.into(), decimal_dtype, NonNullable)?;
54    let max_scalar = if min == max {
55        min_scalar.clone()
56    } else {
57        Scalar::try_decimal(max.into(), decimal_dtype, NonNullable)?
58    };
59
60    Ok(Some(MinMaxResult {
61        min: min_scalar,
62        max: max_scalar,
63    }))
64}
65
66/// Returns the smallest and the largest valid value, or `None` when no value is valid.
67///
68/// Null slots can hold any value and do not contribute to the range. The scan allocates nothing
69/// and does not check decimal precision.
70///
71/// # Panics
72///
73/// Panics if `validity` and `values` have different lengths.
74pub fn valid_range<T: NativeDecimalType>(values: &[T], validity: &Mask) -> Option<(T, T)> {
75    assert_eq!(
76        validity.len(),
77        values.len(),
78        "valid_range requires one validity bit per value"
79    );
80
81    match validity {
82        Mask::AllTrue(_) => compute_min_max(values.iter()),
83        Mask::AllFalse(_) => None,
84        Mask::Values(validity) => compute_min_max(
85            values
86                .iter()
87                .zip(validity.bit_buffer().iter())
88                .filter_map(|(value, valid)| valid.then_some(value)),
89        ),
90    }
91}
92
93fn compute_min_max<'a, T>(iter: impl Iterator<Item = &'a T>) -> Option<(T, T)>
94where
95    T: NativeDecimalType,
96{
97    match iter.minmax_by(|a, b| a.cmp(b)) {
98        itertools::MinMaxResult::NoElements => None,
99        itertools::MinMaxResult::OneElement(&value) => Some((value, value)),
100        itertools::MinMaxResult::MinMax(&min, &max) => Some((min, max)),
101    }
102}