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::convert::Infallible;
9use std::fmt::Formatter;
10use std::sync::Arc;
11
12use arrow_array::cast::AsArray;
13use arrow_array::temporal_conversions::{NANOSECONDS, SECONDS_IN_DAY};
14use arrow_array::timezone::Tz;
15use arrow_array::types::*;
16use arrow_array::*;
17use arrow_buffer::{
18    ArrowNativeType, DivisorI32, DivisorI64, DivisorU32, DivisorU64, IntervalDayTime,
19    IntervalMonthDayNano,
20};
21use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
22use num_traits::{CheckedMul, ToPrimitive};
23
24use crate::arity::{binary, try_binary};
25
26/// Perform `lhs + rhs`, returning an error on overflow
27pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
28    arithmetic_op(Op::Add, lhs, rhs)
29}
30
31/// Perform `lhs + rhs`, wrapping on overflow for [`DataType::is_integer`]
32pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
33    arithmetic_op(Op::AddWrapping, lhs, rhs)
34}
35
36/// Perform `lhs - rhs`, returning an error on overflow
37pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
38    arithmetic_op(Op::Sub, lhs, rhs)
39}
40
41/// Perform `lhs - rhs`, wrapping on overflow for [`DataType::is_integer`]
42pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
43    arithmetic_op(Op::SubWrapping, lhs, rhs)
44}
45
46/// Perform `lhs * rhs`, returning an error on overflow
47pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
48    arithmetic_op(Op::Mul, lhs, rhs)
49}
50
51/// Perform `lhs * rhs`, wrapping on overflow for [`DataType::is_integer`]
52pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
53    arithmetic_op(Op::MulWrapping, lhs, rhs)
54}
55
56/// Perform `lhs / rhs`
57///
58/// Overflow or division by zero will result in an error, with exception to
59/// floating point numbers, which instead follow the IEEE 754 rules
60pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
61    arithmetic_op(Op::Div, lhs, rhs)
62}
63
64/// Perform `lhs % rhs`
65///
66/// Division by zero will result in an error, with exception to
67/// floating point numbers, which instead follow the IEEE 754 rules
68///
69/// `signed_integer::MIN % -1` will not result in an error but return 0
70pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
71    arithmetic_op(Op::Rem, lhs, rhs)
72}
73
74macro_rules! neg_checked {
75    ($t:ty, $a:ident) => {{
76        let array = $a
77            .as_primitive::<$t>()
78            .try_unary::<_, $t, _>(|x| x.neg_checked())?;
79        Ok(Arc::new(array))
80    }};
81}
82
83macro_rules! neg_wrapping {
84    ($t:ty, $a:ident) => {{
85        let array = $a.as_primitive::<$t>().unary::<_, $t>(|x| x.neg_wrapping());
86        Ok(Arc::new(array))
87    }};
88}
89
90/// Negates each element of  `array`, returning an error on overflow
91///
92/// Note: negation of unsigned arrays is not supported and will return in an error,
93/// for wrapping unsigned negation consider using [`neg_wrapping`][neg_wrapping()]
94pub fn neg(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
95    use DataType::*;
96    use IntervalUnit::*;
97    use TimeUnit::*;
98
99    match array.data_type() {
100        Int8 => neg_checked!(Int8Type, array),
101        Int16 => neg_checked!(Int16Type, array),
102        Int32 => neg_checked!(Int32Type, array),
103        Int64 => neg_checked!(Int64Type, array),
104        Float16 => neg_wrapping!(Float16Type, array),
105        Float32 => neg_wrapping!(Float32Type, array),
106        Float64 => neg_wrapping!(Float64Type, array),
107        Decimal32(p, s) => {
108            let a = array
109                .as_primitive::<Decimal32Type>()
110                .try_unary::<_, Decimal32Type, _>(|x| x.neg_checked())?;
111
112            Ok(Arc::new(a.with_precision_and_scale(*p, *s)?))
113        }
114        Decimal64(p, s) => {
115            let a = array
116                .as_primitive::<Decimal64Type>()
117                .try_unary::<_, Decimal64Type, _>(|x| x.neg_checked())?;
118
119            Ok(Arc::new(a.with_precision_and_scale(*p, *s)?))
120        }
121        Decimal128(p, s) => {
122            let a = array
123                .as_primitive::<Decimal128Type>()
124                .try_unary::<_, Decimal128Type, _>(|x| x.neg_checked())?;
125
126            Ok(Arc::new(a.with_precision_and_scale(*p, *s)?))
127        }
128        Decimal256(p, s) => {
129            let a = array
130                .as_primitive::<Decimal256Type>()
131                .try_unary::<_, Decimal256Type, _>(|x| x.neg_checked())?;
132
133            Ok(Arc::new(a.with_precision_and_scale(*p, *s)?))
134        }
135        Duration(Second) => neg_checked!(DurationSecondType, array),
136        Duration(Millisecond) => neg_checked!(DurationMillisecondType, array),
137        Duration(Microsecond) => neg_checked!(DurationMicrosecondType, array),
138        Duration(Nanosecond) => neg_checked!(DurationNanosecondType, array),
139        Interval(YearMonth) => neg_checked!(IntervalYearMonthType, array),
140        Interval(DayTime) => {
141            let a = array
142                .as_primitive::<IntervalDayTimeType>()
143                .try_unary::<_, IntervalDayTimeType, ArrowError>(|x| {
144                    let (days, ms) = IntervalDayTimeType::to_parts(x);
145                    Ok(IntervalDayTimeType::make_value(
146                        days.neg_checked()?,
147                        ms.neg_checked()?,
148                    ))
149                })?;
150            Ok(Arc::new(a))
151        }
152        Interval(MonthDayNano) => {
153            let a = array
154                .as_primitive::<IntervalMonthDayNanoType>()
155                .try_unary::<_, IntervalMonthDayNanoType, ArrowError>(|x| {
156                    let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(x);
157                    Ok(IntervalMonthDayNanoType::make_value(
158                        months.neg_checked()?,
159                        days.neg_checked()?,
160                        nanos.neg_checked()?,
161                    ))
162                })?;
163            Ok(Arc::new(a))
164        }
165        t => Err(ArrowError::InvalidArgumentError(format!(
166            "Invalid arithmetic operation: !{t}"
167        ))),
168    }
169}
170
171/// Negates each element of  `array`, wrapping on overflow for [`DataType::is_integer`]
172pub fn neg_wrapping(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
173    downcast_integer! {
174        array.data_type() => (neg_wrapping, array),
175        _ => neg(array),
176    }
177}
178
179/// An enumeration of arithmetic operations
180///
181/// This allows sharing the type dispatch logic across the various kernels
182#[derive(Debug, Copy, Clone)]
183enum Op {
184    AddWrapping,
185    Add,
186    SubWrapping,
187    Sub,
188    MulWrapping,
189    Mul,
190    Div,
191    Rem,
192}
193
194impl std::fmt::Display for Op {
195    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
196        match self {
197            Op::AddWrapping | Op::Add => write!(f, "+"),
198            Op::SubWrapping | Op::Sub => write!(f, "-"),
199            Op::MulWrapping | Op::Mul => write!(f, "*"),
200            Op::Div => write!(f, "/"),
201            Op::Rem => write!(f, "%"),
202        }
203    }
204}
205
206impl Op {
207    fn commutative(&self) -> bool {
208        matches!(
209            self,
210            Self::Add | Self::AddWrapping | Self::Mul | Self::MulWrapping
211        )
212    }
213}
214
215/// Dispatch the given `op` to the appropriate specialized kernel
216fn arithmetic_op(op: Op, lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
217    use DataType::*;
218    use IntervalUnit::*;
219    use TimeUnit::*;
220
221    macro_rules! integer_helper {
222        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
223            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
224        };
225    }
226
227    let (l, l_scalar) = lhs.get();
228    let (r, r_scalar) = rhs.get();
229    if matches!(op, Op::Div | Op::Rem) && !l_scalar && r_scalar {
230        let array = match (l.data_type(), r.data_type()) {
231            (Int32, Int32) => divisor_op_i32(op, l, r),
232            (Int64, Int64) => divisor_op_i64(op, l, r),
233            (UInt32, UInt32) => divisor_op_u32(op, l, r),
234            (UInt64, UInt64) => divisor_op_u64(op, l, r),
235            _ => None,
236        };
237        if let Some(array) = array {
238            return Ok(array);
239        }
240    }
241    downcast_integer! {
242        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
243        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
244        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
245        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
246        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
247        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
248        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
249        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
250        (Duration(Second), Duration(Second)) => duration_op::<DurationSecondType>(op, l, l_scalar, r, r_scalar),
251        (Duration(Millisecond), Duration(Millisecond)) => duration_op::<DurationMillisecondType>(op, l, l_scalar, r, r_scalar),
252        (Duration(Microsecond), Duration(Microsecond)) => duration_op::<DurationMicrosecondType>(op, l, l_scalar, r, r_scalar),
253        (Duration(Nanosecond), Duration(Nanosecond)) => duration_op::<DurationNanosecondType>(op, l, l_scalar, r, r_scalar),
254        (Interval(YearMonth), Interval(YearMonth) | Int64) => interval_op::<IntervalYearMonthType>(op, l, l_scalar, r, r_scalar),
255        (Interval(DayTime), Interval(DayTime) | Int64) => interval_op::<IntervalDayTimeType>(op, l, l_scalar, r, r_scalar),
256        (Interval(MonthDayNano), Interval(MonthDayNano) | Int64) => interval_op::<IntervalMonthDayNanoType>(op, l, l_scalar, r, r_scalar),
257        (Interval(MonthDayNano), Float64) => interval_f64_op(op, l, l_scalar, r, r_scalar),
258        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
259        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
260        (Decimal32(_, _), Decimal32(_, _)) => decimal_op::<Decimal32Type>(op, l, l_scalar, r, r_scalar),
261        (Decimal64(_, _), Decimal64(_, _)) => decimal_op::<Decimal64Type>(op, l, l_scalar, r, r_scalar),
262        (Decimal128(_, _), Decimal128(_, _)) => decimal_op::<Decimal128Type>(op, l, l_scalar, r, r_scalar),
263        (Decimal256(_, _), Decimal256(_, _)) => decimal_op::<Decimal256Type>(op, l, l_scalar, r, r_scalar),
264        (l_t, r_t) => match (l_t, r_t) {
265            (Duration(_) | Interval(_), Date32 | Date64 | Timestamp(_, _)) if op.commutative() => {
266                arithmetic_op(op, rhs, lhs)
267            }
268            (Int64, Interval(_)) | (Float64, Interval(MonthDayNano))
269                if matches!(op, Op::Mul) =>
270            {
271                arithmetic_op(op, rhs, lhs)
272            }
273            _ => Err(ArrowError::InvalidArgumentError(
274              format!("Invalid arithmetic operation: {l_t} {op} {r_t}")
275            ))
276        }
277    }
278}
279
280/// Perform an infallible binary operation on potentially scalar inputs
281macro_rules! op {
282    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
283        match ($l_s, $r_s) {
284            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
285            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
286                None => PrimitiveArray::new_null($r.len()),
287                Some($l) => $r.unary(|$r| $op),
288            },
289            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
290                None => PrimitiveArray::new_null($l.len()),
291                Some($r) => $l.unary(|$l| $op),
292            },
293        }
294    };
295}
296
297/// Same as `op` but with a type hint for the returned array
298macro_rules! op_ref {
299    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
300        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
301        Arc::new(array)
302    }};
303}
304
305/// Perform a fallible binary operation on potentially scalar inputs
306macro_rules! try_op {
307    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
308        match ($l_s, $r_s) {
309            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
310            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
311                None => PrimitiveArray::new_null($r.len()),
312                Some($l) => $r.try_unary(|$r| $op)?,
313            },
314            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
315                None => PrimitiveArray::new_null($l.len()),
316                Some($r) => $l.try_unary(|$l| $op)?,
317            },
318        }
319    };
320}
321
322/// Same as `try_op` but with a type hint for the returned array
323macro_rules! try_op_ref {
324    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
325        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
326        Arc::new(array)
327    }};
328}
329
330/// Defines `$fn`, which computes `/` or `%` of an array by a scalar with a precomputed divisor.
331/// It returns `None` for an op other than `/` and `%`, when the scalar is null, or when a value
332/// could fail to divide by it (zero, or `$fallible` for `/`), so that `integer_op` returns an
333/// error only for a valid value that fails. Otherwise no value can fail, and `unary` divides
334/// every slot, null or not, unless the array has more than `$max_nulls` nulls, where dividing
335/// only the valid values with `try_unary` costs less
336macro_rules! divisor_op {
337    (
338        $fn:ident,
339        $t:ty,
340        $divisor:ident,
341        |$d:ident| $fallible:expr,
342        |$len:ident| $max_nulls:expr,
343        [$($variant:ident),+]
344    ) => {
345        fn $fn(op: Op, l: &dyn Array, r: &dyn Array) -> Option<ArrayRef> {
346            let r = r.as_primitive::<$t>();
347            if r.null_count() != 0 {
348                return None;
349            }
350            let $d = r.value(0);
351            if matches!(op, Op::Div) && $fallible {
352                return None;
353            }
354            let divisor = $divisor::new($d)?;
355            let l = l.as_primitive::<$t>();
356            let $len = l.len();
357            if l.null_count() > $max_nulls {
358                // Calling the enum's `wrapping_div_rem`, which matches on the variant, keeps this
359                // to one `try_unary` per op
360                let Ok(array) = match op {
361                    Op::Div => l.try_unary::<_, $t, Infallible>(move |n| {
362                        Ok(divisor.wrapping_div_rem(n).0)
363                    }),
364                    Op::Rem => l.try_unary::<_, $t, Infallible>(move |n| {
365                        Ok(divisor.wrapping_div_rem(n).1)
366                    }),
367                    _ => return None,
368                };
369                return Some(Arc::new(array));
370            }
371            // Match on the variant once, outside the loop, and move it into the closure, so the
372            // loop doesn't branch on the variant. The `Op::Div` and `Op::Rem` arms after the
373            // variants cover variants that arrow-buffer may add later
374            let array: PrimitiveArray<$t> = match (op, divisor) {
375                $(
376                    (Op::Div, $divisor::$variant(d)) => l.unary(move |n| d.wrapping_div_rem(n).0),
377                    (Op::Rem, $divisor::$variant(d)) => l.unary(move |n| d.wrapping_div_rem(n).1),
378                )+
379                (Op::Div, d) => l.unary(move |n| d.wrapping_div_rem(n).0),
380                (Op::Rem, d) => l.unary(move |n| d.wrapping_div_rem(n).1),
381                _ => return None,
382            };
383            Some(Arc::new(array))
384        }
385    };
386}
387
388// `MIN / -1` overflows, but `%` by -1 doesn't, because `integer_op` computes `%` with
389// `mod_wrapping`.
390//
391// `unary` costs the same whatever the nulls, and `try_unary` visits only the valid values. On x86,
392// `unary` is slower than `integer_op`'s `try_unary` with a hardware divide above roughly 60% nulls
393// for `Int32` and `Int64`, so more than half null takes `try_unary`. `UInt32`'s `unary` loop is
394// the cheapest, and on x86 its `try_unary` costs about as much as `integer_op`'s, so it stays on
395// `unary` up to three quarters null. Its `%` on `unary` falls behind `integer_op`'s at roughly 80%
396divisor_op!(
397    divisor_op_i32,
398    Int32Type,
399    DivisorI32,
400    |d| d == -1,
401    |len| len / 2,
402    [PowerOfTwo, AddIndicator]
403);
404divisor_op!(
405    divisor_op_i64,
406    Int64Type,
407    DivisorI64,
408    |d| d == -1,
409    |len| len / 2,
410    [PowerOfTwo, AddIndicator]
411);
412divisor_op!(
413    divisor_op_u32,
414    UInt32Type,
415    DivisorU32,
416    |_d| false,
417    |len| len / 4 * 3,
418    [PowerOfTwo, Up, Down, AddIndicator]
419);
420divisor_op!(
421    divisor_op_u64,
422    UInt64Type,
423    DivisorU64,
424    |_d| false,
425    |len| len / 2,
426    [PowerOfTwo, Up, AddIndicator]
427);
428
429/// Perform an arithmetic operation on integers
430fn integer_op<T: ArrowPrimitiveType>(
431    op: Op,
432    l: &dyn Array,
433    l_s: bool,
434    r: &dyn Array,
435    r_s: bool,
436) -> Result<ArrayRef, ArrowError> {
437    let l = l.as_primitive::<T>();
438    let r = r.as_primitive::<T>();
439    let array: PrimitiveArray<T> = match op {
440        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
441        Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)),
442        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
443        Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
444        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
445        Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
446        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
447        Op::Rem => try_op!(l, l_s, r, r_s, {
448            if r.is_zero() {
449                Err(ArrowError::DivideByZero)
450            } else {
451                Ok(l.mod_wrapping(r))
452            }
453        }),
454    };
455    Ok(Arc::new(array))
456}
457
458/// Perform an arithmetic operation on floats
459fn float_op<T: ArrowPrimitiveType>(
460    op: Op,
461    l: &dyn Array,
462    l_s: bool,
463    r: &dyn Array,
464    r_s: bool,
465) -> Result<ArrayRef, ArrowError> {
466    let l = l.as_primitive::<T>();
467    let r = r.as_primitive::<T>();
468    let array: PrimitiveArray<T> = match op {
469        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),
470        Op::SubWrapping | Op::Sub => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
471        Op::MulWrapping | Op::Mul => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
472        Op::Div => op!(l, l_s, r, r_s, l.div_wrapping(r)),
473        Op::Rem => op!(l, l_s, r, r_s, l.mod_wrapping(r)),
474    };
475    Ok(Arc::new(array))
476}
477
478/// Arithmetic trait for timestamp arrays
479trait TimestampOp: ArrowTimestampType {
480    type Duration: ArrowPrimitiveType<Native = i64>;
481
482    fn add_year_month(timestamp: i64, delta: i32, tz: Tz) -> Option<i64>;
483    fn add_day_time(timestamp: i64, delta: IntervalDayTime, tz: Tz) -> Option<i64>;
484    fn add_month_day_nano(timestamp: i64, delta: IntervalMonthDayNano, tz: Tz) -> Option<i64>;
485
486    fn sub_year_month(timestamp: i64, delta: i32, tz: Tz) -> Option<i64>;
487    fn sub_day_time(timestamp: i64, delta: IntervalDayTime, tz: Tz) -> Option<i64>;
488    fn sub_month_day_nano(timestamp: i64, delta: IntervalMonthDayNano, tz: Tz) -> Option<i64>;
489}
490
491macro_rules! timestamp {
492    ($t:ty, $d:ty) => {
493        impl TimestampOp for $t {
494            type Duration = $d;
495
496            fn add_year_month(left: i64, right: i32, tz: Tz) -> Option<i64> {
497                Self::add_year_months(left, right, tz)
498            }
499
500            fn add_day_time(left: i64, right: IntervalDayTime, tz: Tz) -> Option<i64> {
501                Self::add_day_time(left, right, tz)
502            }
503
504            fn add_month_day_nano(left: i64, right: IntervalMonthDayNano, tz: Tz) -> Option<i64> {
505                Self::add_month_day_nano(left, right, tz)
506            }
507
508            fn sub_year_month(left: i64, right: i32, tz: Tz) -> Option<i64> {
509                Self::subtract_year_months(left, right, tz)
510            }
511
512            fn sub_day_time(left: i64, right: IntervalDayTime, tz: Tz) -> Option<i64> {
513                Self::subtract_day_time(left, right, tz)
514            }
515
516            fn sub_month_day_nano(left: i64, right: IntervalMonthDayNano, tz: Tz) -> Option<i64> {
517                Self::subtract_month_day_nano(left, right, tz)
518            }
519        }
520    };
521}
522timestamp!(TimestampSecondType, DurationSecondType);
523timestamp!(TimestampMillisecondType, DurationMillisecondType);
524timestamp!(TimestampMicrosecondType, DurationMicrosecondType);
525timestamp!(TimestampNanosecondType, DurationNanosecondType);
526
527/// Perform arithmetic operation on a timestamp array
528fn timestamp_op<T: TimestampOp>(
529    op: Op,
530    l: &dyn Array,
531    l_s: bool,
532    r: &dyn Array,
533    r_s: bool,
534) -> Result<ArrayRef, ArrowError> {
535    use DataType::*;
536    use IntervalUnit::*;
537
538    let l = l.as_primitive::<T>();
539    let l_tz: Tz = l.timezone().unwrap_or("+00:00").parse()?;
540
541    let array: PrimitiveArray<T> = match (op, r.data_type()) {
542        (Op::Sub | Op::SubWrapping, Timestamp(unit, _)) if unit == &T::UNIT => {
543            let r = r.as_primitive::<T>();
544            return Ok(try_op_ref!(T::Duration, l, l_s, r, r_s, l.sub_checked(r)));
545        }
546
547        (Op::Add | Op::AddWrapping, Duration(unit)) if unit == &T::UNIT => {
548            let r = r.as_primitive::<T::Duration>();
549            try_op!(l, l_s, r, r_s, l.add_checked(r))
550        }
551        (Op::Sub | Op::SubWrapping, Duration(unit)) if unit == &T::UNIT => {
552            let r = r.as_primitive::<T::Duration>();
553            try_op!(l, l_s, r, r_s, l.sub_checked(r))
554        }
555
556        (Op::Add | Op::AddWrapping, Interval(YearMonth)) => {
557            let r = r.as_primitive::<IntervalYearMonthType>();
558            try_op!(
559                l,
560                l_s,
561                r,
562                r_s,
563                T::add_year_month(l, r, l_tz).ok_or(ArrowError::ComputeError(
564                    "Timestamp out of range".to_string()
565                ))
566            )
567        }
568        (Op::Sub | Op::SubWrapping, Interval(YearMonth)) => {
569            let r = r.as_primitive::<IntervalYearMonthType>();
570            try_op!(
571                l,
572                l_s,
573                r,
574                r_s,
575                T::sub_year_month(l, r, l_tz).ok_or(ArrowError::ComputeError(
576                    "Timestamp out of range".to_string()
577                ))
578            )
579        }
580
581        (Op::Add | Op::AddWrapping, Interval(DayTime)) => {
582            let r = r.as_primitive::<IntervalDayTimeType>();
583            try_op!(
584                l,
585                l_s,
586                r,
587                r_s,
588                T::add_day_time(l, r, l_tz).ok_or(ArrowError::ComputeError(
589                    "Timestamp out of range".to_string()
590                ))
591            )
592        }
593        (Op::Sub | Op::SubWrapping, Interval(DayTime)) => {
594            let r = r.as_primitive::<IntervalDayTimeType>();
595            try_op!(
596                l,
597                l_s,
598                r,
599                r_s,
600                T::sub_day_time(l, r, l_tz).ok_or(ArrowError::ComputeError(
601                    "Timestamp out of range".to_string()
602                ))
603            )
604        }
605
606        (Op::Add | Op::AddWrapping, Interval(MonthDayNano)) => {
607            let r = r.as_primitive::<IntervalMonthDayNanoType>();
608            try_op!(
609                l,
610                l_s,
611                r,
612                r_s,
613                T::add_month_day_nano(l, r, l_tz).ok_or(ArrowError::ComputeError(
614                    "Timestamp out of range".to_string()
615                ))
616            )
617        }
618        (Op::Sub | Op::SubWrapping, Interval(MonthDayNano)) => {
619            let r = r.as_primitive::<IntervalMonthDayNanoType>();
620            try_op!(
621                l,
622                l_s,
623                r,
624                r_s,
625                T::sub_month_day_nano(l, r, l_tz).ok_or(ArrowError::ComputeError(
626                    "Timestamp out of range".to_string()
627                ))
628            )
629        }
630        _ => {
631            return Err(ArrowError::InvalidArgumentError(format!(
632                "Invalid timestamp arithmetic operation: {} {op} {}",
633                l.data_type(),
634                r.data_type()
635            )));
636        }
637    };
638    Ok(Arc::new(array.with_timezone_opt(l.timezone())))
639}
640
641/// Arithmetic trait for date arrays
642trait DateOp: ArrowTemporalType {
643    fn add_year_month(timestamp: Self::Native, delta: i32) -> Result<Self::Native, ArrowError>;
644    fn add_day_time(
645        timestamp: Self::Native,
646        delta: IntervalDayTime,
647    ) -> Result<Self::Native, ArrowError>;
648    fn add_month_day_nano(
649        timestamp: Self::Native,
650        delta: IntervalMonthDayNano,
651    ) -> Result<Self::Native, ArrowError>;
652
653    fn sub_year_month(timestamp: Self::Native, delta: i32) -> Result<Self::Native, ArrowError>;
654    fn sub_day_time(
655        timestamp: Self::Native,
656        delta: IntervalDayTime,
657    ) -> Result<Self::Native, ArrowError>;
658    fn sub_month_day_nano(
659        timestamp: Self::Native,
660        delta: IntervalMonthDayNano,
661    ) -> Result<Self::Native, ArrowError>;
662}
663
664macro_rules! date {
665    ($t:ty) => {
666        impl DateOp for $t {
667            fn add_year_month(left: Self::Native, right: i32) -> Result<Self::Native, ArrowError> {
668                Self::add_year_months_opt(left, right).ok_or_else(|| {
669                    ArrowError::ComputeError(format!(
670                        "Date arithmetic overflow: {left} + {right} months"
671                    ))
672                })
673            }
674
675            fn add_day_time(
676                left: Self::Native,
677                right: IntervalDayTime,
678            ) -> Result<Self::Native, ArrowError> {
679                Self::add_day_time_opt(left, right).ok_or_else(|| {
680                    ArrowError::ComputeError(format!(
681                        "Date arithmetic overflow: {left} + {right:?}"
682                    ))
683                })
684            }
685
686            fn add_month_day_nano(
687                left: Self::Native,
688                right: IntervalMonthDayNano,
689            ) -> Result<Self::Native, ArrowError> {
690                Self::add_month_day_nano_opt(left, right).ok_or_else(|| {
691                    ArrowError::ComputeError(format!(
692                        "Date arithmetic overflow: {left} + {right:?}"
693                    ))
694                })
695            }
696
697            fn sub_year_month(left: Self::Native, right: i32) -> Result<Self::Native, ArrowError> {
698                Self::subtract_year_months_opt(left, right).ok_or_else(|| {
699                    ArrowError::ComputeError(format!(
700                        "Date arithmetic overflow: {left} - {right} months"
701                    ))
702                })
703            }
704
705            fn sub_day_time(
706                left: Self::Native,
707                right: IntervalDayTime,
708            ) -> Result<Self::Native, ArrowError> {
709                Self::subtract_day_time_opt(left, right).ok_or_else(|| {
710                    ArrowError::ComputeError(format!(
711                        "Date arithmetic overflow: {left} - {right:?}"
712                    ))
713                })
714            }
715
716            fn sub_month_day_nano(
717                left: Self::Native,
718                right: IntervalMonthDayNano,
719            ) -> Result<Self::Native, ArrowError> {
720                Self::subtract_month_day_nano_opt(left, right).ok_or_else(|| {
721                    ArrowError::ComputeError(format!(
722                        "Date arithmetic overflow: {left} - {right:?}"
723                    ))
724                })
725            }
726        }
727    };
728}
729
730date!(Date32Type);
731date!(Date64Type);
732
733/// Arithmetic trait for interval arrays
734trait IntervalOp: ArrowPrimitiveType {
735    fn add(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError>;
736    fn sub(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError>;
737    fn mul_i64(left: Self::Native, right: i64) -> Result<Self::Native, ArrowError>;
738}
739
740fn mul_i32_i64(left: i32, right: i64) -> Result<i32, ArrowError> {
741    let value = i64::from(left).mul_checked(right)?;
742    i32::try_from(value).map_err(|_| {
743        ArrowError::ArithmeticOverflow(format!("Overflow happened on: {left} * {right}"))
744    })
745}
746
747impl IntervalOp for IntervalYearMonthType {
748    fn add(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
749        left.add_checked(right)
750    }
751
752    fn sub(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
753        left.sub_checked(right)
754    }
755
756    fn mul_i64(left: Self::Native, right: i64) -> Result<Self::Native, ArrowError> {
757        mul_i32_i64(left, right)
758    }
759}
760
761impl IntervalOp for IntervalDayTimeType {
762    fn add(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
763        let (l_days, l_ms) = Self::to_parts(left);
764        let (r_days, r_ms) = Self::to_parts(right);
765        let days = l_days.add_checked(r_days)?;
766        let ms = l_ms.add_checked(r_ms)?;
767        Ok(Self::make_value(days, ms))
768    }
769
770    fn sub(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
771        let (l_days, l_ms) = Self::to_parts(left);
772        let (r_days, r_ms) = Self::to_parts(right);
773        let days = l_days.sub_checked(r_days)?;
774        let ms = l_ms.sub_checked(r_ms)?;
775        Ok(Self::make_value(days, ms))
776    }
777
778    fn mul_i64(left: Self::Native, right: i64) -> Result<Self::Native, ArrowError> {
779        let (days, ms) = Self::to_parts(left);
780        Ok(Self::make_value(
781            mul_i32_i64(days, right)?,
782            mul_i32_i64(ms, right)?,
783        ))
784    }
785}
786
787impl IntervalOp for IntervalMonthDayNanoType {
788    fn add(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
789        let (l_months, l_days, l_nanos) = Self::to_parts(left);
790        let (r_months, r_days, r_nanos) = Self::to_parts(right);
791        let months = l_months.add_checked(r_months)?;
792        let days = l_days.add_checked(r_days)?;
793        let nanos = l_nanos.add_checked(r_nanos)?;
794        Ok(Self::make_value(months, days, nanos))
795    }
796
797    fn sub(left: Self::Native, right: Self::Native) -> Result<Self::Native, ArrowError> {
798        let (l_months, l_days, l_nanos) = Self::to_parts(left);
799        let (r_months, r_days, r_nanos) = Self::to_parts(right);
800        let months = l_months.sub_checked(r_months)?;
801        let days = l_days.sub_checked(r_days)?;
802        let nanos = l_nanos.sub_checked(r_nanos)?;
803        Ok(Self::make_value(months, days, nanos))
804    }
805
806    fn mul_i64(left: Self::Native, right: i64) -> Result<Self::Native, ArrowError> {
807        let (months, days, nanos) = Self::to_parts(left);
808        Ok(Self::make_value(
809            mul_i32_i64(months, right)?,
810            mul_i32_i64(days, right)?,
811            nanos.mul_checked(right)?,
812        ))
813    }
814}
815
816fn interval_mul_op<T: IntervalOp>(
817    interval: &dyn Array,
818    interval_scalar: bool,
819    factor: &dyn Array,
820    factor_scalar: bool,
821) -> Result<ArrayRef, ArrowError> {
822    let interval = interval.as_primitive::<T>();
823    let factor = factor.as_primitive::<Int64Type>();
824    Ok(try_op_ref!(
825        T,
826        interval,
827        interval_scalar,
828        factor,
829        factor_scalar,
830        T::mul_i64(interval, factor)
831    ))
832}
833
834/// Multiplies an `IntervalMonthDayNano` by an `f64`, mirroring DuckDB's
835/// `interval_t` layout of months, days, and a sub-day component (nanoseconds in
836/// Arrow, microseconds in DuckDB).
837/// <https://github.com/duckdb/duckdb/blob/21aca0424f1faf78b593b1e6fbfdd4846624c987/src/include/duckdb/common/types/interval.hpp#L24-L27>
838///
839/// Algorithm:
840///
841/// 1. use checked integer multiplication when `factor` fits in `i64` (early return).
842/// 2. multiply months and days separately
843/// 3. cascade remainders: convert fractional months to days using 30
844///    days per month, then fractional days to a sub-day value using 24 hours
845///    per day.
846/// 4. combine the cascaded remainder with the scaled input nanoseconds and round ties-to-even at nanosecond precision.
847/// 5. return an overflow error if any output component is out of
848///    range.
849fn interval_mul_f64(
850    interval: IntervalMonthDayNano,
851    factor: f64,
852) -> Result<IntervalMonthDayNano, ArrowError> {
853    const DAYS_PER_MONTH: f64 = 30.;
854    const NANOS_PER_SECOND: f64 = NANOSECONDS as f64;
855    const SECONDS_PER_DAY: f64 = SECONDS_IN_DAY as f64;
856
857    // Keep integral factors exact instead of round-tripping i64 nanoseconds through f64.
858    if factor.fract() == 0.
859        && let Some(factor) = ToPrimitive::to_i64(&factor)
860    {
861        return IntervalMonthDayNanoType::mul_i64(interval, factor);
862    }
863
864    // Based on DuckDB's INTERVAL * DOUBLE implementation, which is referenced from PostgreSQL's interval_mul:
865    // https://github.com/duckdb/duckdb/blob/21aca0424f1faf78b593b1e6fbfdd4846624c987/src/function/scalar/operator/multiply.cpp#L48-L123
866    // PostgreSQL's interval_mul:
867    // https://github.com/postgres/postgres/blob/78758d37306cd89ab060f00cb06f249018d5b8da/src/backend/utils/adt/timestamp.c#L3627-L3744
868    let overflow =
869        |component| ArrowError::ArithmeticOverflow(format!("Overflow in interval {component}"));
870    let timestamp_round =
871        |value: f64| (value * NANOS_PER_SECOND).round_ties_even() / NANOS_PER_SECOND;
872
873    let months_product = f64::from(interval.months) * factor;
874    if !months_product.is_finite()
875        || months_product < f64::from(i32::MIN)
876        || months_product > f64::from(i32::MAX)
877    {
878        return Err(overflow("months"));
879    }
880    let months = months_product.to_i32().ok_or_else(|| overflow("months"))?;
881
882    let days_product = f64::from(interval.days) * factor;
883    if !days_product.is_finite()
884        || days_product < f64::from(i32::MIN)
885        || days_product > f64::from(i32::MAX)
886    {
887        return Err(overflow("days"));
888    }
889    let mut days = days_product.to_i32().ok_or_else(|| overflow("days"))?;
890
891    let month_remainder = timestamp_round(months_product.fract() * DAYS_PER_MONTH);
892    let month_remainder_days = month_remainder
893        .to_i32()
894        .ok_or_else(|| overflow("month remainder"))?;
895    // Same order of operations as DuckDB; float arithmetic isn't associative and we're aiming
896    // to replicate DuckDB accuracy
897    let mut seconds_remainder = timestamp_round(
898        (days_product - f64::from(days) + month_remainder - f64::from(month_remainder_days))
899            * SECONDS_PER_DAY,
900    );
901
902    if seconds_remainder.abs() >= SECONDS_PER_DAY {
903        let remainder_days = (seconds_remainder / SECONDS_PER_DAY)
904            .to_i32()
905            .ok_or_else(|| overflow("day remainder"))?;
906        days = days
907            .checked_add(remainder_days)
908            .ok_or_else(|| overflow("days"))?;
909        seconds_remainder -= f64::from(remainder_days) * SECONDS_PER_DAY;
910    }
911    days = days
912        .checked_add(month_remainder_days)
913        .ok_or_else(|| overflow("days"))?;
914
915    let nanoseconds = ((interval.nanoseconds as f64) * factor
916        + seconds_remainder * NANOS_PER_SECOND)
917        .round_ties_even();
918    let nanoseconds = ToPrimitive::to_i64(&nanoseconds).ok_or_else(|| {
919        ArrowError::ArithmeticOverflow(format!("Overflow in interval nanoseconds: {nanoseconds}"))
920    })?;
921
922    Ok(IntervalMonthDayNano::new(months, days, nanoseconds))
923}
924
925fn interval_f64_op(
926    op: Op,
927    interval: &dyn Array,
928    interval_scalar: bool,
929    factor: &dyn Array,
930    factor_scalar: bool,
931) -> Result<ArrayRef, ArrowError> {
932    let interval = interval.as_primitive::<IntervalMonthDayNanoType>();
933    let factor = factor.as_primitive::<Float64Type>();
934    Ok(try_op_ref!(
935        IntervalMonthDayNanoType,
936        interval,
937        interval_scalar,
938        factor,
939        factor_scalar,
940        {
941            match op {
942                Op::Mul => interval_mul_f64(interval, factor),
943                Op::Div if factor == 0. => Err(ArrowError::DivideByZero),
944                // DuckDB defines interval division as multiplication by the reciprocal:
945                // https://github.com/duckdb/duckdb/blob/21aca0424f1faf78b593b1e6fbfdd4846624c987/src/function/scalar/operator/arithmetic.cpp#L1102-L1110
946                Op::Div => interval_mul_f64(interval, 1. / factor),
947                _ => Err(ArrowError::InvalidArgumentError(format!(
948                    "Invalid interval arithmetic operation: Interval(MonthDayNano) {op} Float64"
949                ))),
950            }
951        }
952    ))
953}
954
955/// Perform arithmetic operation on an interval array
956fn interval_op<T: IntervalOp>(
957    op: Op,
958    l: &dyn Array,
959    l_s: bool,
960    r: &dyn Array,
961    r_s: bool,
962) -> Result<ArrayRef, ArrowError> {
963    match (op, r.data_type()) {
964        (Op::Add | Op::AddWrapping, data_type) if data_type == l.data_type() => {
965            let l = l.as_primitive::<T>();
966            let r = r.as_primitive::<T>();
967            Ok(try_op_ref!(T, l, l_s, r, r_s, T::add(l, r)))
968        }
969        (Op::Sub | Op::SubWrapping, data_type) if data_type == l.data_type() => {
970            let l = l.as_primitive::<T>();
971            let r = r.as_primitive::<T>();
972            Ok(try_op_ref!(T, l, l_s, r, r_s, T::sub(l, r)))
973        }
974        (Op::Mul, DataType::Int64) => interval_mul_op::<T>(l, l_s, r, r_s),
975        _ => Err(ArrowError::InvalidArgumentError(format!(
976            "Invalid interval arithmetic operation: {} {op} {}",
977            l.data_type(),
978            r.data_type()
979        ))),
980    }
981}
982
983fn duration_op<T: ArrowPrimitiveType>(
984    op: Op,
985    l: &dyn Array,
986    l_s: bool,
987    r: &dyn Array,
988    r_s: bool,
989) -> Result<ArrayRef, ArrowError> {
990    let l = l.as_primitive::<T>();
991    let r = r.as_primitive::<T>();
992    match op {
993        Op::Add | Op::AddWrapping => Ok(try_op_ref!(T, l, l_s, r, r_s, l.add_checked(r))),
994        Op::Sub | Op::SubWrapping => Ok(try_op_ref!(T, l, l_s, r, r_s, l.sub_checked(r))),
995        _ => Err(ArrowError::InvalidArgumentError(format!(
996            "Invalid duration arithmetic operation: {} {op} {}",
997            l.data_type(),
998            r.data_type()
999        ))),
1000    }
1001}
1002
1003/// Perform arithmetic operation on a date array
1004fn date_op<T: DateOp>(
1005    op: Op,
1006    l: &dyn Array,
1007    l_s: bool,
1008    r: &dyn Array,
1009    r_s: bool,
1010) -> Result<ArrayRef, ArrowError> {
1011    use DataType::*;
1012    use IntervalUnit::*;
1013
1014    const NUM_SECONDS_IN_DAY: i64 = 60 * 60 * 24;
1015
1016    let r_t = r.data_type();
1017    match (T::DATA_TYPE, op, r_t) {
1018        (Date32, Op::Sub | Op::SubWrapping, Date32) => {
1019            let l = l.as_primitive::<Date32Type>();
1020            let r = r.as_primitive::<Date32Type>();
1021            return Ok(op_ref!(
1022                DurationSecondType,
1023                l,
1024                l_s,
1025                r,
1026                r_s,
1027                ((l as i64) - (r as i64)) * NUM_SECONDS_IN_DAY
1028            ));
1029        }
1030        (Date64, Op::Sub | Op::SubWrapping, Date64) => {
1031            let l = l.as_primitive::<Date64Type>();
1032            let r = r.as_primitive::<Date64Type>();
1033            let result = try_op_ref!(DurationMillisecondType, l, l_s, r, r_s, l.sub_checked(r));
1034            return Ok(result);
1035        }
1036        _ => {}
1037    }
1038
1039    let l = l.as_primitive::<T>();
1040    match (op, r_t) {
1041        (Op::Add | Op::AddWrapping, Interval(YearMonth)) => {
1042            let r = r.as_primitive::<IntervalYearMonthType>();
1043            Ok(try_op_ref!(T, l, l_s, r, r_s, T::add_year_month(l, r)))
1044        }
1045        (Op::Sub | Op::SubWrapping, Interval(YearMonth)) => {
1046            let r = r.as_primitive::<IntervalYearMonthType>();
1047            Ok(try_op_ref!(T, l, l_s, r, r_s, T::sub_year_month(l, r)))
1048        }
1049
1050        (Op::Add | Op::AddWrapping, Interval(DayTime)) => {
1051            let r = r.as_primitive::<IntervalDayTimeType>();
1052            Ok(try_op_ref!(T, l, l_s, r, r_s, T::add_day_time(l, r)))
1053        }
1054        (Op::Sub | Op::SubWrapping, Interval(DayTime)) => {
1055            let r = r.as_primitive::<IntervalDayTimeType>();
1056            Ok(try_op_ref!(T, l, l_s, r, r_s, T::sub_day_time(l, r)))
1057        }
1058
1059        (Op::Add | Op::AddWrapping, Interval(MonthDayNano)) => {
1060            let r = r.as_primitive::<IntervalMonthDayNanoType>();
1061            Ok(try_op_ref!(T, l, l_s, r, r_s, T::add_month_day_nano(l, r)))
1062        }
1063        (Op::Sub | Op::SubWrapping, Interval(MonthDayNano)) => {
1064            let r = r.as_primitive::<IntervalMonthDayNanoType>();
1065            Ok(try_op_ref!(T, l, l_s, r, r_s, T::sub_month_day_nano(l, r)))
1066        }
1067
1068        _ => Err(ArrowError::InvalidArgumentError(format!(
1069            "Invalid date arithmetic operation: {} {op} {}",
1070            l.data_type(),
1071            r.data_type()
1072        ))),
1073    }
1074}
1075
1076/// Returns the scalar divisor `r` scaled by `r_mul`, when `l` is an array and dividing any value
1077/// by it can't fail. That needs `r` to be valid and the product to fit and be neither 0 nor -1.
1078///
1079/// The kernel then needs no per-value checks of the divisor, which keeps the closure small
1080/// enough for LLVM to inline into the loop of `try_unary`. Otherwise it returns `None`, and the
1081/// kernel takes the general path, which reports any errors.
1082fn scalar_divisor<T: DecimalType>(
1083    l_s: bool,
1084    r: &PrimitiveArray<T>,
1085    r_s: bool,
1086    r_mul: T::Native,
1087) -> Option<T::Native>
1088where
1089    T::Native: CheckedMul,
1090{
1091    if l_s || !r_s || r.null_count() != 0 {
1092        return None;
1093    }
1094    let divisor = r.value(0).checked_mul(&r_mul)?;
1095    let minus_one = T::Native::ONE.neg_wrapping();
1096    (!divisor.is_zero() && !divisor.is_eq(minus_one)).then_some(divisor)
1097}
1098
1099/// [`ArrowNativeTypeOp::mul_checked`] out of line, for closures that call it only after
1100/// `checked_mul` overflows, so that building the error doesn't stop them from being inlined
1101#[cold]
1102#[inline(never)]
1103fn mul_checked_cold<T: ArrowNativeTypeOp>(l: T, r: T) -> Result<T, ArrowError> {
1104    l.mul_checked(r)
1105}
1106
1107/// Divides `l * 10^mul_pow` by `r` a digit at a time, without forming the scaled numerator.
1108/// Used when scaling `l` would overflow `T::Native`, which it does well before the quotient
1109/// does.
1110///
1111/// Runs on magnitudes and restores the sign last, so it truncates toward zero.
1112fn scaled_div<T: DecimalType>(
1113    l: T::Native,
1114    r: T::Native,
1115    mul_pow: i8,
1116) -> Result<T::Native, ArrowError> {
1117    let zero = T::Native::ZERO;
1118    let negative = l.is_lt(zero) != r.is_lt(zero);
1119    let dividend = abs_checked::<T>(l)?;
1120    let divisor = abs_checked::<T>(r)?;
1121
1122    let (mut quotient, mut remainder) = dividend.div_rem_checked(divisor)?;
1123    for _ in 0..mul_pow {
1124        // `remainder * 10` overflows for divisors near `T::Native::MAX`, so add the remainder
1125        // ten times and take the divisor off whenever the running sum reaches it.
1126        let mut carried = zero;
1127        let mut digit = zero;
1128        for _ in 0..10 {
1129            let headroom = divisor.sub_wrapping(remainder);
1130            if carried.is_lt(headroom) {
1131                carried = carried.add_wrapping(remainder);
1132            } else {
1133                carried = carried.sub_wrapping(headroom);
1134                digit = digit.add_wrapping(T::Native::ONE);
1135            }
1136        }
1137        quotient = quotient
1138            .mul_checked(T::Native::usize_as(10))?
1139            .add_checked(digit)?;
1140        remainder = carried;
1141    }
1142
1143    if negative {
1144        quotient.neg_checked()
1145    } else {
1146        Ok(quotient)
1147    }
1148}
1149
1150fn abs_checked<T: DecimalType>(value: T::Native) -> Result<T::Native, ArrowError> {
1151    if value.is_lt(T::Native::ZERO) {
1152        value.neg_checked()
1153    } else {
1154        Ok(value)
1155    }
1156}
1157
1158/// Perform arithmetic operation on decimal arrays
1159fn decimal_op<T: DecimalType>(
1160    op: Op,
1161    l: &dyn Array,
1162    l_s: bool,
1163    r: &dyn Array,
1164    r_s: bool,
1165) -> Result<ArrayRef, ArrowError>
1166where
1167    T::Native: CheckedMul,
1168{
1169    let l = l.as_primitive::<T>();
1170    let r = r.as_primitive::<T>();
1171
1172    let (p1, s1, p2, s2) = match (l.data_type(), r.data_type()) {
1173        (DataType::Decimal32(p1, s1), DataType::Decimal32(p2, s2)) => (p1, s1, p2, s2),
1174        (DataType::Decimal64(p1, s1), DataType::Decimal64(p2, s2)) => (p1, s1, p2, s2),
1175        (DataType::Decimal128(p1, s1), DataType::Decimal128(p2, s2)) => (p1, s1, p2, s2),
1176        (DataType::Decimal256(p1, s1), DataType::Decimal256(p2, s2)) => (p1, s1, p2, s2),
1177        _ => unreachable!(),
1178    };
1179
1180    // Follow the Hive decimal arithmetic rules
1181    // https://cwiki.apache.org/confluence/download/attachments/27362075/Hive_Decimal_Precision_Scale_Support.pdf
1182    let array: PrimitiveArray<T> = match op {
1183        Op::Add | Op::AddWrapping | Op::Sub | Op::SubWrapping => {
1184            let (p1, s1, p2, s2) = (*p1 as i16, *s1 as i16, *p2 as i16, *s2 as i16);
1185            // max(s1, s2)
1186            let result_scale = s1.max(s2);
1187
1188            // max(s1, s2) + max(p1-s1, p2-s2) + 1
1189            let result_precision =
1190                (result_scale + (p1 - s1).max(p2 - s2) + 1).min(T::MAX_PRECISION as i16) as u8;
1191
1192            let l_mul = T::Native::usize_as(10).pow_checked((result_scale - s1) as _)?;
1193            let r_mul = T::Native::usize_as(10).pow_checked((result_scale - s2) as _)?;
1194
1195            match op {
1196                // Equal scales make both decimal multipliers one.
1197                Op::Add | Op::AddWrapping if s1 == s2 => {
1198                    try_op!(l, l_s, r, r_s, l.add_checked(r))
1199                }
1200                Op::Sub | Op::SubWrapping if s1 == s2 => {
1201                    try_op!(l, l_s, r, r_s, l.sub_checked(r))
1202                }
1203                Op::Add | Op::AddWrapping => {
1204                    try_op!(
1205                        l,
1206                        l_s,
1207                        r,
1208                        r_s,
1209                        l.mul_checked(l_mul)?.add_checked(r.mul_checked(r_mul)?)
1210                    )
1211                }
1212                Op::Sub | Op::SubWrapping => {
1213                    try_op!(
1214                        l,
1215                        l_s,
1216                        r,
1217                        r_s,
1218                        l.mul_checked(l_mul)?.sub_checked(r.mul_checked(r_mul)?)
1219                    )
1220                }
1221                _ => unreachable!(),
1222            }
1223            .with_precision_and_scale(result_precision, result_scale as i8)?
1224        }
1225        Op::Mul | Op::MulWrapping => {
1226            let result_precision = p1.saturating_add(p2 + 1).min(T::MAX_PRECISION);
1227            let result_scale = *s1 as i16 + *s2 as i16;
1228            if result_scale > T::MAX_SCALE as i16 {
1229                // SQL standard says that if the resulting scale of a multiply operation goes
1230                // beyond the maximum, rounding is not acceptable and thus an error occurs
1231                return Err(ArrowError::InvalidArgumentError(format!(
1232                    "Output scale of {} {op} {} would exceed max scale of {}",
1233                    l.data_type(),
1234                    r.data_type(),
1235                    T::MAX_SCALE
1236                )));
1237            }
1238            let result_scale = i8::try_from(result_scale).map_err(|_| {
1239                ArrowError::InvalidArgumentError(format!(
1240                    "Output scale of {} {op} {} would be less than min scale of {}",
1241                    l.data_type(),
1242                    r.data_type(),
1243                    i8::MIN
1244                ))
1245            })?;
1246
1247            try_op!(l, l_s, r, r_s, l.mul_checked(r))
1248                .with_precision_and_scale(result_precision, result_scale)?
1249        }
1250
1251        Op::Div => {
1252            // Follow postgres and MySQL adding a fixed scale increment of 4
1253            // s1 + 4
1254            let result_scale = s1.saturating_add(4).min(T::MAX_SCALE);
1255            let mul_pow = result_scale - s1 + s2;
1256
1257            // p1 - s1 + s2 + result_scale
1258            // Precision must be positive and at least the output scale.
1259            let result_precision = (mul_pow as i16 + *p1 as i16)
1260                .clamp(result_scale.max(1) as i16, T::MAX_PRECISION as i16)
1261                as u8;
1262
1263            let (l_mul, r_mul) = match mul_pow.cmp(&0) {
1264                Ordering::Greater => (
1265                    T::Native::usize_as(10).pow_checked(mul_pow as _)?,
1266                    T::Native::ONE,
1267                ),
1268                Ordering::Equal => (T::Native::ONE, T::Native::ONE),
1269                Ordering::Less => (
1270                    T::Native::ONE,
1271                    T::Native::usize_as(10).pow_checked(mul_pow.neg_wrapping() as _)?,
1272                ),
1273            };
1274
1275            match scalar_divisor(l_s, r, r_s, r_mul) {
1276                Some(divisor) => {
1277                    let r = r.value(0);
1278                    l.try_unary(|l| match l.checked_mul(&l_mul) {
1279                        // `divisor` is neither 0 nor -1, so the division can't fail
1280                        Some(scaled) => Ok(scaled.div_wrapping(divisor)),
1281                        None => scaled_div::<T>(l, r, mul_pow),
1282                    })?
1283                }
1284                None => try_op!(
1285                    l,
1286                    l_s,
1287                    r,
1288                    r_s,
1289                    match l.checked_mul(&l_mul) {
1290                        Some(scaled) => scaled.div_checked(r.mul_checked(r_mul)?),
1291                        None => scaled_div::<T>(l, r, mul_pow),
1292                    }
1293                ),
1294            }
1295            .with_precision_and_scale(result_precision, result_scale)?
1296        }
1297
1298        Op::Rem => {
1299            let (p1, s1, p2, s2) = (*p1 as i16, *s1 as i16, *p2 as i16, *s2 as i16);
1300            // max(s1, s2)
1301            let result_scale = s1.max(s2);
1302            // min(p1-s1, p2 -s2) + max( s1,s2 )
1303            let result_precision =
1304                (result_scale + (p1 - s1).min(p2 - s2)).min(T::MAX_PRECISION as i16) as u8;
1305
1306            let l_mul = T::Native::usize_as(10).pow_checked((result_scale - s1) as _)?;
1307            let r_mul = T::Native::usize_as(10).pow_checked((result_scale - s2) as _)?;
1308
1309            match scalar_divisor(l_s, r, r_s, r_mul) {
1310                // `divisor` is neither 0 nor -1, so the remainder can't fail
1311                Some(divisor) => l.try_unary(|l| match l.checked_mul(&l_mul) {
1312                    Some(scaled) => Ok(scaled.mod_wrapping(divisor)),
1313                    None => mul_checked_cold(l, l_mul).map(|scaled| scaled.mod_wrapping(divisor)),
1314                })?,
1315                None => try_op!(
1316                    l,
1317                    l_s,
1318                    r,
1319                    r_s,
1320                    l.mul_checked(l_mul)?.mod_checked(r.mul_checked(r_mul)?)
1321                ),
1322            }
1323            .with_precision_and_scale(result_precision, result_scale as i8)?
1324        }
1325    };
1326
1327    Ok(Arc::new(array))
1328}
1329
1330#[cfg(test)]
1331mod tests {
1332    use super::*;
1333    use arrow_array::temporal_conversions::{as_date, as_datetime};
1334    use arrow_buffer::{NullBuffer, ScalarBuffer, i256};
1335    use chrono::{DateTime, NaiveDate};
1336
1337    // The valid date range of NaiveDate is from January 1, -262143 to December 31, 262142 (Gregorian calendar).
1338    const MAX_VALID_DATE: NaiveDate = NaiveDate::from_ymd_opt(262142, 12, 31).unwrap();
1339    const MIN_VALID_DATE: NaiveDate = NaiveDate::from_ymd_opt(-262143, 1, 1).unwrap();
1340    const MAX_VALID_MILLIS: i64 = date_to_millis(MAX_VALID_DATE);
1341    const MIN_VALID_MILLIS: i64 = date_to_millis(MIN_VALID_DATE);
1342    const MAX_VALID_DAYS: i32 = date_to_days(MAX_VALID_DATE);
1343    const MIN_VALID_DAYS: i32 = date_to_days(MIN_VALID_DATE);
1344    const EPOCH: NaiveDate = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
1345    const YEAR_2000: NaiveDate = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
1346
1347    const fn date_to_millis(date: NaiveDate) -> i64 {
1348        date.signed_duration_since(EPOCH).num_milliseconds()
1349    }
1350
1351    const fn date_to_days(date: NaiveDate) -> i32 {
1352        date.signed_duration_since(EPOCH).num_days() as i32
1353    }
1354
1355    fn assert_kernel_result<T: ArrowPrimitiveType>(
1356        actual: Result<ArrayRef, ArrowError>,
1357        expected: Result<Vec<Option<T::Native>>, ArrowError>,
1358        context: &str,
1359    ) {
1360        match (actual, expected) {
1361            (Ok(actual), Ok(expected)) => {
1362                let actual: Vec<_> = actual.as_primitive::<T>().iter().collect();
1363                assert_eq!(actual, expected, "{context}");
1364            }
1365            (Err(actual), Err(expected)) => {
1366                assert_eq!(actual.to_string(), expected.to_string(), "{context}")
1367            }
1368            (actual, expected) => panic!("{context}: {actual:?} != {expected:?}"),
1369        }
1370    }
1371
1372    /// Checks `div` and `rem` of `values` by each of `divisors` and by a null divisor, against
1373    /// `div_checked` and `mod_wrapping` on each valid value, as `integer_op` computes them.
1374    /// `values` is repeated to 64 values so that the vectorized loop runs, and is also checked
1375    /// sliced to 50 values, which leaves a remainder for the scalar loop, with seven in eight
1376    /// values null, all null, and empty
1377    fn test_div_rem_by_scalar<T: ArrowPrimitiveType>(
1378        values: &[Option<T::Native>],
1379        divisors: &[T::Native],
1380    ) {
1381        let values: PrimitiveArray<T> = values.iter().cycle().take(64).collect();
1382        let mostly_null = NullBuffer::from_iter((0..values.len()).map(|i| i % 8 == 0));
1383        let arrays = [
1384            values.slice(3, 50),
1385            PrimitiveArray::new(values.values().clone(), Some(mostly_null)),
1386            values.slice(0, 0),
1387            PrimitiveArray::new_null(2),
1388            values,
1389        ];
1390        for array in &arrays {
1391            for &d in divisors {
1392                let divisor = PrimitiveArray::<T>::new_scalar(d);
1393                let expected = array
1394                    .iter()
1395                    .map(|v| v.map(|v| v.div_checked(d)).transpose())
1396                    .collect();
1397                assert_kernel_result::<T>(div(array, &divisor), expected, &format!("/ {d:?}"));
1398                let expected = array
1399                    .iter()
1400                    .map(|v| {
1401                        v.map(|v| match d.is_zero() {
1402                            true => Err(ArrowError::DivideByZero),
1403                            false => Ok(v.mod_wrapping(d)),
1404                        })
1405                        .transpose()
1406                    })
1407                    .collect();
1408                assert_kernel_result::<T>(rem(array, &divisor), expected, &format!("% {d:?}"));
1409            }
1410            // A null divisor gives a null result, whatever its slot holds
1411            for slot in [0, 7] {
1412                let slot = vec![T::Native::usize_as(slot)].into();
1413                let divisor = Scalar::new(PrimitiveArray::<T>::new(
1414                    slot,
1415                    Some(NullBuffer::new_null(1)),
1416                ));
1417                assert_eq!(div(array, &divisor).unwrap().null_count(), array.len());
1418                assert_eq!(rem(array, &divisor).unwrap().null_count(), array.len());
1419            }
1420        }
1421    }
1422
1423    #[test]
1424    fn test_div_rem_by_scalar_integer() {
1425        // 16, 13, 7, -16 and -7 reach each variant of the precomputed divisor. 0, and -1 for `/`, fall back
1426        // to `integer_op`, which returns an error for a valid value and `Ok` otherwise
1427        let values = [
1428            Some(i32::MIN),
1429            Some(i32::MIN + 1),
1430            Some(-7),
1431            None,
1432            Some(0),
1433            Some(13),
1434            Some(i32::MAX),
1435        ];
1436        test_div_rem_by_scalar::<Int32Type>(&values, &[16, 13, 7, -16, -7, 0, -1]);
1437        let values = [
1438            Some(i64::MIN),
1439            Some(i64::MIN + 1),
1440            Some(-7),
1441            None,
1442            Some(0),
1443            Some(13),
1444            Some(i64::MAX),
1445        ];
1446        test_div_rem_by_scalar::<Int64Type>(&values, &[16, 13, 7, -16, -7, 0, -1]);
1447        let values = [
1448            Some(0),
1449            Some(1),
1450            None,
1451            Some(13),
1452            Some(u32::MAX - 1),
1453            Some(u32::MAX),
1454        ];
1455        test_div_rem_by_scalar::<UInt32Type>(&values, &[16, 13, 7, 0]);
1456        let values = [
1457            Some(0),
1458            Some(1),
1459            None,
1460            Some(13),
1461            Some(u64::MAX - 1),
1462            Some(u64::MAX),
1463        ];
1464        test_div_rem_by_scalar::<UInt64Type>(&values, &[16, 13, 7, 0]);
1465    }
1466
1467    fn test_neg_primitive<T: ArrowPrimitiveType>(
1468        input: &[T::Native],
1469        out: Result<&[T::Native], &str>,
1470    ) {
1471        let a = PrimitiveArray::<T>::new(ScalarBuffer::from(input.to_vec()), None);
1472        match out {
1473            Ok(expected) => {
1474                let result = neg(&a).unwrap();
1475                assert_eq!(result.as_primitive::<T>().values(), expected);
1476            }
1477            Err(e) => {
1478                let err = neg(&a).unwrap_err().to_string();
1479                assert_eq!(e, err);
1480            }
1481        }
1482    }
1483
1484    #[test]
1485    fn test_neg() {
1486        let input = &[1, -5, 2, 693, 3929];
1487        let output = &[-1, 5, -2, -693, -3929];
1488        test_neg_primitive::<Int32Type>(input, Ok(output));
1489
1490        let input = &[1, -5, 2, 693, 3929];
1491        let output = &[-1, 5, -2, -693, -3929];
1492        test_neg_primitive::<Int64Type>(input, Ok(output));
1493        test_neg_primitive::<DurationSecondType>(input, Ok(output));
1494        test_neg_primitive::<DurationMillisecondType>(input, Ok(output));
1495        test_neg_primitive::<DurationMicrosecondType>(input, Ok(output));
1496        test_neg_primitive::<DurationNanosecondType>(input, Ok(output));
1497
1498        let input = &[f32::MAX, f32::MIN, f32::INFINITY, 1.3, 0.5];
1499        let output = &[f32::MIN, f32::MAX, f32::NEG_INFINITY, -1.3, -0.5];
1500        test_neg_primitive::<Float32Type>(input, Ok(output));
1501
1502        test_neg_primitive::<Int32Type>(
1503            &[i32::MIN],
1504            Err("Arithmetic overflow: Overflow happened on: - -2147483648"),
1505        );
1506        test_neg_primitive::<Int64Type>(
1507            &[i64::MIN],
1508            Err("Arithmetic overflow: Overflow happened on: - -9223372036854775808"),
1509        );
1510        test_neg_primitive::<DurationSecondType>(
1511            &[i64::MIN],
1512            Err("Arithmetic overflow: Overflow happened on: - -9223372036854775808"),
1513        );
1514
1515        let r = neg_wrapping(&Int32Array::from(vec![i32::MIN])).unwrap();
1516        assert_eq!(r.as_primitive::<Int32Type>().value(0), i32::MIN);
1517
1518        let r = neg_wrapping(&Int64Array::from(vec![i64::MIN])).unwrap();
1519        assert_eq!(r.as_primitive::<Int64Type>().value(0), i64::MIN);
1520
1521        let err = neg_wrapping(&DurationSecondArray::from(vec![i64::MIN]))
1522            .unwrap_err()
1523            .to_string();
1524
1525        assert_eq!(
1526            err,
1527            "Arithmetic overflow: Overflow happened on: - -9223372036854775808"
1528        );
1529
1530        let a = Decimal32Array::from(vec![1, 3, -44, 2, 4])
1531            .with_precision_and_scale(9, 6)
1532            .unwrap();
1533
1534        let r = neg(&a).unwrap();
1535        assert_eq!(r.data_type(), a.data_type());
1536        assert_eq!(
1537            r.as_primitive::<Decimal32Type>().values(),
1538            &[-1, -3, 44, -2, -4]
1539        );
1540
1541        let a = Decimal64Array::from(vec![1, 3, -44, 2, 4])
1542            .with_precision_and_scale(9, 6)
1543            .unwrap();
1544
1545        let r = neg(&a).unwrap();
1546        assert_eq!(r.data_type(), a.data_type());
1547        assert_eq!(
1548            r.as_primitive::<Decimal64Type>().values(),
1549            &[-1, -3, 44, -2, -4]
1550        );
1551
1552        let a = Decimal128Array::from(vec![1, 3, -44, 2, 4])
1553            .with_precision_and_scale(9, 6)
1554            .unwrap();
1555
1556        let r = neg(&a).unwrap();
1557        assert_eq!(r.data_type(), a.data_type());
1558        assert_eq!(
1559            r.as_primitive::<Decimal128Type>().values(),
1560            &[-1, -3, 44, -2, -4]
1561        );
1562
1563        let a = Decimal256Array::from(vec![
1564            i256::from_i128(342),
1565            i256::from_i128(-4949),
1566            i256::from_i128(3),
1567        ])
1568        .with_precision_and_scale(9, 6)
1569        .unwrap();
1570
1571        let r = neg(&a).unwrap();
1572        assert_eq!(r.data_type(), a.data_type());
1573        assert_eq!(
1574            r.as_primitive::<Decimal256Type>().values(),
1575            &[
1576                i256::from_i128(-342),
1577                i256::from_i128(4949),
1578                i256::from_i128(-3),
1579            ]
1580        );
1581
1582        let a = IntervalYearMonthArray::from(vec![
1583            IntervalYearMonthType::make_value(2, 4),
1584            IntervalYearMonthType::make_value(2, -4),
1585            IntervalYearMonthType::make_value(-3, -5),
1586        ]);
1587        let r = neg(&a).unwrap();
1588        assert_eq!(
1589            r.as_primitive::<IntervalYearMonthType>().values(),
1590            &[
1591                IntervalYearMonthType::make_value(-2, -4),
1592                IntervalYearMonthType::make_value(-2, 4),
1593                IntervalYearMonthType::make_value(3, 5),
1594            ]
1595        );
1596
1597        let a = IntervalDayTimeArray::from(vec![
1598            IntervalDayTimeType::make_value(2, 4),
1599            IntervalDayTimeType::make_value(2, -4),
1600            IntervalDayTimeType::make_value(-3, -5),
1601        ]);
1602        let r = neg(&a).unwrap();
1603        assert_eq!(
1604            r.as_primitive::<IntervalDayTimeType>().values(),
1605            &[
1606                IntervalDayTimeType::make_value(-2, -4),
1607                IntervalDayTimeType::make_value(-2, 4),
1608                IntervalDayTimeType::make_value(3, 5),
1609            ]
1610        );
1611
1612        let a = IntervalMonthDayNanoArray::from(vec![
1613            IntervalMonthDayNanoType::make_value(2, 4, 5953394),
1614            IntervalMonthDayNanoType::make_value(2, -4, -45839),
1615            IntervalMonthDayNanoType::make_value(-3, -5, 6944),
1616        ]);
1617        let r = neg(&a).unwrap();
1618        assert_eq!(
1619            r.as_primitive::<IntervalMonthDayNanoType>().values(),
1620            &[
1621                IntervalMonthDayNanoType::make_value(-2, -4, -5953394),
1622                IntervalMonthDayNanoType::make_value(-2, 4, 45839),
1623                IntervalMonthDayNanoType::make_value(3, 5, -6944),
1624            ]
1625        );
1626    }
1627
1628    #[test]
1629    fn test_integer() {
1630        let a = Int32Array::from(vec![4, 3, 5, -6, 100]);
1631        let b = Int32Array::from(vec![6, 2, 5, -7, 3]);
1632        let result = add(&a, &b).unwrap();
1633        assert_eq!(
1634            result.as_ref(),
1635            &Int32Array::from(vec![10, 5, 10, -13, 103])
1636        );
1637        let result = sub(&a, &b).unwrap();
1638        assert_eq!(result.as_ref(), &Int32Array::from(vec![-2, 1, 0, 1, 97]));
1639        let result = div(&a, &b).unwrap();
1640        assert_eq!(result.as_ref(), &Int32Array::from(vec![0, 1, 1, 0, 33]));
1641        let result = mul(&a, &b).unwrap();
1642        assert_eq!(result.as_ref(), &Int32Array::from(vec![24, 6, 25, 42, 300]));
1643        let result = rem(&a, &b).unwrap();
1644        assert_eq!(result.as_ref(), &Int32Array::from(vec![4, 1, 0, -6, 1]));
1645
1646        let a = Int8Array::from(vec![Some(2), None, Some(45)]);
1647        let b = Int8Array::from(vec![Some(5), Some(3), None]);
1648        let result = add(&a, &b).unwrap();
1649        assert_eq!(result.as_ref(), &Int8Array::from(vec![Some(7), None, None]));
1650
1651        let a = UInt8Array::from(vec![56, 5, 3]);
1652        let b = UInt8Array::from(vec![200, 2, 5]);
1653        let err = add(&a, &b).unwrap_err().to_string();
1654        assert_eq!(err, "Arithmetic overflow: Overflow happened on: 56 + 200");
1655        let result = add_wrapping(&a, &b).unwrap();
1656        assert_eq!(result.as_ref(), &UInt8Array::from(vec![0, 7, 8]));
1657
1658        let a = UInt8Array::from(vec![34, 5, 3]);
1659        let b = UInt8Array::from(vec![200, 2, 5]);
1660        let err = sub(&a, &b).unwrap_err().to_string();
1661        assert_eq!(err, "Arithmetic overflow: Overflow happened on: 34 - 200");
1662        let result = sub_wrapping(&a, &b).unwrap();
1663        assert_eq!(result.as_ref(), &UInt8Array::from(vec![90, 3, 254]));
1664
1665        let a = UInt8Array::from(vec![34, 5, 3]);
1666        let b = UInt8Array::from(vec![200, 2, 5]);
1667        let err = mul(&a, &b).unwrap_err().to_string();
1668        assert_eq!(err, "Arithmetic overflow: Overflow happened on: 34 * 200");
1669        let result = mul_wrapping(&a, &b).unwrap();
1670        assert_eq!(result.as_ref(), &UInt8Array::from(vec![144, 10, 15]));
1671
1672        let a = Int16Array::from(vec![i16::MIN]);
1673        let b = Int16Array::from(vec![-1]);
1674        let err = div(&a, &b).unwrap_err().to_string();
1675        assert_eq!(
1676            err,
1677            "Arithmetic overflow: Overflow happened on: -32768 / -1"
1678        );
1679
1680        let a = Int16Array::from(vec![i16::MIN]);
1681        let b = Int16Array::from(vec![-1]);
1682        let result = rem(&a, &b).unwrap();
1683        assert_eq!(result.as_ref(), &Int16Array::from(vec![0]));
1684
1685        let a = Int16Array::from(vec![21]);
1686        let b = Int16Array::from(vec![0]);
1687        let err = div(&a, &b).unwrap_err().to_string();
1688        assert_eq!(err, "Divide by zero error");
1689
1690        let a = Int16Array::from(vec![21]);
1691        let b = Int16Array::from(vec![0]);
1692        let err = rem(&a, &b).unwrap_err().to_string();
1693        assert_eq!(err, "Divide by zero error");
1694    }
1695
1696    #[test]
1697    fn test_float() {
1698        let a = Float32Array::from(vec![1., f32::MAX, 6., -4., -1., 0.]);
1699        let b = Float32Array::from(vec![1., f32::MAX, f32::MAX, -3., 45., 0.]);
1700        let result = add(&a, &b).unwrap();
1701        assert_eq!(
1702            result.as_ref(),
1703            &Float32Array::from(vec![2., f32::INFINITY, f32::MAX, -7., 44.0, 0.])
1704        );
1705
1706        let result = sub(&a, &b).unwrap();
1707        assert_eq!(
1708            result.as_ref(),
1709            &Float32Array::from(vec![0., 0., f32::MIN, -1., -46., 0.])
1710        );
1711
1712        let result = mul(&a, &b).unwrap();
1713        assert_eq!(
1714            result.as_ref(),
1715            &Float32Array::from(vec![1., f32::INFINITY, f32::INFINITY, 12., -45., 0.])
1716        );
1717
1718        let result = div(&a, &b).unwrap();
1719        let r = result.as_primitive::<Float32Type>();
1720        assert_eq!(r.value(0), 1.);
1721        assert_eq!(r.value(1), 1.);
1722        assert!(r.value(2) < f32::EPSILON);
1723        assert_eq!(r.value(3), -4. / -3.);
1724        assert!(r.value(5).is_nan());
1725
1726        let result = rem(&a, &b).unwrap();
1727        let r = result.as_primitive::<Float32Type>();
1728        assert_eq!(&r.values()[..5], &[0., 0., 6., -1., -1.]);
1729        assert!(r.value(5).is_nan());
1730    }
1731
1732    #[test]
1733    fn test_decimal() {
1734        // 0.015 7.842 -0.577 0.334 -0.078 0.003
1735        let a = Decimal128Array::from(vec![15, 0, -577, 334, -78, 3])
1736            .with_precision_and_scale(12, 3)
1737            .unwrap();
1738
1739        // 5.4 0 -35.6 0.3 0.6 7.45
1740        let b = Decimal128Array::from(vec![54, 34, -356, 3, 6, 745])
1741            .with_precision_and_scale(12, 1)
1742            .unwrap();
1743
1744        let result = add(&a, &b).unwrap();
1745        assert_eq!(result.data_type(), &DataType::Decimal128(15, 3));
1746        assert_eq!(
1747            result.as_primitive::<Decimal128Type>().values(),
1748            &[5415, 3400, -36177, 634, 522, 74503]
1749        );
1750
1751        let result = sub(&a, &b).unwrap();
1752        assert_eq!(result.data_type(), &DataType::Decimal128(15, 3));
1753        assert_eq!(
1754            result.as_primitive::<Decimal128Type>().values(),
1755            &[-5385, -3400, 35023, 34, -678, -74497]
1756        );
1757
1758        let result = mul(&a, &b).unwrap();
1759        assert_eq!(result.data_type(), &DataType::Decimal128(25, 4));
1760        assert_eq!(
1761            result.as_primitive::<Decimal128Type>().values(),
1762            &[810, 0, 205412, 1002, -468, 2235]
1763        );
1764
1765        let result = div(&a, &b).unwrap();
1766        assert_eq!(result.data_type(), &DataType::Decimal128(17, 7));
1767        assert_eq!(
1768            result.as_primitive::<Decimal128Type>().values(),
1769            &[27777, 0, 162078, 11133333, -1300000, 402]
1770        );
1771
1772        let result = rem(&a, &b).unwrap();
1773        assert_eq!(result.data_type(), &DataType::Decimal128(12, 3));
1774        assert_eq!(
1775            result.as_primitive::<Decimal128Type>().values(),
1776            &[15, 0, -577, 34, -78, 3]
1777        );
1778
1779        let a = Decimal128Array::from(vec![1])
1780            .with_precision_and_scale(3, 3)
1781            .unwrap();
1782        let b = Decimal128Array::from(vec![1])
1783            .with_precision_and_scale(37, 37)
1784            .unwrap();
1785        let err = mul(&a, &b).unwrap_err().to_string();
1786        assert_eq!(
1787            err,
1788            "Invalid argument error: Output scale of Decimal128(3, 3) * Decimal128(37, 37) would exceed max scale of 38"
1789        );
1790
1791        let a = Decimal128Array::from(vec![1])
1792            .with_precision_and_scale(3, -2)
1793            .unwrap();
1794        let err = add(&a, &b).unwrap_err().to_string();
1795        assert_eq!(err, "Arithmetic overflow: Overflow happened on: 10 ^ 39");
1796
1797        let a = Decimal128Array::from(vec![10])
1798            .with_precision_and_scale(3, -1)
1799            .unwrap();
1800        let err = add(&a, &b).unwrap_err().to_string();
1801        assert_eq!(
1802            err,
1803            "Arithmetic overflow: Overflow happened on: 10 * 100000000000000000000000000000000000000"
1804        );
1805
1806        let b = Decimal128Array::from(vec![0])
1807            .with_precision_and_scale(1, 1)
1808            .unwrap();
1809        let err = div(&a, &b).unwrap_err().to_string();
1810        assert_eq!(err, "Divide by zero error");
1811        let err = rem(&a, &b).unwrap_err().to_string();
1812        assert_eq!(err, "Divide by zero error");
1813    }
1814
1815    #[test]
1816    fn test_decimal256_add_sub_negative_scale_metadata() {
1817        let a = Decimal256Array::from(vec![Some(i256::ONE), Some(i256::MINUS_ONE), None])
1818            .with_precision_and_scale(76, -52)
1819            .unwrap();
1820        let b = Decimal256Array::from(vec![i256::from_i128(2), i256::ONE, i256::ONE])
1821            .with_precision_and_scale(76, -52)
1822            .unwrap();
1823        let expected =
1824            Decimal256Array::from(vec![Some(i256::from_i128(3)), Some(i256::ZERO), None])
1825                .with_precision_and_scale(76, -52)
1826                .unwrap();
1827        assert_eq!(add(&a, &b).unwrap().as_ref(), &expected);
1828
1829        let expected =
1830            Decimal256Array::from(vec![Some(i256::MINUS_ONE), Some(i256::from_i128(-2)), None])
1831                .with_precision_and_scale(76, -52)
1832                .unwrap();
1833        assert_eq!(sub(&a, &b).unwrap().as_ref(), &expected);
1834    }
1835
1836    #[test]
1837    fn test_decimal256_add_sub_minimum_scale() {
1838        let a = Decimal256Array::from(vec![i256::ONE])
1839            .with_precision_and_scale(20, i8::MIN)
1840            .unwrap();
1841        let b = Decimal256Array::from(vec![i256::from_i128(2)])
1842            .with_precision_and_scale(20, i8::MIN)
1843            .unwrap();
1844        let expected = Decimal256Array::from(vec![i256::from_i128(3)])
1845            .with_precision_and_scale(21, i8::MIN)
1846            .unwrap();
1847        assert_eq!(add(&a, &b).unwrap().as_ref(), &expected);
1848
1849        let expected = Decimal256Array::from(vec![i256::MINUS_ONE])
1850            .with_precision_and_scale(21, i8::MIN)
1851            .unwrap();
1852        assert_eq!(sub(&a, &b).unwrap().as_ref(), &expected);
1853    }
1854
1855    #[test]
1856    fn test_decimal256_remainder_negative_scale_metadata() {
1857        let a = Decimal256Array::from(vec![Some(i256::ONE), Some(i256::MINUS_ONE), None])
1858            .with_precision_and_scale(76, -52)
1859            .unwrap();
1860        let b = Decimal256Array::from(vec![i256::from_i128(2), i256::ONE, i256::ONE])
1861            .with_precision_and_scale(76, -52)
1862            .unwrap();
1863        let expected = Decimal256Array::from(vec![Some(i256::ONE), Some(i256::ZERO), None])
1864            .with_precision_and_scale(76, -52)
1865            .unwrap();
1866        assert_eq!(rem(&a, &b).unwrap().as_ref(), &expected);
1867    }
1868
1869    #[test]
1870    fn test_decimal256_adjacent_minimum_scales() {
1871        let a = Decimal256Array::from(vec![i256::ONE])
1872            .with_precision_and_scale(20, i8::MIN)
1873            .unwrap();
1874        let b = Decimal256Array::from(vec![i256::from_i128(2)])
1875            .with_precision_and_scale(20, i8::MIN + 1)
1876            .unwrap();
1877        let expected = Decimal256Array::from(vec![i256::from_i128(12)])
1878            .with_precision_and_scale(22, -127)
1879            .unwrap();
1880        assert_eq!(add(&a, &b).unwrap().as_ref(), &expected);
1881
1882        let expected = Decimal256Array::from(vec![i256::from_i128(8)])
1883            .with_precision_and_scale(22, -127)
1884            .unwrap();
1885        assert_eq!(sub(&a, &b).unwrap().as_ref(), &expected);
1886
1887        let expected = Decimal256Array::from(vec![i256::ZERO])
1888            .with_precision_and_scale(20, -127)
1889            .unwrap();
1890        assert_eq!(rem(&a, &b).unwrap().as_ref(), &expected);
1891    }
1892
1893    #[test]
1894    fn test_decimal256_extreme_scale_difference_overflow() {
1895        let a = Decimal256Array::from(vec![i256::ONE])
1896            .with_precision_and_scale(20, i8::MIN)
1897            .unwrap();
1898        let b = Decimal256Array::from(vec![i256::from_i128(2)])
1899            .with_precision_and_scale(76, 76)
1900            .unwrap();
1901        let expected = "Arithmetic overflow: Overflow happened on: 10 ^ 204";
1902        assert_eq!(add(&a, &b).unwrap_err().to_string(), expected);
1903        assert_eq!(sub(&a, &b).unwrap_err().to_string(), expected);
1904        assert_eq!(rem(&a, &b).unwrap_err().to_string(), expected);
1905    }
1906
1907    #[test]
1908    fn test_decimal256_multiply_minimum_scale() {
1909        let a = Decimal256Array::from(vec![i256::ONE])
1910            .with_precision_and_scale(76, -64)
1911            .unwrap();
1912        let expected = Decimal256Array::from(vec![i256::ONE])
1913            .with_precision_and_scale(76, i8::MIN)
1914            .unwrap();
1915        assert_eq!(mul(&a, &a).unwrap().as_ref(), &expected);
1916
1917        let b = a.clone().with_precision_and_scale(76, -65).unwrap();
1918        assert_eq!(
1919            mul(&a, &b).unwrap_err().to_string(),
1920            "Invalid argument error: Output scale of Decimal256(76, -64) * Decimal256(76, -65) would be less than min scale of -128"
1921        );
1922    }
1923
1924    #[test]
1925    fn test_decimal_div_precision_at_least_scale() {
1926        fn check<T: DecimalType>()
1927        where
1928            T::Native: From<i32>,
1929        {
1930            let a: PrimitiveArray<T> = [Some(1), Some(-1), Some(0), None]
1931                .into_iter()
1932                .map(|v| v.map(T::Native::from))
1933                .collect();
1934            let a = a.with_precision_and_scale(1, 1).unwrap();
1935            for (scale, coefficient) in [(0, 10000), (-1, 1000), (-4, 1), (-5, 0), (-6, 0)] {
1936                let b = PrimitiveArray::<T>::from_iter_values(
1937                    [1, 1, 1, 0].into_iter().map(T::Native::from),
1938                )
1939                .with_precision_and_scale(1, scale)
1940                .unwrap();
1941                let expected: PrimitiveArray<T> =
1942                    [Some(coefficient), Some(-coefficient), Some(0), None]
1943                        .into_iter()
1944                        .map(|v| v.map(T::Native::from))
1945                        .collect();
1946                let expected = expected.with_precision_and_scale(5, 5).unwrap();
1947                assert_eq!(div(&a, &b).unwrap().as_ref(), &expected);
1948            }
1949        }
1950        check::<Decimal32Type>();
1951        check::<Decimal64Type>();
1952        check::<Decimal128Type>();
1953        check::<Decimal256Type>();
1954    }
1955
1956    #[test]
1957    fn test_decimal_div_precision_at_least_one() {
1958        fn check<T: DecimalType>()
1959        where
1960            T::Native: From<i32>,
1961        {
1962            for scale in [-4, -5] {
1963                let a: PrimitiveArray<T> = [Some(1), Some(-1), Some(0), None]
1964                    .into_iter()
1965                    .map(|v| v.map(T::Native::from))
1966                    .collect();
1967                let a = a.with_precision_and_scale(1, scale).unwrap();
1968                for (divisor_scale, coefficient) in [(-4, 1), (-5, 0), (-6, 0)] {
1969                    let b = PrimitiveArray::<T>::from_iter_values(
1970                        [1, 1, 1, 0].into_iter().map(T::Native::from),
1971                    )
1972                    .with_precision_and_scale(1, divisor_scale)
1973                    .unwrap();
1974                    let expected: PrimitiveArray<T> =
1975                        [Some(coefficient), Some(-coefficient), Some(0), None]
1976                            .into_iter()
1977                            .map(|v| v.map(T::Native::from))
1978                            .collect();
1979                    let expected = expected.with_precision_and_scale(1, scale + 4).unwrap();
1980                    assert_eq!(div(&a, &b).unwrap().as_ref(), &expected);
1981                }
1982            }
1983        }
1984        check::<Decimal32Type>();
1985        check::<Decimal64Type>();
1986        check::<Decimal128Type>();
1987        check::<Decimal256Type>();
1988    }
1989
1990    #[test]
1991    fn test_decimal_div_scaling_overflow_boundary() {
1992        // `div` scales `l` by 10^6, which overflows just past `MAX / 10^6` and `MIN / 10^6`.
1993        // Dividing by 10^6 returns each value, on either side of the boundary.
1994        fn check<T: DecimalType>() {
1995            let one = T::Native::ONE;
1996            let pow = T::Native::usize_as(1_000_000);
1997            let max = T::Native::MAX_TOTAL_ORDER.div_wrapping(pow);
1998            let min = T::Native::MIN_TOTAL_ORDER.div_wrapping(pow);
1999            let values = [
2000                max,
2001                max.add_wrapping(one),
2002                min,
2003                min.sub_wrapping(one),
2004                T::Native::MAX_TOTAL_ORDER,
2005                T::Native::MIN_TOTAL_ORDER.add_wrapping(one),
2006            ];
2007            let a = PrimitiveArray::<T>::from_iter_values(values)
2008                .with_precision_and_scale(T::MAX_PRECISION, 2)
2009                .unwrap();
2010            for (divisor, negate) in [(pow, false), (pow.neg_wrapping(), true)] {
2011                let b = PrimitiveArray::<T>::from_iter_values([divisor])
2012                    .with_precision_and_scale(T::MAX_PRECISION, 2)
2013                    .unwrap();
2014                let result = div(&a, &Scalar::new(b)).unwrap();
2015                let expected = values.map(|v| if negate { v.neg_wrapping() } else { v });
2016                assert_eq!(result.as_primitive::<T>().values().as_ref(), expected);
2017            }
2018        }
2019        check::<Decimal32Type>();
2020        check::<Decimal64Type>();
2021        check::<Decimal128Type>();
2022        check::<Decimal256Type>();
2023    }
2024
2025    #[test]
2026    fn test_decimal256_div_wide_intermediate() {
2027        // Dividing two scale-37 values needs l * 10^41, which is 79 digits and does not
2028        // fit in an i256, even though the 41-digit quotient does.
2029        let a = Decimal256Array::from(vec![i256::from_i128(
2030            60096743305738933273387748827369321010i128,
2031        )])
2032        .with_precision_and_scale(38, 37)
2033        .unwrap();
2034        let b = Decimal256Array::from(vec![i256::from_i128(
2035            60096763826458053191384497987259478584i128,
2036        )])
2037        .with_precision_and_scale(38, 37)
2038        .unwrap();
2039
2040        let result = div(&a, &b).unwrap();
2041        assert_eq!(result.data_type(), &DataType::Decimal256(76, 41));
2042        assert_eq!(
2043            result.as_primitive::<Decimal256Type>().value(0),
2044            i256::from_string("99999965853869970143724273117679321341339").unwrap()
2045        );
2046
2047        // Truncation stays toward zero on either side of the fallback.
2048        let neg_a = neg(&a).unwrap();
2049        let result = div(neg_a.as_primitive::<Decimal256Type>(), &b).unwrap();
2050        assert_eq!(
2051            result.as_primitive::<Decimal256Type>().value(0),
2052            i256::from_string("-99999965853869970143724273117679321341339").unwrap()
2053        );
2054
2055        let neg_b = neg(&b).unwrap();
2056        let result = div(&a, neg_b.as_primitive::<Decimal256Type>()).unwrap();
2057        assert_eq!(
2058            result.as_primitive::<Decimal256Type>().value(0),
2059            i256::from_string("-99999965853869970143724273117679321341339").unwrap()
2060        );
2061
2062        let zero = Decimal256Array::from(vec![i256::ZERO])
2063            .with_precision_and_scale(38, 37)
2064            .unwrap();
2065        let err = div(&a, &zero).unwrap_err().to_string();
2066        assert_eq!(err, "Divide by zero error");
2067    }
2068
2069    #[test]
2070    fn test_decimal256_div_divisor_near_max() {
2071        // A divisor past i256::MAX / 10 leaves no room to scale the running remainder either.
2072        let a = Decimal256Array::from(vec![
2073            i256::from_string(
2074                "5900000000000000000000000000000000000000000000000000000000000000000000000000",
2075            )
2076            .unwrap(),
2077        ])
2078        .with_precision_and_scale(76, 37)
2079        .unwrap();
2080        let b = Decimal256Array::from(vec![
2081            i256::from_string(
2082                "6000000000000000000000000000000000000000000000000000000000000000000000000000",
2083            )
2084            .unwrap(),
2085        ])
2086        .with_precision_and_scale(76, 37)
2087        .unwrap();
2088
2089        let result = div(&a, &b).unwrap();
2090        assert_eq!(
2091            result.as_primitive::<Decimal256Type>().value(0),
2092            i256::from_string("98333333333333333333333333333333333333333").unwrap()
2093        );
2094    }
2095
2096    #[test]
2097    fn test_decimal128_div_wide_intermediate() {
2098        // Same overflow one type down: 3.0 / 6.0 at scale 37 needs l * 10^38, 76 digits in i128.
2099        let a = Decimal128Array::from(vec![30000000000000000000000000000000000000i128])
2100            .with_precision_and_scale(38, 37)
2101            .unwrap();
2102        let b = Decimal128Array::from(vec![60000000000000000000000000000000000000i128])
2103            .with_precision_and_scale(38, 37)
2104            .unwrap();
2105
2106        let result = div(&a, &b).unwrap();
2107        assert_eq!(result.data_type(), &DataType::Decimal128(38, 38));
2108        assert_eq!(
2109            result.as_primitive::<Decimal128Type>().value(0),
2110            50000000000000000000000000000000000000i128
2111        );
2112    }
2113
2114    #[test]
2115    fn test_scaled_div_agrees_with_direct_division() {
2116        for (l, r, mul_pow) in [
2117            (7i128, 3i128, 4i8),
2118            (-7, 3, 4),
2119            (7, -3, 4),
2120            (-7, -3, 4),
2121            (1, 999_999_999, 9),
2122            (i128::MAX / 10, 7, 1),
2123            (i128::MAX / 10, -i128::MAX / 11, 1),
2124            (0, 5, 6),
2125        ] {
2126            let scaled = l * 10i128.pow(mul_pow as u32);
2127            assert_eq!(
2128                scaled_div::<Decimal128Type>(l, r, mul_pow).unwrap(),
2129                scaled / r,
2130                "{l} * 10^{mul_pow} / {r}"
2131            );
2132        }
2133    }
2134
2135    #[test]
2136    fn test_decimal_div_rem_by_scalar() {
2137        // `div` and `rem` by a scalar give the same results and errors as by an array that
2138        // repeats it, which takes `try_binary`
2139        fn check<T: DecimalType>() {
2140            let one = T::Native::ONE;
2141            let pow = T::Native::usize_as(1_000_000);
2142            let (max, min) = (T::Native::MAX_TOTAL_ORDER, T::Native::MIN_TOTAL_ORDER);
2143            let seven = T::Native::usize_as(7);
2144            let values = [
2145                Some(T::Native::ZERO),
2146                Some(one),
2147                Some(one.neg_wrapping()),
2148                Some(seven.neg_wrapping()),
2149                None,
2150                Some(max.div_wrapping(pow)),
2151                Some(max.div_wrapping(pow).add_wrapping(one)),
2152                Some(min.div_wrapping(pow).sub_wrapping(one)),
2153                Some(max),
2154                Some(min.add_wrapping(one)),
2155                Some(min),
2156            ];
2157            let divisors = [
2158                T::Native::ZERO,
2159                one,
2160                one.neg_wrapping(),
2161                seven,
2162                seven.neg_wrapping(),
2163                T::Native::usize_as(10_000),
2164                max,
2165                min,
2166            ];
2167            // Scale pairs where the multipliers of `div` and `rem` are 1, a power of ten, and
2168            // one that overflows the divisor
2169            let scales = [(2, 2), (2, 4), (4, 2), (2, -6), (0, 0)];
2170            for (s1, s2) in scales {
2171                let a = PrimitiveArray::<T>::from_iter(values)
2172                    .with_precision_and_scale(T::MAX_PRECISION, s1)
2173                    .unwrap();
2174                let arrays = [
2175                    a.clone(),
2176                    a.slice(1, 6),
2177                    a.slice(0, 0),
2178                    PrimitiveArray::<T>::new_null(3)
2179                        .with_precision_and_scale(T::MAX_PRECISION, s1)
2180                        .unwrap(),
2181                ];
2182                for divisor in divisors {
2183                    let repeat = |len| {
2184                        PrimitiveArray::<T>::from_iter_values(vec![divisor; len])
2185                            .with_precision_and_scale(T::MAX_PRECISION, s2)
2186                            .unwrap()
2187                    };
2188                    let scalar = Scalar::new(repeat(1));
2189                    for a in &arrays {
2190                        let b = repeat(a.len());
2191                        for kernel in [div, rem] {
2192                            let msg = format!("{a:?} by {divisor:?} at scales {s1}, {s2}");
2193                            match (kernel(a, &scalar), kernel(a, &b)) {
2194                                (Ok(s), Ok(b)) => assert_eq!(s.to_data(), b.to_data(), "{msg}"),
2195                                (Err(s), Err(b)) => {
2196                                    assert_eq!(s.to_string(), b.to_string(), "{msg}")
2197                                }
2198                                (s, b) => panic!("{msg}: {s:?} != {b:?}"),
2199                            }
2200                        }
2201                    }
2202                }
2203            }
2204        }
2205        check::<Decimal32Type>();
2206        check::<Decimal64Type>();
2207        check::<Decimal128Type>();
2208        check::<Decimal256Type>();
2209    }
2210
2211    #[test]
2212    fn test_decimal256_same_scale_add_sub() {
2213        let lhs = Decimal256Array::from(vec![
2214            Some(i256::from_parts(u128::MAX, 0)),
2215            Some(i256::MINUS_ONE),
2216            None,
2217        ])
2218        .with_precision_and_scale(70, 2)
2219        .unwrap();
2220        let rhs = Decimal256Array::from(vec![Some(i256::ONE), Some(i256::ONE), Some(i256::MAX)])
2221            .with_precision_and_scale(70, 2)
2222            .unwrap();
2223
2224        let expected =
2225            Decimal256Array::from(vec![Some(i256::from_parts(0, 1)), Some(i256::ZERO), None])
2226                .with_precision_and_scale(71, 2)
2227                .unwrap();
2228        for operation in [add, add_wrapping] {
2229            let result = operation(&lhs, &rhs).unwrap();
2230            assert_eq!(result.as_primitive::<Decimal256Type>(), &expected);
2231        }
2232
2233        let expected = Decimal256Array::from(vec![
2234            Some(i256::from_parts(u128::MAX - 1, 0)),
2235            Some(i256::from_i128(-2)),
2236            None,
2237        ])
2238        .with_precision_and_scale(71, 2)
2239        .unwrap();
2240        for operation in [sub, sub_wrapping] {
2241            let result = operation(&lhs, &rhs).unwrap();
2242            assert_eq!(result.as_primitive::<Decimal256Type>(), &expected);
2243        }
2244
2245        let lhs = Decimal256Array::from(vec![i256::MAX])
2246            .with_precision_and_scale(76, 0)
2247            .unwrap();
2248        let rhs = Decimal256Array::from(vec![i256::ONE])
2249            .with_precision_and_scale(76, 0)
2250            .unwrap();
2251        for operation in [add, add_wrapping] {
2252            assert_eq!(
2253                operation(&lhs, &rhs).unwrap_err().to_string(),
2254                format!(
2255                    "Arithmetic overflow: Overflow happened on: {:?} + {:?}",
2256                    i256::MAX,
2257                    i256::ONE
2258                )
2259            );
2260        }
2261
2262        let lhs = Decimal256Array::from(vec![i256::MIN])
2263            .with_precision_and_scale(76, 0)
2264            .unwrap();
2265        for operation in [sub, sub_wrapping] {
2266            assert_eq!(
2267                operation(&lhs, &rhs).unwrap_err().to_string(),
2268                format!(
2269                    "Arithmetic overflow: Overflow happened on: {:?} - {:?}",
2270                    i256::MIN,
2271                    i256::ONE
2272                )
2273            );
2274        }
2275    }
2276
2277    fn test_timestamp_impl<T: TimestampOp>() {
2278        let a = PrimitiveArray::<T>::new(vec![2000000, 434030324, 53943340].into(), None);
2279        let b = PrimitiveArray::<T>::new(vec![329593, 59349, 694994].into(), None);
2280
2281        let result = sub(&a, &b).unwrap();
2282        assert_eq!(
2283            result.as_primitive::<T::Duration>().values(),
2284            &[1670407, 433970975, 53248346]
2285        );
2286
2287        let r2 = add(&b, &result.as_ref()).unwrap();
2288        assert_eq!(r2.as_ref(), &a);
2289
2290        let r3 = add(&result.as_ref(), &b).unwrap();
2291        assert_eq!(r3.as_ref(), &a);
2292
2293        let format_array = |x: &dyn Array| -> Vec<String> {
2294            x.as_primitive::<T>()
2295                .values()
2296                .into_iter()
2297                .map(|x| as_datetime::<T>(*x).unwrap().to_string())
2298                .collect()
2299        };
2300
2301        let values = vec![
2302            "1970-01-01T00:00:00Z",
2303            "2010-04-01T04:00:20Z",
2304            "1960-01-30T04:23:20Z",
2305        ]
2306        .into_iter()
2307        .map(|x| {
2308            T::from_naive_datetime(DateTime::parse_from_rfc3339(x).unwrap().naive_utc(), None)
2309                .unwrap()
2310        })
2311        .collect();
2312
2313        let a = PrimitiveArray::<T>::new(values, None);
2314        let b = IntervalYearMonthArray::from(vec![
2315            IntervalYearMonthType::make_value(5, 34),
2316            IntervalYearMonthType::make_value(-2, 4),
2317            IntervalYearMonthType::make_value(7, -4),
2318        ]);
2319        let r4 = add(&a, &b).unwrap();
2320        assert_eq!(
2321            &format_array(r4.as_ref()),
2322            &[
2323                "1977-11-01 00:00:00".to_string(),
2324                "2008-08-01 04:00:20".to_string(),
2325                "1966-09-30 04:23:20".to_string()
2326            ]
2327        );
2328
2329        let r5 = sub(&r4, &b).unwrap();
2330        assert_eq!(r5.as_ref(), &a);
2331
2332        let b = IntervalDayTimeArray::from(vec![
2333            IntervalDayTimeType::make_value(5, 454000),
2334            IntervalDayTimeType::make_value(-34, 0),
2335            IntervalDayTimeType::make_value(7, -4000),
2336        ]);
2337        let r6 = add(&a, &b).unwrap();
2338        assert_eq!(
2339            &format_array(r6.as_ref()),
2340            &[
2341                "1970-01-06 00:07:34".to_string(),
2342                "2010-02-26 04:00:20".to_string(),
2343                "1960-02-06 04:23:16".to_string()
2344            ]
2345        );
2346
2347        let r7 = sub(&r6, &b).unwrap();
2348        assert_eq!(r7.as_ref(), &a);
2349
2350        let b = IntervalMonthDayNanoArray::from(vec![
2351            IntervalMonthDayNanoType::make_value(344, 34, -43_000_000_000),
2352            IntervalMonthDayNanoType::make_value(-593, -33, 13_000_000_000),
2353            IntervalMonthDayNanoType::make_value(5, 2, 493_000_000_000),
2354        ]);
2355        let r8 = add(&a, &b).unwrap();
2356        assert_eq!(
2357            &format_array(r8.as_ref()),
2358            &[
2359                "1998-10-04 23:59:17".to_string(),
2360                "1960-09-29 04:00:33".to_string(),
2361                "1960-07-02 04:31:33".to_string()
2362            ]
2363        );
2364
2365        let r9 = sub(&r8, &b).unwrap();
2366        // Note: subtraction is not the inverse of addition for intervals
2367        assert_eq!(
2368            &format_array(r9.as_ref()),
2369            &[
2370                "1970-01-02 00:00:00".to_string(),
2371                "2010-04-02 04:00:20".to_string(),
2372                "1960-01-31 04:23:20".to_string()
2373            ]
2374        );
2375    }
2376
2377    #[test]
2378    fn test_timestamp() {
2379        test_timestamp_impl::<TimestampSecondType>();
2380        test_timestamp_impl::<TimestampMillisecondType>();
2381        test_timestamp_impl::<TimestampMicrosecondType>();
2382        test_timestamp_impl::<TimestampNanosecondType>();
2383    }
2384
2385    #[test]
2386    fn test_interval() {
2387        let a = IntervalYearMonthArray::from(vec![
2388            IntervalYearMonthType::make_value(32, 4),
2389            IntervalYearMonthType::make_value(32, 4),
2390        ]);
2391        let b = IntervalYearMonthArray::from(vec![
2392            IntervalYearMonthType::make_value(-4, 6),
2393            IntervalYearMonthType::make_value(-3, 23),
2394        ]);
2395        let result = add(&a, &b).unwrap();
2396        assert_eq!(
2397            result.as_ref(),
2398            &IntervalYearMonthArray::from(vec![
2399                IntervalYearMonthType::make_value(28, 10),
2400                IntervalYearMonthType::make_value(29, 27)
2401            ])
2402        );
2403        let result = sub(&a, &b).unwrap();
2404        assert_eq!(
2405            result.as_ref(),
2406            &IntervalYearMonthArray::from(vec![
2407                IntervalYearMonthType::make_value(36, -2),
2408                IntervalYearMonthType::make_value(35, -19)
2409            ])
2410        );
2411
2412        let a = IntervalDayTimeArray::from(vec![
2413            IntervalDayTimeType::make_value(32, 4),
2414            IntervalDayTimeType::make_value(32, 4),
2415        ]);
2416        let b = IntervalDayTimeArray::from(vec![
2417            IntervalDayTimeType::make_value(-4, 6),
2418            IntervalDayTimeType::make_value(-3, 23),
2419        ]);
2420        let result = add(&a, &b).unwrap();
2421        assert_eq!(
2422            result.as_ref(),
2423            &IntervalDayTimeArray::from(vec![
2424                IntervalDayTimeType::make_value(28, 10),
2425                IntervalDayTimeType::make_value(29, 27)
2426            ])
2427        );
2428        let result = sub(&a, &b).unwrap();
2429        assert_eq!(
2430            result.as_ref(),
2431            &IntervalDayTimeArray::from(vec![
2432                IntervalDayTimeType::make_value(36, -2),
2433                IntervalDayTimeType::make_value(35, -19)
2434            ])
2435        );
2436        let a = IntervalMonthDayNanoArray::from(vec![
2437            IntervalMonthDayNanoType::make_value(32, 4, 4000000000000),
2438            IntervalMonthDayNanoType::make_value(32, 4, 45463000000000000),
2439        ]);
2440        let b = IntervalMonthDayNanoArray::from(vec![
2441            IntervalMonthDayNanoType::make_value(-4, 6, 46000000000000),
2442            IntervalMonthDayNanoType::make_value(-3, 23, 3564000000000000),
2443        ]);
2444        let result = add(&a, &b).unwrap();
2445        assert_eq!(
2446            result.as_ref(),
2447            &IntervalMonthDayNanoArray::from(vec![
2448                IntervalMonthDayNanoType::make_value(28, 10, 50000000000000),
2449                IntervalMonthDayNanoType::make_value(29, 27, 49027000000000000)
2450            ])
2451        );
2452        let result = sub(&a, &b).unwrap();
2453        assert_eq!(
2454            result.as_ref(),
2455            &IntervalMonthDayNanoArray::from(vec![
2456                IntervalMonthDayNanoType::make_value(36, -2, -42000000000000),
2457                IntervalMonthDayNanoType::make_value(35, -19, 41899000000000000)
2458            ])
2459        );
2460        let a = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNano::MAX]);
2461        let b = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNano::ONE]);
2462        let err = add(&a, &b).unwrap_err().to_string();
2463        assert_eq!(
2464            err,
2465            "Arithmetic overflow: Overflow happened on: 2147483647 + 1"
2466        );
2467    }
2468
2469    #[test]
2470    fn test_interval_mul_i64() {
2471        let interval = IntervalYearMonthArray::from(vec![16, 5, 0]);
2472        let factor = Int64Array::from(vec![3, -2, i64::MAX]);
2473        let expected = IntervalYearMonthArray::from(vec![48, -10, 0]);
2474        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
2475        assert_eq!(mul(&factor, &interval).unwrap().as_ref(), &expected);
2476
2477        let interval = IntervalDayTimeArray::from(vec![
2478            Some(IntervalDayTimeType::make_value(10, 2 * 60 * 60 * 1000)),
2479            None,
2480        ]);
2481        let factor = Int64Array::new_scalar(3);
2482        let expected = IntervalDayTimeArray::from(vec![
2483            Some(IntervalDayTimeType::make_value(30, 6 * 60 * 60 * 1000)),
2484            None,
2485        ]);
2486        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
2487        assert_eq!(mul(&factor, &interval).unwrap().as_ref(), &expected);
2488
2489        let null_factor = Scalar::new(Int64Array::new_null(1));
2490        let expected = IntervalDayTimeArray::new_null(interval.len());
2491        assert_eq!(mul(&interval, &null_factor).unwrap().as_ref(), &expected);
2492        assert_eq!(mul(&null_factor, &interval).unwrap().as_ref(), &expected);
2493
2494        let interval = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(
2495            12,
2496            15,
2497            5_000_000_000,
2498        ));
2499        let factor = Int64Array::from(vec![2, 0, -1]);
2500        let expected = IntervalMonthDayNanoArray::from(vec![
2501            IntervalMonthDayNanoType::make_value(24, 30, 10_000_000_000),
2502            IntervalMonthDayNanoType::make_value(0, 0, 0),
2503            IntervalMonthDayNanoType::make_value(-12, -15, -5_000_000_000),
2504        ]);
2505        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
2506        assert_eq!(mul(&factor, &interval).unwrap().as_ref(), &expected);
2507
2508        let float_factor = Float64Array::new_scalar(2.);
2509        assert!(mul_wrapping(&float_factor, &interval).is_err());
2510        assert!(mul_wrapping(&factor, &interval).is_err());
2511    }
2512
2513    #[test]
2514    fn test_interval_mul_div_f64() {
2515        const HOUR_NANOS: i64 = 3_600_000_000_000;
2516        const MINUTE_NANOS: i64 = 60_000_000_000;
2517
2518        // Adapted from DuckDB's interval multiplication tests:
2519        // https://github.com/duckdb/duckdb/blob/21aca0424f1faf78b593b1e6fbfdd4846624c987/test/sql/function/interval/test_interval_muldiv.test#L1-L99
2520        // DuckDB's cases come from PostgreSQL's interval regression tests:
2521        // https://github.com/postgres/postgres/blob/78758d37306cd89ab060f00cb06f249018d5b8da/src/test/regress/sql/interval.sql#L118-L164
2522        let interval = IntervalMonthDayNanoArray::from(vec![
2523            IntervalMonthDayNanoType::make_value(41, 12, 360 * HOUR_NANOS),
2524            IntervalMonthDayNanoType::make_value(-41, -12, 360 * HOUR_NANOS),
2525            IntervalMonthDayNanoType::make_value(1, 1, 0),
2526            IntervalMonthDayNanoType::make_value(0, 0, 1),
2527            IntervalMonthDayNanoType::make_value(0, 0, 3),
2528            IntervalMonthDayNanoType::make_value(0, 0, -1),
2529            IntervalMonthDayNanoType::make_value(0, 0, -3),
2530        ]);
2531        let factor = Float64Array::from(vec![0.3, 0.3, 1.5, 0.5, 0.5, 0.5, 0.5]);
2532        let expected = IntervalMonthDayNanoArray::from(vec![
2533            IntervalMonthDayNanoType::make_value(12, 12, 122 * HOUR_NANOS + 24 * MINUTE_NANOS),
2534            IntervalMonthDayNanoType::make_value(-12, -12, 93 * HOUR_NANOS + 36 * MINUTE_NANOS),
2535            IntervalMonthDayNanoType::make_value(1, 16, 12 * HOUR_NANOS),
2536            IntervalMonthDayNanoType::make_value(0, 0, 0),
2537            IntervalMonthDayNanoType::make_value(0, 0, 2),
2538            IntervalMonthDayNanoType::make_value(0, 0, 0),
2539            IntervalMonthDayNanoType::make_value(0, 0, -2),
2540        ]);
2541        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
2542        assert_eq!(mul(&factor, &interval).unwrap().as_ref(), &expected);
2543
2544        let interval = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
2545            9,
2546            -27,
2547            45_296 * NANOSECONDS,
2548        )]);
2549        let factor = Float64Array::new_scalar(0.3);
2550        let expected = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
2551            2,
2552            13,
2553            4_948_800_000_000,
2554        )]);
2555        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
2556
2557        let interval = IntervalMonthDayNanoArray::from(vec![
2558            IntervalMonthDayNanoType::make_value(0, 1, 0),
2559            IntervalMonthDayNanoType::make_value(4, 0, 0),
2560            IntervalMonthDayNanoType::make_value(1, 1, 0),
2561            IntervalMonthDayNanoType::make_value(0, 0, (1_i64 << 53) - 1),
2562            IntervalMonthDayNanoType::make_value(0, 0, i64::MAX),
2563            IntervalMonthDayNanoType::make_value(1, 1, 1),
2564            IntervalMonthDayNanoType::make_value(1, 1, 1),
2565            IntervalMonthDayNanoType::make_value(1, 0, 0),
2566        ]);
2567        let factor = Float64Array::from(vec![
2568            3.,
2569            5.,
2570            2.,
2571            0.7,
2572            1.,
2573            f64::INFINITY,
2574            f64::NEG_INFINITY,
2575            -2.,
2576        ]);
2577        let expected = IntervalMonthDayNanoArray::from(vec![
2578            IntervalMonthDayNanoType::make_value(0, 0, 8 * HOUR_NANOS),
2579            IntervalMonthDayNanoType::make_value(0, 24, 0),
2580            IntervalMonthDayNanoType::make_value(0, 15, 12 * HOUR_NANOS),
2581            IntervalMonthDayNanoType::make_value(0, 0, 12_867_427_506_772_844),
2582            IntervalMonthDayNanoType::make_value(0, 0, i64::MAX),
2583            IntervalMonthDayNanoType::make_value(0, 0, 0),
2584            IntervalMonthDayNanoType::make_value(0, 0, 0),
2585            IntervalMonthDayNanoType::make_value(0, -15, 0),
2586        ]);
2587        assert_eq!(div(&interval, &factor).unwrap().as_ref(), &expected);
2588
2589        let null_factor = Scalar::new(Float64Array::new_null(1));
2590        assert_eq!(
2591            mul(&interval, &null_factor).unwrap().as_ref(),
2592            &IntervalMonthDayNanoArray::new_null(interval.len())
2593        );
2594    }
2595
2596    #[test]
2597    fn test_interval_mul_div_f64_matches_duckdb_rounding() {
2598        // Regression test for https://github.com/apache/arrow-rs/issues/12004: each of these
2599        // results is off by 1 ns unless the sub-day remainder is summed in DuckDB's order.
2600        let interval = IntervalMonthDayNanoArray::from(vec![
2601            IntervalMonthDayNanoType::make_value(1, 1, 0),
2602            IntervalMonthDayNanoType::make_value(1, 1, 0),
2603            IntervalMonthDayNanoType::make_value(1, 2, 0),
2604            IntervalMonthDayNanoType::make_value(1, 1, 0),
2605        ]);
2606        let factor = Float64Array::from(vec![32. / 7., 10. / 13., 5. / 7., -32. / 7.]);
2607        let expected = IntervalMonthDayNanoArray::from(vec![
2608            IntervalMonthDayNanoType::make_value(4, 21, 61_714_285_726_628),
2609            IntervalMonthDayNanoType::make_value(0, 23, 73_107_692_314_339),
2610            IntervalMonthDayNanoType::make_value(0, 22, 74_057_142_894_171),
2611            IntervalMonthDayNanoType::make_value(-4, -21, -61_714_285_726_628),
2612        ]);
2613        assert_eq!(mul(&interval, &factor).unwrap().as_ref(), &expected);
2614
2615        // Division multiplies by the reciprocal, so it follows the same order.
2616        let interval =
2617            IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(1, 1, 0)]);
2618        let factor = Float64Array::new_scalar(7. / 32.);
2619        let expected = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
2620            4,
2621            21,
2622            61_714_285_726_628,
2623        )]);
2624        assert_eq!(div(&interval, &factor).unwrap().as_ref(), &expected);
2625    }
2626
2627    #[test]
2628    fn test_interval_mul_div_f64_errors() {
2629        let factor = Float64Array::new_scalar(2.);
2630        let year_month = IntervalYearMonthArray::new_scalar(1);
2631        let day_time = IntervalDayTimeArray::new_scalar(IntervalDayTime::new(1, 1));
2632        for interval in [&year_month as &dyn Datum, &day_time] {
2633            assert!(mul(interval, &factor).is_err());
2634            assert!(mul(&factor, interval).is_err());
2635            assert!(div(interval, &factor).is_err());
2636        }
2637
2638        let interval =
2639            IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(1, 1, 1));
2640
2641        assert!(matches!(
2642            add(&interval, &factor),
2643            Err(ArrowError::InvalidArgumentError(_))
2644        ));
2645
2646        let zero = Float64Array::new_scalar(-0.);
2647        assert!(matches!(
2648            div(&interval, &zero),
2649            Err(ArrowError::DivideByZero)
2650        ));
2651
2652        assert!(div(&factor, &interval).is_err());
2653
2654        for factor in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
2655            let factor = Float64Array::new_scalar(factor);
2656            assert!(matches!(
2657                mul(&interval, &factor),
2658                Err(ArrowError::ArithmeticOverflow(_))
2659            ));
2660        }
2661
2662        let nan = Float64Array::new_scalar(f64::NAN);
2663        assert!(matches!(
2664            div(&interval, &nan),
2665            Err(ArrowError::ArithmeticOverflow(_))
2666        ));
2667
2668        let interval = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(
2669            i32::MAX,
2670            0,
2671            0,
2672        ));
2673        assert!(matches!(
2674            mul(&interval, &factor),
2675            Err(ArrowError::ArithmeticOverflow(_))
2676        ));
2677
2678        let factor = Float64Array::new_scalar(1.5);
2679        let interval = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(
2680            0,
2681            0,
2682            i64::MAX,
2683        ));
2684        assert!(matches!(
2685            mul(&interval, &factor),
2686            Err(ArrowError::ArithmeticOverflow(_))
2687        ));
2688
2689        let factor = Float64Array::new_scalar(1.000_000_000_4);
2690        let interval = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(
2691            i32::MIN,
2692            0,
2693            0,
2694        ));
2695        assert!(matches!(
2696            mul(&interval, &factor),
2697            Err(ArrowError::ArithmeticOverflow(_))
2698        ));
2699
2700        let factor = Float64Array::new_scalar(0.999_999_999);
2701        let interval = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNanoType::make_value(
2702            1,
2703            i32::MAX,
2704            0,
2705        ));
2706        assert!(matches!(
2707            mul(&interval, &factor),
2708            Err(ArrowError::ArithmeticOverflow(_))
2709        ));
2710    }
2711
2712    #[test]
2713    fn test_interval_mul_i64_overflow() {
2714        let interval = IntervalYearMonthArray::from(vec![i32::MAX]);
2715        let factor = Int64Array::from(vec![2]);
2716        assert_eq!(
2717            mul(&interval, &factor).unwrap_err().to_string(),
2718            "Arithmetic overflow: Overflow happened on: 2147483647 * 2"
2719        );
2720
2721        let interval = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
2722            0,
2723            0,
2724            i64::MAX,
2725        )]);
2726        assert_eq!(
2727            mul(&interval, &factor).unwrap_err().to_string(),
2728            "Arithmetic overflow: Overflow happened on: 9223372036854775807 * 2"
2729        );
2730    }
2731
2732    fn test_duration_impl<T: ArrowPrimitiveType<Native = i64>>() {
2733        let a = PrimitiveArray::<T>::new(vec![1000, 4394, -3944].into(), None);
2734        let b = PrimitiveArray::<T>::new(vec![4, -5, -243].into(), None);
2735
2736        let result = add(&a, &b).unwrap();
2737        assert_eq!(result.as_primitive::<T>().values(), &[1004, 4389, -4187]);
2738        let result = sub(&a, &b).unwrap();
2739        assert_eq!(result.as_primitive::<T>().values(), &[996, 4399, -3701]);
2740
2741        let err = mul(&a, &b).unwrap_err().to_string();
2742        assert!(
2743            err.contains("Invalid duration arithmetic operation"),
2744            "{err}"
2745        );
2746
2747        let err = div(&a, &b).unwrap_err().to_string();
2748        assert!(
2749            err.contains("Invalid duration arithmetic operation"),
2750            "{err}"
2751        );
2752
2753        let err = rem(&a, &b).unwrap_err().to_string();
2754        assert!(
2755            err.contains("Invalid duration arithmetic operation"),
2756            "{err}"
2757        );
2758
2759        let a = PrimitiveArray::<T>::new(vec![i64::MAX].into(), None);
2760        let b = PrimitiveArray::<T>::new(vec![1].into(), None);
2761        let err = add(&a, &b).unwrap_err().to_string();
2762        assert_eq!(
2763            err,
2764            "Arithmetic overflow: Overflow happened on: 9223372036854775807 + 1"
2765        );
2766    }
2767
2768    #[test]
2769    fn test_duration() {
2770        test_duration_impl::<DurationSecondType>();
2771        test_duration_impl::<DurationMillisecondType>();
2772        test_duration_impl::<DurationMicrosecondType>();
2773        test_duration_impl::<DurationNanosecondType>();
2774    }
2775
2776    fn test_date_impl<T: ArrowPrimitiveType, F>(f: F)
2777    where
2778        F: Fn(NaiveDate) -> T::Native,
2779        T::Native: TryInto<i64>,
2780    {
2781        let a = PrimitiveArray::<T>::new(
2782            vec![
2783                f(NaiveDate::from_ymd_opt(1979, 1, 30).unwrap()),
2784                f(NaiveDate::from_ymd_opt(2010, 4, 3).unwrap()),
2785                f(NaiveDate::from_ymd_opt(2008, 2, 29).unwrap()),
2786            ]
2787            .into(),
2788            None,
2789        );
2790
2791        let b = IntervalYearMonthArray::from(vec![
2792            IntervalYearMonthType::make_value(34, 2),
2793            IntervalYearMonthType::make_value(3, -3),
2794            IntervalYearMonthType::make_value(-12, 4),
2795        ]);
2796
2797        let format_array = |x: &dyn Array| -> Vec<String> {
2798            x.as_primitive::<T>()
2799                .values()
2800                .into_iter()
2801                .map(|x| {
2802                    as_date::<T>((*x).try_into().ok().unwrap())
2803                        .unwrap()
2804                        .to_string()
2805                })
2806                .collect()
2807        };
2808
2809        let result = add(&a, &b).unwrap();
2810        assert_eq!(
2811            &format_array(result.as_ref()),
2812            &[
2813                "2013-03-30".to_string(),
2814                "2013-01-03".to_string(),
2815                "1996-06-29".to_string(),
2816            ]
2817        );
2818        let result = sub(&result, &b).unwrap();
2819        assert_eq!(result.as_ref(), &a);
2820
2821        let b = IntervalDayTimeArray::from(vec![
2822            IntervalDayTimeType::make_value(34, 2),
2823            IntervalDayTimeType::make_value(3, -3),
2824            IntervalDayTimeType::make_value(-12, 4),
2825        ]);
2826
2827        let result = add(&a, &b).unwrap();
2828        assert_eq!(
2829            &format_array(result.as_ref()),
2830            &[
2831                "1979-03-05".to_string(),
2832                "2010-04-06".to_string(),
2833                "2008-02-17".to_string(),
2834            ]
2835        );
2836        let result = sub(&result, &b).unwrap();
2837        assert_eq!(result.as_ref(), &a);
2838
2839        let b = IntervalMonthDayNanoArray::from(vec![
2840            IntervalMonthDayNanoType::make_value(34, 2, -34353534),
2841            IntervalMonthDayNanoType::make_value(3, -3, 2443),
2842            IntervalMonthDayNanoType::make_value(-12, 4, 2323242423232),
2843        ]);
2844
2845        let result = add(&a, &b).unwrap();
2846        assert_eq!(
2847            &format_array(result.as_ref()),
2848            &[
2849                "1981-12-02".to_string(),
2850                "2010-06-30".to_string(),
2851                "2007-03-04".to_string(),
2852            ]
2853        );
2854        let result = sub(&result, &b).unwrap();
2855        assert_eq!(
2856            &format_array(result.as_ref()),
2857            &[
2858                "1979-01-31".to_string(),
2859                "2010-04-02".to_string(),
2860                "2008-02-29".to_string(),
2861            ]
2862        );
2863    }
2864
2865    #[test]
2866    fn test_date() {
2867        test_date_impl::<Date32Type, _>(Date32Type::from_naive_date);
2868        test_date_impl::<Date64Type, _>(Date64Type::from_naive_date);
2869
2870        let a = Date32Array::from(vec![i32::MIN, i32::MAX, 23, 7684]);
2871        let b = Date32Array::from(vec![i32::MIN, i32::MIN, -2, 45]);
2872        let result = sub(&a, &b).unwrap();
2873        assert_eq!(
2874            result.as_primitive::<DurationSecondType>().values(),
2875            &[0, 371085174288000, 2160000, 660009600]
2876        );
2877
2878        let a = Date64Array::from(vec![4343, 76676, 3434]);
2879        let b = Date64Array::from(vec![3, -5, 5]);
2880        let result = sub(&a, &b).unwrap();
2881        assert_eq!(
2882            result.as_primitive::<DurationMillisecondType>().values(),
2883            &[4340, 76681, 3429]
2884        );
2885
2886        let a = Date64Array::from(vec![i64::MAX]);
2887        let b = Date64Array::from(vec![-1]);
2888        let err = sub(&a, &b).unwrap_err().to_string();
2889        assert_eq!(
2890            err,
2891            "Arithmetic overflow: Overflow happened on: 9223372036854775807 - -1"
2892        );
2893    }
2894
2895    #[test]
2896    fn test_date32_to_naive_date_opt_boundaries() {
2897        assert_eq!(MAX_VALID_DAYS, 95026236);
2898        assert_eq!(MIN_VALID_DAYS, -96465292);
2899
2900        // Valid boundary dates work
2901        assert!(Date32Type::to_naive_date_opt(MAX_VALID_DAYS).is_some());
2902        assert!(Date32Type::to_naive_date_opt(MIN_VALID_DAYS).is_some());
2903
2904        // Beyond boundaries fail
2905        assert!(Date32Type::to_naive_date_opt(MAX_VALID_DAYS + 1).is_none());
2906        assert!(Date32Type::to_naive_date_opt(MIN_VALID_DAYS - 1).is_none());
2907
2908        // Extreme values fail
2909        assert!(Date32Type::to_naive_date_opt(i32::MAX).is_none());
2910        assert!(Date32Type::to_naive_date_opt(i32::MIN).is_none());
2911
2912        // Common values work
2913        assert!(Date32Type::to_naive_date_opt(0).is_some());
2914        assert!(Date32Type::to_naive_date_opt(date_to_days(YEAR_2000)).is_some());
2915    }
2916
2917    #[test]
2918    fn test_date64_to_naive_date_opt_boundaries() {
2919        const MS_PER_DAY: i64 = 24 * 60 * 60 * 1000;
2920
2921        // Verify boundary millisecond values
2922        assert_eq!(MAX_VALID_MILLIS, 8210266790400000i64);
2923        assert_eq!(MIN_VALID_MILLIS, -8334601228800000i64);
2924
2925        // Valid boundary dates work
2926        assert!(Date64Type::to_naive_date_opt(MAX_VALID_MILLIS).is_some());
2927        assert!(Date64Type::to_naive_date_opt(MIN_VALID_MILLIS).is_some());
2928
2929        // Beyond boundaries fail
2930        assert!(Date64Type::to_naive_date_opt(MAX_VALID_MILLIS + MS_PER_DAY).is_none());
2931        assert!(Date64Type::to_naive_date_opt(MIN_VALID_MILLIS - MS_PER_DAY).is_none());
2932
2933        // Extreme values fail
2934        assert!(Date64Type::to_naive_date_opt(i64::MAX).is_none());
2935        assert!(Date64Type::to_naive_date_opt(i64::MIN).is_none());
2936
2937        // Common values work
2938        assert!(Date64Type::to_naive_date_opt(0).is_some());
2939        assert!(Date64Type::to_naive_date_opt(date_to_millis(YEAR_2000)).is_some());
2940    }
2941
2942    macro_rules! test_year_month_ops {
2943        ($type:ty, $date_fn:expr) => {{
2944            let date = $date_fn(YEAR_2000);
2945
2946            // Normal operations succeed
2947            assert!(
2948                <$type>::add_year_months_opt(date, 120).is_some(),
2949                "add_year_months: normal add"
2950            );
2951            assert!(
2952                <$type>::add_year_months_opt(date, 0).is_some(),
2953                "add_year_months: zero interval"
2954            );
2955            assert!(
2956                <$type>::subtract_year_months_opt(date, 120).is_some(),
2957                "subtract_year_months: normal subtract"
2958            );
2959            assert!(
2960                <$type>::subtract_year_months_opt(date, 0).is_some(),
2961                "subtract_year_months: zero interval"
2962            );
2963
2964            // Large but valid years work
2965            let large_year = $date_fn(NaiveDate::from_ymd_opt(5000, 1, 1).unwrap());
2966            let neg_year = $date_fn(NaiveDate::from_ymd_opt(-5000, 12, 31).unwrap());
2967            assert!(
2968                <$type>::add_year_months_opt(large_year, 12).is_some(),
2969                "add_year_months: large year"
2970            );
2971            assert!(
2972                <$type>::add_year_months_opt(neg_year, -12).is_some(),
2973                "add_year_months: negative year"
2974            );
2975            assert!(
2976                <$type>::subtract_year_months_opt(large_year, 12).is_some(),
2977                "subtract_year_months: large year"
2978            );
2979            assert!(
2980                <$type>::subtract_year_months_opt(neg_year, -12).is_some(),
2981                "subtract_year_months: negative year"
2982            );
2983
2984            // Overflow handling
2985            assert!(
2986                <$type>::subtract_year_months_opt($date_fn(MIN_VALID_DATE), 1).is_none(),
2987                "subtract_year_months: overflow days from min"
2988            );
2989            assert!(
2990                <$type>::subtract_year_months_opt($date_fn(MAX_VALID_DATE), -1).is_none(),
2991                "subtract_year_months: overflow neg days from max"
2992            );
2993            assert!(
2994                <$type>::add_year_months_opt($date_fn(MAX_VALID_DATE), 1).is_none(),
2995                "add_year_months: overflow days"
2996            );
2997            assert!(
2998                <$type>::add_year_months_opt($date_fn(MIN_VALID_DATE), -1).is_none(),
2999                "add_year_months: overflow neg days"
3000            );
3001        }};
3002    }
3003
3004    #[test]
3005    fn test_date_year_month_operations() {
3006        test_year_month_ops!(Date32Type, date_to_days);
3007        test_year_month_ops!(Date64Type, date_to_millis);
3008    }
3009
3010    macro_rules! test_day_time_ops {
3011        ($type:ty, $date_fn:expr) => {{
3012            let date = $date_fn(YEAR_2000);
3013
3014            // Moderate intervals succeed
3015            assert!(
3016                <$type>::add_day_time_opt(date, IntervalDayTime::new(30, 0)).is_some(),
3017                "add_day_time: +30 days"
3018            );
3019            assert!(
3020                <$type>::add_day_time_opt(date, IntervalDayTime::new(-30, 0)).is_some(),
3021                "add_day_time: -30 days"
3022            );
3023            assert!(
3024                <$type>::add_day_time_opt(date, IntervalDayTime::new(1000, 12345)).is_some(),
3025                "add_day_time: normal"
3026            );
3027            assert!(
3028                <$type>::subtract_day_time_opt(date, IntervalDayTime::new(30, 0)).is_some(),
3029                "subtract_day_time: +30 days"
3030            );
3031            assert!(
3032                <$type>::subtract_day_time_opt(date, IntervalDayTime::new(-30, 0)).is_some(),
3033                "subtract_day_time: -30 days"
3034            );
3035            assert!(
3036                <$type>::subtract_day_time_opt(date, IntervalDayTime::new(1000, 12345)).is_some(),
3037                "subtract_day_time: normal"
3038            );
3039
3040            // Overflow handling - subtract
3041            assert!(
3042                <$type>::subtract_day_time_opt(
3043                    $date_fn(MIN_VALID_DATE),
3044                    IntervalDayTime::new(1, 0)
3045                )
3046                .is_none(),
3047                "subtract_day_time: overflow days from min"
3048            );
3049            assert!(
3050                <$type>::subtract_day_time_opt(
3051                    $date_fn(MAX_VALID_DATE),
3052                    IntervalDayTime::new(-1, 0)
3053                )
3054                .is_none(),
3055                "subtract_day_time: overflow neg days from max"
3056            );
3057
3058            // Overflow handling - add
3059            assert!(
3060                <$type>::add_day_time_opt($date_fn(MAX_VALID_DATE), IntervalDayTime::new(1, 0))
3061                    .is_none(),
3062                "add_day_time: overflow days"
3063            );
3064            assert!(
3065                <$type>::add_day_time_opt($date_fn(MIN_VALID_DATE), IntervalDayTime::new(-1, 0))
3066                    .is_none(),
3067                "add_day_time: overflow neg days"
3068            );
3069
3070            // Extreme intervals fail
3071            assert!(
3072                <$type>::add_day_time_opt(
3073                    $date_fn(EPOCH),
3074                    IntervalDayTime::new(i32::MAX, i32::MAX)
3075                )
3076                .is_none(),
3077                "add_day_time: max interval"
3078            );
3079            assert!(
3080                <$type>::add_day_time_opt(
3081                    $date_fn(EPOCH),
3082                    IntervalDayTime::new(i32::MIN, i32::MIN)
3083                )
3084                .is_none(),
3085                "add_day_time: min interval"
3086            );
3087            assert!(
3088                <$type>::subtract_day_time_opt(
3089                    $date_fn(EPOCH),
3090                    IntervalDayTime::new(i32::MAX, i32::MAX)
3091                )
3092                .is_none(),
3093                "subtract_day_time: max interval"
3094            );
3095            assert!(
3096                <$type>::subtract_day_time_opt(
3097                    $date_fn(EPOCH),
3098                    IntervalDayTime::new(i32::MIN, i32::MIN)
3099                )
3100                .is_none(),
3101                "subtract_day_time: min interval"
3102            );
3103        }};
3104    }
3105
3106    #[test]
3107    fn test_date_day_time_operations() {
3108        test_day_time_ops!(Date32Type, date_to_days);
3109        test_day_time_ops!(Date64Type, date_to_millis);
3110    }
3111
3112    macro_rules! test_month_day_nano_ops {
3113        ($type:ty, $date_fn:expr) => {{
3114            let date = $date_fn(YEAR_2000);
3115            let zero = IntervalMonthDayNano::new(0, 0, 0);
3116
3117            // Normal operations succeed
3118            assert!(
3119                <$type>::add_month_day_nano_opt(date, IntervalMonthDayNano::new(1, 30, 0))
3120                    .is_some(),
3121                "add_month_day_nano: +1mo +30d"
3122            );
3123            assert!(
3124                <$type>::add_month_day_nano_opt(date, IntervalMonthDayNano::new(-1, -30, 0))
3125                    .is_some(),
3126                "add_month_day_nano: -1mo -30d"
3127            );
3128            assert!(
3129                <$type>::add_month_day_nano_opt(date, zero).is_some(),
3130                "add_month_day_nano: zero interval"
3131            );
3132            assert!(
3133                <$type>::add_month_day_nano_opt(
3134                    date,
3135                    IntervalMonthDayNano::new(2, 10, 123_456_789_000)
3136                )
3137                .is_some(),
3138                "add_month_day_nano: normal"
3139            );
3140            assert!(
3141                <$type>::subtract_month_day_nano_opt(date, IntervalMonthDayNano::new(1, 30, 0))
3142                    .is_some(),
3143                "subtract_month_day_nano: +1mo +30d"
3144            );
3145            assert!(
3146                <$type>::subtract_month_day_nano_opt(date, IntervalMonthDayNano::new(-1, -30, 0))
3147                    .is_some(),
3148                "subtract_month_day_nano: -1mo -30d"
3149            );
3150            assert!(
3151                <$type>::subtract_month_day_nano_opt(date, zero).is_some(),
3152                "subtract_month_day_nano: zero interval"
3153            );
3154            assert!(
3155                <$type>::subtract_month_day_nano_opt(
3156                    date,
3157                    IntervalMonthDayNano::new(2, 10, 123_456_789_000)
3158                )
3159                .is_some(),
3160                "subtract_month_day_nano: normal"
3161            );
3162
3163            // Overflow handling - subtract
3164            assert!(
3165                <$type>::subtract_month_day_nano_opt(
3166                    $date_fn(MIN_VALID_DATE),
3167                    IntervalMonthDayNano::new(0, 1, 0)
3168                )
3169                .is_none(),
3170                "subtract_month_day_nano: overflow days from min"
3171            );
3172            assert!(
3173                <$type>::subtract_month_day_nano_opt(
3174                    $date_fn(MAX_VALID_DATE),
3175                    IntervalMonthDayNano::new(0, -1, 0)
3176                )
3177                .is_none(),
3178                "subtract_month_day_nano: overflow neg days from max"
3179            );
3180
3181            // Overflow handling - add
3182            assert!(
3183                <$type>::add_month_day_nano_opt(
3184                    $date_fn(MAX_VALID_DATE),
3185                    IntervalMonthDayNano::new(0, 1, 0)
3186                )
3187                .is_none(),
3188                "add_month_day_nano: overflow days"
3189            );
3190            assert!(
3191                <$type>::add_month_day_nano_opt(
3192                    $date_fn(MIN_VALID_DATE),
3193                    IntervalMonthDayNano::new(0, -1, 0)
3194                )
3195                .is_none(),
3196                "add_month_day_nano: overflow neg days"
3197            );
3198
3199            // Nanosecond precision works
3200            assert!(
3201                <$type>::add_month_day_nano_opt(date, IntervalMonthDayNano::new(0, 0, 999_999_999))
3202                    .is_some(),
3203                "add_month_day_nano: nanos"
3204            );
3205            assert!(
3206                <$type>::subtract_month_day_nano_opt(
3207                    date,
3208                    IntervalMonthDayNano::new(0, 0, 999_999_999)
3209                )
3210                .is_some(),
3211                "subtract_month_day_nano: nanos"
3212            );
3213            // 1 day in nanos
3214            assert!(
3215                <$type>::add_month_day_nano_opt(
3216                    date,
3217                    IntervalMonthDayNano::new(0, 0, 86_400_000_000_000)
3218                )
3219                .is_some(),
3220                "add_month_day_nano: 1 day nanos"
3221            );
3222            assert!(
3223                <$type>::subtract_month_day_nano_opt(
3224                    date,
3225                    IntervalMonthDayNano::new(0, 0, 86_400_000_000_000)
3226                )
3227                .is_some(),
3228                "subtract_month_day_nano: 1 day nanos"
3229            );
3230        }};
3231    }
3232
3233    #[test]
3234    fn test_date_month_day_nano_operations() {
3235        test_month_day_nano_ops!(Date32Type, date_to_days);
3236        test_month_day_nano_ops!(Date64Type, date_to_millis);
3237    }
3238
3239    #[test]
3240    fn test_date_sub_interval_min_months() {
3241        // Subtracting i32::MIN months requires negating i32::MIN, which
3242        // overflows i32: the date kernels must return the Date arithmetic
3243        // overflow error instead of panicking in debug builds
3244        // https://github.com/apache/arrow-rs/issues/11600
3245        let dates: [ArrayRef; 2] = [
3246            Arc::new(Date32Array::from(vec![0])),
3247            Arc::new(Date64Array::from(vec![0])),
3248        ];
3249        let year_month = IntervalYearMonthArray::from(vec![i32::MIN]);
3250        let month_day_nano =
3251            IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNano::new(i32::MIN, 0, 0)]);
3252        for dates in &dates {
3253            assert_eq!(
3254                sub(dates, &year_month).unwrap_err().to_string(),
3255                "Compute error: Date arithmetic overflow: 0 - -2147483648 months"
3256            );
3257            assert_eq!(
3258                sub(dates, &month_day_nano).unwrap_err().to_string(),
3259                "Compute error: Date arithmetic overflow: 0 - IntervalMonthDayNano { months: -2147483648, days: 0, nanoseconds: 0 }"
3260            );
3261        }
3262    }
3263}