Skip to main content

arrow_arith/
numeric.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 numeric arithmetic kernels on [`PrimitiveArray`], such as [`add`]
6
7use std::cmp::Ordering;
8use std::collections::TryReserveError;
9use std::convert::Infallible;
10use std::fmt::Formatter;
11use std::sync::Arc;
12
13use arrow_array::cast::AsArray;
14use arrow_array::temporal_conversions::{NANOSECONDS, SECONDS_IN_DAY};
15use arrow_array::timezone::Tz;
16use arrow_array::types::*;
17use arrow_array::*;
18use arrow_buffer::{
19    ArrowNativeType, BooleanBuffer, DivisorI32, DivisorI64, DivisorU32, DivisorU64,
20    IntervalDayTime, IntervalMonthDayNano, NullBuffer, i256,
21};
22use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
23use num_traits::{CheckedMul, ToPrimitive};
24
25use crate::arity::{binary, try_binary};
26
27/// Perform `lhs + rhs`, returning an error on overflow
28pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
29    arithmetic_op(Op::Add, lhs, rhs)
30}
31
32/// Perform `lhs + rhs`, wrapping on overflow for [`DataType::is_integer`]
33pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
34    arithmetic_op(Op::AddWrapping, lhs, rhs)
35}
36
37/// Perform `lhs - rhs`, returning an error on overflow
38pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
39    arithmetic_op(Op::Sub, lhs, rhs)
40}
41
42/// Perform `lhs - rhs`, wrapping on overflow for [`DataType::is_integer`]
43pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
44    arithmetic_op(Op::SubWrapping, lhs, rhs)
45}
46
47/// Perform `lhs * rhs`, returning an error on overflow
48pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
49    arithmetic_op(Op::Mul, lhs, rhs)
50}
51
52/// Perform `lhs * rhs`, wrapping on overflow for [`DataType::is_integer`]
53pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
54    arithmetic_op(Op::MulWrapping, lhs, rhs)
55}
56
57/// Perform `lhs / rhs`
58///
59/// Overflow or division by zero will result in an error, with exception to
60/// floating point numbers, which instead follow the IEEE 754 rules
61pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
62    arithmetic_op(Op::Div, lhs, rhs)
63}
64
65/// Perform `lhs % rhs`
66///
67/// Division by zero will result in an error, with exception to
68/// floating point numbers, which instead follow the IEEE 754 rules
69///
70/// `signed_integer::MIN % -1` will not result in an error but return 0
71pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
72    arithmetic_op(Op::Rem, lhs, rhs)
73}
74
75macro_rules! neg_checked {
76    ($t:ty, $a:ident) => {{
77        let array = $a
78            .as_primitive::<$t>()
79            .try_unary::<_, $t, _>(|x| x.neg_checked())?;
80        Ok(Arc::new(array))
81    }};
82}
83
84macro_rules! neg_wrapping {
85    ($t:ty, $a:ident) => {{
86        let array = $a.as_primitive::<$t>().unary::<_, $t>(|x| x.neg_wrapping());
87        Ok(Arc::new(array))
88    }};
89}
90
91/// Negates each element of  `array`, returning an error on overflow
92///
93/// Note: negation of unsigned arrays is not supported and will return in an error,
94/// for wrapping unsigned negation consider using [`neg_wrapping`][neg_wrapping()]
95pub fn neg(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
96    use DataType::*;
97    use IntervalUnit::*;
98    use TimeUnit::*;
99
100    match array.data_type() {
101        Int8 => neg_checked!(Int8Type, array),
102        Int16 => neg_checked!(Int16Type, array),
103        Int32 => neg_checked!(Int32Type, array),
104        Int64 => neg_checked!(Int64Type, array),
105        Float16 => neg_wrapping!(Float16Type, array),
106        Float32 => neg_wrapping!(Float32Type, array),
107        Float64 => neg_wrapping!(Float64Type, array),
108        Decimal32(p, s) => {
109            let a = array
110                .as_primitive::<Decimal32Type>()
111                .try_unary::<_, Decimal32Type, _>(|x| x.neg_checked())?;
112
113            Ok(Arc::new(a.with_precision_and_scale(*p, *s)?))
114        }
115        Decimal64(p, s) => {
116            let a = array
117                .as_primitive::<Decimal64Type>()
118                .try_unary::<_, Decimal64Type, _>(|x| x.neg_checked())?;
119
120            Ok(Arc::new(a.with_precision_and_scale(*p, *s)?))
121        }
122        Decimal128(p, s) => {
123            let a = array
124                .as_primitive::<Decimal128Type>()
125                .try_unary::<_, Decimal128Type, _>(|x| x.neg_checked())?;
126
127            Ok(Arc::new(a.with_precision_and_scale(*p, *s)?))
128        }
129        Decimal256(p, s) => {
130            let a = array
131                .as_primitive::<Decimal256Type>()
132                .try_unary::<_, Decimal256Type, _>(|x| x.neg_checked())?;
133
134            Ok(Arc::new(a.with_precision_and_scale(*p, *s)?))
135        }
136        Duration(Second) => neg_checked!(DurationSecondType, array),
137        Duration(Millisecond) => neg_checked!(DurationMillisecondType, array),
138        Duration(Microsecond) => neg_checked!(DurationMicrosecondType, array),
139        Duration(Nanosecond) => neg_checked!(DurationNanosecondType, array),
140        Interval(YearMonth) => neg_checked!(IntervalYearMonthType, array),
141        Interval(DayTime) => {
142            let a = array
143                .as_primitive::<IntervalDayTimeType>()
144                .try_unary::<_, IntervalDayTimeType, ArrowError>(|x| {
145                    let (days, ms) = IntervalDayTimeType::to_parts(x);
146                    Ok(IntervalDayTimeType::make_value(
147                        days.neg_checked()?,
148                        ms.neg_checked()?,
149                    ))
150                })?;
151            Ok(Arc::new(a))
152        }
153        Interval(MonthDayNano) => {
154            let a = array
155                .as_primitive::<IntervalMonthDayNanoType>()
156                .try_unary::<_, IntervalMonthDayNanoType, ArrowError>(|x| {
157                    let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(x);
158                    Ok(IntervalMonthDayNanoType::make_value(
159                        months.neg_checked()?,
160                        days.neg_checked()?,
161                        nanos.neg_checked()?,
162                    ))
163                })?;
164            Ok(Arc::new(a))
165        }
166        t => Err(ArrowError::InvalidArgumentError(format!(
167            "Invalid arithmetic operation: !{t}"
168        ))),
169    }
170}
171
172/// Negates each element of  `array`, wrapping on overflow for [`DataType::is_integer`]
173pub fn neg_wrapping(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
174    downcast_integer! {
175        array.data_type() => (neg_wrapping, array),
176        _ => neg(array),
177    }
178}
179
180/// An enumeration of arithmetic operations
181///
182/// This allows sharing the type dispatch logic across the various kernels
183#[derive(Debug, Copy, Clone)]
184enum Op {
185    AddWrapping,
186    Add,
187    SubWrapping,
188    Sub,
189    MulWrapping,
190    Mul,
191    Div,
192    Rem,
193}
194
195impl std::fmt::Display for Op {
196    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
197        match self {
198            Op::AddWrapping | Op::Add => write!(f, "+"),
199            Op::SubWrapping | Op::Sub => write!(f, "-"),
200            Op::MulWrapping | Op::Mul => write!(f, "*"),
201            Op::Div => write!(f, "/"),
202            Op::Rem => write!(f, "%"),
203        }
204    }
205}
206
207impl Op {
208    fn commutative(&self) -> bool {
209        matches!(
210            self,
211            Self::Add | Self::AddWrapping | Self::Mul | Self::MulWrapping
212        )
213    }
214}
215
216/// Dispatch the given `op` to the appropriate specialized kernel
217fn arithmetic_op(op: Op, lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
218    use DataType::*;
219    use IntervalUnit::*;
220    use TimeUnit::*;
221
222    macro_rules! integer_helper {
223        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
224            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
225        };
226    }
227
228    let (l, l_scalar) = lhs.get();
229    let (r, r_scalar) = rhs.get();
230    if matches!(op, Op::Div | Op::Rem) && !l_scalar && r_scalar {
231        let array = match (l.data_type(), r.data_type()) {
232            (Int32, Int32) => divisor_op_i32(op, l, r),
233            (Int64, Int64) => divisor_op_i64(op, l, r),
234            (UInt32, UInt32) => divisor_op_u32(op, l, r),
235            (UInt64, UInt64) => divisor_op_u64(op, l, r),
236            _ => None,
237        };
238        if let Some(array) = array {
239            return Ok(array);
240        }
241    }
242    downcast_integer! {
243        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
244        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
245        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
246        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
247        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
248        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
249        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
250        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
251        (Duration(Second), Duration(Second)) => duration_op::<DurationSecondType>(op, l, l_scalar, r, r_scalar),
252        (Duration(Millisecond), Duration(Millisecond)) => duration_op::<DurationMillisecondType>(op, l, l_scalar, r, r_scalar),
253        (Duration(Microsecond), Duration(Microsecond)) => duration_op::<DurationMicrosecondType>(op, l, l_scalar, r, r_scalar),
254        (Duration(Nanosecond), Duration(Nanosecond)) => duration_op::<DurationNanosecondType>(op, l, l_scalar, r, r_scalar),
255        (Interval(YearMonth), Interval(YearMonth) | Int64) => interval_op::<IntervalYearMonthType>(op, l, l_scalar, r, r_scalar),
256        (Interval(DayTime), Interval(DayTime) | Int64) => interval_op::<IntervalDayTimeType>(op, l, l_scalar, r, r_scalar),
257        (Interval(MonthDayNano), Interval(MonthDayNano) | Int64) => interval_op::<IntervalMonthDayNanoType>(op, l, l_scalar, r, r_scalar),
258        (Interval(MonthDayNano), Float64) => interval_f64_op(op, l, l_scalar, r, r_scalar),
259        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
260        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
261        (Decimal32(_, _), Decimal32(_, _)) => decimal_op::<Decimal32Type>(op, l, l_scalar, r, r_scalar),
262        (Decimal64(_, _), Decimal64(_, _)) => decimal_op::<Decimal64Type>(op, l, l_scalar, r, r_scalar),
263        (Decimal128(_, _), Decimal128(_, _)) => decimal_op::<Decimal128Type>(op, l, l_scalar, r, r_scalar),
264        (Decimal256(_, _), Decimal256(_, _)) => decimal_op::<Decimal256Type>(op, l, l_scalar, r, r_scalar),
265        (l_t, r_t) => match (l_t, r_t) {
266            (Duration(_) | Interval(_), Date32 | Date64 | Timestamp(_, _)) if op.commutative() => {
267                arithmetic_op(op, rhs, lhs)
268            }
269            (Int64, Interval(_)) | (Float64, Interval(MonthDayNano))
270                if matches!(op, Op::Mul) =>
271            {
272                arithmetic_op(op, rhs, lhs)
273            }
274            _ => Err(ArrowError::InvalidArgumentError(
275              format!("Invalid arithmetic operation: {l_t} {op} {r_t}")
276            ))
277        }
278    }
279}
280
281/// Perform an infallible binary operation on potentially scalar inputs
282macro_rules! op {
283    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
284        match ($l_s, $r_s) {
285            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
286            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
287                None => PrimitiveArray::new_null($r.len()),
288                Some($l) => $r.unary(|$r| $op),
289            },
290            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
291                None => PrimitiveArray::new_null($l.len()),
292                Some($r) => $l.unary(|$l| $op),
293            },
294        }
295    };
296}
297
298/// Same as `op` but with a type hint for the returned array
299macro_rules! op_ref {
300    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
301        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
302        Arc::new(array)
303    }};
304}
305
306/// Perform a fallible binary operation on potentially scalar inputs
307macro_rules! try_op {
308    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
309        match ($l_s, $r_s) {
310            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
311            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
312                None => PrimitiveArray::new_null($r.len()),
313                Some($l) => $r.try_unary(|$r| $op)?,
314            },
315            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
316                None => PrimitiveArray::new_null($l.len()),
317                Some($r) => $l.try_unary(|$l| $op)?,
318            },
319        }
320    };
321}
322
323/// Same as `try_op` but with a type hint for the returned array
324macro_rules! try_op_ref {
325    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
326        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
327        Arc::new(array)
328    }};
329}
330
331/// Wrapping `+`, `-` and `*` that also report whether they overflowed, written
332/// so that LLVM vectorizes a loop over them.
333///
334/// The signed `overflowing_add` and `overflowing_sub` lower to
335/// `llvm.sadd.with.overflow` and `llvm.ssub.with.overflow`, which LLVM doesn't
336/// vectorize, so the signed impls test the sign bits instead.
337trait OverflowingOp: Sized {
338    /// Whether the checked kernels use the one-pass path for this type. When
339    /// it's false, [`overflowing_op`] returns `None` without doing any work.
340    const ONE_PASS: bool = true;
341
342    fn add_overflowing(self, rhs: Self) -> (Self, bool);
343    fn sub_overflowing(self, rhs: Self) -> (Self, bool);
344    fn mul_overflowing(self, rhs: Self) -> (Self, bool);
345}
346
347macro_rules! signed_overflowing_op {
348    ($($t:ty $(=> $wide:ty)?),*) => {$(
349        impl OverflowingOp for $t {
350            #[inline]
351            fn add_overflowing(self, rhs: Self) -> (Self, bool) {
352                let sum = self.wrapping_add(rhs);
353                // Overflow iff both operands have the same sign and `sum` has the other.
354                (sum, (self ^ sum) & (rhs ^ sum) < 0)
355            }
356
357            #[inline]
358            fn sub_overflowing(self, rhs: Self) -> (Self, bool) {
359                let difference = self.wrapping_sub(rhs);
360                // Overflow iff the operands have different signs and `difference`
361                // doesn't have the sign of `self`.
362                (difference, (self ^ rhs) & (self ^ difference) < 0)
363            }
364
365            #[inline]
366            fn mul_overflowing(self, rhs: Self) -> (Self, bool) {
367                signed_mul_overflowing!(self, rhs, $t $(, $wide)?)
368            }
369        }
370    )*};
371}
372
373/// The wrapping product of two signed integers and whether it overflowed.
374macro_rules! signed_mul_overflowing {
375    // The truncating cast is the wrapping product. It overflowed iff widening
376    // it back doesn't give the full product.
377    ($l:expr, $r:expr, $t:ty, $wide:ty) => {{
378        let product = <$wide>::from($l) * <$wide>::from($r);
379        (product as $t, <$wide>::from(product as $t) != product)
380    }};
381    // Widened to `i128`, an `i64` multiply stays a scalar `imul` on x86-64, and
382    // LLVM packs each row's overflow flag into vector registers around it,
383    // which made the loop slower than the checked kernel with
384    // `-C target-cpu=x86-64-v3`.
385    ($l:expr, $r:expr, $t:ty) => {
386        $l.overflowing_mul($r)
387    };
388}
389
390signed_overflowing_op!(i8 => i16, i16 => i32, i32 => i64, i64);
391
392macro_rules! unsigned_overflowing_op {
393    ($($t:ty),*) => {$(
394        // LLVM vectorizes the unsigned `overflowing_add` and `overflowing_sub`.
395        // It folds a widening unsigned multiply back into `llvm.umul.with.overflow`,
396        // which it doesn't vectorize, so `mul` stays scalar either way.
397        impl OverflowingOp for $t {
398            #[inline]
399            fn add_overflowing(self, rhs: Self) -> (Self, bool) {
400                self.overflowing_add(rhs)
401            }
402
403            #[inline]
404            fn sub_overflowing(self, rhs: Self) -> (Self, bool) {
405                self.overflowing_sub(rhs)
406            }
407
408            #[inline]
409            fn mul_overflowing(self, rhs: Self) -> (Self, bool) {
410                self.overflowing_mul(rhs)
411            }
412        }
413    )*};
414}
415
416unsigned_overflowing_op!(u8, u16, u32, u64);
417
418/// Applies `op` to every slot of `l` and `r`, including null slots, without
419/// branching on overflow.
420///
421/// Returns `Ok(None)` if a valid row overflowed or the array lengths differ,
422/// so the caller can fall back to the checked kernel to report the error.
423fn overflowing_op<T, F>(
424    l: &PrimitiveArray<T>,
425    l_s: bool,
426    r: &PrimitiveArray<T>,
427    r_s: bool,
428    op: F,
429) -> Result<Option<PrimitiveArray<T>>, ArrowError>
430where
431    T: ArrowPrimitiveType,
432    T::Native: OverflowingOp,
433    F: Fn(T::Native, T::Native) -> (T::Native, bool),
434{
435    if !T::Native::ONE_PASS {
436        return Ok(None);
437    }
438    match (l_s, r_s) {
439        (true, true) | (false, false) => {
440            if l.len() != r.len() {
441                return Ok(None);
442            }
443            let pairs = l.values().iter().zip(r.values());
444            let values = collect_overflowing(pairs.map(|(&l, &r)| op(l, r)))?;
445            let nulls = NullBuffer::union(l.nulls(), r.nulls());
446            let (l, r) = (l.values(), r.values());
447            Ok(unless_valid_overflow(values, nulls, |i| op(l[i], r[i]).1))
448        }
449        (true, false) => match (l.null_count() == 0).then(|| l.value(0)) {
450            None => Ok(Some(PrimitiveArray::new_null(r.len()))),
451            Some(l) => {
452                let values = collect_overflowing(r.values().iter().map(|&r| op(l, r)))?;
453                let (nulls, r) = (r.nulls().cloned(), r.values());
454                Ok(unless_valid_overflow(values, nulls, |i| op(l, r[i]).1))
455            }
456        },
457        (false, true) => match (r.null_count() == 0).then(|| r.value(0)) {
458            None => Ok(Some(PrimitiveArray::new_null(l.len()))),
459            Some(r) => {
460                let values = collect_overflowing(l.values().iter().map(|&l| op(l, r)))?;
461                let (nulls, l) = (l.nulls().cloned(), l.values());
462                Ok(unless_valid_overflow(values, nulls, |i| op(l[i], r).1))
463            }
464        },
465    }
466}
467
468/// Builds the array from the output of [`collect_overflowing`], or returns
469/// `None` if a valid row overflowed.
470///
471/// A null slot can hold any value, such as the 0 that builders write, which
472/// overflows unsigned `0 - 1`. So when a slot overflowed, this recomputes the
473/// overflow of every row with `overflowed` and masks it with the validity
474/// bits, instead of making the caller rerun the whole batch.
475fn unless_valid_overflow<T: ArrowPrimitiveType>(
476    (values, overflow): (Vec<T::Native>, bool),
477    nulls: Option<NullBuffer>,
478    overflowed: impl Fn(usize) -> bool,
479) -> Option<PrimitiveArray<T>> {
480    let valid_overflow = overflow
481        && nulls
482            .as_ref()
483            .is_none_or(|n| any_valid(n, &BooleanBuffer::collect_bool(n.len(), overflowed)));
484    (!valid_overflow).then(|| PrimitiveArray::new(values.into(), nulls))
485}
486
487/// Whether any valid row of `nulls` is set in `overflowed`
488fn any_valid(nulls: &NullBuffer, overflowed: &BooleanBuffer) -> bool {
489    let valid = nulls.inner().bit_chunks().iter_padded();
490    valid
491        .zip(overflowed.bit_chunks().iter_padded())
492        .any(|(v, o)| v & o != 0)
493}
494
495/// Converts an allocation failure in [`collect_overflowing`].
496///
497/// One shared, out-of-line copy keeps the formatting code out of every
498/// instance of [`collect_overflowing`], as [`mul_checked_cold`] does for the
499/// decimal `div` and `rem` closures.
500#[cold]
501#[inline(never)]
502fn memory_error(e: TryReserveError) -> ArrowError {
503    ArrowError::MemoryError(e.to_string())
504}
505
506/// Collects the values of `iter`, and whether any was flagged as overflowed.
507///
508/// This intentional `inline(never)` keeps `overflow` in a register. Inlined
509/// into its caller under thin LTO, LLVM keeps the flag in memory and loads
510/// and stores it on every row, which serializes the loop and keeps it from
511/// vectorizing. The loop writes into the `Vec`'s spare capacity itself,
512/// because whether LLVM inlines the loop inside `collect` depends on the
513/// closure and the target, and when it doesn't, that loop reaches the flag
514/// through a pointer. The checked `add` cases of the `arithmetic_kernels`
515/// benchmark measure this.
516#[inline(never)]
517fn collect_overflowing<N>(
518    iter: impl ExactSizeIterator<Item = (N, bool)>,
519) -> Result<(Vec<N>, bool), ArrowError> {
520    let mut values = Vec::new();
521    values.try_reserve_exact(iter.len()).map_err(memory_error)?;
522    let mut overflow = false;
523    let mut written = 0;
524    for (slot, (value, overflowed)) in values.spare_capacity_mut().iter_mut().zip(iter) {
525        slot.write(value);
526        overflow |= overflowed;
527        written += 1;
528    }
529    debug_assert!(written <= values.capacity());
530    // SAFETY: the loop initialized the first `written` slots of the spare
531    // capacity, and `written` counts those writes, so it doesn't rely on
532    // `iter.len()`.
533    unsafe { values.set_len(written) };
534    Ok((values, overflow))
535}
536
537// No vector lanes are 128 or 256 bits wide, so loops over these types stay
538// scalar. Their `overflowing_*` methods don't branch on overflow, which still
539// removes the early return of the checked kernel.
540impl OverflowingOp for i128 {
541    #[inline]
542    fn add_overflowing(self, rhs: Self) -> (Self, bool) {
543        self.overflowing_add(rhs)
544    }
545
546    #[inline]
547    fn sub_overflowing(self, rhs: Self) -> (Self, bool) {
548        self.overflowing_sub(rhs)
549    }
550
551    #[inline]
552    fn mul_overflowing(self, rhs: Self) -> (Self, bool) {
553        // Decimal values usually fit in 64 bits, and the product of two `i64`
554        // can't overflow `i128`, so this skips the full 128-bit multiply.
555        match (i64::try_from(self), i64::try_from(rhs)) {
556            (Ok(l), Ok(r)) => (i128::from(l) * i128::from(r), false),
557            _ => self.overflowing_mul(rhs),
558        }
559    }
560}
561
562// On `x86-64-v3`, LLVM vectorizes the one-pass `i256` add loop by packing the
563// carries into vector registers, which is slower than the checked kernel.
564impl OverflowingOp for i256 {
565    const ONE_PASS: bool = false;
566
567    #[inline]
568    fn add_overflowing(self, rhs: Self) -> (Self, bool) {
569        self.overflowing_add(rhs)
570    }
571
572    #[inline]
573    fn sub_overflowing(self, rhs: Self) -> (Self, bool) {
574        self.overflowing_sub(rhs)
575    }
576
577    #[inline]
578    fn mul_overflowing(self, rhs: Self) -> (Self, bool) {
579        // `i256` has no `overflowing_mul`.
580        match self.checked_mul(rhs) {
581            Some(product) => (product, false),
582            None => (self.wrapping_mul(rhs), true),
583        }
584    }
585}
586
587/// Multiplies `l` by `mul`, then applies `op`, reporting whether either step
588/// overflowed. With unequal scales only the operand with the smaller scale is
589/// multiplied, because the other multiplier is one.
590#[inline]
591fn rescale_left<N: OverflowingOp>(l: N, mul: N, r: N, op: impl Fn(N, N) -> (N, bool)) -> (N, bool) {
592    let (l, l_overflow) = l.mul_overflowing(mul);
593    let (value, overflow) = op(l, r);
594    (value, l_overflow | overflow)
595}
596
597/// Like [`rescale_left`], but multiplies `r` by `mul`.
598#[inline]
599fn rescale_right<N: OverflowingOp>(
600    l: N,
601    r: N,
602    mul: N,
603    op: impl Fn(N, N) -> (N, bool),
604) -> (N, bool) {
605    let (r, r_overflow) = r.mul_overflowing(mul);
606    let (value, overflow) = op(l, r);
607    (value, r_overflow | overflow)
608}
609
610/// Multiplies the value of the decimal scalar `array` by `mul`, so that the
611/// kernel doesn't rescale it on every row.
612///
613/// Returns `None` if `array` isn't a valid scalar, `mul` is one, the product
614/// overflows, or its allocation fails. The kernel then rescales the scalar on
615/// every row, so that an overflow is an error only if a valid row needs the
616/// value, and an allocation failure reaches the kernel's fallible reservation.
617fn rescale_scalar<T: ArrowPrimitiveType>(
618    array: &PrimitiveArray<T>,
619    is_scalar: bool,
620    mul: T::Native,
621) -> Option<PrimitiveArray<T>>
622where
623    T::Native: OverflowingOp,
624{
625    if !is_scalar || mul.is_eq(T::Native::ONE) || array.is_null(0) {
626        return None;
627    }
628    let (value, overflow) = array.value(0).mul_overflowing(mul);
629    if overflow {
630        return None;
631    }
632    let mut values = Vec::new();
633    values.try_reserve_exact(1).ok()?;
634    values.push(value);
635    Some(PrimitiveArray::new(values.into(), None))
636}
637
638/// Defines `$fn`, which computes `/` or `%` of an array by a scalar with a precomputed divisor.
639/// It returns `None` for an op other than `/` and `%`, when the scalar is null, or when a value
640/// could fail to divide by it (zero, or `$fallible` for `/`), so that `integer_op` returns an
641/// error only for a valid value that fails. Otherwise no value can fail, and `unary` divides
642/// every slot, null or not, unless the array has more than `$max_nulls` nulls, where dividing
643/// only the valid values with `try_unary` costs less
644macro_rules! divisor_op {
645    (
646        $fn:ident,
647        $t:ty,
648        $divisor:ident,
649        |$d:ident| $fallible:expr,
650        |$len:ident| $max_nulls:expr,
651        [$($variant:ident),+]
652    ) => {
653        fn $fn(op: Op, l: &dyn Array, r: &dyn Array) -> Option<ArrayRef> {
654            let r = r.as_primitive::<$t>();
655            if r.null_count() != 0 {
656                return None;
657            }
658            let $d = r.value(0);
659            if matches!(op, Op::Div) && $fallible {
660                return None;
661            }
662            let divisor = $divisor::new($d)?;
663            let l = l.as_primitive::<$t>();
664            let $len = l.len();
665            if l.null_count() > $max_nulls {
666                // Calling the enum's `wrapping_div_rem`, which matches on the variant, keeps this
667                // to one `try_unary` per op
668                let Ok(array) = match op {
669                    Op::Div => l.try_unary::<_, $t, Infallible>(move |n| {
670                        Ok(divisor.wrapping_div_rem(n).0)
671                    }),
672                    Op::Rem => l.try_unary::<_, $t, Infallible>(move |n| {
673                        Ok(divisor.wrapping_div_rem(n).1)
674                    }),
675                    _ => return None,
676                };
677                return Some(Arc::new(array));
678            }
679            // Match on the variant once, outside the loop, and move it into the closure, so the
680            // loop doesn't branch on the variant. The `Op::Div` and `Op::Rem` arms after the
681            // variants cover variants that arrow-buffer may add later
682            let array: PrimitiveArray<$t> = match (op, divisor) {
683                $(
684                    (Op::Div, $divisor::$variant(d)) => l.unary(move |n| d.wrapping_div_rem(n).0),
685                    (Op::Rem, $divisor::$variant(d)) => l.unary(move |n| d.wrapping_div_rem(n).1),
686                )+
687                (Op::Div, d) => l.unary(move |n| d.wrapping_div_rem(n).0),
688                (Op::Rem, d) => l.unary(move |n| d.wrapping_div_rem(n).1),
689                _ => return None,
690            };
691            Some(Arc::new(array))
692        }
693    };
694}
695
696// `MIN / -1` overflows, but `%` by -1 doesn't, because `integer_op` computes `%` with
697// `mod_wrapping`.
698//
699// `unary` costs the same whatever the nulls, and `try_unary` visits only the valid values. On x86,
700// `unary` is slower than `integer_op`'s `try_unary` with a hardware divide above roughly 60% nulls
701// for `Int32` and `Int64`, so more than half null takes `try_unary`. `UInt32`'s `unary` loop is
702// the cheapest, and on x86 its `try_unary` costs about as much as `integer_op`'s, so it stays on
703// `unary` up to three quarters null. Its `%` on `unary` falls behind `integer_op`'s at roughly 80%
704divisor_op!(
705    divisor_op_i32,
706    Int32Type,
707    DivisorI32,
708    |d| d == -1,
709    |len| len / 2,
710    [PowerOfTwo, AddIndicator]
711);
712divisor_op!(
713    divisor_op_i64,
714    Int64Type,
715    DivisorI64,
716    |d| d == -1,
717    |len| len / 2,
718    [PowerOfTwo, AddIndicator]
719);
720divisor_op!(
721    divisor_op_u32,
722    UInt32Type,
723    DivisorU32,
724    |_d| false,
725    |len| len / 4 * 3,
726    [PowerOfTwo, Up, Down, AddIndicator]
727);
728divisor_op!(
729    divisor_op_u64,
730    UInt64Type,
731    DivisorU64,
732    |_d| false,
733    |len| len / 2,
734    [PowerOfTwo, Up, AddIndicator]
735);
736
737/// Perform an arithmetic operation on integers
738fn integer_op<T>(
739    op: Op,
740    l: &dyn Array,
741    l_s: bool,
742    r: &dyn Array,
743    r_s: bool,
744) -> Result<ArrayRef, ArrowError>
745where
746    T: ArrowPrimitiveType,
747    T::Native: OverflowingOp,
748{
749    let l = l.as_primitive::<T>();
750    let r = r.as_primitive::<T>();
751    let array: PrimitiveArray<T> = match op {
752        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
753        Op::Add => match overflowing_op(l, l_s, r, r_s, T::Native::add_overflowing)? {
754            Some(array) => array,
755            None => try_op!(l, l_s, r, r_s, l.add_checked(r)),
756        },
757        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
758        Op::Sub => match overflowing_op(l, l_s, r, r_s, T::Native::sub_overflowing)? {
759            Some(array) => array,
760            None => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
761        },
762        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
763        Op::Mul => match overflowing_op(l, l_s, r, r_s, T::Native::mul_overflowing)? {
764            Some(array) => array,
765            None => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
766        },
767        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
768        Op::Rem => try_op!(l, l_s, r, r_s, {
769            if r.is_zero() {
770                Err(ArrowError::DivideByZero)
771            } else {
772                Ok(l.mod_wrapping(r))
773            }
774        }),
775    };
776    Ok(Arc::new(array))
777}
778
779/// Perform an arithmetic operation on floats
780fn float_op<T: ArrowPrimitiveType>(
781    op: Op,
782    l: &dyn Array,
783    l_s: bool,
784    r: &dyn Array,
785    r_s: bool,
786) -> Result<ArrayRef, ArrowError> {
787    let l = l.as_primitive::<T>();
788    let r = r.as_primitive::<T>();
789    let array: PrimitiveArray<T> = match op {
790        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),
791        Op::SubWrapping | Op::Sub => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
792        Op::MulWrapping | Op::Mul => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
793        Op::Div => op!(l, l_s, r, r_s, l.div_wrapping(r)),
794        Op::Rem => op!(l, l_s, r, r_s, l.mod_wrapping(r)),
795    };
796    Ok(Arc::new(array))
797}
798
799/// Arithmetic trait for timestamp arrays
800trait TimestampOp: ArrowTimestampType {
801    type Duration: ArrowPrimitiveType<Native = i64>;
802
803    fn add_year_month(timestamp: i64, delta: i32, tz: Tz) -> Option<i64>;
804    fn add_day_time(timestamp: i64, delta: IntervalDayTime, tz: Tz) -> Option<i64>;
805    fn add_month_day_nano(timestamp: i64, delta: IntervalMonthDayNano, tz: Tz) -> Option<i64>;
806
807    fn sub_year_month(timestamp: i64, delta: i32, tz: Tz) -> Option<i64>;
808    fn sub_day_time(timestamp: i64, delta: IntervalDayTime, tz: Tz) -> Option<i64>;
809    fn sub_month_day_nano(timestamp: i64, delta: IntervalMonthDayNano, tz: Tz) -> Option<i64>;
810}
811
812macro_rules! timestamp {
813    ($t:ty, $d:ty) => {
814        impl TimestampOp for $t {
815            type Duration = $d;
816
817            fn add_year_month(left: i64, right: i32, tz: Tz) -> Option<i64> {
818                Self::add_year_months(left, right, tz)
819            }
820
821            fn add_day_time(left: i64, right: IntervalDayTime, tz: Tz) -> Option<i64> {
822                Self::add_day_time(left, right, tz)
823            }
824
825            fn add_month_day_nano(left: i64, right: IntervalMonthDayNano, tz: Tz) -> Option<i64> {
826                Self::add_month_day_nano(left, right, tz)
827            }
828
829            fn sub_year_month(left: i64, right: i32, tz: Tz) -> Option<i64> {
830                Self::subtract_year_months(left, right, tz)
831            }
832
833            fn sub_day_time(left: i64, right: IntervalDayTime, tz: Tz) -> Option<i64> {
834                Self::subtract_day_time(left, right, tz)
835            }
836
837            fn sub_month_day_nano(left: i64, right: IntervalMonthDayNano, tz: Tz) -> Option<i64> {
838                Self::subtract_month_day_nano(left, right, tz)
839            }
840        }
841    };
842}
843timestamp!(TimestampSecondType, DurationSecondType);
844timestamp!(TimestampMillisecondType, DurationMillisecondType);
845timestamp!(TimestampMicrosecondType, DurationMicrosecondType);
846timestamp!(TimestampNanosecondType, DurationNanosecondType);
847
848/// Perform arithmetic operation on a timestamp array
849fn timestamp_op<T: TimestampOp>(
850    op: Op,
851    l: &dyn Array,
852    l_s: bool,
853    r: &dyn Array,
854    r_s: bool,
855) -> Result<ArrayRef, ArrowError> {
856    use DataType::*;
857    use IntervalUnit::*;
858
859    let l = l.as_primitive::<T>();
860    let l_tz: Tz = l.timezone().unwrap_or("+00:00").parse()?;
861
862    let array: PrimitiveArray<T> = match (op, r.data_type()) {
863        (Op::Sub | Op::SubWrapping, Timestamp(unit, _)) if unit == &T::UNIT => {
864            let r = r.as_primitive::<T>();
865            return Ok(try_op_ref!(T::Duration, l, l_s, r, r_s, l.sub_checked(r)));
866        }
867
868        (Op::Add | Op::AddWrapping, Duration(unit)) if unit == &T::UNIT => {
869            let r = r.as_primitive::<T::Duration>();
870            try_op!(l, l_s, r, r_s, l.add_checked(r))
871        }
872        (Op::Sub | Op::SubWrapping, Duration(unit)) if unit == &T::UNIT => {
873            let r = r.as_primitive::<T::Duration>();
874            try_op!(l, l_s, r, r_s, l.sub_checked(r))
875        }
876
877        (Op::Add | Op::AddWrapping, Interval(YearMonth)) => {
878            let r = r.as_primitive::<IntervalYearMonthType>();
879            try_op!(
880                l,
881                l_s,
882                r,
883                r_s,
884                T::add_year_month(l, r, l_tz).ok_or(ArrowError::ComputeError(
885                    "Timestamp out of range".to_string()
886                ))
887            )
888        }
889        (Op::Sub | Op::SubWrapping, Interval(YearMonth)) => {
890            let r = r.as_primitive::<IntervalYearMonthType>();
891            try_op!(
892                l,
893                l_s,
894                r,
895                r_s,
896                T::sub_year_month(l, r, l_tz).ok_or(ArrowError::ComputeError(
897                    "Timestamp out of range".to_string()
898                ))
899            )
900        }
901
902        (Op::Add | Op::AddWrapping, Interval(DayTime)) => {
903            let r = r.as_primitive::<IntervalDayTimeType>();
904            try_op!(
905                l,
906                l_s,
907                r,
908                r_s,
909                T::add_day_time(l, r, l_tz).ok_or(ArrowError::ComputeError(
910                    "Timestamp out of range".to_string()
911                ))
912            )
913        }
914        (Op::Sub | Op::SubWrapping, Interval(DayTime)) => {
915            let r = r.as_primitive::<IntervalDayTimeType>();
916            try_op!(
917                l,
918                l_s,
919                r,
920                r_s,
921                T::sub_day_time(l, r, l_tz).ok_or(ArrowError::ComputeError(
922                    "Timestamp out of range".to_string()
923                ))
924            )
925        }
926
927        (Op::Add | Op::AddWrapping, Interval(MonthDayNano)) => {
928            let r = r.as_primitive::<IntervalMonthDayNanoType>();
929            try_op!(
930                l,
931                l_s,
932                r,
933                r_s,
934                T::add_month_day_nano(l, r, l_tz).ok_or(ArrowError::ComputeError(
935                    "Timestamp out of range".to_string()
936                ))
937            )
938        }
939        (Op::Sub | Op::SubWrapping, Interval(MonthDayNano)) => {
940            let r = r.as_primitive::<IntervalMonthDayNanoType>();
941            try_op!(
942                l,
943                l_s,
944                r,
945                r_s,
946                T::sub_month_day_nano(l, r, l_tz).ok_or(ArrowError::ComputeError(
947                    "Timestamp out of range".to_string()
948                ))
949            )
950        }
951        _ => {
952            return Err(ArrowError::InvalidArgumentError(format!(
953                "Invalid timestamp arithmetic operation: {} {op} {}",
954                l.data_type(),
955                r.data_type()
956            )));
957        }
958    };
959    Ok(Arc::new(array.with_timezone_opt(l.timezone())))
960}
961
962/// Arithmetic trait for date arrays
963trait DateOp: ArrowTemporalType {
964    fn add_year_month(timestamp: Self::Native, delta: i32) -> Result<Self::Native, ArrowError>;
965    fn add_day_time(
966        timestamp: Self::Native,
967        delta: IntervalDayTime,
968    ) -> Result<Self::Native, ArrowError>;
969    fn add_month_day_nano(
970        timestamp: Self::Native,
971        delta: IntervalMonthDayNano,
972    ) -> Result<Self::Native, ArrowError>;
973
974    fn sub_year_month(timestamp: Self::Native, delta: i32) -> Result<Self::Native, ArrowError>;
975    fn sub_day_time(
976        timestamp: Self::Native,
977        delta: IntervalDayTime,
978    ) -> Result<Self::Native, ArrowError>;
979    fn sub_month_day_nano(
980        timestamp: Self::Native,
981        delta: IntervalMonthDayNano,
982    ) -> Result<Self::Native, ArrowError>;
983}
984
985macro_rules! date {
986    ($t:ty) => {
987        impl DateOp for $t {
988            fn add_year_month(left: Self::Native, right: i32) -> Result<Self::Native, ArrowError> {
989                Self::add_year_months_opt(left, right).ok_or_else(|| {
990                    ArrowError::ComputeError(format!(
991                        "Date arithmetic overflow: {left} + {right} months"
992                    ))
993                })
994            }
995
996            fn add_day_time(
997                left: Self::Native,
998                right: IntervalDayTime,
999            ) -> Result<Self::Native, ArrowError> {
1000                Self::add_day_time_opt(left, right).ok_or_else(|| {
1001                    ArrowError::ComputeError(format!(
1002                        "Date arithmetic overflow: {left} + {right:?}"
1003                    ))
1004                })
1005            }
1006
1007            fn add_month_day_nano(
1008                left: Self::Native,
1009                right: IntervalMonthDayNano,
1010            ) -> Result<Self::Native, ArrowError> {
1011                Self::add_month_day_nano_opt(left, right).ok_or_else(|| {
1012                    ArrowError::ComputeError(format!(
1013                        "Date arithmetic overflow: {left} + {right:?}"
1014                    ))
1015                })
1016            }
1017
1018            fn sub_year_month(left: Self::Native, right: i32) -> Result<Self::Native, ArrowError> {
1019                Self::subtract_year_months_opt(left, right).ok_or_else(|| {
1020                    ArrowError::ComputeError(format!(
1021                        "Date arithmetic overflow: {left} - {right} months"
1022                    ))
1023                })
1024            }
1025
1026            fn sub_day_time(
1027                left: Self::Native,
1028                right: IntervalDayTime,
1029            ) -> Result<Self::Native, ArrowError> {
1030                Self::subtract_day_time_opt(left, right).ok_or_else(|| {
1031                    ArrowError::ComputeError(format!(
1032                        "Date arithmetic overflow: {left} - {right:?}"
1033                    ))
1034                })
1035            }
1036
1037            fn sub_month_day_nano(
1038                left: Self::Native,
1039                right: IntervalMonthDayNano,
1040            ) -> Result<Self::Native, ArrowError> {
1041                Self::subtract_month_day_nano_opt(left, right).ok_or_else(|| {
1042                    ArrowError::ComputeError(format!(
1043                        "Date arithmetic overflow: {left} - {right:?}"
1044                    ))
1045                })
1046            }
1047        }
1048    };
1049}
1050
1051date!(Date32Type);
1052date!(Date64Type);
1053
1054/// Arithmetic trait for interval arrays
1055trait IntervalOp: ArrowPrimitiveType {
1056    fn add(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError>;
1057    fn sub(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError>;
1058    fn mul_i64(left: Self::Native, right: i64) -> Result<Self::Native, ArrowError>;
1059}
1060
1061fn mul_i32_i64(left: i32, right: i64) -> Result<i32, ArrowError> {
1062    let value = i64::from(left).mul_checked(right)?;
1063    i32::try_from(value).map_err(|_| {
1064        ArrowError::ArithmeticOverflow(format!("Overflow happened on: {left} * {right}"))
1065    })
1066}
1067
1068impl IntervalOp for IntervalYearMonthType {
1069    fn add(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
1070        left.add_checked(right)
1071    }
1072
1073    fn sub(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
1074        left.sub_checked(right)
1075    }
1076
1077    fn mul_i64(left: Self::Native, right: i64) -> Result<Self::Native, ArrowError> {
1078        mul_i32_i64(left, right)
1079    }
1080}
1081
1082impl IntervalOp for IntervalDayTimeType {
1083    fn add(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
1084        let (l_days, l_ms) = Self::to_parts(left);
1085        let (r_days, r_ms) = Self::to_parts(right);
1086        let days = l_days.add_checked(r_days)?;
1087        let ms = l_ms.add_checked(r_ms)?;
1088        Ok(Self::make_value(days, ms))
1089    }
1090
1091    fn sub(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
1092        let (l_days, l_ms) = Self::to_parts(left);
1093        let (r_days, r_ms) = Self::to_parts(right);
1094        let days = l_days.sub_checked(r_days)?;
1095        let ms = l_ms.sub_checked(r_ms)?;
1096        Ok(Self::make_value(days, ms))
1097    }
1098
1099    fn mul_i64(left: Self::Native, right: i64) -> Result<Self::Native, ArrowError> {
1100        let (days, ms) = Self::to_parts(left);
1101        Ok(Self::make_value(
1102            mul_i32_i64(days, right)?,
1103            mul_i32_i64(ms, right)?,
1104        ))
1105    }
1106}
1107
1108impl IntervalOp for IntervalMonthDayNanoType {
1109    fn add(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
1110        let (l_months, l_days, l_nanos) = Self::to_parts(left);
1111        let (r_months, r_days, r_nanos) = Self::to_parts(right);
1112        let months = l_months.add_checked(r_months)?;
1113        let days = l_days.add_checked(r_days)?;
1114        let nanos = l_nanos.add_checked(r_nanos)?;
1115        Ok(Self::make_value(months, days, nanos))
1116    }
1117
1118    fn sub(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
1119        let (l_months, l_days, l_nanos) = Self::to_parts(left);
1120        let (r_months, r_days, r_nanos) = Self::to_parts(right);
1121        let months = l_months.sub_checked(r_months)?;
1122        let days = l_days.sub_checked(r_days)?;
1123        let nanos = l_nanos.sub_checked(r_nanos)?;
1124        Ok(Self::make_value(months, days, nanos))
1125    }
1126
1127    fn mul_i64(left: Self::Native, right: i64) -> Result<Self::Native, ArrowError> {
1128        let (months, days, nanos) = Self::to_parts(left);
1129        Ok(Self::make_value(
1130            mul_i32_i64(months, right)?,
1131            mul_i32_i64(days, right)?,
1132            nanos.mul_checked(right)?,
1133        ))
1134    }
1135}
1136
1137fn interval_mul_op<T: IntervalOp>(
1138    interval: &dyn Array,
1139    interval_scalar: bool,
1140    factor: &dyn Array,
1141    factor_scalar: bool,
1142) -> Result<ArrayRef, ArrowError> {
1143    let interval = interval.as_primitive::<T>();
1144    let factor = factor.as_primitive::<Int64Type>();
1145    Ok(try_op_ref!(
1146        T,
1147        interval,
1148        interval_scalar,
1149        factor,
1150        factor_scalar,
1151        T::mul_i64(interval, factor)
1152    ))
1153}
1154
1155/// Multiplies an `IntervalMonthDayNano` by an `f64`, mirroring DuckDB's
1156/// `interval_t` layout of months, days, and a sub-day component (nanoseconds in
1157/// Arrow, microseconds in DuckDB).
1158/// <https://github.com/duckdb/duckdb/blob/21aca0424f1faf78b593b1e6fbfdd4846624c987/src/include/duckdb/common/types/interval.hpp#L24-L27>
1159///
1160/// Algorithm:
1161///
1162/// 1. use checked integer multiplication when `factor` fits in `i64` (early return).
1163/// 2. multiply months and days separately
1164/// 3. cascade remainders: convert fractional months to days using 30
1165///    days per month, then fractional days to a sub-day value using 24 hours
1166///    per day.
1167/// 4. combine the cascaded remainder with the scaled input nanoseconds and round ties-to-even at nanosecond precision.
1168/// 5. return an overflow error if any output component is out of
1169///    range.
1170fn interval_mul_f64(
1171    interval: IntervalMonthDayNano,
1172    factor: f64,
1173) -> Result<IntervalMonthDayNano, ArrowError> {
1174    const DAYS_PER_MONTH: f64 = 30.;
1175    const NANOS_PER_SECOND: f64 = NANOSECONDS as f64;
1176    const SECONDS_PER_DAY: f64 = SECONDS_IN_DAY as f64;
1177
1178    // Keep integral factors exact instead of round-tripping i64 nanoseconds through f64.
1179    if factor.fract() == 0.
1180        && let Some(factor) = ToPrimitive::to_i64(&factor)
1181    {
1182        return IntervalMonthDayNanoType::mul_i64(interval, factor);
1183    }
1184
1185    // Based on DuckDB's INTERVAL * DOUBLE implementation, which is referenced from PostgreSQL's interval_mul:
1186    // https://github.com/duckdb/duckdb/blob/21aca0424f1faf78b593b1e6fbfdd4846624c987/src/function/scalar/operator/multiply.cpp#L48-L123
1187    // PostgreSQL's interval_mul:
1188    // https://github.com/postgres/postgres/blob/78758d37306cd89ab060f00cb06f249018d5b8da/src/backend/utils/adt/timestamp.c#L3627-L3744
1189    let overflow =
1190        |component| ArrowError::ArithmeticOverflow(format!("Overflow in interval {component}"));
1191    let timestamp_round =
1192        |value: f64| (value * NANOS_PER_SECOND).round_ties_even() / NANOS_PER_SECOND;
1193
1194    let months_product = f64::from(interval.months) * factor;
1195    if !months_product.is_finite()
1196        || months_product < f64::from(i32::MIN)
1197        || months_product > f64::from(i32::MAX)
1198    {
1199        return Err(overflow("months"));
1200    }
1201    let months = months_product.to_i32().ok_or_else(|| overflow("months"))?;
1202
1203    let days_product = f64::from(interval.days) * factor;
1204    if !days_product.is_finite()
1205        || days_product < f64::from(i32::MIN)
1206        || days_product > f64::from(i32::MAX)
1207    {
1208        return Err(overflow("days"));
1209    }
1210    let mut days = days_product.to_i32().ok_or_else(|| overflow("days"))?;
1211
1212    let month_remainder = timestamp_round(months_product.fract() * DAYS_PER_MONTH);
1213    let month_remainder_days = month_remainder
1214        .to_i32()
1215        .ok_or_else(|| overflow("month remainder"))?;
1216    // Same order of operations as DuckDB; float arithmetic isn't associative and we're aiming
1217    // to replicate DuckDB accuracy
1218    let mut seconds_remainder = timestamp_round(
1219        (days_product - f64::from(days) + month_remainder - f64::from(month_remainder_days))
1220            * SECONDS_PER_DAY,
1221    );
1222
1223    if seconds_remainder.abs() >= SECONDS_PER_DAY {
1224        let remainder_days = (seconds_remainder / SECONDS_PER_DAY)
1225            .to_i32()
1226            .ok_or_else(|| overflow("day remainder"))?;
1227        days = days
1228            .checked_add(remainder_days)
1229            .ok_or_else(|| overflow("days"))?;
1230        seconds_remainder -= f64::from(remainder_days) * SECONDS_PER_DAY;
1231    }
1232    days = days
1233        .checked_add(month_remainder_days)
1234        .ok_or_else(|| overflow("days"))?;
1235
1236    let nanoseconds = ((interval.nanoseconds as f64) * factor
1237        + seconds_remainder * NANOS_PER_SECOND)
1238        .round_ties_even();
1239    let nanoseconds = ToPrimitive::to_i64(&nanoseconds).ok_or_else(|| {
1240        ArrowError::ArithmeticOverflow(format!("Overflow in interval nanoseconds: {nanoseconds}"))
1241    })?;
1242
1243    Ok(IntervalMonthDayNano::new(months, days, nanoseconds))
1244}
1245
1246fn interval_f64_op(
1247    op: Op,
1248    interval: &dyn Array,
1249    interval_scalar: bool,
1250    factor: &dyn Array,
1251    factor_scalar: bool,
1252) -> Result<ArrayRef, ArrowError> {
1253    let interval = interval.as_primitive::<IntervalMonthDayNanoType>();
1254    let factor = factor.as_primitive::<Float64Type>();
1255    Ok(try_op_ref!(
1256        IntervalMonthDayNanoType,
1257        interval,
1258        interval_scalar,
1259        factor,
1260        factor_scalar,
1261        {
1262            match op {
1263                Op::Mul => interval_mul_f64(interval, factor),
1264                Op::Div if factor == 0. => Err(ArrowError::DivideByZero),
1265                // DuckDB defines interval division as multiplication by the reciprocal:
1266                // https://github.com/duckdb/duckdb/blob/21aca0424f1faf78b593b1e6fbfdd4846624c987/src/function/scalar/operator/arithmetic.cpp#L1102-L1110
1267                Op::Div => interval_mul_f64(interval, 1. / factor),
1268                _ => Err(ArrowError::InvalidArgumentError(format!(
1269                    "Invalid interval arithmetic operation: Interval(MonthDayNano) {op} Float64"
1270                ))),
1271            }
1272        }
1273    ))
1274}
1275
1276/// Perform arithmetic operation on an interval array
1277fn interval_op<T: IntervalOp>(
1278    op: Op,
1279    l: &dyn Array,
1280    l_s: bool,
1281    r: &dyn Array,
1282    r_s: bool,
1283) -> Result<ArrayRef, ArrowError> {
1284    match (op, r.data_type()) {
1285        (Op::Add | Op::AddWrapping, data_type) if data_type == l.data_type() => {
1286            let l = l.as_primitive::<T>();
1287            let r = r.as_primitive::<T>();
1288            Ok(try_op_ref!(T, l, l_s, r, r_s, T::add(l, r)))
1289        }
1290        (Op::Sub | Op::SubWrapping, data_type) if data_type == l.data_type() => {
1291            let l = l.as_primitive::<T>();
1292            let r = r.as_primitive::<T>();
1293            Ok(try_op_ref!(T, l, l_s, r, r_s, T::sub(l, r)))
1294        }
1295        (Op::Mul, DataType::Int64) => interval_mul_op::<T>(l, l_s, r, r_s),
1296        _ => Err(ArrowError::InvalidArgumentError(format!(
1297            "Invalid interval arithmetic operation: {} {op} {}",
1298            l.data_type(),
1299            r.data_type()
1300        ))),
1301    }
1302}
1303
1304fn duration_op<T: ArrowPrimitiveType>(
1305    op: Op,
1306    l: &dyn Array,
1307    l_s: bool,
1308    r: &dyn Array,
1309    r_s: bool,
1310) -> Result<ArrayRef, ArrowError> {
1311    let l = l.as_primitive::<T>();
1312    let r = r.as_primitive::<T>();
1313    match op {
1314        Op::Add | Op::AddWrapping => Ok(try_op_ref!(T, l, l_s, r, r_s, l.add_checked(r))),
1315        Op::Sub | Op::SubWrapping => Ok(try_op_ref!(T, l, l_s, r, r_s, l.sub_checked(r))),
1316        _ => Err(ArrowError::InvalidArgumentError(format!(
1317            "Invalid duration arithmetic operation: {} {op} {}",
1318            l.data_type(),
1319            r.data_type()
1320        ))),
1321    }
1322}
1323
1324/// Perform arithmetic operation on a date array
1325fn date_op<T: DateOp>(
1326    op: Op,
1327    l: &dyn Array,
1328    l_s: bool,
1329    r: &dyn Array,
1330    r_s: bool,
1331) -> Result<ArrayRef, ArrowError> {
1332    use DataType::*;
1333    use IntervalUnit::*;
1334
1335    const NUM_SECONDS_IN_DAY: i64 = 60 * 60 * 24;
1336
1337    let r_t = r.data_type();
1338    match (T::DATA_TYPE, op, r_t) {
1339        (Date32, Op::Sub | Op::SubWrapping, Date32) => {
1340            let l = l.as_primitive::<Date32Type>();
1341            let r = r.as_primitive::<Date32Type>();
1342            return Ok(op_ref!(
1343                DurationSecondType,
1344                l,
1345                l_s,
1346                r,
1347                r_s,
1348                ((l as i64) - (r as i64)) * NUM_SECONDS_IN_DAY
1349            ));
1350        }
1351        (Date64, Op::Sub | Op::SubWrapping, Date64) => {
1352            let l = l.as_primitive::<Date64Type>();
1353            let r = r.as_primitive::<Date64Type>();
1354            let result = try_op_ref!(DurationMillisecondType, l, l_s, r, r_s, l.sub_checked(r));
1355            return Ok(result);
1356        }
1357        _ => {}
1358    }
1359
1360    let l = l.as_primitive::<T>();
1361    match (op, r_t) {
1362        (Op::Add | Op::AddWrapping, Interval(YearMonth)) => {
1363            let r = r.as_primitive::<IntervalYearMonthType>();
1364            Ok(try_op_ref!(T, l, l_s, r, r_s, T::add_year_month(l, r)))
1365        }
1366        (Op::Sub | Op::SubWrapping, Interval(YearMonth)) => {
1367            let r = r.as_primitive::<IntervalYearMonthType>();
1368            Ok(try_op_ref!(T, l, l_s, r, r_s, T::sub_year_month(l, r)))
1369        }
1370
1371        (Op::Add | Op::AddWrapping, Interval(DayTime)) => {
1372            let r = r.as_primitive::<IntervalDayTimeType>();
1373            Ok(try_op_ref!(T, l, l_s, r, r_s, T::add_day_time(l, r)))
1374        }
1375        (Op::Sub | Op::SubWrapping, Interval(DayTime)) => {
1376            let r = r.as_primitive::<IntervalDayTimeType>();
1377            Ok(try_op_ref!(T, l, l_s, r, r_s, T::sub_day_time(l, r)))
1378        }
1379
1380        (Op::Add | Op::AddWrapping, Interval(MonthDayNano)) => {
1381            let r = r.as_primitive::<IntervalMonthDayNanoType>();
1382            Ok(try_op_ref!(T, l, l_s, r, r_s, T::add_month_day_nano(l, r)))
1383        }
1384        (Op::Sub | Op::SubWrapping, Interval(MonthDayNano)) => {
1385            let r = r.as_primitive::<IntervalMonthDayNanoType>();
1386            Ok(try_op_ref!(T, l, l_s, r, r_s, T::sub_month_day_nano(l, r)))
1387        }
1388
1389        _ => Err(ArrowError::InvalidArgumentError(format!(
1390            "Invalid date arithmetic operation: {} {op} {}",
1391            l.data_type(),
1392            r.data_type()
1393        ))),
1394    }
1395}
1396
1397/// Returns the scalar divisor `r` scaled by `r_mul`, when `l` is an array and dividing any value
1398/// by it can't fail. That needs `r` to be valid and the product to fit and be neither 0 nor -1.
1399///
1400/// The kernel then needs no per-value checks of the divisor, which keeps the closure small
1401/// enough for LLVM to inline into the loop of `try_unary`. Otherwise it returns `None`, and the
1402/// kernel takes the general path, which reports any errors.
1403fn scalar_divisor<T: DecimalType>(
1404    l_s: bool,
1405    r: &PrimitiveArray<T>,
1406    r_s: bool,
1407    r_mul: T::Native,
1408) -> Option<T::Native>
1409where
1410    T::Native: CheckedMul,
1411{
1412    if l_s || !r_s || r.null_count() != 0 {
1413        return None;
1414    }
1415    let divisor = r.value(0).checked_mul(&r_mul)?;
1416    let minus_one = T::Native::ONE.neg_wrapping();
1417    (!divisor.is_zero() && !divisor.is_eq(minus_one)).then_some(divisor)
1418}
1419
1420/// [`ArrowNativeTypeOp::mul_checked`] out of line, for closures that call it only after
1421/// `checked_mul` overflows, so that building the error doesn't stop them from being inlined
1422#[cold]
1423#[inline(never)]
1424fn mul_checked_cold<T: ArrowNativeTypeOp>(l: T, r: T) -> Result<T, ArrowError> {
1425    l.mul_checked(r)
1426}
1427
1428/// Divides `l * 10^mul_pow` by `r` a digit at a time, without forming the scaled numerator.
1429/// Used when scaling `l` would overflow `T::Native`, which it does well before the quotient
1430/// does.
1431///
1432/// Runs on magnitudes and restores the sign last, so it truncates toward zero.
1433fn scaled_div<T: DecimalType>(
1434    l: T::Native,
1435    r: T::Native,
1436    mul_pow: i8,
1437) -> Result<T::Native, ArrowError> {
1438    let zero = T::Native::ZERO;
1439    let negative = l.is_lt(zero) != r.is_lt(zero);
1440    let dividend = abs_checked::<T>(l)?;
1441    let divisor = abs_checked::<T>(r)?;
1442
1443    let (mut quotient, mut remainder) = dividend.div_rem_checked(divisor)?;
1444    for _ in 0..mul_pow {
1445        // `remainder * 10` overflows for divisors near `T::Native::MAX`, so add the remainder
1446        // ten times and take the divisor off whenever the running sum reaches it.
1447        let mut carried = zero;
1448        let mut digit = zero;
1449        for _ in 0..10 {
1450            let headroom = divisor.sub_wrapping(remainder);
1451            if carried.is_lt(headroom) {
1452                carried = carried.add_wrapping(remainder);
1453            } else {
1454                carried = carried.sub_wrapping(headroom);
1455                digit = digit.add_wrapping(T::Native::ONE);
1456            }
1457        }
1458        quotient = quotient
1459            .mul_checked(T::Native::usize_as(10))?
1460            .add_checked(digit)?;
1461        remainder = carried;
1462    }
1463
1464    if negative {
1465        quotient.neg_checked()
1466    } else {
1467        Ok(quotient)
1468    }
1469}
1470
1471fn abs_checked<T: DecimalType>(value: T::Native) -> Result<T::Native, ArrowError> {
1472    if value.is_lt(T::Native::ZERO) {
1473        value.neg_checked()
1474    } else {
1475        Ok(value)
1476    }
1477}
1478
1479/// Perform arithmetic operation on decimal arrays
1480fn decimal_op<T: DecimalType>(
1481    op: Op,
1482    l: &dyn Array,
1483    l_s: bool,
1484    r: &dyn Array,
1485    r_s: bool,
1486) -> Result<ArrayRef, ArrowError>
1487where
1488    T::Native: CheckedMul + OverflowingOp,
1489{
1490    let l = l.as_primitive::<T>();
1491    let r = r.as_primitive::<T>();
1492
1493    let (p1, s1, p2, s2) = match (l.data_type(), r.data_type()) {
1494        (DataType::Decimal32(p1, s1), DataType::Decimal32(p2, s2)) => (p1, s1, p2, s2),
1495        (DataType::Decimal64(p1, s1), DataType::Decimal64(p2, s2)) => (p1, s1, p2, s2),
1496        (DataType::Decimal128(p1, s1), DataType::Decimal128(p2, s2)) => (p1, s1, p2, s2),
1497        (DataType::Decimal256(p1, s1), DataType::Decimal256(p2, s2)) => (p1, s1, p2, s2),
1498        _ => unreachable!(),
1499    };
1500
1501    // Follow the Hive decimal arithmetic rules
1502    // https://cwiki.apache.org/confluence/download/attachments/27362075/Hive_Decimal_Precision_Scale_Support.pdf
1503    let array: PrimitiveArray<T> = match op {
1504        Op::Add | Op::AddWrapping | Op::Sub | Op::SubWrapping => {
1505            let (p1, s1, p2, s2) = (*p1 as i16, *s1 as i16, *p2 as i16, *s2 as i16);
1506            // max(s1, s2)
1507            let result_scale = s1.max(s2);
1508
1509            // max(s1, s2) + max(p1-s1, p2-s2) + 1
1510            let result_precision =
1511                (result_scale + (p1 - s1).max(p2 - s2) + 1).min(T::MAX_PRECISION as i16) as u8;
1512
1513            let l_mul = T::Native::usize_as(10).pow_checked((result_scale - s1) as _)?;
1514            let r_mul = T::Native::usize_as(10).pow_checked((result_scale - s2) as _)?;
1515
1516            // A scalar with the smaller scale is rescaled once here, rather than
1517            // on every row, which makes its multiplier one.
1518            let (l_rescaled, r_rescaled) =
1519                (rescale_scalar(l, l_s, l_mul), rescale_scalar(r, r_s, r_mul));
1520            let one = T::Native::ONE;
1521            let (l, l_mul) = l_rescaled.as_ref().map_or((l, l_mul), |l| (l, one));
1522            let (r, r_mul) = r_rescaled.as_ref().map_or((r, r_mul), |r| (r, one));
1523            let unscaled = l_mul.is_eq(one) && r_mul.is_eq(one);
1524
1525            // `move` copies the multipliers into the closures. Borrowed, they
1526            // keep the loop from vectorizing under thin LTO, like the borrowed
1527            // captures #11525 fixed in `unary`.
1528            macro_rules! rescaled_op {
1529                ($overflowing:ident, $checked:ident) => {{
1530                    let op = T::Native::$overflowing;
1531                    let array = match s1 < s2 {
1532                        true => overflowing_op(l, l_s, r, r_s, move |l, r| {
1533                            rescale_left(l, l_mul, r, op)
1534                        })?,
1535                        false => overflowing_op(l, l_s, r, r_s, move |l, r| {
1536                            rescale_right(l, r, r_mul, op)
1537                        })?,
1538                    };
1539                    match array {
1540                        Some(array) => array,
1541                        None => try_op!(
1542                            l,
1543                            l_s,
1544                            r,
1545                            r_s,
1546                            l.mul_checked(l_mul)?.$checked(r.mul_checked(r_mul)?)
1547                        ),
1548                    }
1549                }};
1550            }
1551
1552            match op {
1553                Op::Add | Op::AddWrapping if unscaled => {
1554                    match overflowing_op(l, l_s, r, r_s, T::Native::add_overflowing)? {
1555                        Some(array) => array,
1556                        None => try_op!(l, l_s, r, r_s, l.add_checked(r)),
1557                    }
1558                }
1559                Op::Sub | Op::SubWrapping if unscaled => {
1560                    match overflowing_op(l, l_s, r, r_s, T::Native::sub_overflowing)? {
1561                        Some(array) => array,
1562                        None => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
1563                    }
1564                }
1565                Op::Add | Op::AddWrapping => rescaled_op!(add_overflowing, add_checked),
1566                Op::Sub | Op::SubWrapping => rescaled_op!(sub_overflowing, sub_checked),
1567                _ => unreachable!(),
1568            }
1569            .with_precision_and_scale(result_precision, result_scale as i8)?
1570        }
1571        Op::Mul | Op::MulWrapping => {
1572            let result_precision = p1.saturating_add(p2 + 1).min(T::MAX_PRECISION);
1573            let result_scale = *s1 as i16 + *s2 as i16;
1574            if result_scale > T::MAX_SCALE as i16 {
1575                // SQL standard says that if the resulting scale of a multiply operation goes
1576                // beyond the maximum, rounding is not acceptable and thus an error occurs
1577                return Err(ArrowError::InvalidArgumentError(format!(
1578                    "Output scale of {} {op} {} would exceed max scale of {}",
1579                    l.data_type(),
1580                    r.data_type(),
1581                    T::MAX_SCALE
1582                )));
1583            }
1584            let result_scale = i8::try_from(result_scale).map_err(|_| {
1585                ArrowError::InvalidArgumentError(format!(
1586                    "Output scale of {} {op} {} would be less than min scale of {}",
1587                    l.data_type(),
1588                    r.data_type(),
1589                    i8::MIN
1590                ))
1591            })?;
1592
1593            match overflowing_op(l, l_s, r, r_s, T::Native::mul_overflowing)? {
1594                Some(array) => array,
1595                None => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
1596            }
1597            .with_precision_and_scale(result_precision, result_scale)?
1598        }
1599
1600        Op::Div => {
1601            // Follow postgres and MySQL adding a fixed scale increment of 4
1602            // s1 + 4
1603            let result_scale = s1.saturating_add(4).min(T::MAX_SCALE);
1604            let mul_pow = result_scale - s1 + s2;
1605
1606            // p1 - s1 + s2 + result_scale
1607            // Precision must be positive and at least the output scale.
1608            let result_precision = (mul_pow as i16 + *p1 as i16)
1609                .clamp(result_scale.max(1) as i16, T::MAX_PRECISION as i16)
1610                as u8;
1611
1612            let (l_mul, r_mul) = match mul_pow.cmp(&0) {
1613                Ordering::Greater => (
1614                    T::Native::usize_as(10).pow_checked(mul_pow as _)?,
1615                    T::Native::ONE,
1616                ),
1617                Ordering::Equal => (T::Native::ONE, T::Native::ONE),
1618                Ordering::Less => (
1619                    T::Native::ONE,
1620                    T::Native::usize_as(10).pow_checked(mul_pow.neg_wrapping() as _)?,
1621                ),
1622            };
1623
1624            match scalar_divisor(l_s, r, r_s, r_mul) {
1625                Some(divisor) => {
1626                    let r = r.value(0);
1627                    l.try_unary(|l| match l.checked_mul(&l_mul) {
1628                        // `divisor` is neither 0 nor -1, so the division can't fail
1629                        Some(scaled) => Ok(scaled.div_wrapping(divisor)),
1630                        None => scaled_div::<T>(l, r, mul_pow),
1631                    })?
1632                }
1633                None => try_op!(
1634                    l,
1635                    l_s,
1636                    r,
1637                    r_s,
1638                    match l.checked_mul(&l_mul) {
1639                        Some(scaled) => scaled.div_checked(r.mul_checked(r_mul)?),
1640                        None => scaled_div::<T>(l, r, mul_pow),
1641                    }
1642                ),
1643            }
1644            .with_precision_and_scale(result_precision, result_scale)?
1645        }
1646
1647        Op::Rem => {
1648            let (p1, s1, p2, s2) = (*p1 as i16, *s1 as i16, *p2 as i16, *s2 as i16);
1649            // max(s1, s2)
1650            let result_scale = s1.max(s2);
1651            // min(p1-s1, p2 -s2) + max( s1,s2 )
1652            let result_precision =
1653                (result_scale + (p1 - s1).min(p2 - s2)).min(T::MAX_PRECISION as i16) as u8;
1654
1655            let l_mul = T::Native::usize_as(10).pow_checked((result_scale - s1) as _)?;
1656            let r_mul = T::Native::usize_as(10).pow_checked((result_scale - s2) as _)?;
1657
1658            match scalar_divisor(l_s, r, r_s, r_mul) {
1659                // `divisor` is neither 0 nor -1, so the remainder can't fail
1660                Some(divisor) => l.try_unary(|l| match l.checked_mul(&l_mul) {
1661                    Some(scaled) => Ok(scaled.mod_wrapping(divisor)),
1662                    None => mul_checked_cold(l, l_mul).map(|scaled| scaled.mod_wrapping(divisor)),
1663                })?,
1664                None => try_op!(
1665                    l,
1666                    l_s,
1667                    r,
1668                    r_s,
1669                    l.mul_checked(l_mul)?.mod_checked(r.mul_checked(r_mul)?)
1670                ),
1671            }
1672            .with_precision_and_scale(result_precision, result_scale as i8)?
1673        }
1674    };
1675
1676    Ok(Arc::new(array))
1677}
1678
1679#[cfg(test)]
1680mod tests {
1681    use super::*;
1682    use arrow_array::temporal_conversions::{as_date, as_datetime};
1683    use arrow_buffer::{NullBuffer, ScalarBuffer, i256};
1684    use chrono::{DateTime, NaiveDate};
1685
1686    // The valid date range of NaiveDate is from January 1, -262143 to December 31, 262142 (Gregorian calendar).
1687    const MAX_VALID_DATE: NaiveDate = NaiveDate::from_ymd_opt(262142, 12, 31).unwrap();
1688    const MIN_VALID_DATE: NaiveDate = NaiveDate::from_ymd_opt(-262143, 1, 1).unwrap();
1689    const MAX_VALID_MILLIS: i64 = date_to_millis(MAX_VALID_DATE);
1690    const MIN_VALID_MILLIS: i64 = date_to_millis(MIN_VALID_DATE);
1691    const MAX_VALID_DAYS: i32 = date_to_days(MAX_VALID_DATE);
1692    const MIN_VALID_DAYS: i32 = date_to_days(MIN_VALID_DATE);
1693    const EPOCH: NaiveDate = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
1694    const YEAR_2000: NaiveDate = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
1695
1696    const fn date_to_millis(date: NaiveDate) -> i64 {
1697        date.signed_duration_since(EPOCH).num_milliseconds()
1698    }
1699
1700    const fn date_to_days(date: NaiveDate) -> i32 {
1701        date.signed_duration_since(EPOCH).num_days() as i32
1702    }
1703
1704    fn assert_kernel_result<T: ArrowPrimitiveType>(
1705        actual: Result<ArrayRef, ArrowError>,
1706        expected: Result<Vec<Option<T::Native>>, ArrowError>,
1707        context: &str,
1708    ) {
1709        match (actual, expected) {
1710            (Ok(actual), Ok(expected)) => {
1711                let actual: Vec<_> = actual.as_primitive::<T>().iter().collect();
1712                assert_eq!(actual, expected, "{context}");
1713            }
1714            (Err(actual), Err(expected)) => {
1715                assert_eq!(actual.to_string(), expected.to_string(), "{context}")
1716            }
1717            (actual, expected) => panic!("{context}: {actual:?} != {expected:?}"),
1718        }
1719    }
1720
1721    /// Checks `div` and `rem` of `values` by each of `divisors` and by a null divisor, against
1722    /// `div_checked` and `mod_wrapping` on each valid value, as `integer_op` computes them.
1723    /// `values` is repeated to 64 values so that the vectorized loop runs, and is also checked
1724    /// sliced to 50 values, which leaves a remainder for the scalar loop, with seven in eight
1725    /// values null, all null, and empty
1726    fn test_div_rem_by_scalar<T: ArrowPrimitiveType>(
1727        values: &[Option<T::Native>],
1728        divisors: &[T::Native],
1729    ) {
1730        let values: PrimitiveArray<T> = values.iter().cycle().take(64).collect();
1731        let mostly_null = NullBuffer::from_iter((0..values.len()).map(|i| i % 8 == 0));
1732        let arrays = [
1733            values.slice(3, 50),
1734            PrimitiveArray::new(values.values().clone(), Some(mostly_null)),
1735            values.slice(0, 0),
1736            PrimitiveArray::new_null(2),
1737            values,
1738        ];
1739        for array in &arrays {
1740            for &d in divisors {
1741                let divisor = PrimitiveArray::<T>::new_scalar(d);
1742                let expected = array
1743                    .iter()
1744                    .map(|v| v.map(|v| v.div_checked(d)).transpose())
1745                    .collect();
1746                assert_kernel_result::<T>(div(array, &divisor), expected, &format!("/ {d:?}"));
1747                let expected = array
1748                    .iter()
1749                    .map(|v| {
1750                        v.map(|v| match d.is_zero() {
1751                            true => Err(ArrowError::DivideByZero),
1752                            false => Ok(v.mod_wrapping(d)),
1753                        })
1754                        .transpose()
1755                    })
1756                    .collect();
1757                assert_kernel_result::<T>(rem(array, &divisor), expected, &format!("% {d:?}"));
1758            }
1759            // A null divisor gives a null result, whatever its slot holds
1760            for slot in [0, 7] {
1761                let slot = vec![T::Native::usize_as(slot)].into();
1762                let divisor = Scalar::new(PrimitiveArray::<T>::new(
1763                    slot,
1764                    Some(NullBuffer::new_null(1)),
1765                ));
1766                assert_eq!(div(array, &divisor).unwrap().null_count(), array.len());
1767                assert_eq!(rem(array, &divisor).unwrap().null_count(), array.len());
1768            }
1769        }
1770    }
1771
1772    #[test]
1773    fn test_div_rem_by_scalar_integer() {
1774        // 16, 13, 7, -16 and -7 reach each variant of the precomputed divisor. 0, and -1 for `/`, fall back
1775        // to `integer_op`, which returns an error for a valid value and `Ok` otherwise
1776        let values = [
1777            Some(i32::MIN),
1778            Some(i32::MIN + 1),
1779            Some(-7),
1780            None,
1781            Some(0),
1782            Some(13),
1783            Some(i32::MAX),
1784        ];
1785        test_div_rem_by_scalar::<Int32Type>(&values, &[16, 13, 7, -16, -7, 0, -1]);
1786        let values = [
1787            Some(i64::MIN),
1788            Some(i64::MIN + 1),
1789            Some(-7),
1790            None,
1791            Some(0),
1792            Some(13),
1793            Some(i64::MAX),
1794        ];
1795        test_div_rem_by_scalar::<Int64Type>(&values, &[16, 13, 7, -16, -7, 0, -1]);
1796        let values = [
1797            Some(0),
1798            Some(1),
1799            None,
1800            Some(13),
1801            Some(u32::MAX - 1),
1802            Some(u32::MAX),
1803        ];
1804        test_div_rem_by_scalar::<UInt32Type>(&values, &[16, 13, 7, 0]);
1805        let values = [
1806            Some(0),
1807            Some(1),
1808            None,
1809            Some(13),
1810            Some(u64::MAX - 1),
1811            Some(u64::MAX),
1812        ];
1813        test_div_rem_by_scalar::<UInt64Type>(&values, &[16, 13, 7, 0]);
1814    }
1815
1816    fn test_neg_primitive<T: ArrowPrimitiveType>(
1817        input: &[T::Native],
1818        out: Result<&[T::Native], &str>,
1819    ) {
1820        let a = PrimitiveArray::<T>::new(ScalarBuffer::from(input.to_vec()), None);
1821        match out {
1822            Ok(expected) => {
1823                let result = neg(&a).unwrap();
1824                assert_eq!(result.as_primitive::<T>().values(), expected);
1825            }
1826            Err(e) => {
1827                let err = neg(&a).unwrap_err().to_string();
1828                assert_eq!(e, err);
1829            }
1830        }
1831    }
1832
1833    #[test]
1834    fn test_neg() {
1835        let input = &[1, -5, 2, 693, 3929];
1836        let output = &[-1, 5, -2, -693, -3929];
1837        test_neg_primitive::<Int32Type>(input, Ok(output));
1838
1839        let input = &[1, -5, 2, 693, 3929];
1840        let output = &[-1, 5, -2, -693, -3929];
1841        test_neg_primitive::<Int64Type>(input, Ok(output));
1842        test_neg_primitive::<DurationSecondType>(input, Ok(output));
1843        test_neg_primitive::<DurationMillisecondType>(input, Ok(output));
1844        test_neg_primitive::<DurationMicrosecondType>(input, Ok(output));
1845        test_neg_primitive::<DurationNanosecondType>(input, Ok(output));
1846
1847        let input = &[f32::MAX, f32::MIN, f32::INFINITY, 1.3, 0.5];
1848        let output = &[f32::MIN, f32::MAX, f32::NEG_INFINITY, -1.3, -0.5];
1849        test_neg_primitive::<Float32Type>(input, Ok(output));
1850
1851        test_neg_primitive::<Int32Type>(
1852            &[i32::MIN],
1853            Err("Arithmetic overflow: Overflow happened on: - -2147483648"),
1854        );
1855        test_neg_primitive::<Int64Type>(
1856            &[i64::MIN],
1857            Err("Arithmetic overflow: Overflow happened on: - -9223372036854775808"),
1858        );
1859        test_neg_primitive::<DurationSecondType>(
1860            &[i64::MIN],
1861            Err("Arithmetic overflow: Overflow happened on: - -9223372036854775808"),
1862        );
1863
1864        let r = neg_wrapping(&Int32Array::from(vec![i32::MIN])).unwrap();
1865        assert_eq!(r.as_primitive::<Int32Type>().value(0), i32::MIN);
1866
1867        let r = neg_wrapping(&Int64Array::from(vec![i64::MIN])).unwrap();
1868        assert_eq!(r.as_primitive::<Int64Type>().value(0), i64::MIN);
1869
1870        let err = neg_wrapping(&DurationSecondArray::from(vec![i64::MIN]))
1871            .unwrap_err()
1872            .to_string();
1873
1874        assert_eq!(
1875            err,
1876            "Arithmetic overflow: Overflow happened on: - -9223372036854775808"
1877        );
1878
1879        let a = Decimal32Array::from(vec![1, 3, -44, 2, 4])
1880            .with_precision_and_scale(9, 6)
1881            .unwrap();
1882
1883        let r = neg(&a).unwrap();
1884        assert_eq!(r.data_type(), a.data_type());
1885        assert_eq!(
1886            r.as_primitive::<Decimal32Type>().values(),
1887            &[-1, -3, 44, -2, -4]
1888        );
1889
1890        let a = Decimal64Array::from(vec![1, 3, -44, 2, 4])
1891            .with_precision_and_scale(9, 6)
1892            .unwrap();
1893
1894        let r = neg(&a).unwrap();
1895        assert_eq!(r.data_type(), a.data_type());
1896        assert_eq!(
1897            r.as_primitive::<Decimal64Type>().values(),
1898            &[-1, -3, 44, -2, -4]
1899        );
1900
1901        let a = Decimal128Array::from(vec![1, 3, -44, 2, 4])
1902            .with_precision_and_scale(9, 6)
1903            .unwrap();
1904
1905        let r = neg(&a).unwrap();
1906        assert_eq!(r.data_type(), a.data_type());
1907        assert_eq!(
1908            r.as_primitive::<Decimal128Type>().values(),
1909            &[-1, -3, 44, -2, -4]
1910        );
1911
1912        let a = Decimal256Array::from(vec![
1913            i256::from_i128(342),
1914            i256::from_i128(-4949),
1915            i256::from_i128(3),
1916        ])
1917        .with_precision_and_scale(9, 6)
1918        .unwrap();
1919
1920        let r = neg(&a).unwrap();
1921        assert_eq!(r.data_type(), a.data_type());
1922        assert_eq!(
1923            r.as_primitive::<Decimal256Type>().values(),
1924            &[
1925                i256::from_i128(-342),
1926                i256::from_i128(4949),
1927                i256::from_i128(-3),
1928            ]
1929        );
1930
1931        let a = IntervalYearMonthArray::from(vec![
1932            IntervalYearMonthType::make_value(2, 4),
1933            IntervalYearMonthType::make_value(2, -4),
1934            IntervalYearMonthType::make_value(-3, -5),
1935        ]);
1936        let r = neg(&a).unwrap();
1937        assert_eq!(
1938            r.as_primitive::<IntervalYearMonthType>().values(),
1939            &[
1940                IntervalYearMonthType::make_value(-2, -4),
1941                IntervalYearMonthType::make_value(-2, 4),
1942                IntervalYearMonthType::make_value(3, 5),
1943            ]
1944        );
1945
1946        let a = IntervalDayTimeArray::from(vec![
1947            IntervalDayTimeType::make_value(2, 4),
1948            IntervalDayTimeType::make_value(2, -4),
1949            IntervalDayTimeType::make_value(-3, -5),
1950        ]);
1951        let r = neg(&a).unwrap();
1952        assert_eq!(
1953            r.as_primitive::<IntervalDayTimeType>().values(),
1954            &[
1955                IntervalDayTimeType::make_value(-2, -4),
1956                IntervalDayTimeType::make_value(-2, 4),
1957                IntervalDayTimeType::make_value(3, 5),
1958            ]
1959        );
1960
1961        let a = IntervalMonthDayNanoArray::from(vec![
1962            IntervalMonthDayNanoType::make_value(2, 4, 5953394),
1963            IntervalMonthDayNanoType::make_value(2, -4, -45839),
1964            IntervalMonthDayNanoType::make_value(-3, -5, 6944),
1965        ]);
1966        let r = neg(&a).unwrap();
1967        assert_eq!(
1968            r.as_primitive::<IntervalMonthDayNanoType>().values(),
1969            &[
1970                IntervalMonthDayNanoType::make_value(-2, -4, -5953394),
1971                IntervalMonthDayNanoType::make_value(-2, 4, 45839),
1972                IntervalMonthDayNanoType::make_value(3, 5, -6944),
1973            ]
1974        );
1975    }
1976
1977    #[test]
1978    fn test_integer() {
1979        let a = Int32Array::from(vec![4, 3, 5, -6, 100]);
1980        let b = Int32Array::from(vec![6, 2, 5, -7, 3]);
1981        let result = add(&a, &b).unwrap();
1982        assert_eq!(
1983            result.as_ref(),
1984            &Int32Array::from(vec![10, 5, 10, -13, 103])
1985        );
1986        let result = sub(&a, &b).unwrap();
1987        assert_eq!(result.as_ref(), &Int32Array::from(vec![-2, 1, 0, 1, 97]));
1988        let result = div(&a, &b).unwrap();
1989        assert_eq!(result.as_ref(), &Int32Array::from(vec![0, 1, 1, 0, 33]));
1990        let result = mul(&a, &b).unwrap();
1991        assert_eq!(result.as_ref(), &Int32Array::from(vec![24, 6, 25, 42, 300]));
1992        let result = rem(&a, &b).unwrap();
1993        assert_eq!(result.as_ref(), &Int32Array::from(vec![4, 1, 0, -6, 1]));
1994
1995        let a = Int8Array::from(vec![Some(2), None, Some(45)]);
1996        let b = Int8Array::from(vec![Some(5), Some(3), None]);
1997        let result = add(&a, &b).unwrap();
1998        assert_eq!(result.as_ref(), &Int8Array::from(vec![Some(7), None, None]));
1999
2000        let a = UInt8Array::from(vec![56, 5, 3]);
2001        let b = UInt8Array::from(vec![200, 2, 5]);
2002        let err = add(&a, &b).unwrap_err().to_string();
2003        assert_eq!(err, "Arithmetic overflow: Overflow happened on: 56 + 200");
2004        let result = add_wrapping(&a, &b).unwrap();
2005        assert_eq!(result.as_ref(), &UInt8Array::from(vec![0, 7, 8]));
2006
2007        let a = UInt8Array::from(vec![34, 5, 3]);
2008        let b = UInt8Array::from(vec![200, 2, 5]);
2009        let err = sub(&a, &b).unwrap_err().to_string();
2010        assert_eq!(err, "Arithmetic overflow: Overflow happened on: 34 - 200");
2011        let result = sub_wrapping(&a, &b).unwrap();
2012        assert_eq!(result.as_ref(), &UInt8Array::from(vec![90, 3, 254]));
2013
2014        let a = UInt8Array::from(vec![34, 5, 3]);
2015        let b = UInt8Array::from(vec![200, 2, 5]);
2016        let err = mul(&a, &b).unwrap_err().to_string();
2017        assert_eq!(err, "Arithmetic overflow: Overflow happened on: 34 * 200");
2018        let result = mul_wrapping(&a, &b).unwrap();
2019        assert_eq!(result.as_ref(), &UInt8Array::from(vec![144, 10, 15]));
2020
2021        let a = Int16Array::from(vec![i16::MIN]);
2022        let b = Int16Array::from(vec![-1]);
2023        let err = div(&a, &b).unwrap_err().to_string();
2024        assert_eq!(
2025            err,
2026            "Arithmetic overflow: Overflow happened on: -32768 / -1"
2027        );
2028
2029        let a = Int16Array::from(vec![i16::MIN]);
2030        let b = Int16Array::from(vec![-1]);
2031        let result = rem(&a, &b).unwrap();
2032        assert_eq!(result.as_ref(), &Int16Array::from(vec![0]));
2033
2034        let a = Int16Array::from(vec![21]);
2035        let b = Int16Array::from(vec![0]);
2036        let err = div(&a, &b).unwrap_err().to_string();
2037        assert_eq!(err, "Divide by zero error");
2038
2039        let a = Int16Array::from(vec![21]);
2040        let b = Int16Array::from(vec![0]);
2041        let err = rem(&a, &b).unwrap_err().to_string();
2042        assert_eq!(err, "Divide by zero error");
2043    }
2044
2045    /// Checks `add`, `sub` and `mul` against the scalar checked operations for
2046    /// every pair of `edges`, with arrays on both sides and with a scalar on
2047    /// either side.
2048    fn test_checked_integer_ops<T: ArrowPrimitiveType>(edges: &[T::Native]) {
2049        test_checked_integer_op::<T>(edges, add, |l, r| l.add_checked(r));
2050        test_checked_integer_op::<T>(edges, sub, |l, r| l.sub_checked(r));
2051        test_checked_integer_op::<T>(edges, mul, |l, r| l.mul_checked(r));
2052    }
2053
2054    fn test_checked_integer_op<T: ArrowPrimitiveType>(
2055        edges: &[T::Native],
2056        kernel: Kernel,
2057        checked: Checked<T::Native>,
2058    ) {
2059        let (l, r): (Vec<_>, Vec<_>) = edges
2060            .iter()
2061            .flat_map(|&x| edges.iter().map(move |&y| (x, y)))
2062            .unzip();
2063        // With every third row null, null slots also hold values that overflow.
2064        // Without nulls, every pair is checked, because when the number of
2065        // edges is a multiple of 3 the null rows always pair with the same
2066        // right-hand values.
2067        let every_third = NullBuffer::from_iter((0..l.len()).map(|i| i % 3 != 2));
2068        for nulls in [Some(every_third), None] {
2069            let valid = |i| nulls.as_ref().is_none_or(|n| n.is_valid(i));
2070            let l_array = PrimitiveArray::<T>::new(l.clone().into(), nulls.clone());
2071            let r_array = PrimitiveArray::<T>::from_iter_values(r.iter().copied());
2072            let context = if nulls.is_some() { "nulls" } else { "no nulls" };
2073
2074            // The kernels report the first valid row that overflows.
2075            let expected = (0..l.len())
2076                .map(|i| valid(i).then(|| checked(l[i], r[i])).transpose())
2077                .collect();
2078            assert_kernel_result::<T>(
2079                kernel(&l_array, &r_array),
2080                expected,
2081                &format!("{context}: array, array"),
2082            );
2083
2084            // An overflow in one row sends the whole array to the checked kernel,
2085            // which would hide a missed overflow in another row, so also check each
2086            // row alone.
2087            for i in 0..l.len() {
2088                let expected = match valid(i) {
2089                    true => checked(l[i], r[i]).map(|v| vec![Some(v)]),
2090                    false => Ok(vec![None]),
2091                };
2092                let actual = kernel(&l_array.slice(i, 1), &r_array.slice(i, 1));
2093                assert_kernel_result::<T>(actual, expected, &format!("{context}: row {i}"));
2094            }
2095
2096            for &x in edges {
2097                let scalar = PrimitiveArray::<T>::new_scalar(x);
2098                let expected = r.iter().map(|&y| checked(x, y).map(Some)).collect();
2099                assert_kernel_result::<T>(
2100                    kernel(&scalar, &r_array),
2101                    expected,
2102                    &format!("{context}: scalar {x:?}, array"),
2103                );
2104                let expected = (0..l.len())
2105                    .map(|i| valid(i).then(|| checked(l[i], x)).transpose())
2106                    .collect();
2107                assert_kernel_result::<T>(
2108                    kernel(&l_array, &scalar),
2109                    expected,
2110                    &format!("{context}: array, scalar {x:?}"),
2111                );
2112            }
2113        }
2114    }
2115
2116    #[test]
2117    fn test_checked_integer_edges() {
2118        macro_rules! signed {
2119            ($a:ty, $t:ty) => {
2120                test_checked_integer_ops::<$a>(&[
2121                    <$t>::MIN,
2122                    <$t>::MIN + 1,
2123                    <$t>::MIN / 2,
2124                    -3,
2125                    -1,
2126                    0,
2127                    1,
2128                    3,
2129                    <$t>::MAX / 2,
2130                    <$t>::MAX / 2 + 1,
2131                    <$t>::MAX - 1,
2132                    <$t>::MAX,
2133                ])
2134            };
2135        }
2136        macro_rules! unsigned {
2137            ($a:ty, $t:ty) => {
2138                test_checked_integer_ops::<$a>(&[
2139                    0,
2140                    1,
2141                    3,
2142                    <$t>::MAX / 2,
2143                    <$t>::MAX / 2 + 1,
2144                    <$t>::MAX - 1,
2145                    <$t>::MAX,
2146                ])
2147            };
2148        }
2149        signed!(Int8Type, i8);
2150        signed!(Int16Type, i16);
2151        signed!(Int32Type, i32);
2152        signed!(Int64Type, i64);
2153        unsigned!(UInt8Type, u8);
2154        unsigned!(UInt16Type, u16);
2155        unsigned!(UInt32Type, u32);
2156        unsigned!(UInt64Type, u64);
2157    }
2158
2159    /// Moves one row that overflows through a batch, so that each lane of the
2160    /// vector loop and each row of the scalar remainder holds it once, with an
2161    /// array and a scalar on either side. The same row is also checked as a
2162    /// null slot, which is not an error.
2163    fn test_checked_integer_overflow_position<T: ArrowPrimitiveType>() {
2164        // Two iterations of the widest vector loop we build, 32 `i8` lanes of
2165        // AVX2 unrolled four times, plus a remainder.
2166        const LEN: usize = 300;
2167        let one = T::Native::ONE;
2168        // The kernel, its checked scalar operation, the value that overflows,
2169        // and the other operand.
2170        type Case<N> = (Kernel, Checked<N>, N, N);
2171        let cases: [Case<T::Native>; 3] = [
2172            (
2173                add,
2174                |l, r| l.add_checked(r),
2175                T::Native::MAX_TOTAL_ORDER,
2176                one,
2177            ),
2178            (
2179                sub,
2180                |l, r| l.sub_checked(r),
2181                T::Native::MIN_TOTAL_ORDER,
2182                one,
2183            ),
2184            (
2185                mul,
2186                |l, r| l.mul_checked(r),
2187                T::Native::MAX_TOTAL_ORDER,
2188                one.add_wrapping(one),
2189            ),
2190        ];
2191        for (kernel, checked, edge, other) in cases {
2192            let other_array = PrimitiveArray::<T>::from_value(other, LEN);
2193            let other_scalar = PrimitiveArray::<T>::new_scalar(other);
2194            for i in 0..LEN {
2195                let mut values = vec![one; LEN];
2196                values[i] = edge;
2197                for null in [None, Some(i)] {
2198                    let nulls = null.map(|i| NullBuffer::from_iter((0..LEN).map(|j| j != i)));
2199                    let array = PrimitiveArray::<T>::new(values.clone().into(), nulls);
2200                    let expected = |f: &dyn Fn(T::Native) -> Result<T::Native, ArrowError>| {
2201                        (0..LEN)
2202                            .map(|j| match Some(j) == null {
2203                                true => Ok(None),
2204                                false => f(values[j]).map(Some),
2205                            })
2206                            .collect()
2207                    };
2208                    let context = format!("row {i}, null {null:?}");
2209                    assert_kernel_result::<T>(
2210                        kernel(&array, &other_array),
2211                        expected(&|v| checked(v, other)),
2212                        &format!("{context}: array, array"),
2213                    );
2214                    assert_kernel_result::<T>(
2215                        kernel(&other_array, &array),
2216                        expected(&|v| checked(other, v)),
2217                        &format!("{context}: other array, array"),
2218                    );
2219                    assert_kernel_result::<T>(
2220                        kernel(&array, &other_scalar),
2221                        expected(&|v| checked(v, other)),
2222                        &format!("{context}: array, scalar"),
2223                    );
2224                    assert_kernel_result::<T>(
2225                        kernel(&other_scalar, &array),
2226                        expected(&|v| checked(other, v)),
2227                        &format!("{context}: scalar, array"),
2228                    );
2229                }
2230            }
2231        }
2232    }
2233
2234    #[test]
2235    fn test_checked_null_slot_overflow_sliced() {
2236        // Sliced at 3, the validity bits start mid-byte and the 200 rows span
2237        // three full 64-row chunks plus a remainder. Row 5 is null and always
2238        // overflows, so every case checks the valid rows.
2239        const LEN: usize = 203;
2240        let nulls = NullBuffer::from_iter((0..LEN).map(|j| j % 5 != 0));
2241        let one = Int32Array::new_scalar(1);
2242        for i in 3..LEN {
2243            let mut values = vec![1; LEN];
2244            values[5] = i32::MAX;
2245            values[i] = i32::MAX;
2246            let array = Int32Array::new(values.into(), Some(nulls.clone())).slice(3, LEN - 3);
2247            let result = add(&array, &one);
2248            match nulls.is_valid(i) {
2249                true => assert!(result.is_err(), "row {i}"),
2250                false => {
2251                    let expected: Int32Array =
2252                        (3..LEN).map(|j| nulls.is_valid(j).then_some(2)).collect();
2253                    assert_eq!(
2254                        result.unwrap().as_primitive::<Int32Type>(),
2255                        &expected,
2256                        "row {i}"
2257                    );
2258                }
2259            }
2260        }
2261    }
2262
2263    #[test]
2264    #[cfg_attr(miri, ignore)] // Checks the lanes of vectorized loops, which Miri doesn't run
2265    fn test_checked_integer_overflow_positions() {
2266        test_checked_integer_overflow_position::<Int8Type>();
2267        test_checked_integer_overflow_position::<Int16Type>();
2268        test_checked_integer_overflow_position::<Int32Type>();
2269        test_checked_integer_overflow_position::<Int64Type>();
2270        test_checked_integer_overflow_position::<UInt8Type>();
2271        test_checked_integer_overflow_position::<UInt16Type>();
2272        test_checked_integer_overflow_position::<UInt32Type>();
2273        test_checked_integer_overflow_position::<UInt64Type>();
2274    }
2275
2276    #[test]
2277    fn test_checked_integer_slice_null_scalar_and_lengths() {
2278        // Overflowing values outside the slice are not an error.
2279        let array = Int64Array::from(vec![i64::MAX, 1, 2, i64::MAX]).slice(1, 2);
2280        let one = Int64Array::new_scalar(1);
2281        let result = add(&array, &one).unwrap();
2282        assert_eq!(
2283            result.as_primitive::<Int64Type>(),
2284            &Int64Array::from(vec![2, 3])
2285        );
2286
2287        // A null scalar gives an all-null result whatever the array holds.
2288        let null = Scalar::new(Int64Array::new_null(1));
2289        let max = Int64Array::from(vec![i64::MAX; 3]);
2290        assert_eq!(add(&max, &null).unwrap().null_count(), 3);
2291        assert_eq!(mul(&null, &max).unwrap().null_count(), 3);
2292
2293        // An all-null array that overflows in every slot is not an error.
2294        let all_null = Int64Array::new(vec![i64::MAX; 3].into(), Some(NullBuffer::new_null(3)));
2295        assert_eq!(add(&all_null, &one).unwrap().null_count(), 3);
2296
2297        // The builder fills null slots with 0, which overflows `0 - 1`.
2298        let array = UInt64Array::from(vec![Some(10), None, Some(20)]);
2299        assert_eq!(array.values()[1], 0);
2300        let result = sub(&array, &UInt64Array::new_scalar(1)).unwrap();
2301        assert_eq!(
2302            result.as_primitive::<UInt64Type>(),
2303            &UInt64Array::from(vec![Some(9), None, Some(19)])
2304        );
2305
2306        let empty = Int64Array::from(Vec::<i64>::new());
2307        assert!(add(&empty, &empty).unwrap().is_empty());
2308        assert!(sub(&empty, &one).unwrap().is_empty());
2309
2310        let err = add(&Int64Array::from(vec![1, 2]), &Int64Array::from(vec![1])).unwrap_err();
2311        assert_eq!(
2312            err.to_string(),
2313            "Compute error: Cannot perform a binary operation on arrays of different length"
2314        );
2315    }
2316
2317    #[test]
2318    fn test_float() {
2319        let a = Float32Array::from(vec![1., f32::MAX, 6., -4., -1., 0.]);
2320        let b = Float32Array::from(vec![1., f32::MAX, f32::MAX, -3., 45., 0.]);
2321        let result = add(&a, &b).unwrap();
2322        assert_eq!(
2323            result.as_ref(),
2324            &Float32Array::from(vec![2., f32::INFINITY, f32::MAX, -7., 44.0, 0.])
2325        );
2326
2327        let result = sub(&a, &b).unwrap();
2328        assert_eq!(
2329            result.as_ref(),
2330            &Float32Array::from(vec![0., 0., f32::MIN, -1., -46., 0.])
2331        );
2332
2333        let result = mul(&a, &b).unwrap();
2334        assert_eq!(
2335            result.as_ref(),
2336            &Float32Array::from(vec![1., f32::INFINITY, f32::INFINITY, 12., -45., 0.])
2337        );
2338
2339        let result = div(&a, &b).unwrap();
2340        let r = result.as_primitive::<Float32Type>();
2341        assert_eq!(r.value(0), 1.);
2342        assert_eq!(r.value(1), 1.);
2343        assert!(r.value(2) < f32::EPSILON);
2344        assert_eq!(r.value(3), -4. / -3.);
2345        assert!(r.value(5).is_nan());
2346
2347        let result = rem(&a, &b).unwrap();
2348        let r = result.as_primitive::<Float32Type>();
2349        assert_eq!(&r.values()[..5], &[0., 0., 6., -1., -1.]);
2350        assert!(r.value(5).is_nan());
2351    }
2352
2353    #[test]
2354    fn test_decimal() {
2355        // 0.015 7.842 -0.577 0.334 -0.078 0.003
2356        let a = Decimal128Array::from(vec![15, 0, -577, 334, -78, 3])
2357            .with_precision_and_scale(12, 3)
2358            .unwrap();
2359
2360        // 5.4 0 -35.6 0.3 0.6 7.45
2361        let b = Decimal128Array::from(vec![54, 34, -356, 3, 6, 745])
2362            .with_precision_and_scale(12, 1)
2363            .unwrap();
2364
2365        let result = add(&a, &b).unwrap();
2366        assert_eq!(result.data_type(), &DataType::Decimal128(15, 3));
2367        assert_eq!(
2368            result.as_primitive::<Decimal128Type>().values(),
2369            &[5415, 3400, -36177, 634, 522, 74503]
2370        );
2371
2372        let result = sub(&a, &b).unwrap();
2373        assert_eq!(result.data_type(), &DataType::Decimal128(15, 3));
2374        assert_eq!(
2375            result.as_primitive::<Decimal128Type>().values(),
2376            &[-5385, -3400, 35023, 34, -678, -74497]
2377        );
2378
2379        let result = mul(&a, &b).unwrap();
2380        assert_eq!(result.data_type(), &DataType::Decimal128(25, 4));
2381        assert_eq!(
2382            result.as_primitive::<Decimal128Type>().values(),
2383            &[810, 0, 205412, 1002, -468, 2235]
2384        );
2385
2386        let result = div(&a, &b).unwrap();
2387        assert_eq!(result.data_type(), &DataType::Decimal128(17, 7));
2388        assert_eq!(
2389            result.as_primitive::<Decimal128Type>().values(),
2390            &[27777, 0, 162078, 11133333, -1300000, 402]
2391        );
2392
2393        let result = rem(&a, &b).unwrap();
2394        assert_eq!(result.data_type(), &DataType::Decimal128(12, 3));
2395        assert_eq!(
2396            result.as_primitive::<Decimal128Type>().values(),
2397            &[15, 0, -577, 34, -78, 3]
2398        );
2399
2400        let a = Decimal128Array::from(vec![1])
2401            .with_precision_and_scale(3, 3)
2402            .unwrap();
2403        let b = Decimal128Array::from(vec![1])
2404            .with_precision_and_scale(37, 37)
2405            .unwrap();
2406        let err = mul(&a, &b).unwrap_err().to_string();
2407        assert_eq!(
2408            err,
2409            "Invalid argument error: Output scale of Decimal128(3, 3) * Decimal128(37, 37) would exceed max scale of 38"
2410        );
2411
2412        let a = Decimal128Array::from(vec![1])
2413            .with_precision_and_scale(3, -2)
2414            .unwrap();
2415        let err = add(&a, &b).unwrap_err().to_string();
2416        assert_eq!(err, "Arithmetic overflow: Overflow happened on: 10 ^ 39");
2417
2418        let a = Decimal128Array::from(vec![10])
2419            .with_precision_and_scale(3, -1)
2420            .unwrap();
2421        let err = add(&a, &b).unwrap_err().to_string();
2422        assert_eq!(
2423            err,
2424            "Arithmetic overflow: Overflow happened on: 10 * 100000000000000000000000000000000000000"
2425        );
2426
2427        let b = Decimal128Array::from(vec![0])
2428            .with_precision_and_scale(1, 1)
2429            .unwrap();
2430        let err = div(&a, &b).unwrap_err().to_string();
2431        assert_eq!(err, "Divide by zero error");
2432        let err = rem(&a, &b).unwrap_err().to_string();
2433        assert_eq!(err, "Divide by zero error");
2434    }
2435
2436    type Kernel = fn(&dyn Datum, &dyn Datum) -> Result<ArrayRef, ArrowError>;
2437    type Checked<N> = fn(N, N) -> Result<N, ArrowError>;
2438
2439    /// Checks `kernel` against `checked` for every pair of `edges`, with
2440    /// arrays on both sides, with each pair as a one-row slice, and with a
2441    /// scalar on either side. Every third row of the left array is null, so
2442    /// null slots also hold values that overflow.
2443    fn test_checked_decimal_op<T: DecimalType>(
2444        edges: &[T::Native],
2445        (l_scale, r_scale): (i8, i8),
2446        kernel: Kernel,
2447        checked: impl Fn(T::Native, T::Native) -> Result<T::Native, ArrowError>,
2448    ) {
2449        let decimal = |array: PrimitiveArray<T>, scale| {
2450            array
2451                .with_precision_and_scale(T::MAX_PRECISION, scale)
2452                .unwrap()
2453        };
2454        let (l, r): (Vec<_>, Vec<_>) = edges
2455            .iter()
2456            .flat_map(|&x| edges.iter().map(move |&y| (x, y)))
2457            .unzip();
2458        let nulls = NullBuffer::from_iter((0..l.len()).map(|i| i % 3 != 2));
2459        let l_array = decimal(
2460            PrimitiveArray::new(l.clone().into(), Some(nulls.clone())),
2461            l_scale,
2462        );
2463        let r_array = decimal(PrimitiveArray::from_iter_values(r.iter().copied()), r_scale);
2464        let row = |i: usize, x, y| match nulls.is_valid(i) {
2465            true => checked(x, y).map(Some),
2466            false => Ok(None),
2467        };
2468        let context = format!("scales {l_scale} and {r_scale}");
2469
2470        // The kernels report the first valid row that overflows.
2471        let expected = (0..l.len()).map(|i| row(i, l[i], r[i])).collect();
2472        assert_kernel_result::<T>(
2473            kernel(&l_array, &r_array),
2474            expected,
2475            &format!("{context}: array, array"),
2476        );
2477
2478        // An overflow in one row sends the whole array to the checked kernel,
2479        // which would hide a missed overflow in another row, so also check each
2480        // row alone.
2481        for i in 0..l.len() {
2482            let actual = kernel(&l_array.slice(i, 1), &r_array.slice(i, 1));
2483            let expected = row(i, l[i], r[i]).map(|v| vec![v]);
2484            assert_kernel_result::<T>(actual, expected, &format!("{context}: row {i}"));
2485        }
2486
2487        for &x in edges {
2488            let l_scalar = Scalar::new(decimal(PrimitiveArray::from_iter_values([x]), l_scale));
2489            let expected = r.iter().map(|&y| checked(x, y).map(Some)).collect();
2490            assert_kernel_result::<T>(
2491                kernel(&l_scalar, &r_array),
2492                expected,
2493                &format!("{context}: scalar {x:?}, array"),
2494            );
2495            let r_scalar = Scalar::new(decimal(PrimitiveArray::from_iter_values([x]), r_scale));
2496            let expected = (0..l.len()).map(|i| row(i, l[i], x)).collect();
2497            assert_kernel_result::<T>(
2498                kernel(&l_array, &r_scalar),
2499                expected,
2500                &format!("{context}: array, scalar {x:?}"),
2501            );
2502        }
2503    }
2504
2505    /// Checks `add`, `sub` and `mul` of `T` at its edge values, with equal
2506    /// scales and with either side rescaled by 100.
2507    fn test_checked_decimal_ops<T: DecimalType>() {
2508        let one = T::Native::ONE;
2509        let three = T::Native::usize_as(3);
2510        let two = T::Native::usize_as(2);
2511        let hundred = T::Native::usize_as(100);
2512        let (min, max) = (T::Native::MIN_TOTAL_ORDER, T::Native::MAX_TOTAL_ORDER);
2513        let edges = [
2514            min,
2515            min.add_wrapping(one),
2516            min.div_wrapping(two),
2517            min.div_wrapping(hundred),
2518            min.div_wrapping(hundred).sub_wrapping(one),
2519            three.neg_wrapping(),
2520            one.neg_wrapping(),
2521            T::Native::ZERO,
2522            one,
2523            three,
2524            max.div_wrapping(hundred),
2525            max.div_wrapping(hundred).add_wrapping(one),
2526            max.div_wrapping(two),
2527            max.div_wrapping(two).add_wrapping(one),
2528            max.sub_wrapping(one),
2529            max,
2530        ];
2531
2532        for scales in [(2, 2), (2, 4), (4, 2)] {
2533            let (l_mul, r_mul) = match scales {
2534                (2, 4) => (hundred, one),
2535                (4, 2) => (one, hundred),
2536                _ => (one, one),
2537            };
2538            let rescale = move |l: T::Native, r: T::Native| {
2539                Ok::<_, ArrowError>((l.mul_checked(l_mul)?, r.mul_checked(r_mul)?))
2540            };
2541            test_checked_decimal_op::<T>(&edges, scales, add, |l, r| {
2542                let (l, r) = rescale(l, r)?;
2543                l.add_checked(r)
2544            });
2545            test_checked_decimal_op::<T>(&edges, scales, sub, |l, r| {
2546                let (l, r) = rescale(l, r)?;
2547                l.sub_checked(r)
2548            });
2549            test_checked_decimal_op::<T>(&edges, scales, add_wrapping, |l, r| {
2550                let (l, r) = rescale(l, r)?;
2551                l.add_checked(r)
2552            });
2553        }
2554        // Multiplication doesn't rescale its operands.
2555        test_checked_decimal_op::<T>(&edges, (2, 2), mul, |l, r| l.mul_checked(r));
2556        test_checked_decimal_op::<T>(&edges, (2, 4), mul_wrapping, |l, r| l.mul_checked(r));
2557    }
2558
2559    #[test]
2560    fn test_checked_decimal_edges() {
2561        test_checked_decimal_ops::<Decimal32Type>();
2562        test_checked_decimal_ops::<Decimal64Type>();
2563        test_checked_decimal_ops::<Decimal128Type>();
2564        test_checked_decimal_ops::<Decimal256Type>();
2565    }
2566
2567    #[test]
2568    fn test_checked_decimal128_mul_i64_boundary() {
2569        // `i128` multiplies through `i64` when both operands fit, so check both
2570        // sides of each `i64` bound. `i64::MIN * i64::MIN` is 2^126.
2571        let (min, max) = (i64::MIN as i128, i64::MAX as i128);
2572        let edges = [min - 1, min, min + 1, -1, 0, 1, max - 1, max, max + 1];
2573        test_checked_decimal_op::<Decimal128Type>(&edges, (2, 2), mul, |l, r| l.mul_checked(r));
2574        test_checked_decimal_op::<Decimal128Type>(&edges, (2, 4), add, |l, r| {
2575            l.mul_checked(100)?.add_checked(r)
2576        });
2577    }
2578
2579    /// Moves one row that overflows through a batch, so that each lane of the
2580    /// vector loop and each row of the scalar remainder holds it once, with an
2581    /// array and a scalar on either side. The rescaled cases overflow only in
2582    /// the rescale. The same row is also checked as a null slot, which is not
2583    /// an error.
2584    fn test_checked_decimal_overflow_position<T: DecimalType>() {
2585        // Three iterations of the widest vector loop we build, 8 `i32` lanes of
2586        // AVX2 unrolled four times, plus a remainder.
2587        const LEN: usize = 100;
2588        let one = T::Native::ONE;
2589        let two = T::Native::usize_as(2);
2590        let hundred = T::Native::usize_as(100);
2591        let (min, max) = (T::Native::MIN_TOTAL_ORDER, T::Native::MAX_TOTAL_ORDER);
2592        // Multiplying by 100 overflows, but adding or subtracting 1 doesn't.
2593        let rescale_overflow = max.div_wrapping(hundred).add_wrapping(one);
2594        // The kernel, its checked scalar operation, whether it rescales, the
2595        // scales of the batch and the other operand, the value that overflows,
2596        // and the other operand.
2597        type Case<N> = (Kernel, Checked<N>, bool, (i8, i8), N, N);
2598        let cases: [Case<T::Native>; 5] = [
2599            (add, |l, r| l.add_checked(r), true, (2, 2), max, one),
2600            (sub, |l, r| l.sub_checked(r), true, (2, 2), min, one),
2601            (mul, |l, r| l.mul_checked(r), false, (2, 2), max, two),
2602            (
2603                add,
2604                |l, r| l.add_checked(r),
2605                true,
2606                (2, 4),
2607                rescale_overflow,
2608                one,
2609            ),
2610            (
2611                sub,
2612                |l, r| l.sub_checked(r),
2613                true,
2614                (2, 4),
2615                rescale_overflow,
2616                one,
2617            ),
2618        ];
2619        let decimal = |array: PrimitiveArray<T>, scale| {
2620            array
2621                .with_precision_and_scale(T::MAX_PRECISION, scale)
2622                .unwrap()
2623        };
2624        for (kernel, checked, rescales, (batch_scale, other_scale), edge, other) in cases {
2625            // The checked result of `l op r`, rescaling the operand with the smaller scale.
2626            let row = |l: T::Native, l_scale, r: T::Native, r_scale| {
2627                if !rescales {
2628                    return checked(l, r);
2629                }
2630                let l = if l_scale < r_scale {
2631                    l.mul_checked(hundred)?
2632                } else {
2633                    l
2634                };
2635                let r = if r_scale < l_scale {
2636                    r.mul_checked(hundred)?
2637                } else {
2638                    r
2639                };
2640                checked(l, r)
2641            };
2642            let other_array = decimal(PrimitiveArray::from_value(other, LEN), other_scale);
2643            let other_scalar =
2644                Scalar::new(decimal(PrimitiveArray::from_value(other, 1), other_scale));
2645            for i in 0..LEN {
2646                let mut values = vec![one; LEN];
2647                values[i] = edge;
2648                for null in [None, Some(i)] {
2649                    let nulls = null.map(|i| NullBuffer::from_iter((0..LEN).map(|j| j != i)));
2650                    let array = decimal(
2651                        PrimitiveArray::new(values.clone().into(), nulls),
2652                        batch_scale,
2653                    );
2654                    let expected =
2655                        |batch_left: bool| -> Result<Vec<Option<T::Native>>, ArrowError> {
2656                            (0..LEN)
2657                                .map(|j| match (Some(j) == null, batch_left) {
2658                                    (true, _) => Ok(None),
2659                                    (false, true) => {
2660                                        row(values[j], batch_scale, other, other_scale).map(Some)
2661                                    }
2662                                    (false, false) => {
2663                                        row(other, other_scale, values[j], batch_scale).map(Some)
2664                                    }
2665                                })
2666                                .collect()
2667                        };
2668                    let context =
2669                        format!("row {i}, null {null:?}, scales {batch_scale} and {other_scale}");
2670                    assert_kernel_result::<T>(
2671                        kernel(&array, &other_array),
2672                        expected(true),
2673                        &format!("{context}: array, array"),
2674                    );
2675                    assert_kernel_result::<T>(
2676                        kernel(&other_array, &array),
2677                        expected(false),
2678                        &format!("{context}: other array, array"),
2679                    );
2680                    assert_kernel_result::<T>(
2681                        kernel(&array, &other_scalar),
2682                        expected(true),
2683                        &format!("{context}: array, scalar"),
2684                    );
2685                    assert_kernel_result::<T>(
2686                        kernel(&other_scalar, &array),
2687                        expected(false),
2688                        &format!("{context}: scalar, array"),
2689                    );
2690                }
2691            }
2692        }
2693    }
2694
2695    #[test]
2696    fn test_checked_decimal_null_slot_overflow_sliced() {
2697        // Sliced at 3, the validity bits start mid-byte and the 200 rows span
2698        // three full 64-row chunks plus a remainder. Row 5 is null and always
2699        // overflows, so every case checks the valid rows.
2700        const LEN: usize = 203;
2701        let nulls = NullBuffer::from_iter((0..LEN).map(|j| j % 5 != 0));
2702        let decimal = |array: Decimal64Array| array.with_precision_and_scale(18, 2).unwrap();
2703        let one = Scalar::new(decimal(Decimal64Array::from_iter_values([1])));
2704        for i in 3..LEN {
2705            let mut values = vec![1; LEN];
2706            values[5] = i64::MAX;
2707            values[i] = i64::MAX;
2708            let array = decimal(Decimal64Array::new(values.into(), Some(nulls.clone())));
2709            let result = add(&array.slice(3, LEN - 3), &one);
2710            match nulls.is_valid(i) {
2711                true => assert!(result.is_err(), "row {i}"),
2712                false => {
2713                    let actual: Vec<_> = result
2714                        .unwrap()
2715                        .as_primitive::<Decimal64Type>()
2716                        .iter()
2717                        .collect();
2718                    let expected: Vec<_> =
2719                        (3..LEN).map(|j| nulls.is_valid(j).then_some(2)).collect();
2720                    assert_eq!(actual, expected, "row {i}");
2721                }
2722            }
2723        }
2724    }
2725
2726    #[test]
2727    #[cfg_attr(miri, ignore)] // Checks the lanes of vectorized loops, which Miri doesn't run
2728    fn test_checked_decimal_overflow_positions() {
2729        test_checked_decimal_overflow_position::<Decimal32Type>();
2730        test_checked_decimal_overflow_position::<Decimal64Type>();
2731        test_checked_decimal_overflow_position::<Decimal128Type>();
2732        test_checked_decimal_overflow_position::<Decimal256Type>();
2733    }
2734
2735    #[test]
2736    fn test_decimal_rescaled_scalar() {
2737        let decimal = |values: Vec<Option<i128>>, scale| {
2738            Decimal128Array::from(values)
2739                .with_precision_and_scale(38, scale)
2740                .unwrap()
2741        };
2742        let values =
2743            |array: ArrayRef| -> Vec<_> { array.as_primitive::<Decimal128Type>().iter().collect() };
2744        // `col + 1.5` and `1.5 - col`, with `col` at scale 4.
2745        let col = decimal(vec![Some(10_000), None, Some(-25_000)], 4);
2746        let scalar = Scalar::new(decimal(vec![Some(150)], 2));
2747        assert_eq!(
2748            values(add(&col, &scalar).unwrap()),
2749            [Some(25_000), None, Some(-10_000)]
2750        );
2751        assert_eq!(
2752            values(sub(&scalar, &col).unwrap()),
2753            [Some(5_000), None, Some(40_000)]
2754        );
2755
2756        // A scalar whose rescale overflows is an error only if a valid row needs it.
2757        let big_value = i128::MAX / 10;
2758        let big = Scalar::new(decimal(vec![Some(big_value)], 2));
2759        let err = big_value.mul_checked(100).unwrap_err().to_string();
2760        assert_eq!(add(&col, &big).unwrap_err().to_string(), err);
2761        assert_eq!(sub(&big, &col).unwrap_err().to_string(), err);
2762        let all_null = decimal(vec![None, None], 4);
2763        assert_eq!(values(add(&all_null, &big).unwrap()), [None, None]);
2764        assert_eq!(values(sub(&big, &all_null).unwrap()), [None, None]);
2765        let empty = decimal(vec![], 4);
2766        assert!(add(&empty, &big).unwrap().is_empty());
2767
2768        let null = Scalar::new(decimal(vec![None], 2));
2769        assert_eq!(values(add(&col, &null).unwrap()), [None, None, None]);
2770
2771        // `1.50 + 1.0000` and `1.0000 - 1.50`, with both operands scalars.
2772        let ten_thousandths = Scalar::new(decimal(vec![Some(10_000)], 4));
2773        assert_eq!(
2774            values(add(&scalar, &ten_thousandths).unwrap()),
2775            [Some(25_000)]
2776        );
2777        assert_eq!(
2778            values(sub(&ten_thousandths, &scalar).unwrap()),
2779            [Some(-5_000)]
2780        );
2781    }
2782
2783    #[test]
2784    fn test_decimal256_add_sub_negative_scale_metadata() {
2785        let a = Decimal256Array::from(vec![Some(i256::ONE), Some(i256::MINUS_ONE), None])
2786            .with_precision_and_scale(76, -52)
2787            .unwrap();
2788        let b = Decimal256Array::from(vec![i256::from_i128(2), i256::ONE, i256::ONE])
2789            .with_precision_and_scale(76, -52)
2790            .unwrap();
2791        let expected =
2792            Decimal256Array::from(vec![Some(i256::from_i128(3)), Some(i256::ZERO), None])
2793                .with_precision_and_scale(76, -52)
2794                .unwrap();
2795        assert_eq!(add(&a, &b).unwrap().as_ref(), &expected);
2796
2797        let expected =
2798            Decimal256Array::from(vec![Some(i256::MINUS_ONE), Some(i256::from_i128(-2)), None])
2799                .with_precision_and_scale(76, -52)
2800                .unwrap();
2801        assert_eq!(sub(&a, &b).unwrap().as_ref(), &expected);
2802    }
2803
2804    #[test]
2805    fn test_decimal256_add_sub_minimum_scale() {
2806        let a = Decimal256Array::from(vec![i256::ONE])
2807            .with_precision_and_scale(20, i8::MIN)
2808            .unwrap();
2809        let b = Decimal256Array::from(vec![i256::from_i128(2)])
2810            .with_precision_and_scale(20, i8::MIN)
2811            .unwrap();
2812        let expected = Decimal256Array::from(vec![i256::from_i128(3)])
2813            .with_precision_and_scale(21, i8::MIN)
2814            .unwrap();
2815        assert_eq!(add(&a, &b).unwrap().as_ref(), &expected);
2816
2817        let expected = Decimal256Array::from(vec![i256::MINUS_ONE])
2818            .with_precision_and_scale(21, i8::MIN)
2819            .unwrap();
2820        assert_eq!(sub(&a, &b).unwrap().as_ref(), &expected);
2821    }
2822
2823    #[test]
2824    fn test_decimal256_remainder_negative_scale_metadata() {
2825        let a = Decimal256Array::from(vec![Some(i256::ONE), Some(i256::MINUS_ONE), None])
2826            .with_precision_and_scale(76, -52)
2827            .unwrap();
2828        let b = Decimal256Array::from(vec![i256::from_i128(2), i256::ONE, i256::ONE])
2829            .with_precision_and_scale(76, -52)
2830            .unwrap();
2831        let expected = Decimal256Array::from(vec![Some(i256::ONE), Some(i256::ZERO), None])
2832            .with_precision_and_scale(76, -52)
2833            .unwrap();
2834        assert_eq!(rem(&a, &b).unwrap().as_ref(), &expected);
2835    }
2836
2837    #[test]
2838    fn test_decimal256_adjacent_minimum_scales() {
2839        let a = Decimal256Array::from(vec![i256::ONE])
2840            .with_precision_and_scale(20, i8::MIN)
2841            .unwrap();
2842        let b = Decimal256Array::from(vec![i256::from_i128(2)])
2843            .with_precision_and_scale(20, i8::MIN + 1)
2844            .unwrap();
2845        let expected = Decimal256Array::from(vec![i256::from_i128(12)])
2846            .with_precision_and_scale(22, -127)
2847            .unwrap();
2848        assert_eq!(add(&a, &b).unwrap().as_ref(), &expected);
2849
2850        let expected = Decimal256Array::from(vec![i256::from_i128(8)])
2851            .with_precision_and_scale(22, -127)
2852            .unwrap();
2853        assert_eq!(sub(&a, &b).unwrap().as_ref(), &expected);
2854
2855        let expected = Decimal256Array::from(vec![i256::ZERO])
2856            .with_precision_and_scale(20, -127)
2857            .unwrap();
2858        assert_eq!(rem(&a, &b).unwrap().as_ref(), &expected);
2859    }
2860
2861    #[test]
2862    fn test_decimal256_extreme_scale_difference_overflow() {
2863        let a = Decimal256Array::from(vec![i256::ONE])
2864            .with_precision_and_scale(20, i8::MIN)
2865            .unwrap();
2866        let b = Decimal256Array::from(vec![i256::from_i128(2)])
2867            .with_precision_and_scale(76, 76)
2868            .unwrap();
2869        let expected = "Arithmetic overflow: Overflow happened on: 10 ^ 204";
2870        assert_eq!(add(&a, &b).unwrap_err().to_string(), expected);
2871        assert_eq!(sub(&a, &b).unwrap_err().to_string(), expected);
2872        assert_eq!(rem(&a, &b).unwrap_err().to_string(), expected);
2873    }
2874
2875    #[test]
2876    fn test_decimal256_multiply_minimum_scale() {
2877        let a = Decimal256Array::from(vec![i256::ONE])
2878            .with_precision_and_scale(76, -64)
2879            .unwrap();
2880        let expected = Decimal256Array::from(vec![i256::ONE])
2881            .with_precision_and_scale(76, i8::MIN)
2882            .unwrap();
2883        assert_eq!(mul(&a, &a).unwrap().as_ref(), &expected);
2884
2885        let b = a.clone().with_precision_and_scale(76, -65).unwrap();
2886        assert_eq!(
2887            mul(&a, &b).unwrap_err().to_string(),
2888            "Invalid argument error: Output scale of Decimal256(76, -64) * Decimal256(76, -65) would be less than min scale of -128"
2889        );
2890    }
2891
2892    #[test]
2893    fn test_decimal_div_precision_at_least_scale() {
2894        fn check<T: DecimalType>()
2895        where
2896            T::Native: From<i32>,
2897        {
2898            let a: PrimitiveArray<T> = [Some(1), Some(-1), Some(0), None]
2899                .into_iter()
2900                .map(|v| v.map(T::Native::from))
2901                .collect();
2902            let a = a.with_precision_and_scale(1, 1).unwrap();
2903            for (scale, coefficient) in [(0, 10000), (-1, 1000), (-4, 1), (-5, 0), (-6, 0)] {
2904                let b = PrimitiveArray::<T>::from_iter_values(
2905                    [1, 1, 1, 0].into_iter().map(T::Native::from),
2906                )
2907                .with_precision_and_scale(1, scale)
2908                .unwrap();
2909                let expected: PrimitiveArray<T> =
2910                    [Some(coefficient), Some(-coefficient), Some(0), None]
2911                        .into_iter()
2912                        .map(|v| v.map(T::Native::from))
2913                        .collect();
2914                let expected = expected.with_precision_and_scale(5, 5).unwrap();
2915                assert_eq!(div(&a, &b).unwrap().as_ref(), &expected);
2916            }
2917        }
2918        check::<Decimal32Type>();
2919        check::<Decimal64Type>();
2920        check::<Decimal128Type>();
2921        check::<Decimal256Type>();
2922    }
2923
2924    #[test]
2925    fn test_decimal_div_precision_at_least_one() {
2926        fn check<T: DecimalType>()
2927        where
2928            T::Native: From<i32>,
2929        {
2930            for scale in [-4, -5] {
2931                let a: PrimitiveArray<T> = [Some(1), Some(-1), Some(0), None]
2932                    .into_iter()
2933                    .map(|v| v.map(T::Native::from))
2934                    .collect();
2935                let a = a.with_precision_and_scale(1, scale).unwrap();
2936                for (divisor_scale, coefficient) in [(-4, 1), (-5, 0), (-6, 0)] {
2937                    let b = PrimitiveArray::<T>::from_iter_values(
2938                        [1, 1, 1, 0].into_iter().map(T::Native::from),
2939                    )
2940                    .with_precision_and_scale(1, divisor_scale)
2941                    .unwrap();
2942                    let expected: PrimitiveArray<T> =
2943                        [Some(coefficient), Some(-coefficient), Some(0), None]
2944                            .into_iter()
2945                            .map(|v| v.map(T::Native::from))
2946                            .collect();
2947                    let expected = expected.with_precision_and_scale(1, scale + 4).unwrap();
2948                    assert_eq!(div(&a, &b).unwrap().as_ref(), &expected);
2949                }
2950            }
2951        }
2952        check::<Decimal32Type>();
2953        check::<Decimal64Type>();
2954        check::<Decimal128Type>();
2955        check::<Decimal256Type>();
2956    }
2957
2958    #[test]
2959    fn test_decimal_div_scaling_overflow_boundary() {
2960        // `div` scales `l` by 10^6, which overflows just past `MAX / 10^6` and `MIN / 10^6`.
2961        // Dividing by 10^6 returns each value, on either side of the boundary.
2962        fn check<T: DecimalType>() {
2963            let one = T::Native::ONE;
2964            let pow = T::Native::usize_as(1_000_000);
2965            let max = T::Native::MAX_TOTAL_ORDER.div_wrapping(pow);
2966            let min = T::Native::MIN_TOTAL_ORDER.div_wrapping(pow);
2967            let values = [
2968                max,
2969                max.add_wrapping(one),
2970                min,
2971                min.sub_wrapping(one),
2972                T::Native::MAX_TOTAL_ORDER,
2973                T::Native::MIN_TOTAL_ORDER.add_wrapping(one),
2974            ];
2975            let a = PrimitiveArray::<T>::from_iter_values(values)
2976                .with_precision_and_scale(T::MAX_PRECISION, 2)
2977                .unwrap();
2978            for (divisor, negate) in [(pow, false), (pow.neg_wrapping(), true)] {
2979                let b = PrimitiveArray::<T>::from_iter_values([divisor])
2980                    .with_precision_and_scale(T::MAX_PRECISION, 2)
2981                    .unwrap();
2982                let result = div(&a, &Scalar::new(b)).unwrap();
2983                let expected = values.map(|v| if negate { v.neg_wrapping() } else { v });
2984                assert_eq!(result.as_primitive::<T>().values().as_ref(), expected);
2985            }
2986        }
2987        check::<Decimal32Type>();
2988        check::<Decimal64Type>();
2989        check::<Decimal128Type>();
2990        check::<Decimal256Type>();
2991    }
2992
2993    #[test]
2994    fn test_decimal256_div_wide_intermediate() {
2995        // Dividing two scale-37 values needs l * 10^41, which is 79 digits and does not
2996        // fit in an i256, even though the 41-digit quotient does.
2997        let a = Decimal256Array::from(vec![i256::from_i128(
2998            60096743305738933273387748827369321010i128,
2999        )])
3000        .with_precision_and_scale(38, 37)
3001        .unwrap();
3002        let b = Decimal256Array::from(vec![i256::from_i128(
3003            60096763826458053191384497987259478584i128,
3004        )])
3005        .with_precision_and_scale(38, 37)
3006        .unwrap();
3007
3008        let result = div(&a, &b).unwrap();
3009        assert_eq!(result.data_type(), &DataType::Decimal256(76, 41));
3010        assert_eq!(
3011            result.as_primitive::<Decimal256Type>().value(0),
3012            i256::from_string("99999965853869970143724273117679321341339").unwrap()
3013        );
3014
3015        // Truncation stays toward zero on either side of the fallback.
3016        let neg_a = neg(&a).unwrap();
3017        let result = div(neg_a.as_primitive::<Decimal256Type>(), &b).unwrap();
3018        assert_eq!(
3019            result.as_primitive::<Decimal256Type>().value(0),
3020            i256::from_string("-99999965853869970143724273117679321341339").unwrap()
3021        );
3022
3023        let neg_b = neg(&b).unwrap();
3024        let result = div(&a, neg_b.as_primitive::<Decimal256Type>()).unwrap();
3025        assert_eq!(
3026            result.as_primitive::<Decimal256Type>().value(0),
3027            i256::from_string("-99999965853869970143724273117679321341339").unwrap()
3028        );
3029
3030        let zero = Decimal256Array::from(vec![i256::ZERO])
3031            .with_precision_and_scale(38, 37)
3032            .unwrap();
3033        let err = div(&a, &zero).unwrap_err().to_string();
3034        assert_eq!(err, "Divide by zero error");
3035    }
3036
3037    #[test]
3038    fn test_decimal256_div_divisor_near_max() {
3039        // A divisor past i256::MAX / 10 leaves no room to scale the running remainder either.
3040        let a = Decimal256Array::from(vec![
3041            i256::from_string(
3042                "5900000000000000000000000000000000000000000000000000000000000000000000000000",
3043            )
3044            .unwrap(),
3045        ])
3046        .with_precision_and_scale(76, 37)
3047        .unwrap();
3048        let b = Decimal256Array::from(vec![
3049            i256::from_string(
3050                "6000000000000000000000000000000000000000000000000000000000000000000000000000",
3051            )
3052            .unwrap(),
3053        ])
3054        .with_precision_and_scale(76, 37)
3055        .unwrap();
3056
3057        let result = div(&a, &b).unwrap();
3058        assert_eq!(
3059            result.as_primitive::<Decimal256Type>().value(0),
3060            i256::from_string("98333333333333333333333333333333333333333").unwrap()
3061        );
3062    }
3063
3064    #[test]
3065    fn test_decimal128_div_wide_intermediate() {
3066        // Same overflow one type down: 3.0 / 6.0 at scale 37 needs l * 10^38, 76 digits in i128.
3067        let a = Decimal128Array::from(vec![30000000000000000000000000000000000000i128])
3068            .with_precision_and_scale(38, 37)
3069            .unwrap();
3070        let b = Decimal128Array::from(vec![60000000000000000000000000000000000000i128])
3071            .with_precision_and_scale(38, 37)
3072            .unwrap();
3073
3074        let result = div(&a, &b).unwrap();
3075        assert_eq!(result.data_type(), &DataType::Decimal128(38, 38));
3076        assert_eq!(
3077            result.as_primitive::<Decimal128Type>().value(0),
3078            50000000000000000000000000000000000000i128
3079        );
3080    }
3081
3082    #[test]
3083    fn test_scaled_div_agrees_with_direct_division() {
3084        for (l, r, mul_pow) in [
3085            (7i128, 3i128, 4i8),
3086            (-7, 3, 4),
3087            (7, -3, 4),
3088            (-7, -3, 4),
3089            (1, 999_999_999, 9),
3090            (i128::MAX / 10, 7, 1),
3091            (i128::MAX / 10, -i128::MAX / 11, 1),
3092            (0, 5, 6),
3093        ] {
3094            let scaled = l * 10i128.pow(mul_pow as u32);
3095            assert_eq!(
3096                scaled_div::<Decimal128Type>(l, r, mul_pow).unwrap(),
3097                scaled / r,
3098                "{l} * 10^{mul_pow} / {r}"
3099            );
3100        }
3101    }
3102
3103    #[test]
3104    fn test_decimal_div_rem_by_scalar() {
3105        // `div` and `rem` by a scalar give the same results and errors as by an array that
3106        // repeats it, which takes `try_binary`
3107        fn check<T: DecimalType>() {
3108            let one = T::Native::ONE;
3109            let pow = T::Native::usize_as(1_000_000);
3110            let (max, min) = (T::Native::MAX_TOTAL_ORDER, T::Native::MIN_TOTAL_ORDER);
3111            let seven = T::Native::usize_as(7);
3112            let values = [
3113                Some(T::Native::ZERO),
3114                Some(one),
3115                Some(one.neg_wrapping()),
3116                Some(seven.neg_wrapping()),
3117                None,
3118                Some(max.div_wrapping(pow)),
3119                Some(max.div_wrapping(pow).add_wrapping(one)),
3120                Some(min.div_wrapping(pow).sub_wrapping(one)),
3121                Some(max),
3122                Some(min.add_wrapping(one)),
3123                Some(min),
3124            ];
3125            let divisors = [
3126                T::Native::ZERO,
3127                one,
3128                one.neg_wrapping(),
3129                seven,
3130                seven.neg_wrapping(),
3131                T::Native::usize_as(10_000),
3132                max,
3133                min,
3134            ];
3135            // Scale pairs where the multipliers of `div` and `rem` are 1, a power of ten, and
3136            // one that overflows the divisor
3137            let scales = [(2, 2), (2, 4), (4, 2), (2, -6), (0, 0)];
3138            for (s1, s2) in scales {
3139                let a = PrimitiveArray::<T>::from_iter(values)
3140                    .with_precision_and_scale(T::MAX_PRECISION, s1)
3141                    .unwrap();
3142                let arrays = [
3143                    a.clone(),
3144                    a.slice(1, 6),
3145                    a.slice(0, 0),
3146                    PrimitiveArray::<T>::new_null(3)
3147                        .with_precision_and_scale(T::MAX_PRECISION, s1)
3148                        .unwrap(),
3149                ];
3150                for divisor in divisors {
3151                    let repeat = |len| {
3152                        PrimitiveArray::<T>::from_iter_values(vec![divisor; len])
3153                            .with_precision_and_scale(T::MAX_PRECISION, s2)
3154                            .unwrap()
3155                    };
3156                    let scalar = Scalar::new(repeat(1));
3157                    for a in &arrays {
3158                        let b = repeat(a.len());
3159                        for kernel in [div, rem] {
3160                            let msg = format!("{a:?} by {divisor:?} at scales {s1}, {s2}");
3161                            match (kernel(a, &scalar), kernel(a, &b)) {
3162                                (Ok(s), Ok(b)) => assert_eq!(s.to_data(), b.to_data(), "{msg}"),
3163                                (Err(s), Err(b)) => {
3164                                    assert_eq!(s.to_string(), b.to_string(), "{msg}")
3165                                }
3166                                (s, b) => panic!("{msg}: {s:?} != {b:?}"),
3167                            }
3168                        }
3169                    }
3170                }
3171            }
3172        }
3173        check::<Decimal32Type>();
3174        check::<Decimal64Type>();
3175        check::<Decimal128Type>();
3176        check::<Decimal256Type>();
3177    }
3178
3179    #[test]
3180    fn test_decimal256_same_scale_add_sub() {
3181        let lhs = Decimal256Array::from(vec![
3182            Some(i256::from_parts(u128::MAX, 0)),
3183            Some(i256::MINUS_ONE),
3184            None,
3185        ])
3186        .with_precision_and_scale(70, 2)
3187        .unwrap();
3188        let rhs = Decimal256Array::from(vec![Some(i256::ONE), Some(i256::ONE), Some(i256::MAX)])
3189            .with_precision_and_scale(70, 2)
3190            .unwrap();
3191
3192        let expected =
3193            Decimal256Array::from(vec![Some(i256::from_parts(0, 1)), Some(i256::ZERO), None])
3194                .with_precision_and_scale(71, 2)
3195                .unwrap();
3196        for operation in [add, add_wrapping] {
3197            let result = operation(&lhs, &rhs).unwrap();
3198            assert_eq!(result.as_primitive::<Decimal256Type>(), &expected);
3199        }
3200
3201        let expected = Decimal256Array::from(vec![
3202            Some(i256::from_parts(u128::MAX - 1, 0)),
3203            Some(i256::from_i128(-2)),
3204            None,
3205        ])
3206        .with_precision_and_scale(71, 2)
3207        .unwrap();
3208        for operation in [sub, sub_wrapping] {
3209            let result = operation(&lhs, &rhs).unwrap();
3210            assert_eq!(result.as_primitive::<Decimal256Type>(), &expected);
3211        }
3212
3213        let lhs = Decimal256Array::from(vec![i256::MAX])
3214            .with_precision_and_scale(76, 0)
3215            .unwrap();
3216        let rhs = Decimal256Array::from(vec![i256::ONE])
3217            .with_precision_and_scale(76, 0)
3218            .unwrap();
3219        for operation in [add, add_wrapping] {
3220            assert_eq!(
3221                operation(&lhs, &rhs).unwrap_err().to_string(),
3222                format!(
3223                    "Arithmetic overflow: Overflow happened on: {:?} + {:?}",
3224                    i256::MAX,
3225                    i256::ONE
3226                )
3227            );
3228        }
3229
3230        let lhs = Decimal256Array::from(vec![i256::MIN])
3231            .with_precision_and_scale(76, 0)
3232            .unwrap();
3233        for operation in [sub, sub_wrapping] {
3234            assert_eq!(
3235                operation(&lhs, &rhs).unwrap_err().to_string(),
3236                format!(
3237                    "Arithmetic overflow: Overflow happened on: {:?} - {:?}",
3238                    i256::MIN,
3239                    i256::ONE
3240                )
3241            );
3242        }
3243    }
3244
3245    fn test_timestamp_impl<T: TimestampOp>() {
3246        let a = PrimitiveArray::<T>::new(vec![2000000, 434030324, 53943340].into(), None);
3247        let b = PrimitiveArray::<T>::new(vec![329593, 59349, 694994].into(), None);
3248
3249        let result = sub(&a, &b).unwrap();
3250        assert_eq!(
3251            result.as_primitive::<T::Duration>().values(),
3252            &[1670407, 433970975, 53248346]
3253        );
3254
3255        let r2 = add(&b, &result.as_ref()).unwrap();
3256        assert_eq!(r2.as_ref(), &a);
3257
3258        let r3 = add(&result.as_ref(), &b).unwrap();
3259        assert_eq!(r3.as_ref(), &a);
3260
3261        let format_array = |x: &dyn Array| -> Vec<String> {
3262            x.as_primitive::<T>()
3263                .values()
3264                .into_iter()
3265                .map(|x| as_datetime::<T>(*x).unwrap().to_string())
3266                .collect()
3267        };
3268
3269        let values = vec![
3270            "1970-01-01T00:00:00Z",
3271            "2010-04-01T04:00:20Z",
3272            "1960-01-30T04:23:20Z",
3273        ]
3274        .into_iter()
3275        .map(|x| {
3276            T::from_naive_datetime(DateTime::parse_from_rfc3339(x).unwrap().naive_utc(), None)
3277                .unwrap()
3278        })
3279        .collect();
3280
3281        let a = PrimitiveArray::<T>::new(values, None);
3282        let b = IntervalYearMonthArray::from(vec![
3283            IntervalYearMonthType::make_value(5, 34),
3284            IntervalYearMonthType::make_value(-2, 4),
3285            IntervalYearMonthType::make_value(7, -4),
3286        ]);
3287        let r4 = add(&a, &b).unwrap();
3288        assert_eq!(
3289            &format_array(r4.as_ref()),
3290            &[
3291                "1977-11-01 00:00:00".to_string(),
3292                "2008-08-01 04:00:20".to_string(),
3293                "1966-09-30 04:23:20".to_string()
3294            ]
3295        );
3296
3297        let r5 = sub(&r4, &b).unwrap();
3298        assert_eq!(r5.as_ref(), &a);
3299
3300        let b = IntervalDayTimeArray::from(vec![
3301            IntervalDayTimeType::make_value(5, 454000),
3302            IntervalDayTimeType::make_value(-34, 0),
3303            IntervalDayTimeType::make_value(7, -4000),
3304        ]);
3305        let r6 = add(&a, &b).unwrap();
3306        assert_eq!(
3307            &format_array(r6.as_ref()),
3308            &[
3309                "1970-01-06 00:07:34".to_string(),
3310                "2010-02-26 04:00:20".to_string(),
3311                "1960-02-06 04:23:16".to_string()
3312            ]
3313        );
3314
3315        let r7 = sub(&r6, &b).unwrap();
3316        assert_eq!(r7.as_ref(), &a);
3317
3318        let b = IntervalMonthDayNanoArray::from(vec![
3319            IntervalMonthDayNanoType::make_value(344, 34, -43_000_000_000),
3320            IntervalMonthDayNanoType::make_value(-593, -33, 13_000_000_000),
3321            IntervalMonthDayNanoType::make_value(5, 2, 493_000_000_000),
3322        ]);
3323        let r8 = add(&a, &b).unwrap();
3324        assert_eq!(
3325            &format_array(r8.as_ref()),
3326            &[
3327                "1998-10-04 23:59:17".to_string(),
3328                "1960-09-29 04:00:33".to_string(),
3329                "1960-07-02 04:31:33".to_string()
3330            ]
3331        );
3332
3333        let r9 = sub(&r8, &b).unwrap();
3334        // Note: subtraction is not the inverse of addition for intervals
3335        assert_eq!(
3336            &format_array(r9.as_ref()),
3337            &[
3338                "1970-01-02 00:00:00".to_string(),
3339                "2010-04-02 04:00:20".to_string(),
3340                "1960-01-31 04:23:20".to_string()
3341            ]
3342        );
3343    }
3344
3345    #[test]
3346    fn test_timestamp() {
3347        test_timestamp_impl::<TimestampSecondType>();
3348        test_timestamp_impl::<TimestampMillisecondType>();
3349        test_timestamp_impl::<TimestampMicrosecondType>();
3350        test_timestamp_impl::<TimestampNanosecondType>();
3351    }
3352
3353    #[test]
3354    fn test_interval() {
3355        let a = IntervalYearMonthArray::from(vec![
3356            IntervalYearMonthType::make_value(32, 4),
3357            IntervalYearMonthType::make_value(32, 4),
3358        ]);
3359        let b = IntervalYearMonthArray::from(vec![
3360            IntervalYearMonthType::make_value(-4, 6),
3361            IntervalYearMonthType::make_value(-3, 23),
3362        ]);
3363        let result = add(&a, &b).unwrap();
3364        assert_eq!(
3365            result.as_ref(),
3366            &IntervalYearMonthArray::from(vec![
3367                IntervalYearMonthType::make_value(28, 10),
3368                IntervalYearMonthType::make_value(29, 27)
3369            ])
3370        );
3371        let result = sub(&a, &b).unwrap();
3372        assert_eq!(
3373            result.as_ref(),
3374            &IntervalYearMonthArray::from(vec![
3375                IntervalYearMonthType::make_value(36, -2),
3376                IntervalYearMonthType::make_value(35, -19)
3377            ])
3378        );
3379
3380        let a = IntervalDayTimeArray::from(vec![
3381            IntervalDayTimeType::make_value(32, 4),
3382            IntervalDayTimeType::make_value(32, 4),
3383        ]);
3384        let b = IntervalDayTimeArray::from(vec![
3385            IntervalDayTimeType::make_value(-4, 6),
3386            IntervalDayTimeType::make_value(-3, 23),
3387        ]);
3388        let result = add(&a, &b).unwrap();
3389        assert_eq!(
3390            result.as_ref(),
3391            &IntervalDayTimeArray::from(vec![
3392                IntervalDayTimeType::make_value(28, 10),
3393                IntervalDayTimeType::make_value(29, 27)
3394            ])
3395        );
3396        let result = sub(&a, &b).unwrap();
3397        assert_eq!(
3398            result.as_ref(),
3399            &IntervalDayTimeArray::from(vec![
3400                IntervalDayTimeType::make_value(36, -2),
3401                IntervalDayTimeType::make_value(35, -19)
3402            ])
3403        );
3404        let a = IntervalMonthDayNanoArray::from(vec![
3405            IntervalMonthDayNanoType::make_value(32, 4, 4000000000000),
3406            IntervalMonthDayNanoType::make_value(32, 4, 45463000000000000),
3407        ]);
3408        let b = IntervalMonthDayNanoArray::from(vec![
3409            IntervalMonthDayNanoType::make_value(-4, 6, 46000000000000),
3410            IntervalMonthDayNanoType::make_value(-3, 23, 3564000000000000),
3411        ]);
3412        let result = add(&a, &b).unwrap();
3413        assert_eq!(
3414            result.as_ref(),
3415            &IntervalMonthDayNanoArray::from(vec![
3416                IntervalMonthDayNanoType::make_value(28, 10, 50000000000000),
3417                IntervalMonthDayNanoType::make_value(29, 27, 49027000000000000)
3418            ])
3419        );
3420        let result = sub(&a, &b).unwrap();
3421        assert_eq!(
3422            result.as_ref(),
3423            &IntervalMonthDayNanoArray::from(vec![
3424                IntervalMonthDayNanoType::make_value(36, -2, -42000000000000),
3425                IntervalMonthDayNanoType::make_value(35, -19, 41899000000000000)
3426            ])
3427        );
3428        let a = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNano::MAX]);
3429        let b = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNano::ONE]);
3430        let err = add(&a, &b).unwrap_err().to_string();
3431        assert_eq!(
3432            err,
3433            "Arithmetic overflow: Overflow happened on: 2147483647 + 1"
3434        );
3435    }
3436
3437    #[test]
3438    fn test_interval_mul_i64() {
3439        let interval = IntervalYearMonthArray::from(vec![16, 5, 0]);
3440        let factor = Int64Array::from(vec![3, -2, i64::MAX]);
3441        let expected = IntervalYearMonthArray::from(vec![48, -10, 0]);
3442        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
3443        assert_eq!(mul(&factor, &interval).unwrap().as_ref(), &expected);
3444
3445        let interval = IntervalDayTimeArray::from(vec![
3446            Some(IntervalDayTimeType::make_value(10, 2 * 60 * 60 * 1000)),
3447            None,
3448        ]);
3449        let factor = Int64Array::new_scalar(3);
3450        let expected = IntervalDayTimeArray::from(vec![
3451            Some(IntervalDayTimeType::make_value(30, 6 * 60 * 60 * 1000)),
3452            None,
3453        ]);
3454        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
3455        assert_eq!(mul(&factor, &interval).unwrap().as_ref(), &expected);
3456
3457        let null_factor = Scalar::new(Int64Array::new_null(1));
3458        let expected = IntervalDayTimeArray::new_null(interval.len());
3459        assert_eq!(mul(&interval, &null_factor).unwrap().as_ref(), &expected);
3460        assert_eq!(mul(&null_factor, &interval).unwrap().as_ref(), &expected);
3461
3462        let interval = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(
3463            12,
3464            15,
3465            5_000_000_000,
3466        ));
3467        let factor = Int64Array::from(vec![2, 0, -1]);
3468        let expected = IntervalMonthDayNanoArray::from(vec![
3469            IntervalMonthDayNanoType::make_value(24, 30, 10_000_000_000),
3470            IntervalMonthDayNanoType::make_value(0, 0, 0),
3471            IntervalMonthDayNanoType::make_value(-12, -15, -5_000_000_000),
3472        ]);
3473        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
3474        assert_eq!(mul(&factor, &interval).unwrap().as_ref(), &expected);
3475
3476        let float_factor = Float64Array::new_scalar(2.);
3477        assert!(mul_wrapping(&float_factor, &interval).is_err());
3478        assert!(mul_wrapping(&factor, &interval).is_err());
3479    }
3480
3481    #[test]
3482    fn test_interval_mul_div_f64() {
3483        const HOUR_NANOS: i64 = 3_600_000_000_000;
3484        const MINUTE_NANOS: i64 = 60_000_000_000;
3485
3486        // Adapted from DuckDB's interval multiplication tests:
3487        // https://github.com/duckdb/duckdb/blob/21aca0424f1faf78b593b1e6fbfdd4846624c987/test/sql/function/interval/test_interval_muldiv.test#L1-L99
3488        // DuckDB's cases come from PostgreSQL's interval regression tests:
3489        // https://github.com/postgres/postgres/blob/78758d37306cd89ab060f00cb06f249018d5b8da/src/test/regress/sql/interval.sql#L118-L164
3490        let interval = IntervalMonthDayNanoArray::from(vec![
3491            IntervalMonthDayNanoType::make_value(41, 12, 360 * HOUR_NANOS),
3492            IntervalMonthDayNanoType::make_value(-41, -12, 360 * HOUR_NANOS),
3493            IntervalMonthDayNanoType::make_value(1, 1, 0),
3494            IntervalMonthDayNanoType::make_value(0, 0, 1),
3495            IntervalMonthDayNanoType::make_value(0, 0, 3),
3496            IntervalMonthDayNanoType::make_value(0, 0, -1),
3497            IntervalMonthDayNanoType::make_value(0, 0, -3),
3498        ]);
3499        let factor = Float64Array::from(vec![0.3, 0.3, 1.5, 0.5, 0.5, 0.5, 0.5]);
3500        let expected = IntervalMonthDayNanoArray::from(vec![
3501            IntervalMonthDayNanoType::make_value(12, 12, 122 * HOUR_NANOS + 24 * MINUTE_NANOS),
3502            IntervalMonthDayNanoType::make_value(-12, -12, 93 * HOUR_NANOS + 36 * MINUTE_NANOS),
3503            IntervalMonthDayNanoType::make_value(1, 16, 12 * HOUR_NANOS),
3504            IntervalMonthDayNanoType::make_value(0, 0, 0),
3505            IntervalMonthDayNanoType::make_value(0, 0, 2),
3506            IntervalMonthDayNanoType::make_value(0, 0, 0),
3507            IntervalMonthDayNanoType::make_value(0, 0, -2),
3508        ]);
3509        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
3510        assert_eq!(mul(&factor, &interval).unwrap().as_ref(), &expected);
3511
3512        let interval = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
3513            9,
3514            -27,
3515            45_296 * NANOSECONDS,
3516        )]);
3517        let factor = Float64Array::new_scalar(0.3);
3518        let expected = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
3519            2,
3520            13,
3521            4_948_800_000_000,
3522        )]);
3523        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
3524
3525        let interval = IntervalMonthDayNanoArray::from(vec![
3526            IntervalMonthDayNanoType::make_value(0, 1, 0),
3527            IntervalMonthDayNanoType::make_value(4, 0, 0),
3528            IntervalMonthDayNanoType::make_value(1, 1, 0),
3529            IntervalMonthDayNanoType::make_value(0, 0, (1_i64 << 53) - 1),
3530            IntervalMonthDayNanoType::make_value(0, 0, i64::MAX),
3531            IntervalMonthDayNanoType::make_value(1, 1, 1),
3532            IntervalMonthDayNanoType::make_value(1, 1, 1),
3533            IntervalMonthDayNanoType::make_value(1, 0, 0),
3534        ]);
3535        let factor = Float64Array::from(vec![
3536            3.,
3537            5.,
3538            2.,
3539            0.7,
3540            1.,
3541            f64::INFINITY,
3542            f64::NEG_INFINITY,
3543            -2.,
3544        ]);
3545        let expected = IntervalMonthDayNanoArray::from(vec![
3546            IntervalMonthDayNanoType::make_value(0, 0, 8 * HOUR_NANOS),
3547            IntervalMonthDayNanoType::make_value(0, 24, 0),
3548            IntervalMonthDayNanoType::make_value(0, 15, 12 * HOUR_NANOS),
3549            IntervalMonthDayNanoType::make_value(0, 0, 12_867_427_506_772_844),
3550            IntervalMonthDayNanoType::make_value(0, 0, i64::MAX),
3551            IntervalMonthDayNanoType::make_value(0, 0, 0),
3552            IntervalMonthDayNanoType::make_value(0, 0, 0),
3553            IntervalMonthDayNanoType::make_value(0, -15, 0),
3554        ]);
3555        assert_eq!(div(&interval, &factor).unwrap().as_ref(), &expected);
3556
3557        let null_factor = Scalar::new(Float64Array::new_null(1));
3558        assert_eq!(
3559            mul(&interval, &null_factor).unwrap().as_ref(),
3560            &IntervalMonthDayNanoArray::new_null(interval.len())
3561        );
3562    }
3563
3564    #[test]
3565    fn test_interval_mul_div_f64_matches_duckdb_rounding() {
3566        // Regression test for https://github.com/apache/arrow-rs/issues/12004: each of these
3567        // results is off by 1 ns unless the sub-day remainder is summed in DuckDB's order.
3568        let interval = IntervalMonthDayNanoArray::from(vec![
3569            IntervalMonthDayNanoType::make_value(1, 1, 0),
3570            IntervalMonthDayNanoType::make_value(1, 1, 0),
3571            IntervalMonthDayNanoType::make_value(1, 2, 0),
3572            IntervalMonthDayNanoType::make_value(1, 1, 0),
3573        ]);
3574        let factor = Float64Array::from(vec![32. / 7., 10. / 13., 5. / 7., -32. / 7.]);
3575        let expected = IntervalMonthDayNanoArray::from(vec![
3576            IntervalMonthDayNanoType::make_value(4, 21, 61_714_285_726_628),
3577            IntervalMonthDayNanoType::make_value(0, 23, 73_107_692_314_339),
3578            IntervalMonthDayNanoType::make_value(0, 22, 74_057_142_894_171),
3579            IntervalMonthDayNanoType::make_value(-4, -21, -61_714_285_726_628),
3580        ]);
3581        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
3582
3583        // Division multiplies by the reciprocal, so it follows the same order.
3584        let interval =
3585            IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(1, 1, 0)]);
3586        let factor = Float64Array::new_scalar(7. / 32.);
3587        let expected = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
3588            4,
3589            21,
3590            61_714_285_726_628,
3591        )]);
3592        assert_eq!(div(&interval, &factor).unwrap().as_ref(), &expected);
3593    }
3594
3595    #[test]
3596    fn test_interval_mul_div_f64_errors() {
3597        let factor = Float64Array::new_scalar(2.);
3598        let year_month = IntervalYearMonthArray::new_scalar(1);
3599        let day_time = IntervalDayTimeArray::new_scalar(IntervalDayTime::new(1, 1));
3600        for interval in [&year_month as &dyn Datum, &day_time] {
3601            assert!(mul(interval, &factor).is_err());
3602            assert!(mul(&factor, interval).is_err());
3603            assert!(div(interval, &factor).is_err());
3604        }
3605
3606        let interval =
3607            IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(1, 1, 1));
3608
3609        assert!(matches!(
3610            add(&interval, &factor),
3611            Err(ArrowError::InvalidArgumentError(_))
3612        ));
3613
3614        let zero = Float64Array::new_scalar(-0.);
3615        assert!(matches!(
3616            div(&interval, &zero),
3617            Err(ArrowError::DivideByZero)
3618        ));
3619
3620        assert!(div(&factor, &interval).is_err());
3621
3622        for factor in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
3623            let factor = Float64Array::new_scalar(factor);
3624            assert!(matches!(
3625                mul(&interval, &factor),
3626                Err(ArrowError::ArithmeticOverflow(_))
3627            ));
3628        }
3629
3630        let nan = Float64Array::new_scalar(f64::NAN);
3631        assert!(matches!(
3632            div(&interval, &nan),
3633            Err(ArrowError::ArithmeticOverflow(_))
3634        ));
3635
3636        let interval = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(
3637            i32::MAX,
3638            0,
3639            0,
3640        ));
3641        assert!(matches!(
3642            mul(&interval, &factor),
3643            Err(ArrowError::ArithmeticOverflow(_))
3644        ));
3645
3646        let factor = Float64Array::new_scalar(1.5);
3647        let interval = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(
3648            0,
3649            0,
3650            i64::MAX,
3651        ));
3652        assert!(matches!(
3653            mul(&interval, &factor),
3654            Err(ArrowError::ArithmeticOverflow(_))
3655        ));
3656
3657        let factor = Float64Array::new_scalar(1.000_000_000_4);
3658        let interval = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(
3659            i32::MIN,
3660            0,
3661            0,
3662        ));
3663        assert!(matches!(
3664            mul(&interval, &factor),
3665            Err(ArrowError::ArithmeticOverflow(_))
3666        ));
3667
3668        let factor = Float64Array::new_scalar(0.999_999_999);
3669        let interval = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(
3670            1,
3671            i32::MAX,
3672            0,
3673        ));
3674        assert!(matches!(
3675            mul(&interval, &factor),
3676            Err(ArrowError::ArithmeticOverflow(_))
3677        ));
3678    }
3679
3680    #[test]
3681    fn test_interval_mul_i64_overflow() {
3682        let interval = IntervalYearMonthArray::from(vec![i32::MAX]);
3683        let factor = Int64Array::from(vec![2]);
3684        assert_eq!(
3685            mul(&interval, &factor).unwrap_err().to_string(),
3686            "Arithmetic overflow: Overflow happened on: 2147483647 * 2"
3687        );
3688
3689        let interval = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
3690            0,
3691            0,
3692            i64::MAX,
3693        )]);
3694        assert_eq!(
3695            mul(&interval, &factor).unwrap_err().to_string(),
3696            "Arithmetic overflow: Overflow happened on: 9223372036854775807 * 2"
3697        );
3698    }
3699
3700    fn test_duration_impl<T: ArrowPrimitiveType<Native = i64>>() {
3701        let a = PrimitiveArray::<T>::new(vec![1000, 4394, -3944].into(), None);
3702        let b = PrimitiveArray::<T>::new(vec![4, -5, -243].into(), None);
3703
3704        let result = add(&a, &b).unwrap();
3705        assert_eq!(result.as_primitive::<T>().values(), &[1004, 4389, -4187]);
3706        let result = sub(&a, &b).unwrap();
3707        assert_eq!(result.as_primitive::<T>().values(), &[996, 4399, -3701]);
3708
3709        let err = mul(&a, &b).unwrap_err().to_string();
3710        assert!(
3711            err.contains("Invalid duration arithmetic operation"),
3712            "{err}"
3713        );
3714
3715        let err = div(&a, &b).unwrap_err().to_string();
3716        assert!(
3717            err.contains("Invalid duration arithmetic operation"),
3718            "{err}"
3719        );
3720
3721        let err = rem(&a, &b).unwrap_err().to_string();
3722        assert!(
3723            err.contains("Invalid duration arithmetic operation"),
3724            "{err}"
3725        );
3726
3727        let a = PrimitiveArray::<T>::new(vec![i64::MAX].into(), None);
3728        let b = PrimitiveArray::<T>::new(vec![1].into(), None);
3729        let err = add(&a, &b).unwrap_err().to_string();
3730        assert_eq!(
3731            err,
3732            "Arithmetic overflow: Overflow happened on: 9223372036854775807 + 1"
3733        );
3734    }
3735
3736    #[test]
3737    fn test_duration() {
3738        test_duration_impl::<DurationSecondType>();
3739        test_duration_impl::<DurationMillisecondType>();
3740        test_duration_impl::<DurationMicrosecondType>();
3741        test_duration_impl::<DurationNanosecondType>();
3742    }
3743
3744    fn test_date_impl<T: ArrowPrimitiveType, F>(f: F)
3745    where
3746        F: Fn(NaiveDate) -> T::Native,
3747        T::Native: TryInto<i64>,
3748    {
3749        let a = PrimitiveArray::<T>::new(
3750            vec![
3751                f(NaiveDate::from_ymd_opt(1979, 1, 30).unwrap()),
3752                f(NaiveDate::from_ymd_opt(2010, 4, 3).unwrap()),
3753                f(NaiveDate::from_ymd_opt(2008, 2, 29).unwrap()),
3754            ]
3755            .into(),
3756            None,
3757        );
3758
3759        let b = IntervalYearMonthArray::from(vec![
3760            IntervalYearMonthType::make_value(34, 2),
3761            IntervalYearMonthType::make_value(3, -3),
3762            IntervalYearMonthType::make_value(-12, 4),
3763        ]);
3764
3765        let format_array = |x: &dyn Array| -> Vec<String> {
3766            x.as_primitive::<T>()
3767                .values()
3768                .into_iter()
3769                .map(|x| {
3770                    as_date::<T>((*x).try_into().ok().unwrap())
3771                        .unwrap()
3772                        .to_string()
3773                })
3774                .collect()
3775        };
3776
3777        let result = add(&a, &b).unwrap();
3778        assert_eq!(
3779            &format_array(result.as_ref()),
3780            &[
3781                "2013-03-30".to_string(),
3782                "2013-01-03".to_string(),
3783                "1996-06-29".to_string(),
3784            ]
3785        );
3786        let result = sub(&result, &b).unwrap();
3787        assert_eq!(result.as_ref(), &a);
3788
3789        let b = IntervalDayTimeArray::from(vec![
3790            IntervalDayTimeType::make_value(34, 2),
3791            IntervalDayTimeType::make_value(3, -3),
3792            IntervalDayTimeType::make_value(-12, 4),
3793        ]);
3794
3795        let result = add(&a, &b).unwrap();
3796        assert_eq!(
3797            &format_array(result.as_ref()),
3798            &[
3799                "1979-03-05".to_string(),
3800                "2010-04-06".to_string(),
3801                "2008-02-17".to_string(),
3802            ]
3803        );
3804        let result = sub(&result, &b).unwrap();
3805        assert_eq!(result.as_ref(), &a);
3806
3807        let b = IntervalMonthDayNanoArray::from(vec![
3808            IntervalMonthDayNanoType::make_value(34, 2, -34353534),
3809            IntervalMonthDayNanoType::make_value(3, -3, 2443),
3810            IntervalMonthDayNanoType::make_value(-12, 4, 2323242423232),
3811        ]);
3812
3813        let result = add(&a, &b).unwrap();
3814        assert_eq!(
3815            &format_array(result.as_ref()),
3816            &[
3817                "1981-12-02".to_string(),
3818                "2010-06-30".to_string(),
3819                "2007-03-04".to_string(),
3820            ]
3821        );
3822        let result = sub(&result, &b).unwrap();
3823        assert_eq!(
3824            &format_array(result.as_ref()),
3825            &[
3826                "1979-01-31".to_string(),
3827                "2010-04-02".to_string(),
3828                "2008-02-29".to_string(),
3829            ]
3830        );
3831    }
3832
3833    #[test]
3834    fn test_date() {
3835        test_date_impl::<Date32Type, _>(Date32Type::from_naive_date);
3836        test_date_impl::<Date64Type, _>(Date64Type::from_naive_date);
3837
3838        let a = Date32Array::from(vec![i32::MIN, i32::MAX, 23, 7684]);
3839        let b = Date32Array::from(vec![i32::MIN, i32::MIN, -2, 45]);
3840        let result = sub(&a, &b).unwrap();
3841        assert_eq!(
3842            result.as_primitive::<DurationSecondType>().values(),
3843            &[0, 371085174288000, 2160000, 660009600]
3844        );
3845
3846        let a = Date64Array::from(vec![4343, 76676, 3434]);
3847        let b = Date64Array::from(vec![3, -5, 5]);
3848        let result = sub(&a, &b).unwrap();
3849        assert_eq!(
3850            result.as_primitive::<DurationMillisecondType>().values(),
3851            &[4340, 76681, 3429]
3852        );
3853
3854        let a = Date64Array::from(vec![i64::MAX]);
3855        let b = Date64Array::from(vec![-1]);
3856        let err = sub(&a, &b).unwrap_err().to_string();
3857        assert_eq!(
3858            err,
3859            "Arithmetic overflow: Overflow happened on: 9223372036854775807 - -1"
3860        );
3861    }
3862
3863    #[test]
3864    fn test_date32_to_naive_date_opt_boundaries() {
3865        assert_eq!(MAX_VALID_DAYS, 95026236);
3866        assert_eq!(MIN_VALID_DAYS, -96465292);
3867
3868        // Valid boundary dates work
3869        assert!(Date32Type::to_naive_date_opt(MAX_VALID_DAYS).is_some());
3870        assert!(Date32Type::to_naive_date_opt(MIN_VALID_DAYS).is_some());
3871
3872        // Beyond boundaries fail
3873        assert!(Date32Type::to_naive_date_opt(MAX_VALID_DAYS + 1).is_none());
3874        assert!(Date32Type::to_naive_date_opt(MIN_VALID_DAYS - 1).is_none());
3875
3876        // Extreme values fail
3877        assert!(Date32Type::to_naive_date_opt(i32::MAX).is_none());
3878        assert!(Date32Type::to_naive_date_opt(i32::MIN).is_none());
3879
3880        // Common values work
3881        assert!(Date32Type::to_naive_date_opt(0).is_some());
3882        assert!(Date32Type::to_naive_date_opt(date_to_days(YEAR_2000)).is_some());
3883    }
3884
3885    #[test]
3886    fn test_date64_to_naive_date_opt_boundaries() {
3887        const MS_PER_DAY: i64 = 24 * 60 * 60 * 1000;
3888
3889        // Verify boundary millisecond values
3890        assert_eq!(MAX_VALID_MILLIS, 8210266790400000i64);
3891        assert_eq!(MIN_VALID_MILLIS, -8334601228800000i64);
3892
3893        // Valid boundary dates work
3894        assert!(Date64Type::to_naive_date_opt(MAX_VALID_MILLIS).is_some());
3895        assert!(Date64Type::to_naive_date_opt(MIN_VALID_MILLIS).is_some());
3896
3897        // Beyond boundaries fail
3898        assert!(Date64Type::to_naive_date_opt(MAX_VALID_MILLIS + MS_PER_DAY).is_none());
3899        assert!(Date64Type::to_naive_date_opt(MIN_VALID_MILLIS - MS_PER_DAY).is_none());
3900
3901        // Extreme values fail
3902        assert!(Date64Type::to_naive_date_opt(i64::MAX).is_none());
3903        assert!(Date64Type::to_naive_date_opt(i64::MIN).is_none());
3904
3905        // Common values work
3906        assert!(Date64Type::to_naive_date_opt(0).is_some());
3907        assert!(Date64Type::to_naive_date_opt(date_to_millis(YEAR_2000)).is_some());
3908    }
3909
3910    macro_rules! test_year_month_ops {
3911        ($type:ty, $date_fn:expr) => {{
3912            let date = $date_fn(YEAR_2000);
3913
3914            // Normal operations succeed
3915            assert!(
3916                <$type>::add_year_months_opt(date, 120).is_some(),
3917                "add_year_months: normal add"
3918            );
3919            assert!(
3920                <$type>::add_year_months_opt(date, 0).is_some(),
3921                "add_year_months: zero interval"
3922            );
3923            assert!(
3924                <$type>::subtract_year_months_opt(date, 120).is_some(),
3925                "subtract_year_months: normal subtract"
3926            );
3927            assert!(
3928                <$type>::subtract_year_months_opt(date, 0).is_some(),
3929                "subtract_year_months: zero interval"
3930            );
3931
3932            // Large but valid years work
3933            let large_year = $date_fn(NaiveDate::from_ymd_opt(5000, 1, 1).unwrap());
3934            let neg_year = $date_fn(NaiveDate::from_ymd_opt(-5000, 12, 31).unwrap());
3935            assert!(
3936                <$type>::add_year_months_opt(large_year, 12).is_some(),
3937                "add_year_months: large year"
3938            );
3939            assert!(
3940                <$type>::add_year_months_opt(neg_year, -12).is_some(),
3941                "add_year_months: negative year"
3942            );
3943            assert!(
3944                <$type>::subtract_year_months_opt(large_year, 12).is_some(),
3945                "subtract_year_months: large year"
3946            );
3947            assert!(
3948                <$type>::subtract_year_months_opt(neg_year, -12).is_some(),
3949                "subtract_year_months: negative year"
3950            );
3951
3952            // Overflow handling
3953            assert!(
3954                <$type>::subtract_year_months_opt($date_fn(MIN_VALID_DATE), 1).is_none(),
3955                "subtract_year_months: overflow days from min"
3956            );
3957            assert!(
3958                <$type>::subtract_year_months_opt($date_fn(MAX_VALID_DATE), -1).is_none(),
3959                "subtract_year_months: overflow neg days from max"
3960            );
3961            assert!(
3962                <$type>::add_year_months_opt($date_fn(MAX_VALID_DATE), 1).is_none(),
3963                "add_year_months: overflow days"
3964            );
3965            assert!(
3966                <$type>::add_year_months_opt($date_fn(MIN_VALID_DATE), -1).is_none(),
3967                "add_year_months: overflow neg days"
3968            );
3969        }};
3970    }
3971
3972    #[test]
3973    fn test_date_year_month_operations() {
3974        test_year_month_ops!(Date32Type, date_to_days);
3975        test_year_month_ops!(Date64Type, date_to_millis);
3976    }
3977
3978    macro_rules! test_day_time_ops {
3979        ($type:ty, $date_fn:expr) => {{
3980            let date = $date_fn(YEAR_2000);
3981
3982            // Moderate intervals succeed
3983            assert!(
3984                <$type>::add_day_time_opt(date, IntervalDayTime::new(30, 0)).is_some(),
3985                "add_day_time: +30 days"
3986            );
3987            assert!(
3988                <$type>::add_day_time_opt(date, IntervalDayTime::new(-30, 0)).is_some(),
3989                "add_day_time: -30 days"
3990            );
3991            assert!(
3992                <$type>::add_day_time_opt(date, IntervalDayTime::new(1000, 12345)).is_some(),
3993                "add_day_time: normal"
3994            );
3995            assert!(
3996                <$type>::subtract_day_time_opt(date, IntervalDayTime::new(30, 0)).is_some(),
3997                "subtract_day_time: +30 days"
3998            );
3999            assert!(
4000                <$type>::subtract_day_time_opt(date, IntervalDayTime::new(-30, 0)).is_some(),
4001                "subtract_day_time: -30 days"
4002            );
4003            assert!(
4004                <$type>::subtract_day_time_opt(date, IntervalDayTime::new(1000, 12345)).is_some(),
4005                "subtract_day_time: normal"
4006            );
4007
4008            // Overflow handling - subtract
4009            assert!(
4010                <$type>::subtract_day_time_opt(
4011                    $date_fn(MIN_VALID_DATE),
4012                    IntervalDayTime::new(1, 0)
4013                )
4014                .is_none(),
4015                "subtract_day_time: overflow days from min"
4016            );
4017            assert!(
4018                <$type>::subtract_day_time_opt(
4019                    $date_fn(MAX_VALID_DATE),
4020                    IntervalDayTime::new(-1, 0)
4021                )
4022                .is_none(),
4023                "subtract_day_time: overflow neg days from max"
4024            );
4025
4026            // Overflow handling - add
4027            assert!(
4028                <$type>::add_day_time_opt($date_fn(MAX_VALID_DATE), IntervalDayTime::new(1, 0))
4029                    .is_none(),
4030                "add_day_time: overflow days"
4031            );
4032            assert!(
4033                <$type>::add_day_time_opt($date_fn(MIN_VALID_DATE), IntervalDayTime::new(-1, 0))
4034                    .is_none(),
4035                "add_day_time: overflow neg days"
4036            );
4037
4038            // Extreme intervals fail
4039            assert!(
4040                <$type>::add_day_time_opt(
4041                    $date_fn(EPOCH),
4042                    IntervalDayTime::new(i32::MAX, i32::MAX)
4043                )
4044                .is_none(),
4045                "add_day_time: max interval"
4046            );
4047            assert!(
4048                <$type>::add_day_time_opt(
4049                    $date_fn(EPOCH),
4050                    IntervalDayTime::new(i32::MIN, i32::MIN)
4051                )
4052                .is_none(),
4053                "add_day_time: min interval"
4054            );
4055            assert!(
4056                <$type>::subtract_day_time_opt(
4057                    $date_fn(EPOCH),
4058                    IntervalDayTime::new(i32::MAX, i32::MAX)
4059                )
4060                .is_none(),
4061                "subtract_day_time: max interval"
4062            );
4063            assert!(
4064                <$type>::subtract_day_time_opt(
4065                    $date_fn(EPOCH),
4066                    IntervalDayTime::new(i32::MIN, i32::MIN)
4067                )
4068                .is_none(),
4069                "subtract_day_time: min interval"
4070            );
4071        }};
4072    }
4073
4074    #[test]
4075    fn test_date_day_time_operations() {
4076        test_day_time_ops!(Date32Type, date_to_days);
4077        test_day_time_ops!(Date64Type, date_to_millis);
4078    }
4079
4080    macro_rules! test_month_day_nano_ops {
4081        ($type:ty, $date_fn:expr) => {{
4082            let date = $date_fn(YEAR_2000);
4083            let zero = IntervalMonthDayNano::new(0, 0, 0);
4084
4085            // Normal operations succeed
4086            assert!(
4087                <$type>::add_month_day_nano_opt(date, IntervalMonthDayNano::new(1, 30, 0))
4088                    .is_some(),
4089                "add_month_day_nano: +1mo +30d"
4090            );
4091            assert!(
4092                <$type>::add_month_day_nano_opt(date, IntervalMonthDayNano::new(-1, -30, 0))
4093                    .is_some(),
4094                "add_month_day_nano: -1mo -30d"
4095            );
4096            assert!(
4097                <$type>::add_month_day_nano_opt(date, zero).is_some(),
4098                "add_month_day_nano: zero interval"
4099            );
4100            assert!(
4101                <$type>::add_month_day_nano_opt(
4102                    date,
4103                    IntervalMonthDayNano::new(2, 10, 123_456_789_000)
4104                )
4105                .is_some(),
4106                "add_month_day_nano: normal"
4107            );
4108            assert!(
4109                <$type>::subtract_month_day_nano_opt(date, IntervalMonthDayNano::new(1, 30, 0))
4110                    .is_some(),
4111                "subtract_month_day_nano: +1mo +30d"
4112            );
4113            assert!(
4114                <$type>::subtract_month_day_nano_opt(date, IntervalMonthDayNano::new(-1, -30, 0))
4115                    .is_some(),
4116                "subtract_month_day_nano: -1mo -30d"
4117            );
4118            assert!(
4119                <$type>::subtract_month_day_nano_opt(date, zero).is_some(),
4120                "subtract_month_day_nano: zero interval"
4121            );
4122            assert!(
4123                <$type>::subtract_month_day_nano_opt(
4124                    date,
4125                    IntervalMonthDayNano::new(2, 10, 123_456_789_000)
4126                )
4127                .is_some(),
4128                "subtract_month_day_nano: normal"
4129            );
4130
4131            // Overflow handling - subtract
4132            assert!(
4133                <$type>::subtract_month_day_nano_opt(
4134                    $date_fn(MIN_VALID_DATE),
4135                    IntervalMonthDayNano::new(0, 1, 0)
4136                )
4137                .is_none(),
4138                "subtract_month_day_nano: overflow days from min"
4139            );
4140            assert!(
4141                <$type>::subtract_month_day_nano_opt(
4142                    $date_fn(MAX_VALID_DATE),
4143                    IntervalMonthDayNano::new(0, -1, 0)
4144                )
4145                .is_none(),
4146                "subtract_month_day_nano: overflow neg days from max"
4147            );
4148
4149            // Overflow handling - add
4150            assert!(
4151                <$type>::add_month_day_nano_opt(
4152                    $date_fn(MAX_VALID_DATE),
4153                    IntervalMonthDayNano::new(0, 1, 0)
4154                )
4155                .is_none(),
4156                "add_month_day_nano: overflow days"
4157            );
4158            assert!(
4159                <$type>::add_month_day_nano_opt(
4160                    $date_fn(MIN_VALID_DATE),
4161                    IntervalMonthDayNano::new(0, -1, 0)
4162                )
4163                .is_none(),
4164                "add_month_day_nano: overflow neg days"
4165            );
4166
4167            // Nanosecond precision works
4168            assert!(
4169                <$type>::add_month_day_nano_opt(date, IntervalMonthDayNano::new(0, 0, 999_999_999))
4170                    .is_some(),
4171                "add_month_day_nano: nanos"
4172            );
4173            assert!(
4174                <$type>::subtract_month_day_nano_opt(
4175                    date,
4176                    IntervalMonthDayNano::new(0, 0, 999_999_999)
4177                )
4178                .is_some(),
4179                "subtract_month_day_nano: nanos"
4180            );
4181            // 1 day in nanos
4182            assert!(
4183                <$type>::add_month_day_nano_opt(
4184                    date,
4185                    IntervalMonthDayNano::new(0, 0, 86_400_000_000_000)
4186                )
4187                .is_some(),
4188                "add_month_day_nano: 1 day nanos"
4189            );
4190            assert!(
4191                <$type>::subtract_month_day_nano_opt(
4192                    date,
4193                    IntervalMonthDayNano::new(0, 0, 86_400_000_000_000)
4194                )
4195                .is_some(),
4196                "subtract_month_day_nano: 1 day nanos"
4197            );
4198        }};
4199    }
4200
4201    #[test]
4202    fn test_date_month_day_nano_operations() {
4203        test_month_day_nano_ops!(Date32Type, date_to_days);
4204        test_month_day_nano_ops!(Date64Type, date_to_millis);
4205    }
4206
4207    #[test]
4208    fn test_date_sub_interval_min_months() {
4209        // Subtracting i32::MIN months requires negating i32::MIN, which
4210        // overflows i32: the date kernels must return the Date arithmetic
4211        // overflow error instead of panicking in debug builds
4212        // https://github.com/apache/arrow-rs/issues/11600
4213        let dates: [ArrayRef; 2] = [
4214            Arc::new(Date32Array::from(vec![0])),
4215            Arc::new(Date64Array::from(vec![0])),
4216        ];
4217        let year_month = IntervalYearMonthArray::from(vec![i32::MIN]);
4218        let month_day_nano =
4219            IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNano::new(i32::MIN, 0, 0)]);
4220        for dates in &dates {
4221            assert_eq!(
4222                sub(dates, &year_month).unwrap_err().to_string(),
4223                "Compute error: Date arithmetic overflow: 0 - -2147483648 months"
4224            );
4225            assert_eq!(
4226                sub(dates, &month_day_nano).unwrap_err().to_string(),
4227                "Compute error: Date arithmetic overflow: 0 - IntervalMonthDayNano { months: -2147483648, days: 0, nanoseconds: 0 }"
4228            );
4229        }
4230    }
4231}