Skip to main content

arrow_arith/
aggregate.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Defines aggregations over Arrow arrays.
6
7use arrow_array::cast::*;
8use arrow_array::iterator::ArrayIter;
9use arrow_array::*;
10use arrow_buffer::NullBuffer;
11use arrow_data::bit_iterator::try_for_each_valid_idx;
12use arrow_schema::*;
13use std::cmp::{self, Ordering};
14use std::ops::{BitAnd, BitOr, BitXor};
15use types::ByteViewType;
16
17/// An accumulator for primitive numeric values.
18trait NumericAccumulator<T: ArrowNativeTypeOp>: Copy + Default {
19    /// Accumulate a non-null value.
20    fn accumulate(&mut self, value: T);
21    /// Accumulate a nullable values.
22    /// If `valid` is false the `value` should not affect the accumulator state.
23    fn accumulate_nullable(&mut self, value: T, valid: bool);
24    /// Merge another accumulator into this accumulator
25    fn merge(&mut self, other: Self);
26    /// Return the aggregated value.
27    fn finish(&mut self) -> T;
28}
29
30/// Helper for branchlessly selecting either `a` or `b` based on the boolean `m`.
31/// After verifying the generated assembly this can be a simple `if`.
32#[inline(always)]
33fn select<T: Copy>(m: bool, a: T, b: T) -> T {
34    if m { a } else { b }
35}
36
37#[derive(Clone, Copy)]
38struct SumAccumulator<T: ArrowNativeTypeOp> {
39    sum: T,
40}
41
42impl<T: ArrowNativeTypeOp> Default for SumAccumulator<T> {
43    fn default() -> Self {
44        Self { sum: T::ZERO }
45    }
46}
47
48impl<T: ArrowNativeTypeOp> NumericAccumulator<T> for SumAccumulator<T> {
49    fn accumulate(&mut self, value: T) {
50        self.sum = self.sum.add_wrapping(value);
51    }
52
53    fn accumulate_nullable(&mut self, value: T, valid: bool) {
54        let sum = self.sum;
55        self.sum = select(valid, sum.add_wrapping(value), sum)
56    }
57
58    fn merge(&mut self, other: Self) {
59        self.sum = self.sum.add_wrapping(other.sum);
60    }
61
62    fn finish(&mut self) -> T {
63        self.sum
64    }
65}
66
67#[derive(Clone, Copy)]
68struct ProductAccumulator<T: ArrowNativeTypeOp> {
69    product: T,
70}
71
72impl<T: ArrowNativeTypeOp> Default for ProductAccumulator<T> {
73    fn default() -> Self {
74        Self { product: T::ONE }
75    }
76}
77
78impl<T: ArrowNativeTypeOp> NumericAccumulator<T> for ProductAccumulator<T> {
79    fn accumulate(&mut self, value: T) {
80        self.product = self.product.mul_wrapping(value);
81    }
82
83    fn accumulate_nullable(&mut self, value: T, valid: bool) {
84        let product = self.product;
85        self.product = select(valid, product.mul_wrapping(value), product)
86    }
87
88    fn merge(&mut self, other: Self) {
89        self.product = self.product.mul_wrapping(other.product);
90    }
91
92    fn finish(&mut self) -> T {
93        self.product
94    }
95}
96
97#[derive(Clone, Copy)]
98struct MinAccumulator<T: ArrowNativeTypeOp> {
99    min: T,
100}
101
102impl<T: ArrowNativeTypeOp> Default for MinAccumulator<T> {
103    fn default() -> Self {
104        Self {
105            min: T::MAX_TOTAL_ORDER,
106        }
107    }
108}
109
110impl<T: ArrowNativeTypeOp> NumericAccumulator<T> for MinAccumulator<T> {
111    fn accumulate(&mut self, value: T) {
112        let min = self.min;
113        self.min = select(value.is_lt(min), value, min);
114    }
115
116    fn accumulate_nullable(&mut self, value: T, valid: bool) {
117        let min = self.min;
118        let is_lt = valid & value.is_lt(min);
119        self.min = select(is_lt, value, min);
120    }
121
122    fn merge(&mut self, other: Self) {
123        self.accumulate(other.min)
124    }
125
126    fn finish(&mut self) -> T {
127        self.min
128    }
129}
130
131#[derive(Clone, Copy)]
132struct MaxAccumulator<T: ArrowNativeTypeOp> {
133    max: T,
134}
135
136impl<T: ArrowNativeTypeOp> Default for MaxAccumulator<T> {
137    fn default() -> Self {
138        Self {
139            max: T::MIN_TOTAL_ORDER,
140        }
141    }
142}
143
144impl<T: ArrowNativeTypeOp> NumericAccumulator<T> for MaxAccumulator<T> {
145    fn accumulate(&mut self, value: T) {
146        let max = self.max;
147        self.max = select(value.is_gt(max), value, max);
148    }
149
150    fn accumulate_nullable(&mut self, value: T, valid: bool) {
151        let max = self.max;
152        let is_gt = value.is_gt(max) & valid;
153        self.max = select(is_gt, value, max);
154    }
155
156    fn merge(&mut self, other: Self) {
157        self.accumulate(other.max)
158    }
159
160    fn finish(&mut self) -> T {
161        self.max
162    }
163}
164
165fn reduce_accumulators<T: ArrowNativeTypeOp, A: NumericAccumulator<T>, const LANES: usize>(
166    mut acc: [A; LANES],
167) -> A {
168    assert!(LANES > 0 && LANES.is_power_of_two());
169    let mut len = LANES;
170
171    // attempt at tree reduction, unfortunately llvm does not fully recognize this pattern,
172    // but the generated code is still a little faster than purely sequential reduction for floats.
173    while len >= 2 {
174        let mid = len / 2;
175        let (h, t) = acc[..len].split_at_mut(mid);
176
177        for i in 0..mid {
178            h[i].merge(t[i]);
179        }
180        len /= 2;
181    }
182    acc[0]
183}
184
185#[inline(always)]
186fn aggregate_nonnull_chunk<T: ArrowNativeTypeOp, A: NumericAccumulator<T>, const LANES: usize>(
187    acc: &mut [A; LANES],
188    values: &[T; LANES],
189) {
190    for i in 0..LANES {
191        acc[i].accumulate(values[i]);
192    }
193}
194
195#[inline(always)]
196fn aggregate_nullable_chunk<T: ArrowNativeTypeOp, A: NumericAccumulator<T>, const LANES: usize>(
197    acc: &mut [A; LANES],
198    values: &[T; LANES],
199    validity: u64,
200) {
201    let mut bit = 1;
202    for i in 0..LANES {
203        acc[i].accumulate_nullable(values[i], (validity & bit) != 0);
204        bit <<= 1;
205    }
206}
207
208fn aggregate_nonnull_simple<T: ArrowNativeTypeOp, A: NumericAccumulator<T>>(values: &[T]) -> T {
209    values
210        .iter()
211        .copied()
212        .fold(A::default(), |mut a, b| {
213            a.accumulate(b);
214            a
215        })
216        .finish()
217}
218
219#[inline(never)]
220fn aggregate_nonnull_lanes<T: ArrowNativeTypeOp, A: NumericAccumulator<T>, const LANES: usize>(
221    values: &[T],
222) -> T {
223    // aggregating into multiple independent accumulators allows the compiler to use vector registers
224    // with a single accumulator the compiler would not be allowed to reorder floating point addition
225    let mut acc = [A::default(); LANES];
226    let (chunks, remainder) = values.as_chunks::<LANES>();
227    chunks.iter().for_each(|chunk| {
228        aggregate_nonnull_chunk(&mut acc, chunk);
229    });
230
231    for i in 0..remainder.len() {
232        acc[i].accumulate(remainder[i]);
233    }
234
235    reduce_accumulators(acc).finish()
236}
237
238#[inline(never)]
239fn aggregate_nullable_lanes<T: ArrowNativeTypeOp, A: NumericAccumulator<T>, const LANES: usize>(
240    values: &[T],
241    validity: &NullBuffer,
242) -> T {
243    assert!(LANES > 0 && 64 % LANES == 0);
244    assert_eq!(values.len(), validity.len());
245
246    // aggregating into multiple independent accumulators allows the compiler to use vector registers
247    let mut acc = [A::default(); LANES];
248    // we process 64 bits of validity at a time
249    let (values_chunks, remainder) = values.as_chunks::<64>();
250    let validity_chunks = validity.inner().bit_chunks();
251    let mut validity_chunks_iter = validity_chunks.iter();
252
253    values_chunks.iter().for_each(|chunk| {
254        // Safety: we asserted that values and validity have the same length and trust the iterator impl
255        let mut validity = unsafe { validity_chunks_iter.next().unwrap_unchecked() };
256        // chunk further based on the number of vector lanes
257        chunk.as_chunks::<LANES>().0.iter().for_each(|chunk| {
258            aggregate_nullable_chunk(&mut acc, chunk, validity);
259            validity >>= LANES;
260        });
261    });
262
263    if !remainder.is_empty() {
264        let mut validity = validity_chunks.remainder_bits();
265
266        let (remainder_chunks, remainder) = remainder.as_chunks::<LANES>();
267        remainder_chunks.iter().for_each(|chunk| {
268            aggregate_nullable_chunk(&mut acc, chunk, validity);
269            validity >>= LANES;
270        });
271
272        if !remainder.is_empty() {
273            let mut bit = 1;
274            for i in 0..remainder.len() {
275                acc[i].accumulate_nullable(remainder[i], (validity & bit) != 0);
276                bit <<= 1;
277            }
278        }
279    }
280
281    reduce_accumulators(acc).finish()
282}
283
284/// The preferred vector size in bytes for the target platform.
285/// Note that the avx512 target feature is still unstable and this also means it is not detected on stable rust.
286const PREFERRED_VECTOR_SIZE: usize =
287    if cfg!(all(target_arch = "x86_64", target_feature = "avx512f")) {
288        64
289    } else if cfg!(all(target_arch = "x86_64", target_feature = "avx")) {
290        32
291    } else {
292        16
293    };
294
295/// non-nullable aggregation requires fewer temporary registers so we can use more of them for accumulators
296const PREFERRED_VECTOR_SIZE_NON_NULL: usize = PREFERRED_VECTOR_SIZE * 2;
297
298/// Generic aggregation for any primitive type.
299/// Returns None if there are no non-null values in `array`.
300fn aggregate<T: ArrowNativeTypeOp, P: ArrowPrimitiveType<Native = T>, A: NumericAccumulator<T>>(
301    array: &PrimitiveArray<P>,
302) -> Option<T> {
303    let null_count = array.null_count();
304    if null_count == array.len() {
305        return None;
306    }
307    let values = array.values().as_ref();
308    match array.nulls() {
309        Some(nulls) if null_count > 0 => {
310            // const generics depending on a generic type parameter are not supported
311            // so we have to match and call aggregate with the corresponding constant
312            match PREFERRED_VECTOR_SIZE / std::mem::size_of::<T>() {
313                64 => Some(aggregate_nullable_lanes::<T, A, 64>(values, nulls)),
314                32 => Some(aggregate_nullable_lanes::<T, A, 32>(values, nulls)),
315                16 => Some(aggregate_nullable_lanes::<T, A, 16>(values, nulls)),
316                8 => Some(aggregate_nullable_lanes::<T, A, 8>(values, nulls)),
317                4 => Some(aggregate_nullable_lanes::<T, A, 4>(values, nulls)),
318                2 => Some(aggregate_nullable_lanes::<T, A, 2>(values, nulls)),
319                _ => Some(aggregate_nullable_lanes::<T, A, 1>(values, nulls)),
320            }
321        }
322        _ => {
323            let is_float = matches!(
324                array.data_type(),
325                DataType::Float16 | DataType::Float32 | DataType::Float64
326            );
327            if is_float {
328                match PREFERRED_VECTOR_SIZE_NON_NULL / std::mem::size_of::<T>() {
329                    64 => Some(aggregate_nonnull_lanes::<T, A, 64>(values)),
330                    32 => Some(aggregate_nonnull_lanes::<T, A, 32>(values)),
331                    16 => Some(aggregate_nonnull_lanes::<T, A, 16>(values)),
332                    8 => Some(aggregate_nonnull_lanes::<T, A, 8>(values)),
333                    4 => Some(aggregate_nonnull_lanes::<T, A, 4>(values)),
334                    2 => Some(aggregate_nonnull_lanes::<T, A, 2>(values)),
335                    _ => Some(aggregate_nonnull_simple::<T, A>(values)),
336                }
337            } else {
338                // for non-null integers its better to not chunk ourselves and instead
339                // let llvm fully handle loop unrolling and vectorization
340                Some(aggregate_nonnull_simple::<T, A>(values))
341            }
342        }
343    }
344}
345
346/// Returns the minimum value in the boolean array.
347///
348/// # Example
349/// ```
350/// # use arrow_array::BooleanArray;
351/// # use arrow_arith::aggregate::min_boolean;
352/// let a = BooleanArray::from(vec![Some(true), None, Some(false)]);
353/// assert_eq!(min_boolean(&a), Some(false))
354/// ```
355pub fn min_boolean(array: &BooleanArray) -> Option<bool> {
356    // short circuit if all nulls / zero length array
357    if array.null_count() == array.len() {
358        return None;
359    }
360
361    // Note the min bool is false (0), so short circuit as soon as we see it
362    match array.nulls() {
363        None => {
364            let bit_chunks = array.values().bit_chunks();
365            if bit_chunks.iter().any(|x| {
366                // u64::MAX has all bits set, so if the value is not that, then there is a false
367                x != u64::MAX
368            }) {
369                return Some(false);
370            }
371            // If the remainder bits are not all set, then there is a false
372            if bit_chunks.remainder_bits().count_ones() as usize != bit_chunks.remainder_len() {
373                Some(false)
374            } else {
375                Some(true)
376            }
377        }
378        Some(nulls) => {
379            let validity_chunks = nulls.inner().bit_chunks();
380            let value_chunks = array.values().bit_chunks();
381
382            if value_chunks
383                .iter()
384                .zip(validity_chunks.iter())
385                .any(|(value, validity)| {
386                    // We are looking for a false value, but because applying the validity mask
387                    // can create a false for a true value (e.g. value: true, validity: false), we instead invert the value, so that we have to look for a true.
388                    (!value & validity) != 0
389                })
390            {
391                return Some(false);
392            }
393
394            // Same trick as above: Instead of looking for a false, we invert the value bits and look for a true
395            if (!value_chunks.remainder_bits() & validity_chunks.remainder_bits()) != 0 {
396                Some(false)
397            } else {
398                Some(true)
399            }
400        }
401    }
402}
403
404/// Returns the maximum value in the boolean array
405///
406/// # Example
407/// ```
408/// # use arrow_array::BooleanArray;
409/// # use arrow_arith::aggregate::max_boolean;
410/// let a = BooleanArray::from(vec![Some(true), None, Some(false)]);
411/// assert_eq!(max_boolean(&a), Some(true))
412/// ```
413pub fn max_boolean(array: &BooleanArray) -> Option<bool> {
414    // short circuit if all nulls / zero length array
415    if array.null_count() == array.len() {
416        return None;
417    }
418
419    // Note the max bool is true (1), so short circuit as soon as we see it
420    match array.nulls() {
421        None => array
422            .values()
423            .bit_chunks()
424            .iter_padded()
425            // We found a true if any bit is set
426            .map(|x| x != 0)
427            .find(|b| *b)
428            .or(Some(false)),
429        Some(nulls) => {
430            let validity_chunks = nulls.inner().bit_chunks().iter_padded();
431            let value_chunks = array.values().bit_chunks().iter_padded();
432            value_chunks
433                .zip(validity_chunks)
434                // We found a true if the value bit is 1, AND the validity bit is 1 for any bits in the chunk
435                .map(|(value_bits, validity_bits)| (value_bits & validity_bits) != 0)
436                .find(|b| *b)
437                .or(Some(false))
438        }
439    }
440}
441
442/// Helper to compute min/max of [`ArrayAccessor`].
443fn min_max_helper<T, A: ArrayAccessor<Item = T>, F>(array: A, cmp: F) -> Option<T>
444where
445    F: Fn(&T, &T) -> bool,
446{
447    let nulls = array.logical_nulls();
448    let null_count = nulls.as_ref().map_or(0, NullBuffer::null_count);
449    if null_count == array.len() {
450        None
451    } else if null_count == 0 {
452        // JUSTIFICATION
453        //  Benefit:  ~8% speedup
454        //  Soundness: `i` is always within the array bounds
455        (0..array.len())
456            .map(|i| unsafe { array.value_unchecked(i) })
457            .reduce(|acc, item| if cmp(&acc, &item) { item } else { acc })
458    } else {
459        let nulls = nulls.unwrap();
460        unsafe {
461            let idx = nulls.valid_indices().reduce(|acc_idx, idx| {
462                let acc = array.value_unchecked(acc_idx);
463                let item = array.value_unchecked(idx);
464                if cmp(&acc, &item) { idx } else { acc_idx }
465            });
466            idx.map(|idx| array.value_unchecked(idx))
467        }
468    }
469}
470
471/// Helper to compute min/max of [`GenericByteViewArray<T>`].
472/// The specialized min/max leverages the inlined values to compare the byte views.
473/// `swap_cond` is the condition to swap current min/max with the new value.
474/// For example, `Ordering::Greater` for max and `Ordering::Less` for min.
475fn min_max_view_helper<T: ByteViewType>(
476    array: &GenericByteViewArray<T>,
477    swap_cond: cmp::Ordering,
478) -> Option<&T::Native> {
479    let null_count = array.null_count();
480    if null_count == array.len() {
481        None
482    } else if null_count == 0 {
483        let target_idx = (0..array.len()).reduce(|acc, item| {
484            // SAFETY:  array's length is correct so item is within bounds
485            let cmp = unsafe { GenericByteViewArray::compare_unchecked(array, item, array, acc) };
486            if cmp == swap_cond { item } else { acc }
487        });
488        // SAFETY: idx came from valid range `0..array.len()`
489        unsafe { target_idx.map(|idx| array.value_unchecked(idx)) }
490    } else {
491        let nulls = array.nulls().unwrap();
492
493        let target_idx = nulls.valid_indices().reduce(|acc_idx, idx| {
494            let cmp =
495                unsafe { GenericByteViewArray::compare_unchecked(array, idx, array, acc_idx) };
496            if cmp == swap_cond { idx } else { acc_idx }
497        });
498
499        // SAFETY: idx came from valid range `0..array.len()`
500        unsafe { target_idx.map(|idx| array.value_unchecked(idx)) }
501    }
502}
503
504/// Returns the maximum value in the binary array, according to the natural order.
505pub fn max_binary<T: OffsetSizeTrait>(array: &GenericBinaryArray<T>) -> Option<&[u8]> {
506    min_max_helper::<&[u8], _, _>(array, |a, b| *a < *b)
507}
508
509/// Returns the maximum value in the binary view array, according to the natural order.
510pub fn max_binary_view(array: &BinaryViewArray) -> Option<&[u8]> {
511    min_max_view_helper(array, Ordering::Greater)
512}
513
514/// Returns the maximum value in the fixed size binary array, according to the natural order.
515pub fn max_fixed_size_binary(array: &FixedSizeBinaryArray) -> Option<&[u8]> {
516    min_max_helper::<&[u8], _, _>(array, |a, b| *a < *b)
517}
518
519/// Returns the minimum value in the binary array, according to the natural order.
520pub fn min_binary<T: OffsetSizeTrait>(array: &GenericBinaryArray<T>) -> Option<&[u8]> {
521    min_max_helper::<&[u8], _, _>(array, |a, b| *a > *b)
522}
523
524/// Returns the minimum value in the binary view array, according to the natural order.
525pub fn min_binary_view(array: &BinaryViewArray) -> Option<&[u8]> {
526    min_max_view_helper(array, Ordering::Less)
527}
528
529/// Returns the minimum value in the fixed size binary array, according to the natural order.
530pub fn min_fixed_size_binary(array: &FixedSizeBinaryArray) -> Option<&[u8]> {
531    min_max_helper::<&[u8], _, _>(array, |a, b| *a > *b)
532}
533
534/// Returns the maximum value in the string array, according to the natural order.
535pub fn max_string<T: OffsetSizeTrait>(array: &GenericStringArray<T>) -> Option<&str> {
536    min_max_helper::<&str, _, _>(array, |a, b| *a < *b)
537}
538
539/// Returns the maximum value in the string view array, according to the natural order.
540pub fn max_string_view(array: &StringViewArray) -> Option<&str> {
541    min_max_view_helper(array, Ordering::Greater)
542}
543
544/// Returns the minimum value in the string array, according to the natural order.
545pub fn min_string<T: OffsetSizeTrait>(array: &GenericStringArray<T>) -> Option<&str> {
546    min_max_helper::<&str, _, _>(array, |a, b| *a > *b)
547}
548
549/// Returns the minimum value in the string view array, according to the natural order.
550pub fn min_string_view(array: &StringViewArray) -> Option<&str> {
551    min_max_view_helper(array, Ordering::Less)
552}
553
554/// Returns the sum of values in the array.
555///
556/// This doesn't detect overflow. Once overflowing, the result will wrap around.
557/// For an overflow-checking variant, use [`sum_array_checked`] instead.
558pub fn sum_array<T: ArrowNumericType, A: ArrayAccessor<Item = T::Native>>(
559    array: A,
560) -> Option<T::Native> {
561    match array.data_type() {
562        DataType::Dictionary(_, _) => {
563            let logical_null_count = array.logical_null_count();
564
565            if logical_null_count == array.len() {
566                return None;
567            }
568
569            let iter = ArrayIter::new(array);
570            let sum = iter
571                .into_iter()
572                .fold(T::default_value(), |accumulator, value| {
573                    if let Some(value) = value {
574                        accumulator.add_wrapping(value)
575                    } else {
576                        accumulator
577                    }
578                });
579
580            Some(sum)
581        }
582        DataType::RunEndEncoded(run_ends, _) => match run_ends.data_type() {
583            DataType::Int16 => ree::sum_wrapping::<types::Int16Type, T>(&array),
584            DataType::Int32 => ree::sum_wrapping::<types::Int32Type, T>(&array),
585            DataType::Int64 => ree::sum_wrapping::<types::Int64Type, T>(&array),
586            _ => unreachable!(),
587        },
588        _ => sum::<T>(as_primitive_array(&array)),
589    }
590}
591
592/// Returns the sum of values in the array.
593///
594/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
595/// use [`sum_array`] instead.
596/// Additionally returns an `Err` on run-end-encoded arrays with a provided
597/// values type parameter that is incorrect.
598pub fn sum_array_checked<T: ArrowNumericType, A: ArrayAccessor<Item = T::Native>>(
599    array: A,
600) -> Result<Option<T::Native>, ArrowError> {
601    match array.data_type() {
602        DataType::Dictionary(_, _) => {
603            let logical_null_count = array.logical_null_count();
604
605            if logical_null_count == array.len() {
606                return Ok(None);
607            }
608
609            let iter = ArrayIter::new(array);
610            let sum = iter
611                .into_iter()
612                .try_fold(T::default_value(), |accumulator, value| {
613                    if let Some(value) = value {
614                        accumulator.add_checked(value)
615                    } else {
616                        Ok(accumulator)
617                    }
618                })?;
619
620            Ok(Some(sum))
621        }
622        DataType::RunEndEncoded(run_ends, _) => match run_ends.data_type() {
623            DataType::Int16 => ree::sum_checked::<types::Int16Type, T>(&array),
624            DataType::Int32 => ree::sum_checked::<types::Int32Type, T>(&array),
625            DataType::Int64 => ree::sum_checked::<types::Int64Type, T>(&array),
626            _ => unreachable!(),
627        },
628        _ => sum_checked::<T>(as_primitive_array(&array)),
629    }
630}
631
632// Logic for summing run-end-encoded arrays.
633mod ree {
634    use std::convert::Infallible;
635
636    use arrow_array::cast::AsArray;
637    use arrow_array::types::RunEndIndexType;
638    use arrow_array::{Array, ArrowNativeTypeOp, ArrowNumericType, PrimitiveArray, TypedRunArray};
639    use arrow_buffer::ArrowNativeType;
640    use arrow_schema::ArrowError;
641
642    /// Downcasts an array to a TypedRunArray.
643    fn downcast<I: RunEndIndexType, V: ArrowNumericType>(
644        array: &dyn Array,
645    ) -> Option<TypedRunArray<'_, I, PrimitiveArray<V>>> {
646        let array = array.as_run_opt::<I>()?;
647        // We only support RunArray wrapping primitive types.
648        array.downcast::<PrimitiveArray<V>>()
649    }
650
651    /// Computes the sum (wrapping) of the array values.
652    pub(super) fn sum_wrapping<I: RunEndIndexType, V: ArrowNumericType>(
653        array: &dyn Array,
654    ) -> Option<V::Native> {
655        let ree = downcast::<I, V>(array)?;
656        let Ok(sum) = fold(ree, |acc, val, len| -> Result<V::Native, Infallible> {
657            Ok(acc.add_wrapping(val.mul_wrapping(V::Native::usize_as(len))))
658        });
659        sum
660    }
661
662    /// Computes the sum (erroring on overflow) of the array values.
663    pub(super) fn sum_checked<I: RunEndIndexType, V: ArrowNumericType>(
664        array: &dyn Array,
665    ) -> Result<Option<V::Native>, ArrowError> {
666        let Some(ree) = downcast::<I, V>(array) else {
667            return Err(ArrowError::InvalidArgumentError(
668                "Input run array values are not a PrimitiveArray".to_string(),
669            ));
670        };
671        fold(ree, |acc, val, len| -> Result<V::Native, ArrowError> {
672            let Some(len) = V::Native::from_usize(len) else {
673                return Err(ArrowError::ArithmeticOverflow(format!(
674                    "Cannot convert a run-end index ({:?}) to the value type ({})",
675                    len,
676                    std::any::type_name::<V::Native>()
677                )));
678            };
679            acc.add_checked(val.mul_checked(len)?)
680        })
681    }
682
683    /// Folds over the values in a run-end-encoded array.
684    fn fold<I: RunEndIndexType, V: ArrowNumericType, F, E>(
685        array: TypedRunArray<'_, I, PrimitiveArray<V>>,
686        mut f: F,
687    ) -> Result<Option<V::Native>, E>
688    where
689        F: FnMut(V::Native, V::Native, usize) -> Result<V::Native, E>,
690    {
691        let run_ends = array.run_ends().sliced_values();
692
693        let values_slice = array.run_array().values_slice();
694        let values = values_slice
695            .as_any()
696            .downcast_ref::<PrimitiveArray<V>>()
697            // Safety: we know the values array is PrimitiveArray<V>.
698            .unwrap();
699
700        let mut prev_end = 0;
701        let mut acc = V::Native::ZERO;
702        let mut has_non_null_value = false;
703
704        for (run_end, value) in run_ends.zip(values) {
705            let current_run_end = run_end.as_usize();
706            let run_length = current_run_end - prev_end;
707
708            if let Some(value) = value {
709                has_non_null_value = true;
710                acc = f(acc, value, run_length)?;
711            }
712
713            prev_end = current_run_end;
714        }
715
716        Ok(if has_non_null_value { Some(acc) } else { None })
717    }
718}
719
720/// Returns the min of values in the array of `ArrowNumericType` type, or dictionary
721/// array with value of `ArrowNumericType` type.
722pub fn min_array<T: ArrowNumericType, A: ArrayAccessor<Item = T::Native>>(
723    array: A,
724) -> Option<T::Native> {
725    min_max_array_helper::<T, A, _, _>(array, |a, b| a.is_gt(*b), min)
726}
727
728/// Returns the max of values in the array of `ArrowNumericType` type, or dictionary
729/// array with value of `ArrowNumericType` type.
730pub fn max_array<T: ArrowNumericType, A: ArrayAccessor<Item = T::Native>>(
731    array: A,
732) -> Option<T::Native> {
733    min_max_array_helper::<T, A, _, _>(array, |a, b| a.is_lt(*b), max)
734}
735
736fn min_max_array_helper<T, A: ArrayAccessor<Item = T::Native>, F, M>(
737    array: A,
738    cmp: F,
739    m: M,
740) -> Option<T::Native>
741where
742    T: ArrowNumericType,
743    F: Fn(&T::Native, &T::Native) -> bool,
744    M: Fn(&PrimitiveArray<T>) -> Option<T::Native>,
745{
746    match array.data_type() {
747        DataType::Dictionary(_, _) => min_max_helper::<T::Native, _, _>(array, cmp),
748        DataType::RunEndEncoded(run_ends, _) => {
749            // We can directly perform min/max on the values child array, as any
750            // run must have non-zero length.
751            let array: &dyn Array = &array;
752            let values = match run_ends.data_type() {
753                DataType::Int16 => array.as_run_opt::<types::Int16Type>()?.values_slice(),
754                DataType::Int32 => array.as_run_opt::<types::Int32Type>()?.values_slice(),
755                DataType::Int64 => array.as_run_opt::<types::Int64Type>()?.values_slice(),
756                _ => return None,
757            };
758            // We only support RunArray wrapping primitive types.
759            let values = values.as_any().downcast_ref::<PrimitiveArray<T>>()?;
760            m(values)
761        }
762        _ => m(as_primitive_array(&array)),
763    }
764}
765
766macro_rules! bit_operation {
767    ($NAME:ident, $OP:ident, $NATIVE:ident, $DEFAULT:expr, $DOC:expr) => {
768        #[doc = $DOC]
769        ///
770        /// Returns `None` if the array is empty or only contains null values.
771        pub fn $NAME<T>(array: &PrimitiveArray<T>) -> Option<T::Native>
772        where
773            T: ArrowNumericType,
774            T::Native: $NATIVE<Output = T::Native> + ArrowNativeTypeOp,
775        {
776            let default;
777            if $DEFAULT == -1 {
778                default = T::Native::ONE.neg_wrapping();
779            } else {
780                default = T::default_value();
781            }
782
783            let null_count = array.null_count();
784
785            if null_count == array.len() {
786                return None;
787            }
788
789            let data: &[T::Native] = array.values();
790
791            match array.nulls() {
792                None => {
793                    let result = data
794                        .iter()
795                        .fold(default, |accumulator, value| accumulator.$OP(*value));
796
797                    Some(result)
798                }
799                Some(nulls) => {
800                    let mut result = default;
801                    let data_chunks = data.chunks_exact(64);
802                    let remainder = data_chunks.remainder();
803
804                    let bit_chunks = nulls.inner().bit_chunks();
805                    data_chunks
806                        .zip(bit_chunks.iter())
807                        .for_each(|(chunk, mask)| {
808                            // index_mask has value 1 << i in the loop
809                            let mut index_mask = 1;
810                            chunk.iter().for_each(|value| {
811                                if (mask & index_mask) != 0 {
812                                    result = result.$OP(*value);
813                                }
814                                index_mask <<= 1;
815                            });
816                        });
817
818                    let remainder_bits = bit_chunks.remainder_bits();
819
820                    remainder.iter().enumerate().for_each(|(i, value)| {
821                        if remainder_bits & (1 << i) != 0 {
822                            result = result.$OP(*value);
823                        }
824                    });
825
826                    Some(result)
827                }
828            }
829        }
830    };
831}
832
833bit_operation!(
834    bit_and,
835    bitand,
836    BitAnd,
837    -1,
838    "Returns the bitwise and of all non-null input values."
839);
840bit_operation!(
841    bit_or,
842    bitor,
843    BitOr,
844    0,
845    "Returns the bitwise or of all non-null input values."
846);
847bit_operation!(
848    bit_xor,
849    bitxor,
850    BitXor,
851    0,
852    "Returns the bitwise xor of all non-null input values."
853);
854
855/// Returns true if all non-null input values are true, otherwise false.
856///
857/// Returns `None` if the array is empty or only contains null values.
858pub fn bool_and(array: &BooleanArray) -> Option<bool> {
859    min_boolean(array)
860}
861
862/// Returns true if any non-null input value is true, otherwise false.
863///
864/// Returns `None` if the array is empty or only contains null values.
865pub fn bool_or(array: &BooleanArray) -> Option<bool> {
866    max_boolean(array)
867}
868
869/// Returns the sum of values in the primitive array.
870///
871/// Returns `Ok(None)` if the array is empty or only contains null values.
872///
873/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
874/// use [`sum`] instead.
875pub fn sum_checked<T: ArrowNumericType>(
876    array: &PrimitiveArray<T>,
877) -> Result<Option<T::Native>, ArrowError> {
878    let null_count = array.null_count();
879
880    if null_count == array.len() {
881        return Ok(None);
882    }
883
884    let data: &[T::Native] = array.values();
885
886    match array.nulls() {
887        None => {
888            let sum = data
889                .iter()
890                .try_fold(T::default_value(), |accumulator, value| {
891                    accumulator.add_checked(*value)
892                })?;
893
894            Ok(Some(sum))
895        }
896        Some(nulls) => {
897            let mut sum = T::default_value();
898
899            try_for_each_valid_idx(
900                nulls.len(),
901                nulls.offset(),
902                nulls.null_count(),
903                Some(nulls.validity()),
904                |idx| {
905                    unsafe { sum = sum.add_checked(array.value_unchecked(idx))? };
906                    Ok::<_, ArrowError>(())
907                },
908            )?;
909
910            Ok(Some(sum))
911        }
912    }
913}
914
915/// Returns the sum of values in the primitive array.
916///
917/// Returns `None` if the array is empty or only contains null values.
918///
919/// This doesn't detect overflow in release mode by default. Once overflowing, the result will
920/// wrap around. For an overflow-checking variant, use [`sum_checked`] instead.
921pub fn sum<T: ArrowNumericType>(array: &PrimitiveArray<T>) -> Option<T::Native> {
922    aggregate::<T::Native, T, SumAccumulator<T::Native>>(array)
923}
924
925/// Returns the product of values in the primitive array.
926///
927/// Returns `None` if the array is empty or only contains null values.
928///
929/// This doesn't detect overflow in release mode by default. Once overflowing, the result will
930/// wrap around. For an overflow-checking variant, use [`product_checked`] instead.
931pub fn product<T: ArrowNumericType>(array: &PrimitiveArray<T>) -> Option<T::Native> {
932    aggregate::<T::Native, T, ProductAccumulator<T::Native>>(array)
933}
934
935/// Returns the product of values in the primitive array.
936///
937/// Returns `Ok(None)` if the array is empty or only contains null values.
938///
939/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
940/// use [`product`] instead.
941pub fn product_checked<T: ArrowNumericType>(
942    array: &PrimitiveArray<T>,
943) -> Result<Option<T::Native>, ArrowError> {
944    let null_count = array.null_count();
945
946    if null_count == array.len() {
947        return Ok(None);
948    }
949
950    let data: &[T::Native] = array.values();
951
952    match array.nulls() {
953        None => {
954            let product = data.iter().try_fold(T::Native::ONE, |accumulator, value| {
955                accumulator.mul_checked(*value)
956            })?;
957
958            Ok(Some(product))
959        }
960        Some(nulls) => {
961            let mut product = T::Native::ONE;
962
963            try_for_each_valid_idx(
964                nulls.len(),
965                nulls.offset(),
966                nulls.null_count(),
967                Some(nulls.validity()),
968                |idx| {
969                    unsafe { product = product.mul_checked(array.value_unchecked(idx))? };
970                    Ok::<_, ArrowError>(())
971                },
972            )?;
973
974            Ok(Some(product))
975        }
976    }
977}
978
979/// Returns the minimum value in the array, according to the natural order.
980///
981/// Floating point values are compared using IEEE 754 totalOrder (see [`f64::total_cmp`]):
982/// a positive NaN is greater than every non-NaN value, including positive infinity, and a
983/// negative NaN is less than every non-NaN value, including negative infinity.
984///
985/// # Example
986/// ```rust
987/// # use arrow_array::Int32Array;
988/// # use arrow_arith::aggregate::min;
989/// let array = Int32Array::from(vec![8, 2, 4]);
990/// let result = min(&array);
991/// assert_eq!(result, Some(2));
992/// ```
993pub fn min<T: ArrowNumericType>(array: &PrimitiveArray<T>) -> Option<T::Native> {
994    aggregate::<T::Native, T, MinAccumulator<T::Native>>(array)
995}
996
997/// Returns the maximum value in the array, according to the natural order.
998///
999/// Floating point values are compared using IEEE 754 totalOrder (see [`f64::total_cmp`]):
1000/// a positive NaN is greater than every non-NaN value, including positive infinity, and a
1001/// negative NaN is less than every non-NaN value, including negative infinity.
1002///
1003/// # Example
1004/// ```rust
1005/// # use arrow_array::Int32Array;
1006/// # use arrow_arith::aggregate::max;
1007/// let array = Int32Array::from(vec![4, 8, 2]);
1008/// let result = max(&array);
1009/// assert_eq!(result, Some(8));
1010/// ```
1011pub fn max<T: ArrowNumericType>(array: &PrimitiveArray<T>) -> Option<T::Native> {
1012    aggregate::<T::Native, T, MaxAccumulator<T::Native>>(array)
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017    use super::*;
1018    use arrow_array::types::*;
1019    use builder::BooleanBuilder;
1020    use std::sync::Arc;
1021
1022    #[test]
1023    fn test_primitive_array_sum() {
1024        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
1025        assert_eq!(15, sum(&a).unwrap());
1026    }
1027
1028    #[test]
1029    fn test_primitive_array_float_sum() {
1030        let a = Float64Array::from(vec![1.1, 2.2, 3.3, 4.4, 5.5]);
1031        assert_eq!(16.5, sum(&a).unwrap());
1032    }
1033
1034    #[test]
1035    fn test_primitive_array_product() {
1036        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
1037        assert_eq!(120, product(&a).unwrap());
1038    }
1039
1040    #[test]
1041    fn test_primitive_array_float_product() {
1042        let a = Float64Array::from(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
1043        assert_eq!(120.0, product(&a).unwrap());
1044    }
1045
1046    #[test]
1047    fn test_primitive_array_product_with_nulls() {
1048        let a = Int32Array::from(vec![None, Some(2), Some(3), None, Some(5)]);
1049        assert_eq!(30, product(&a).unwrap());
1050    }
1051
1052    #[test]
1053    fn test_primitive_array_product_all_nulls() {
1054        let a = Int32Array::from(vec![None, None, None]);
1055        assert_eq!(None, product(&a));
1056    }
1057
1058    #[test]
1059    fn test_primitive_array_product_empty() {
1060        let a = Int32Array::from(Vec::<i32>::new());
1061        assert_eq!(None, product(&a));
1062    }
1063
1064    #[test]
1065    fn test_primitive_array_product_checked() {
1066        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
1067        assert_eq!(120, product_checked(&a).unwrap().unwrap());
1068    }
1069
1070    #[test]
1071    fn test_primitive_array_product_checked_with_nulls() {
1072        let a = Int32Array::from(vec![None, Some(2), Some(3), None, Some(5)]);
1073        assert_eq!(30, product_checked(&a).unwrap().unwrap());
1074    }
1075
1076    #[test]
1077    fn test_primitive_array_product_checked_all_nulls() {
1078        let a = Int32Array::from(vec![None, None, None]);
1079        assert_eq!(None, product_checked(&a).unwrap());
1080    }
1081
1082    #[test]
1083    fn test_product_overflow() {
1084        let a = Int32Array::from(vec![i32::MAX, 2]);
1085        // wrapping variant silently overflows
1086        assert_eq!(product(&a).unwrap(), -2);
1087    }
1088
1089    #[test]
1090    fn test_product_checked_overflow() {
1091        let a = Int32Array::from(vec![i32::MAX, 2]);
1092        product_checked(&a).expect_err("overflow should be detected");
1093    }
1094
1095    #[test]
1096    fn test_primitive_array_sum_with_nulls() {
1097        let a = Int32Array::from(vec![None, Some(2), Some(3), None, Some(5)]);
1098        assert_eq!(10, sum(&a).unwrap());
1099    }
1100
1101    #[test]
1102    fn test_primitive_array_sum_all_nulls() {
1103        let a = Int32Array::from(vec![None, None, None]);
1104        assert_eq!(None, sum(&a));
1105    }
1106
1107    #[test]
1108    fn test_primitive_array_sum_large_float_64() {
1109        let c = Float64Array::new((1..=100).map(|x| x as f64).collect(), None);
1110        assert_eq!(Some((1..=100).sum::<i64>() as f64), sum(&c));
1111
1112        // create an array that actually has non-zero values at the invalid indices
1113        let validity = NullBuffer::new((1..=100).map(|x| x % 3 == 0).collect());
1114        let c = Float64Array::new((1..=100).map(|x| x as f64).collect(), Some(validity));
1115
1116        assert_eq!(
1117            Some((1..=100).filter(|i| i % 3 == 0).sum::<i64>() as f64),
1118            sum(&c)
1119        );
1120    }
1121
1122    #[test]
1123    fn test_primitive_array_sum_large_float_32() {
1124        let c = Float32Array::new((1..=100).map(|x| x as f32).collect(), None);
1125        assert_eq!(Some((1..=100).sum::<i64>() as f32), sum(&c));
1126
1127        // create an array that actually has non-zero values at the invalid indices
1128        let validity = NullBuffer::new((1..=100).map(|x| x % 3 == 0).collect());
1129        let c = Float32Array::new((1..=100).map(|x| x as f32).collect(), Some(validity));
1130
1131        assert_eq!(
1132            Some((1..=100).filter(|i| i % 3 == 0).sum::<i64>() as f32),
1133            sum(&c)
1134        );
1135    }
1136
1137    #[test]
1138    fn test_primitive_array_sum_large_64() {
1139        let c = Int64Array::new((1..=100).collect(), None);
1140        assert_eq!(Some((1..=100).sum()), sum(&c));
1141
1142        // create an array that actually has non-zero values at the invalid indices
1143        let validity = NullBuffer::new((1..=100).map(|x| x % 3 == 0).collect());
1144        let c = Int64Array::new((1..=100).collect(), Some(validity));
1145
1146        assert_eq!(Some((1..=100).filter(|i| i % 3 == 0).sum()), sum(&c));
1147    }
1148
1149    #[test]
1150    fn test_primitive_array_sum_large_32() {
1151        let c = Int32Array::new((1..=100).collect(), None);
1152        assert_eq!(Some((1..=100).sum()), sum(&c));
1153
1154        // create an array that actually has non-zero values at the invalid indices
1155        let validity = NullBuffer::new((1..=100).map(|x| x % 3 == 0).collect());
1156        let c = Int32Array::new((1..=100).collect(), Some(validity));
1157        assert_eq!(Some((1..=100).filter(|i| i % 3 == 0).sum()), sum(&c));
1158    }
1159
1160    #[test]
1161    fn test_primitive_array_sum_large_16() {
1162        let c = Int16Array::new((1..=100).collect(), None);
1163        assert_eq!(Some((1..=100).sum()), sum(&c));
1164
1165        // create an array that actually has non-zero values at the invalid indices
1166        let validity = NullBuffer::new((1..=100).map(|x| x % 3 == 0).collect());
1167        let c = Int16Array::new((1..=100).collect(), Some(validity));
1168        assert_eq!(Some((1..=100).filter(|i| i % 3 == 0).sum()), sum(&c));
1169    }
1170
1171    #[test]
1172    fn test_primitive_array_sum_large_8() {
1173        let c = UInt8Array::new((1..=100).collect(), None);
1174        assert_eq!(
1175            Some((1..=100).fold(0_u8, |a, x| a.wrapping_add(x))),
1176            sum(&c)
1177        );
1178
1179        // create an array that actually has non-zero values at the invalid indices
1180        let validity = NullBuffer::new((1..=100).map(|x| x % 3 == 0).collect());
1181        let c = UInt8Array::new((1..=100).collect(), Some(validity));
1182        assert_eq!(
1183            Some(
1184                (1..=100)
1185                    .filter(|i| i % 3 == 0)
1186                    .fold(0_u8, |a, x| a.wrapping_add(x))
1187            ),
1188            sum(&c)
1189        );
1190    }
1191
1192    #[test]
1193    fn test_primitive_array_bit_and() {
1194        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
1195        assert_eq!(0, bit_and(&a).unwrap());
1196    }
1197
1198    #[test]
1199    fn test_primitive_array_bit_and_with_nulls() {
1200        let a = Int32Array::from(vec![None, Some(2), Some(3), None, None]);
1201        assert_eq!(2, bit_and(&a).unwrap());
1202    }
1203
1204    #[test]
1205    fn test_primitive_array_bit_and_all_nulls() {
1206        let a = Int32Array::from(vec![None, None, None]);
1207        assert_eq!(None, bit_and(&a));
1208    }
1209
1210    #[test]
1211    fn test_primitive_array_bit_or() {
1212        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
1213        assert_eq!(7, bit_or(&a).unwrap());
1214    }
1215
1216    #[test]
1217    fn test_primitive_array_bit_or_with_nulls() {
1218        let a = Int32Array::from(vec![None, Some(2), Some(3), None, Some(5)]);
1219        assert_eq!(7, bit_or(&a).unwrap());
1220    }
1221
1222    #[test]
1223    fn test_primitive_array_bit_or_all_nulls() {
1224        let a = Int32Array::from(vec![None, None, None]);
1225        assert_eq!(None, bit_or(&a));
1226    }
1227
1228    #[test]
1229    fn test_primitive_array_bit_xor() {
1230        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
1231        assert_eq!(1, bit_xor(&a).unwrap());
1232    }
1233
1234    #[test]
1235    fn test_primitive_array_bit_xor_with_nulls() {
1236        let a = Int32Array::from(vec![None, Some(2), Some(3), None, Some(5)]);
1237        assert_eq!(4, bit_xor(&a).unwrap());
1238    }
1239
1240    #[test]
1241    fn test_primitive_array_bit_xor_all_nulls() {
1242        let a = Int32Array::from(vec![None, None, None]);
1243        assert_eq!(None, bit_xor(&a));
1244    }
1245
1246    #[test]
1247    fn test_primitive_array_bool_and() {
1248        let a = BooleanArray::from(vec![true, false, true, false, true]);
1249        assert!(!bool_and(&a).unwrap());
1250    }
1251
1252    #[test]
1253    fn test_primitive_array_bool_and_with_nulls() {
1254        let a = BooleanArray::from(vec![None, Some(true), Some(true), None, Some(true)]);
1255        assert!(bool_and(&a).unwrap());
1256    }
1257
1258    #[test]
1259    fn test_primitive_array_bool_and_all_nulls() {
1260        let a = BooleanArray::from(vec![None, None, None]);
1261        assert_eq!(None, bool_and(&a));
1262    }
1263
1264    #[test]
1265    fn test_primitive_array_bool_or() {
1266        let a = BooleanArray::from(vec![true, false, true, false, true]);
1267        assert!(bool_or(&a).unwrap());
1268    }
1269
1270    #[test]
1271    fn test_primitive_array_bool_or_with_nulls() {
1272        let a = BooleanArray::from(vec![None, Some(false), Some(false), None, Some(false)]);
1273        assert!(!bool_or(&a).unwrap());
1274    }
1275
1276    #[test]
1277    fn test_primitive_array_bool_or_all_nulls() {
1278        let a = BooleanArray::from(vec![None, None, None]);
1279        assert_eq!(None, bool_or(&a));
1280    }
1281
1282    #[test]
1283    fn test_primitive_array_min_max() {
1284        let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
1285        assert_eq!(5, min(&a).unwrap());
1286        assert_eq!(9, max(&a).unwrap());
1287    }
1288
1289    #[test]
1290    fn test_primitive_array_min_max_with_nulls() {
1291        let a = Int32Array::from(vec![Some(5), None, None, Some(8), Some(9)]);
1292        assert_eq!(5, min(&a).unwrap());
1293        assert_eq!(9, max(&a).unwrap());
1294    }
1295
1296    #[test]
1297    fn test_primitive_min_max_1() {
1298        let a = Int32Array::from(vec![None, None, Some(5), Some(2)]);
1299        assert_eq!(Some(2), min(&a));
1300        assert_eq!(Some(5), max(&a));
1301    }
1302
1303    #[test]
1304    fn test_primitive_min_max_float_large_nonnull_array() {
1305        let a: Float64Array = (0..256).map(|i| Some((i + 1) as f64)).collect();
1306        // min/max are on boundaries of chunked data
1307        assert_eq!(Some(1.0), min(&a));
1308        assert_eq!(Some(256.0), max(&a));
1309
1310        // max is last value in remainder after chunking
1311        let a: Float64Array = (0..255).map(|i| Some((i + 1) as f64)).collect();
1312        assert_eq!(Some(255.0), max(&a));
1313
1314        // max is first value in remainder after chunking
1315        let a: Float64Array = (0..257).map(|i| Some((i + 1) as f64)).collect();
1316        assert_eq!(Some(257.0), max(&a));
1317    }
1318
1319    #[test]
1320    fn test_primitive_min_max_float_large_nullable_array() {
1321        let a: Float64Array = (0..256)
1322            .map(|i| {
1323                if (i + 1) % 3 == 0 {
1324                    None
1325                } else {
1326                    Some((i + 1) as f64)
1327                }
1328            })
1329            .collect();
1330        // min/max are on boundaries of chunked data
1331        assert_eq!(Some(1.0), min(&a));
1332        assert_eq!(Some(256.0), max(&a));
1333
1334        let a: Float64Array = (0..256)
1335            .map(|i| {
1336                if i == 0 || i == 255 {
1337                    None
1338                } else {
1339                    Some((i + 1) as f64)
1340                }
1341            })
1342            .collect();
1343        // boundaries of chunked data are null
1344        assert_eq!(Some(2.0), min(&a));
1345        assert_eq!(Some(255.0), max(&a));
1346
1347        let a: Float64Array = (0..256)
1348            .map(|i| if i != 100 { None } else { Some((i) as f64) })
1349            .collect();
1350        // a single non-null value somewhere in the middle
1351        assert_eq!(Some(100.0), min(&a));
1352        assert_eq!(Some(100.0), max(&a));
1353
1354        // max is last value in remainder after chunking
1355        let a: Float64Array = (0..255).map(|i| Some((i + 1) as f64)).collect();
1356        assert_eq!(Some(255.0), max(&a));
1357
1358        // max is first value in remainder after chunking
1359        let a: Float64Array = (0..257).map(|i| Some((i + 1) as f64)).collect();
1360        assert_eq!(Some(257.0), max(&a));
1361    }
1362
1363    #[test]
1364    fn test_primitive_min_max_float_edge_cases() {
1365        let a: Float64Array = (0..100).map(|_| Some(f64::NEG_INFINITY)).collect();
1366        assert_eq!(Some(f64::NEG_INFINITY), min(&a));
1367        assert_eq!(Some(f64::NEG_INFINITY), max(&a));
1368
1369        let a: Float64Array = (0..100).map(|_| Some(f64::MIN)).collect();
1370        assert_eq!(Some(f64::MIN), min(&a));
1371        assert_eq!(Some(f64::MIN), max(&a));
1372
1373        let a: Float64Array = (0..100).map(|_| Some(f64::MAX)).collect();
1374        assert_eq!(Some(f64::MAX), min(&a));
1375        assert_eq!(Some(f64::MAX), max(&a));
1376
1377        let a: Float64Array = (0..100).map(|_| Some(f64::INFINITY)).collect();
1378        assert_eq!(Some(f64::INFINITY), min(&a));
1379        assert_eq!(Some(f64::INFINITY), max(&a));
1380    }
1381
1382    #[test]
1383    fn test_primitive_min_max_float_all_nans_non_null() {
1384        let a: Float64Array = (0..100).map(|_| Some(f64::NAN)).collect();
1385        assert!(max(&a).unwrap().is_nan());
1386        assert!(min(&a).unwrap().is_nan());
1387    }
1388
1389    #[test]
1390    fn test_primitive_min_max_float_negative_nan() {
1391        let a: Float64Array =
1392            Float64Array::from(vec![f64::NEG_INFINITY, f64::NAN, f64::INFINITY, -f64::NAN]);
1393        let max = max(&a).unwrap();
1394        let min = min(&a).unwrap();
1395        assert!(max.is_nan());
1396        assert!(max.is_sign_positive());
1397
1398        assert!(min.is_nan());
1399        assert!(min.is_sign_negative());
1400    }
1401
1402    #[test]
1403    fn test_primitive_min_max_float_first_nan_nonnull() {
1404        let a: Float64Array = (0..100)
1405            .map(|i| {
1406                if i == 0 {
1407                    Some(f64::NAN)
1408                } else {
1409                    Some(i as f64)
1410                }
1411            })
1412            .collect();
1413        assert_eq!(Some(1.0), min(&a));
1414        assert!(max(&a).unwrap().is_nan());
1415    }
1416
1417    #[test]
1418    fn test_primitive_min_max_float_last_nan_nonnull() {
1419        let a: Float64Array = (0..100)
1420            .map(|i| {
1421                if i == 99 {
1422                    Some(f64::NAN)
1423                } else {
1424                    Some((i + 1) as f64)
1425                }
1426            })
1427            .collect();
1428        assert_eq!(Some(1.0), min(&a));
1429        assert!(max(&a).unwrap().is_nan());
1430    }
1431
1432    #[test]
1433    fn test_primitive_min_max_float_first_nan_nullable() {
1434        let a: Float64Array = (0..100)
1435            .map(|i| {
1436                if i == 0 {
1437                    Some(f64::NAN)
1438                } else if i % 2 == 0 {
1439                    None
1440                } else {
1441                    Some(i as f64)
1442                }
1443            })
1444            .collect();
1445        assert_eq!(Some(1.0), min(&a));
1446        assert!(max(&a).unwrap().is_nan());
1447    }
1448
1449    #[test]
1450    fn test_primitive_min_max_float_last_nan_nullable() {
1451        let a: Float64Array = (0..100)
1452            .map(|i| {
1453                if i == 99 {
1454                    Some(f64::NAN)
1455                } else if i % 2 == 0 {
1456                    None
1457                } else {
1458                    Some(i as f64)
1459                }
1460            })
1461            .collect();
1462        assert_eq!(Some(1.0), min(&a));
1463        assert!(max(&a).unwrap().is_nan());
1464    }
1465
1466    #[test]
1467    fn test_primitive_min_max_float_inf_and_nans() {
1468        let a: Float64Array = (0..100)
1469            .map(|i| {
1470                let x = match i % 10 {
1471                    0 => f64::NEG_INFINITY,
1472                    1 => f64::MIN,
1473                    2 => f64::MAX,
1474                    4 => f64::INFINITY,
1475                    5 => f64::NAN,
1476                    _ => i as f64,
1477                };
1478                Some(x)
1479            })
1480            .collect();
1481        assert_eq!(Some(f64::NEG_INFINITY), min(&a));
1482        assert!(max(&a).unwrap().is_nan());
1483    }
1484
1485    fn pad_inputs_and_test_fixed_size_binary(
1486        input: Vec<Option<&[u8]>>,
1487        expected_min: Option<&[u8]>,
1488        expected_max: Option<&[u8]>,
1489    ) {
1490        fn pad_slice(slice: &[u8], len: usize) -> Vec<u8> {
1491            let mut padded = vec![0; len];
1492            padded[..slice.len()].copy_from_slice(slice);
1493            padded
1494        }
1495
1496        let max_len = input
1497            .iter()
1498            .filter_map(|x| x.as_ref().map(|b| b.len()))
1499            .max()
1500            .unwrap_or(0);
1501        let padded_input = input
1502            .iter()
1503            .map(|x| x.as_ref().map(|b| pad_slice(b, max_len)));
1504        let input_arr =
1505            FixedSizeBinaryArray::try_from_sparse_iter_with_size(padded_input, max_len as i32)
1506                .unwrap();
1507        let padded_expected_min = expected_min.map(|b| pad_slice(b, max_len));
1508        let padded_expected_max = expected_max.map(|b| pad_slice(b, max_len));
1509
1510        assert_eq!(
1511            padded_expected_min.as_deref(),
1512            min_fixed_size_binary(&input_arr)
1513        );
1514        assert_eq!(
1515            padded_expected_max.as_deref(),
1516            max_fixed_size_binary(&input_arr)
1517        );
1518    }
1519
1520    macro_rules! test_binary {
1521        ($NAME:ident, $ARRAY:expr, $EXPECTED_MIN:expr, $EXPECTED_MAX: expr) => {
1522            #[test]
1523            fn $NAME() {
1524                let binary = BinaryArray::from($ARRAY);
1525                assert_eq!($EXPECTED_MIN, min_binary(&binary));
1526                assert_eq!($EXPECTED_MAX, max_binary(&binary));
1527
1528                let large_binary = LargeBinaryArray::from($ARRAY);
1529                assert_eq!($EXPECTED_MIN, min_binary(&large_binary));
1530                assert_eq!($EXPECTED_MAX, max_binary(&large_binary));
1531
1532                let binary_view = BinaryViewArray::from($ARRAY);
1533                assert_eq!($EXPECTED_MIN, min_binary_view(&binary_view));
1534                assert_eq!($EXPECTED_MAX, max_binary_view(&binary_view));
1535
1536                pad_inputs_and_test_fixed_size_binary($ARRAY, $EXPECTED_MIN, $EXPECTED_MAX);
1537            }
1538        };
1539    }
1540
1541    test_binary!(
1542        test_binary_min_max_with_nulls,
1543        vec![
1544            Some(b"b01234567890123".as_slice()), // long bytes
1545            None,
1546            None,
1547            Some(b"a"),
1548            Some(b"c"),
1549            Some(b"abcdedfg0123456"),
1550        ],
1551        Some(b"a".as_slice()),
1552        Some(b"c".as_slice())
1553    );
1554
1555    test_binary!(
1556        test_binary_min_max_no_null,
1557        vec![
1558            Some(b"b".as_slice()),
1559            Some(b"abcdefghijklmnopqrst"), // long bytes
1560            Some(b"c"),
1561            Some(b"b01234567890123"), // long bytes for view types
1562        ],
1563        Some(b"abcdefghijklmnopqrst".as_slice()),
1564        Some(b"c".as_slice())
1565    );
1566
1567    test_binary!(test_binary_min_max_all_nulls, vec![None, None], None, None);
1568
1569    test_binary!(
1570        test_binary_min_max_1,
1571        vec![
1572            None,
1573            Some(b"b01234567890123435".as_slice()), // long bytes for view types
1574            None,
1575            Some(b"b0123xxxxxxxxxxx"),
1576            Some(b"a")
1577        ],
1578        Some(b"a".as_slice()),
1579        Some(b"b0123xxxxxxxxxxx".as_slice())
1580    );
1581
1582    macro_rules! test_string {
1583        ($NAME:ident, $ARRAY:expr, $EXPECTED_MIN:expr, $EXPECTED_MAX: expr) => {
1584            #[test]
1585            fn $NAME() {
1586                let string = StringArray::from($ARRAY);
1587                assert_eq!($EXPECTED_MIN, min_string(&string));
1588                assert_eq!($EXPECTED_MAX, max_string(&string));
1589
1590                let large_string = LargeStringArray::from($ARRAY);
1591                assert_eq!($EXPECTED_MIN, min_string(&large_string));
1592                assert_eq!($EXPECTED_MAX, max_string(&large_string));
1593
1594                let string_view = StringViewArray::from($ARRAY);
1595                assert_eq!($EXPECTED_MIN, min_string_view(&string_view));
1596                assert_eq!($EXPECTED_MAX, max_string_view(&string_view));
1597            }
1598        };
1599    }
1600
1601    test_string!(
1602        test_string_min_max_with_nulls,
1603        vec![
1604            Some("b012345678901234"), // long bytes for view types
1605            None,
1606            None,
1607            Some("a"),
1608            Some("c"),
1609            Some("b0123xxxxxxxxxxx")
1610        ],
1611        Some("a"),
1612        Some("c")
1613    );
1614
1615    test_string!(
1616        test_string_min_max_no_null,
1617        vec![
1618            Some("b"),
1619            Some("b012345678901234"), // long bytes for view types
1620            Some("a"),
1621            Some("b012xxxxxxxxxxxx")
1622        ],
1623        Some("a"),
1624        Some("b012xxxxxxxxxxxx")
1625    );
1626
1627    test_string!(
1628        test_string_min_max_all_nulls,
1629        Vec::<Option<&str>>::from_iter([None, None]),
1630        None,
1631        None
1632    );
1633
1634    test_string!(
1635        test_string_min_max_1,
1636        vec![
1637            None,
1638            Some("c12345678901234"), // long bytes for view types
1639            None,
1640            Some("b"),
1641            Some("c1234xxxxxxxxxx")
1642        ],
1643        Some("b"),
1644        Some("c1234xxxxxxxxxx")
1645    );
1646
1647    test_string!(
1648        test_string_min_max_empty,
1649        Vec::<Option<&str>>::new(),
1650        None,
1651        None
1652    );
1653
1654    #[test]
1655    fn test_boolean_min_max_empty() {
1656        let a = BooleanArray::from(vec![] as Vec<Option<bool>>);
1657        assert_eq!(None, min_boolean(&a));
1658        assert_eq!(None, max_boolean(&a));
1659    }
1660
1661    #[test]
1662    fn test_boolean_min_max_all_null() {
1663        let a = BooleanArray::from(vec![None, None]);
1664        assert_eq!(None, min_boolean(&a));
1665        assert_eq!(None, max_boolean(&a));
1666    }
1667
1668    #[test]
1669    fn test_boolean_min_max_no_null() {
1670        let a = BooleanArray::from(vec![Some(true), Some(false), Some(true)]);
1671        assert_eq!(Some(false), min_boolean(&a));
1672        assert_eq!(Some(true), max_boolean(&a));
1673    }
1674
1675    #[test]
1676    fn test_boolean_min_max() {
1677        let a = BooleanArray::from(vec![Some(true), Some(true), None, Some(false), None]);
1678        assert_eq!(Some(false), min_boolean(&a));
1679        assert_eq!(Some(true), max_boolean(&a));
1680
1681        let a = BooleanArray::from(vec![None, Some(true), None, Some(false), None]);
1682        assert_eq!(Some(false), min_boolean(&a));
1683        assert_eq!(Some(true), max_boolean(&a));
1684
1685        let a = BooleanArray::from(vec![Some(false), Some(true), None, Some(false), None]);
1686        assert_eq!(Some(false), min_boolean(&a));
1687        assert_eq!(Some(true), max_boolean(&a));
1688
1689        let a = BooleanArray::from(vec![Some(true), None]);
1690        assert_eq!(Some(true), min_boolean(&a));
1691        assert_eq!(Some(true), max_boolean(&a));
1692
1693        let a = BooleanArray::from(vec![Some(false), None]);
1694        assert_eq!(Some(false), min_boolean(&a));
1695        assert_eq!(Some(false), max_boolean(&a));
1696
1697        let a = BooleanArray::from(vec![Some(true)]);
1698        assert_eq!(Some(true), min_boolean(&a));
1699        assert_eq!(Some(true), max_boolean(&a));
1700
1701        let a = BooleanArray::from(vec![Some(false)]);
1702        assert_eq!(Some(false), min_boolean(&a));
1703        assert_eq!(Some(false), max_boolean(&a));
1704    }
1705
1706    #[test]
1707    fn test_boolean_min_max_smaller() {
1708        let a = BooleanArray::from(vec![Some(false)]);
1709        assert_eq!(Some(false), min_boolean(&a));
1710        assert_eq!(Some(false), max_boolean(&a));
1711
1712        let a = BooleanArray::from(vec![None, Some(false)]);
1713        assert_eq!(Some(false), min_boolean(&a));
1714        assert_eq!(Some(false), max_boolean(&a));
1715
1716        let a = BooleanArray::from(vec![None, Some(true)]);
1717        assert_eq!(Some(true), min_boolean(&a));
1718        assert_eq!(Some(true), max_boolean(&a));
1719
1720        let a = BooleanArray::from(vec![Some(true)]);
1721        assert_eq!(Some(true), min_boolean(&a));
1722        assert_eq!(Some(true), max_boolean(&a));
1723    }
1724
1725    #[test]
1726    fn test_boolean_min_max_64_true_64_false() {
1727        let mut no_nulls = BooleanBuilder::new();
1728        no_nulls.append_slice(&[true; 64]);
1729        no_nulls.append_slice(&[false; 64]);
1730        let no_nulls = no_nulls.finish();
1731
1732        assert_eq!(Some(false), min_boolean(&no_nulls));
1733        assert_eq!(Some(true), max_boolean(&no_nulls));
1734
1735        let mut with_nulls = BooleanBuilder::new();
1736        with_nulls.append_slice(&[true; 31]);
1737        with_nulls.append_null();
1738        with_nulls.append_slice(&[true; 32]);
1739        with_nulls.append_slice(&[false; 1]);
1740        with_nulls.append_nulls(63);
1741        let with_nulls = with_nulls.finish();
1742
1743        assert_eq!(Some(false), min_boolean(&with_nulls));
1744        assert_eq!(Some(true), max_boolean(&with_nulls));
1745    }
1746
1747    #[test]
1748    fn test_boolean_min_max_64_false_64_true() {
1749        let mut no_nulls = BooleanBuilder::new();
1750        no_nulls.append_slice(&[false; 64]);
1751        no_nulls.append_slice(&[true; 64]);
1752        let no_nulls = no_nulls.finish();
1753
1754        assert_eq!(Some(false), min_boolean(&no_nulls));
1755        assert_eq!(Some(true), max_boolean(&no_nulls));
1756
1757        let mut with_nulls = BooleanBuilder::new();
1758        with_nulls.append_slice(&[false; 31]);
1759        with_nulls.append_null();
1760        with_nulls.append_slice(&[false; 32]);
1761        with_nulls.append_slice(&[true; 1]);
1762        with_nulls.append_nulls(63);
1763        let with_nulls = with_nulls.finish();
1764
1765        assert_eq!(Some(false), min_boolean(&with_nulls));
1766        assert_eq!(Some(true), max_boolean(&with_nulls));
1767    }
1768
1769    #[test]
1770    fn test_boolean_min_max_96_true() {
1771        let mut no_nulls = BooleanBuilder::new();
1772        no_nulls.append_slice(&[true; 96]);
1773        let no_nulls = no_nulls.finish();
1774
1775        assert_eq!(Some(true), min_boolean(&no_nulls));
1776        assert_eq!(Some(true), max_boolean(&no_nulls));
1777
1778        let mut with_nulls = BooleanBuilder::new();
1779        with_nulls.append_slice(&[true; 31]);
1780        with_nulls.append_null();
1781        with_nulls.append_slice(&[true; 32]);
1782        with_nulls.append_slice(&[true; 31]);
1783        with_nulls.append_null();
1784        let with_nulls = with_nulls.finish();
1785
1786        assert_eq!(Some(true), min_boolean(&with_nulls));
1787        assert_eq!(Some(true), max_boolean(&with_nulls));
1788    }
1789
1790    #[test]
1791    fn test_boolean_min_max_96_false() {
1792        let mut no_nulls = BooleanBuilder::new();
1793        no_nulls.append_slice(&[false; 96]);
1794        let no_nulls = no_nulls.finish();
1795
1796        assert_eq!(Some(false), min_boolean(&no_nulls));
1797        assert_eq!(Some(false), max_boolean(&no_nulls));
1798
1799        let mut with_nulls = BooleanBuilder::new();
1800        with_nulls.append_slice(&[false; 31]);
1801        with_nulls.append_null();
1802        with_nulls.append_slice(&[false; 32]);
1803        with_nulls.append_slice(&[false; 31]);
1804        with_nulls.append_null();
1805        let with_nulls = with_nulls.finish();
1806
1807        assert_eq!(Some(false), min_boolean(&with_nulls));
1808        assert_eq!(Some(false), max_boolean(&with_nulls));
1809    }
1810
1811    #[test]
1812    fn test_dictionary_aggregates_with_null_values() {
1813        let values = Arc::new(Int32Array::new(
1814            vec![5, -100, 100].into(),
1815            Some(vec![true, false, false].into()),
1816        ));
1817        for (keys, expected) in [
1818            (
1819                vec![Some(0_i8), Some(1), Some(0)],
1820                vec![Some(5), None, Some(5)],
1821            ),
1822            (vec![Some(1), Some(2)], vec![None, None]),
1823            (vec![None, Some(1), Some(0)], vec![None, None, Some(5)]),
1824            (vec![Some(0), Some(0)], vec![Some(5), Some(5)]),
1825            (vec![None, None], vec![None, None]),
1826            (vec![], vec![]),
1827        ] {
1828            let dictionary =
1829                DictionaryArray::<Int8Type>::try_new(Int8Array::from(keys), values.clone())
1830                    .unwrap();
1831            let array = dictionary.downcast_dict::<Int32Array>().unwrap();
1832            let expected = Int32Array::from(expected);
1833            assert_eq!(min_array::<Int32Type, _>(array), min(&expected));
1834            assert_eq!(max_array::<Int32Type, _>(array), max(&expected));
1835            assert_eq!(sum_array::<Int32Type, _>(array), sum(&expected));
1836            assert_eq!(
1837                sum_array_checked::<Int32Type, _>(array).unwrap(),
1838                sum_checked(&expected).unwrap()
1839            );
1840        }
1841    }
1842
1843    #[test]
1844    fn test_sum_dyn() {
1845        let values = Int8Array::from_iter_values([10_i8, 11, 12, 13, 14, 15, 16, 17]);
1846        let values = Arc::new(values) as ArrayRef;
1847        let keys = Int8Array::from_iter_values([2_i8, 3, 4]);
1848
1849        let dict_array = DictionaryArray::new(keys, values.clone());
1850        let array = dict_array.downcast_dict::<Int8Array>().unwrap();
1851        assert_eq!(39, sum_array::<Int8Type, _>(array).unwrap());
1852
1853        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
1854        assert_eq!(15, sum_array::<Int32Type, _>(&a).unwrap());
1855
1856        let keys = Int8Array::from(vec![Some(2_i8), None, Some(4)]);
1857        let dict_array = DictionaryArray::new(keys, values.clone());
1858        let array = dict_array.downcast_dict::<Int8Array>().unwrap();
1859        assert_eq!(26, sum_array::<Int8Type, _>(array).unwrap());
1860
1861        let keys = Int8Array::from(vec![None, None, None]);
1862        let dict_array = DictionaryArray::new(keys, values.clone());
1863        let array = dict_array.downcast_dict::<Int8Array>().unwrap();
1864        assert!(sum_array::<Int8Type, _>(array).is_none());
1865    }
1866
1867    #[test]
1868    fn test_max_min_dyn() {
1869        let values = Int8Array::from_iter_values([10_i8, 11, 12, 13, 14, 15, 16, 17]);
1870        let keys = Int8Array::from_iter_values([2_i8, 3, 4]);
1871        let values = Arc::new(values) as ArrayRef;
1872
1873        let dict_array = DictionaryArray::new(keys, values.clone());
1874        let array = dict_array.downcast_dict::<Int8Array>().unwrap();
1875        assert_eq!(14, max_array::<Int8Type, _>(array).unwrap());
1876
1877        let array = dict_array.downcast_dict::<Int8Array>().unwrap();
1878        assert_eq!(12, min_array::<Int8Type, _>(array).unwrap());
1879
1880        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
1881        assert_eq!(5, max_array::<Int32Type, _>(&a).unwrap());
1882        assert_eq!(1, min_array::<Int32Type, _>(&a).unwrap());
1883
1884        let keys = Int8Array::from(vec![Some(2_i8), None, Some(7)]);
1885        let dict_array = DictionaryArray::new(keys, values.clone());
1886        let array = dict_array.downcast_dict::<Int8Array>().unwrap();
1887        assert_eq!(17, max_array::<Int8Type, _>(array).unwrap());
1888        let array = dict_array.downcast_dict::<Int8Array>().unwrap();
1889        assert_eq!(12, min_array::<Int8Type, _>(array).unwrap());
1890
1891        let keys = Int8Array::from(vec![None, None, None]);
1892        let dict_array = DictionaryArray::new(keys, values.clone());
1893        let array = dict_array.downcast_dict::<Int8Array>().unwrap();
1894        assert!(max_array::<Int8Type, _>(array).is_none());
1895        let array = dict_array.downcast_dict::<Int8Array>().unwrap();
1896        assert!(min_array::<Int8Type, _>(array).is_none());
1897    }
1898
1899    #[test]
1900    fn test_max_min_dyn_nan() {
1901        let values = Float32Array::from(vec![5.0_f32, 2.0_f32, f32::NAN]);
1902        let keys = Int8Array::from_iter_values([0_i8, 1, 2]);
1903
1904        let dict_array = DictionaryArray::new(keys, Arc::new(values));
1905        let array = dict_array.downcast_dict::<Float32Array>().unwrap();
1906        assert!(max_array::<Float32Type, _>(array).unwrap().is_nan());
1907
1908        let array = dict_array.downcast_dict::<Float32Array>().unwrap();
1909        assert_eq!(2.0_f32, min_array::<Float32Type, _>(array).unwrap());
1910    }
1911
1912    #[test]
1913    fn test_min_max_sliced_primitive() {
1914        let expected = Some(4.0);
1915        let input: Float64Array = vec![None, Some(4.0)].into_iter().collect();
1916        let actual = min(&input);
1917        assert_eq!(actual, expected);
1918        let actual = max(&input);
1919        assert_eq!(actual, expected);
1920
1921        let sliced_input: Float64Array = vec![None, None, None, None, None, Some(4.0)]
1922            .into_iter()
1923            .collect();
1924        let sliced_input = sliced_input.slice(4, 2);
1925
1926        assert_eq!(&sliced_input, &input);
1927
1928        let actual = min(&sliced_input);
1929        assert_eq!(actual, expected);
1930        let actual = max(&sliced_input);
1931        assert_eq!(actual, expected);
1932    }
1933
1934    #[test]
1935    fn test_min_max_sliced_boolean() {
1936        let expected = Some(true);
1937        let input: BooleanArray = vec![None, Some(true)].into_iter().collect();
1938        let actual = min_boolean(&input);
1939        assert_eq!(actual, expected);
1940        let actual = max_boolean(&input);
1941        assert_eq!(actual, expected);
1942
1943        let sliced_input: BooleanArray = vec![None, None, None, None, None, Some(true)]
1944            .into_iter()
1945            .collect();
1946        let sliced_input = sliced_input.slice(4, 2);
1947
1948        assert_eq!(sliced_input, input);
1949
1950        let actual = min_boolean(&sliced_input);
1951        assert_eq!(actual, expected);
1952        let actual = max_boolean(&sliced_input);
1953        assert_eq!(actual, expected);
1954    }
1955
1956    #[test]
1957    fn test_min_max_sliced_string() {
1958        let expected = Some("foo");
1959        let input: StringArray = vec![None, Some("foo")].into_iter().collect();
1960        let actual = min_string(&input);
1961        assert_eq!(actual, expected);
1962        let actual = max_string(&input);
1963        assert_eq!(actual, expected);
1964
1965        let sliced_input: StringArray = vec![None, None, None, None, None, Some("foo")]
1966            .into_iter()
1967            .collect();
1968        let sliced_input = sliced_input.slice(4, 2);
1969
1970        assert_eq!(&sliced_input, &input);
1971
1972        let actual = min_string(&sliced_input);
1973        assert_eq!(actual, expected);
1974        let actual = max_string(&sliced_input);
1975        assert_eq!(actual, expected);
1976    }
1977
1978    #[test]
1979    fn test_min_max_sliced_binary() {
1980        let expected: Option<&[u8]> = Some(&[5]);
1981        let input: BinaryArray = vec![None, Some(&[5])].into_iter().collect();
1982        let actual = min_binary(&input);
1983        assert_eq!(actual, expected);
1984        let actual = max_binary(&input);
1985        assert_eq!(actual, expected);
1986
1987        let sliced_input: BinaryArray = vec![None, None, None, None, None, Some(&[5])]
1988            .into_iter()
1989            .collect();
1990        let sliced_input = sliced_input.slice(4, 2);
1991
1992        assert_eq!(&sliced_input, &input);
1993
1994        let actual = min_binary(&sliced_input);
1995        assert_eq!(actual, expected);
1996        let actual = max_binary(&sliced_input);
1997        assert_eq!(actual, expected);
1998    }
1999
2000    #[test]
2001    fn test_sum_overflow() {
2002        let a = Int32Array::from(vec![i32::MAX, 1]);
2003
2004        assert_eq!(sum(&a).unwrap(), -2147483648);
2005        assert_eq!(sum_array::<Int32Type, _>(&a).unwrap(), -2147483648);
2006    }
2007
2008    #[test]
2009    fn test_sum_checked_overflow() {
2010        let a = Int32Array::from(vec![i32::MAX, 1]);
2011
2012        sum_checked(&a).expect_err("overflow should be detected");
2013        sum_array_checked::<Int32Type, _>(&a).expect_err("overflow should be detected");
2014    }
2015
2016    /// Helper for building a RunArray.
2017    fn make_run_array<'a, I: RunEndIndexType, V: ArrowNumericType, ItemType>(
2018        values: impl IntoIterator<Item = &'a ItemType>,
2019    ) -> RunArray<I>
2020    where
2021        ItemType: Clone + Into<Option<V::Native>> + 'static,
2022    {
2023        let mut builder = arrow_array::builder::PrimitiveRunBuilder::<I, V>::new();
2024        for v in values {
2025            builder.append_option((*v).clone().into());
2026        }
2027        builder.finish()
2028    }
2029
2030    #[test]
2031    fn test_ree_sum_array_basic() {
2032        let run_array = make_run_array::<Int16Type, Int32Type, _>(&[10, 10, 20, 30, 30, 30]);
2033        let typed_array = run_array.downcast::<Int32Array>().unwrap();
2034
2035        let result = sum_array::<Int32Type, _>(typed_array);
2036        assert_eq!(result, Some(130));
2037
2038        let result = sum_array_checked::<Int32Type, _>(typed_array).unwrap();
2039        assert_eq!(result, Some(130));
2040    }
2041
2042    #[test]
2043    fn test_ree_sum_array_empty() {
2044        let run_array = make_run_array::<Int16Type, Int32Type, i32>(&[]);
2045        let typed_array = run_array.downcast::<Int32Array>().unwrap();
2046
2047        let result = sum_array::<Int32Type, _>(typed_array);
2048        assert_eq!(result, None);
2049
2050        let result = sum_array_checked::<Int32Type, _>(typed_array).unwrap();
2051        assert_eq!(result, None);
2052    }
2053
2054    #[test]
2055    fn test_ree_sum_array_with_nulls() {
2056        let run_array =
2057            make_run_array::<Int16Type, Int32Type, _>(&[Some(10), None, Some(20), None, Some(30)]);
2058        let typed_array = run_array.downcast::<Int32Array>().unwrap();
2059
2060        let result = sum_array::<Int32Type, _>(typed_array);
2061        assert_eq!(result, Some(60));
2062
2063        let result = sum_array_checked::<Int32Type, _>(typed_array).unwrap();
2064        assert_eq!(result, Some(60));
2065    }
2066
2067    #[test]
2068    fn test_ree_sum_array_with_only_nulls() {
2069        let run_array = make_run_array::<Int16Type, Int16Type, _>(&[None, None, None, None, None]);
2070        let typed_array = run_array.downcast::<Int16Array>().unwrap();
2071
2072        let result = sum_array::<Int16Type, _>(typed_array);
2073        assert_eq!(result, None);
2074
2075        let result = sum_array_checked::<Int16Type, _>(typed_array).unwrap();
2076        assert_eq!(result, None);
2077    }
2078
2079    #[test]
2080    fn test_ree_sum_array_overflow() {
2081        let run_array = make_run_array::<Int16Type, Int8Type, _>(&[126, 2]);
2082        let typed_array = run_array.downcast::<Int8Array>().unwrap();
2083
2084        // i8 range is -128..=127. 126+2 overflows to -128.
2085        let result = sum_array::<Int8Type, _>(typed_array);
2086        assert_eq!(result, Some(-128));
2087
2088        let result = sum_array_checked::<Int8Type, _>(typed_array);
2089        assert!(result.is_err());
2090    }
2091
2092    #[test]
2093    fn test_ree_sum_array_sliced() {
2094        let run_array = make_run_array::<Int16Type, UInt8Type, _>(&[0, 10, 10, 10, 20, 30, 30, 30]);
2095        // Skip 2 values at the start and 1 at the end.
2096        let sliced = run_array.slice(2, 5);
2097        let typed_array = sliced.downcast::<UInt8Array>().unwrap();
2098
2099        let result = sum_array::<UInt8Type, _>(typed_array);
2100        assert_eq!(result, Some(100));
2101
2102        let result = sum_array_checked::<UInt8Type, _>(typed_array).unwrap();
2103        assert_eq!(result, Some(100));
2104    }
2105
2106    #[test]
2107    fn test_ree_sum_array_sliced_across_runs() {
2108        let run_ends = Int16Array::from(vec![4, 8]);
2109        let values = Int32Array::from(vec![10, 100]);
2110        let array = RunArray::<Int16Type>::try_new(&run_ends, &values).unwrap();
2111        let sliced = array.slice(3, 4);
2112        let typed_array = sliced.downcast::<Int32Array>().unwrap();
2113
2114        assert_eq!(sum_array::<Int32Type, _>(typed_array), Some(310));
2115    }
2116
2117    #[test]
2118    fn test_ree_sum_array_all_slices() {
2119        fn check<I: RunEndIndexType>() {
2120            let values = [
2121                Some(2),
2122                Some(2),
2123                None,
2124                None,
2125                Some(-3),
2126                Some(-3),
2127                Some(-3),
2128                Some(4),
2129            ];
2130            let run_array = make_run_array::<I, Int32Type, _>(&values);
2131            let plain_array = Int32Array::from(values.to_vec());
2132
2133            for offset in 0..=values.len() {
2134                for len in 0..=values.len() - offset {
2135                    let sliced = run_array.slice(offset, len);
2136                    let typed = sliced.downcast::<Int32Array>().unwrap();
2137                    let expected = plain_array.slice(offset, len);
2138
2139                    assert_eq!(
2140                        sum_array::<Int32Type, _>(typed),
2141                        sum_array::<Int32Type, _>(&expected),
2142                        "offset={offset}, len={len}"
2143                    );
2144                    assert_eq!(
2145                        sum_array_checked::<Int32Type, _>(typed).unwrap(),
2146                        sum_array_checked::<Int32Type, _>(&expected).unwrap(),
2147                        "offset={offset}, len={len}"
2148                    );
2149                }
2150            }
2151
2152            let nested = run_array.slice(1, 7).slice(2, 4);
2153            let typed = nested.downcast::<Int32Array>().unwrap();
2154            let expected = plain_array.slice(1, 7).slice(2, 4);
2155            assert_eq!(
2156                sum_array::<Int32Type, _>(typed),
2157                sum_array::<Int32Type, _>(&expected)
2158            );
2159            assert_eq!(
2160                sum_array_checked::<Int32Type, _>(typed).unwrap(),
2161                sum_array_checked::<Int32Type, _>(&expected).unwrap()
2162            );
2163        }
2164
2165        check::<Int16Type>();
2166        check::<Int32Type>();
2167        check::<Int64Type>();
2168    }
2169
2170    #[test]
2171    fn test_ree_sum_array_checked_sliced_overflow() {
2172        let values = [50, 50, 50, 50, 1, 1, 1, 1];
2173        let run_array = make_run_array::<Int16Type, Int8Type, _>(&values);
2174        let sliced = run_array.slice(3, 4);
2175        let typed = sliced.downcast::<Int8Array>().unwrap();
2176        assert_eq!(sum_array_checked::<Int8Type, _>(typed).unwrap(), Some(53));
2177
2178        let values = [1, 1, 1, 1, 50, 50, 50, 50];
2179        let run_array = make_run_array::<Int16Type, Int8Type, _>(&values);
2180        let sliced = run_array.slice(3, 4);
2181        let typed = sliced.downcast::<Int8Array>().unwrap();
2182        assert!(sum_array_checked::<Int8Type, _>(typed).is_err());
2183    }
2184
2185    #[test]
2186    fn test_ree_sum_array_sliced_infinity() {
2187        let values = [
2188            1.0,
2189            1.0,
2190            1.0,
2191            1.0,
2192            2.0,
2193            2.0,
2194            2.0,
2195            2.0,
2196            f64::INFINITY,
2197            f64::INFINITY,
2198            f64::INFINITY,
2199            f64::INFINITY,
2200        ];
2201        let run_array = make_run_array::<Int16Type, Float64Type, _>(&values);
2202        let sliced = run_array.slice(5, 4);
2203        let typed = sliced.downcast::<Float64Array>().unwrap();
2204
2205        assert_eq!(sum_array::<Float64Type, _>(typed), Some(f64::INFINITY));
2206    }
2207
2208    #[test]
2209    fn test_ree_min_max_array_basic() {
2210        let run_array = make_run_array::<Int16Type, Int32Type, _>(&[30, 30, 10, 20, 20]);
2211        let typed_array = run_array.downcast::<Int32Array>().unwrap();
2212
2213        let result = min_array::<Int32Type, _>(typed_array);
2214        assert_eq!(result, Some(10));
2215
2216        let result = max_array::<Int32Type, _>(typed_array);
2217        assert_eq!(result, Some(30));
2218    }
2219
2220    #[test]
2221    fn test_ree_min_max_array_empty() {
2222        let run_array = make_run_array::<Int16Type, Int32Type, i32>(&[]);
2223        let typed_array = run_array.downcast::<Int32Array>().unwrap();
2224
2225        let result = min_array::<Int32Type, _>(typed_array);
2226        assert_eq!(result, None);
2227
2228        let result = max_array::<Int32Type, _>(typed_array);
2229        assert_eq!(result, None);
2230    }
2231
2232    #[test]
2233    fn test_ree_min_max_array_float() {
2234        let run_array = make_run_array::<Int16Type, Float64Type, _>(&[5.5, 5.5, 2.1, 8.9, 8.9]);
2235        let typed_array = run_array.downcast::<Float64Array>().unwrap();
2236
2237        let result = min_array::<Float64Type, _>(typed_array);
2238        assert_eq!(result, Some(2.1));
2239
2240        let result = max_array::<Float64Type, _>(typed_array);
2241        assert_eq!(result, Some(8.9));
2242    }
2243
2244    #[test]
2245    fn test_ree_min_max_array_with_nulls() {
2246        let run_array = make_run_array::<Int16Type, UInt8Type, _>(&[None, Some(10)]);
2247        let typed_array = run_array.downcast::<UInt8Array>().unwrap();
2248
2249        let result = min_array::<UInt8Type, _>(typed_array);
2250        assert_eq!(result, Some(10));
2251
2252        let result = max_array::<UInt8Type, _>(typed_array);
2253        assert_eq!(result, Some(10));
2254    }
2255
2256    #[test]
2257    fn test_ree_min_max_array_sliced() {
2258        let run_array = make_run_array::<Int16Type, Int32Type, _>(&[0, 30, 30, 10, 20, 20, 100]);
2259        // Skip 1 value at the start and 1 at the end.
2260        let sliced = run_array.slice(1, 5);
2261        let typed_array = sliced.downcast::<Int32Array>().unwrap();
2262
2263        let result = min_array::<Int32Type, _>(typed_array);
2264        assert_eq!(result, Some(10));
2265
2266        let result = max_array::<Int32Type, _>(typed_array);
2267        assert_eq!(result, Some(30));
2268    }
2269
2270    #[test]
2271    fn test_ree_min_max_array_sliced_mid_run() {
2272        let run_array = make_run_array::<Int16Type, Int32Type, _>(&[0, 0, 30, 10, 20, 100, 100]);
2273        // Skip 1 value at the start and 1 at the end.
2274        let sliced = run_array.slice(1, 5);
2275        let typed_array = sliced.downcast::<Int32Array>().unwrap();
2276
2277        let result = min_array::<Int32Type, _>(typed_array);
2278        assert_eq!(result, Some(0));
2279
2280        let result = max_array::<Int32Type, _>(typed_array);
2281        assert_eq!(result, Some(100));
2282    }
2283}