You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "tustvold (via GitHub)" <gi...@apache.org> on 2023/06/29 13:29:17 UTC

[GitHub] [arrow-rs] tustvold opened a new pull request, #4465: Add Datum based arithmetic kernels (#3999)

tustvold opened a new pull request, #4465:
URL: https://github.com/apache/arrow-rs/pull/4465

   _Draft as builds on #4393 and needs decimal support added_
   
   # Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #.
   
   # Rationale for this change
    
   <!--
   Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
   Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
   -->
   
   # What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   # Are there any user-facing changes?
   
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!---
   If there are any breaking changes to public APIs, please add the `breaking change` label.
   -->
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold merged pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold merged PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1255712269


##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform `lhs + rhs`, wrapping on overflow for integers
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, returning an error on overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, wrapping on overflow for integers
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, returning an error on overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, wrapping on overflow for integers
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform `lhs / rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Perform `lhs % rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+impl Op {
+    fn commutative(&self) -> bool {
+        matches!(self, Self::Add | Self::AddWrapping)
+    }
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Second), Duration(Second)) => duration_op::<DurationSecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Millisecond), Duration(Millisecond)) => duration_op::<DurationMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Microsecond), Duration(Microsecond)) => duration_op::<DurationMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Nanosecond), Duration(Nanosecond)) => duration_op::<DurationNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Interval(YearMonth), Interval(YearMonth)) => interval_op::<IntervalYearMonthType>(op, l, l_scalar, r, r_scalar),
+        (Interval(DayTime), Interval(DayTime)) => interval_op::<IntervalDayTimeType>(op, l, l_scalar, r, r_scalar),
+        (Interval(MonthDayNano), Interval(MonthDayNano)) => interval_op::<IntervalMonthDayNanoType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal128(_, _), Decimal128(_, _)) => decimal_op::<Decimal128Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal256(_, _), Decimal256(_, _)) => decimal_op::<Decimal256Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => match (l_t, r_t) {
+            (Duration(_) | Interval(_), Date32 | Date64 | Timestamp(_, _)) if op.commutative() => {
+                arithmetic_op(op, rhs, lhs)
+            }
+            _ => Err(ArrowError::InvalidArgumentError(
+              format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+            ))
+        }
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs
+macro_rules! op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.unary(|$r| $op),
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.unary(|$l| $op),
+            },
+        }
+    };
+}
+
+/// Same as `op` but with a type hint for the returned array
+macro_rules! op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform a fallible binary operation on potentially scalar inputs
+macro_rules! try_op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.try_unary(|$r| $op)?,
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.try_unary(|$l| $op)?,
+            },
+        }
+    };
+}
+
+/// Same as `try_op` but with a type hint for the returned array
+macro_rules! try_op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform an arithmetic operation on integers
+fn integer_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)),
+        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
+        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.mod_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Perform an arithmetic operation on floats
+fn float_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::SubWrapping | Op::Sub => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::MulWrapping | Op::Mul => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Div => op!(l, l_s, r, r_s, l.div_wrapping(r)),
+        Op::Rem => op!(l, l_s, r, r_s, l.mod_wrapping(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Arithmetic trait for timestamp arrays
+trait TimestampOp: ArrowTimestampType {
+    type Duration: ArrowPrimitiveType<Native = i64>;
+
+    fn add_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn add_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn add_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+
+    fn sub_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn sub_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn sub_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+}
+
+macro_rules! timestamp {
+    ($t:ty, $d:ty) => {
+        impl TimestampOp for $t {
+            type Duration = $d;
+
+            fn add_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::add_year_months(left, right)
+            }
+
+            fn add_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::add_day_time(left, right)
+            }
+
+            fn add_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::add_month_day_nano(left, right)
+            }
+
+            fn sub_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::subtract_year_months(left, right)
+            }
+
+            fn sub_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::subtract_day_time(left, right)
+            }
+
+            fn sub_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::subtract_month_day_nano(left, right)
+            }
+        }
+    };
+}
+timestamp!(TimestampSecondType, DurationSecondType);
+timestamp!(TimestampMillisecondType, DurationMillisecondType);
+timestamp!(TimestampMicrosecondType, DurationMicrosecondType);
+timestamp!(TimestampNanosecondType, DurationNanosecondType);
+
+/// Perform arithmetic operation on a timestamp array
+fn timestamp_op<T: TimestampOp>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+
+    // Note: interval arithmetic should account for timezones (#4457)
+    let l = l.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match (op, r.data_type()) {
+        (Op::Sub | Op::SubWrapping, Timestamp(unit, _)) if unit == &T::UNIT => {
+            let r = r.as_primitive::<T>();
+            return Ok(try_op_ref!(T::Duration, l, l_s, r, r_s, l.sub_checked(r)));

Review Comment:
   I will update to reference `DataType::is_integer`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1251959550


##########
arrow-arith/src/arithmetic.rs:
##########
@@ -2584,11 +2026,11 @@ mod tests {
     }
 
     #[test]
-    #[should_panic(expected = "DivideByZero")]
     fn test_f32_array_modulus_dyn_by_zero() {
         let a = Float32Array::from(vec![1.5]);
         let b = Float32Array::from(vec![0.0]);
-        modulus_dyn(&a, &b).unwrap();
+        let result = modulus_dyn(&a, &b).unwrap();
+        assert!(result.as_primitive::<Float32Type>().value(0).is_nan());

Review Comment:
   Floating point arithmetic now follows the IEEE 754 standard. My research showed databases to handle division by zero very inconsistently, some returning null and some an error. Broadly speaking it seems peculiar to special case division by zero, and not any of the [other cases](https://en.wikipedia.org/wiki/NaN#Operations_generating_NaN) that can lead to `Nan`. Much like we do for total ordering of floats, I think we should just follow the floating point standard rather than trying to copy some subset of the databases in the wild. As a side benefit this is also significantly faster :smile: 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] alamb commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1254436998


##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform `lhs + rhs`, wrapping on overflow for integers
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, returning an error on overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, wrapping on overflow for integers
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, returning an error on overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, wrapping on overflow for integers
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform `lhs / rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Perform `lhs % rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+impl Op {
+    fn commutative(&self) -> bool {
+        matches!(self, Self::Add | Self::AddWrapping)
+    }
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Second), Duration(Second)) => duration_op::<DurationSecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Millisecond), Duration(Millisecond)) => duration_op::<DurationMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Microsecond), Duration(Microsecond)) => duration_op::<DurationMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Nanosecond), Duration(Nanosecond)) => duration_op::<DurationNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Interval(YearMonth), Interval(YearMonth)) => interval_op::<IntervalYearMonthType>(op, l, l_scalar, r, r_scalar),
+        (Interval(DayTime), Interval(DayTime)) => interval_op::<IntervalDayTimeType>(op, l, l_scalar, r, r_scalar),
+        (Interval(MonthDayNano), Interval(MonthDayNano)) => interval_op::<IntervalMonthDayNanoType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal128(_, _), Decimal128(_, _)) => decimal_op::<Decimal128Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal256(_, _), Decimal256(_, _)) => decimal_op::<Decimal256Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => match (l_t, r_t) {
+            (Duration(_) | Interval(_), Date32 | Date64 | Timestamp(_, _)) if op.commutative() => {
+                arithmetic_op(op, rhs, lhs)
+            }
+            _ => Err(ArrowError::InvalidArgumentError(
+              format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+            ))
+        }
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs
+macro_rules! op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.unary(|$r| $op),
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.unary(|$l| $op),
+            },
+        }
+    };
+}
+
+/// Same as `op` but with a type hint for the returned array
+macro_rules! op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform a fallible binary operation on potentially scalar inputs
+macro_rules! try_op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.try_unary(|$r| $op)?,
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.try_unary(|$l| $op)?,
+            },
+        }
+    };
+}
+
+/// Same as `try_op` but with a type hint for the returned array
+macro_rules! try_op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform an arithmetic operation on integers
+fn integer_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)),
+        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
+        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.mod_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Perform an arithmetic operation on floats
+fn float_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::SubWrapping | Op::Sub => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::MulWrapping | Op::Mul => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Div => op!(l, l_s, r, r_s, l.div_wrapping(r)),
+        Op::Rem => op!(l, l_s, r, r_s, l.mod_wrapping(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Arithmetic trait for timestamp arrays
+trait TimestampOp: ArrowTimestampType {
+    type Duration: ArrowPrimitiveType<Native = i64>;
+
+    fn add_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn add_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn add_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+
+    fn sub_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn sub_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn sub_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+}
+
+macro_rules! timestamp {
+    ($t:ty, $d:ty) => {
+        impl TimestampOp for $t {
+            type Duration = $d;
+
+            fn add_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::add_year_months(left, right)
+            }
+
+            fn add_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::add_day_time(left, right)
+            }
+
+            fn add_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::add_month_day_nano(left, right)
+            }
+
+            fn sub_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::subtract_year_months(left, right)
+            }
+
+            fn sub_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::subtract_day_time(left, right)
+            }
+
+            fn sub_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::subtract_month_day_nano(left, right)
+            }
+        }
+    };
+}
+timestamp!(TimestampSecondType, DurationSecondType);
+timestamp!(TimestampMillisecondType, DurationMillisecondType);
+timestamp!(TimestampMicrosecondType, DurationMicrosecondType);
+timestamp!(TimestampNanosecondType, DurationNanosecondType);
+
+/// Perform arithmetic operation on a timestamp array
+fn timestamp_op<T: TimestampOp>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+
+    // Note: interval arithmetic should account for timezones (#4457)
+    let l = l.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match (op, r.data_type()) {
+        (Op::Sub | Op::SubWrapping, Timestamp(unit, _)) if unit == &T::UNIT => {
+            let r = r.as_primitive::<T>();
+            return Ok(try_op_ref!(T::Duration, l, l_s, r, r_s, l.sub_checked(r)));

Review Comment:
   The docs say:
   
   > /// Perform `lhs + rhs`, wrapping on overflow for integers
   
   I think it would improve the UX a lot of it explicitly calls out that wrapping doesn't apply to temporal (given they are stored as integers, we one could imagine people like myself not realizing they didn't wrap on overflow)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] alamb commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1247018083


##########
arrow-arith/src/operation.rs:
##########
@@ -0,0 +1,419 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Arrow arithmetic operations
+
+use crate::arity::{binary, try_binary};
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+use std::sync::Arc;
+
+/// Perform addition between two `Datum`

Review Comment:
   ```suggestion
   /// Perform addition between two [`Datum`]
   ```



##########
arrow-arith/src/operation.rs:
##########
@@ -0,0 +1,419 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Arrow arithmetic operations
+
+use crate::arity::{binary, try_binary};
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+use std::sync::Arc;
+
+/// Perform addition between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform addition between two `Datum`
+///
+/// Unlike [`add`] this will not return an error for integer overflow
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform addition between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform subtraction between two `Datum`
+///
+/// Unlike [`sub`] this will not return an error for integer overflow
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform multiplication between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform multiplication between two `Datum`
+///
+/// Unlike [`mul`] this will not return an error for integer overflow
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform division between two `Datum`
+///
+/// An error will be returned if this results in overflow or would divide by zero
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Compute the remainder of division of two `Datum`
+///
+/// An error will be returned if this results in overflow or would divide by zero
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => Err(ArrowError::InvalidArgumentError(
+            format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+        ))
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs

Review Comment:
   A nit might be to document that `$l` means the left array and `$l_s` is true f that array should be treated as a scalar (single value)



##########
arrow-arith/src/operation.rs:
##########
@@ -0,0 +1,419 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Arrow arithmetic operations
+
+use crate::arity::{binary, try_binary};
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+use std::sync::Arc;
+
+/// Perform addition between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform addition between two `Datum`
+///
+/// Unlike [`add`] this will not return an error for integer overflow
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform addition between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform subtraction between two `Datum`
+///
+/// Unlike [`sub`] this will not return an error for integer overflow
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform multiplication between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform multiplication between two `Datum`
+///
+/// Unlike [`mul`] this will not return an error for integer overflow
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform division between two `Datum`
+///
+/// An error will be returned if this results in overflow or would divide by zero
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Compute the remainder of division of two `Datum`
+///
+/// An error will be returned if this results in overflow or would divide by zero
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => Err(ArrowError::InvalidArgumentError(
+            format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+        ))
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs
+macro_rules! op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.unary(|$r| $op),
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.unary(|$l| $op),
+            },
+        }
+    };
+}
+
+/// Same as `op` but with a type hint for the returned array
+macro_rules! op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform a fallible binary operation on potentially scalar inputs
+macro_rules! try_op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.try_unary(|$r| $op)?,
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.try_unary(|$l| $op)?,
+            },
+        }
+    };
+}
+
+/// Same as `try_op` but with a type hint for the returned array
+macro_rules! try_op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform an arithmetic operation on integers
+fn integer_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)),
+        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
+        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Perform an arithmetic operation on floats
+fn float_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::SubWrapping | Op::Sub => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::MulWrapping | Op::Mul => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Arithmetic trait for timestamp arrays
+trait TimestampOp: ArrowTimestampType {
+    type Duration: ArrowPrimitiveType<Native = i64>;
+
+    fn add_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn add_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn add_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+
+    fn sub_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn sub_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn sub_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+}
+
+macro_rules! timestamp {
+    ($t:ty, $d:ty) => {
+        impl TimestampOp for $t {
+            type Duration = $d;
+
+            fn add_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::add_year_months(left, right)
+            }
+
+            fn add_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::add_day_time(left, right)
+            }
+
+            fn add_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::add_month_day_nano(left, right)
+            }
+
+            fn sub_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::subtract_year_months(left, right)
+            }
+
+            fn sub_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::subtract_day_time(left, right)
+            }
+
+            fn sub_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::subtract_month_day_nano(left, right)
+            }
+        }
+    };
+}
+timestamp!(TimestampSecondType, DurationSecondType);
+timestamp!(TimestampMillisecondType, DurationMillisecondType);
+timestamp!(TimestampMicrosecondType, DurationMicrosecondType);
+timestamp!(TimestampNanosecondType, DurationNanosecondType);
+
+/// Perform arithmetic operation on a timestamp array
+fn timestamp_op<T: TimestampOp>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+
+    // Note: interval arithmetic should account for timezones (#4457)
+    let l = l.as_primitive::<T>();

Review Comment:
   this is quite beautiful 🤗 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1253812848


##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform `lhs + rhs`, wrapping on overflow for integers
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, returning an error on overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, wrapping on overflow for integers
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, returning an error on overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, wrapping on overflow for integers
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform `lhs / rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Perform `lhs % rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+impl Op {
+    fn commutative(&self) -> bool {
+        matches!(self, Self::Add | Self::AddWrapping)
+    }
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Second), Duration(Second)) => duration_op::<DurationSecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Millisecond), Duration(Millisecond)) => duration_op::<DurationMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Microsecond), Duration(Microsecond)) => duration_op::<DurationMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Nanosecond), Duration(Nanosecond)) => duration_op::<DurationNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Interval(YearMonth), Interval(YearMonth)) => interval_op::<IntervalYearMonthType>(op, l, l_scalar, r, r_scalar),
+        (Interval(DayTime), Interval(DayTime)) => interval_op::<IntervalDayTimeType>(op, l, l_scalar, r, r_scalar),
+        (Interval(MonthDayNano), Interval(MonthDayNano)) => interval_op::<IntervalMonthDayNanoType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal128(_, _), Decimal128(_, _)) => decimal_op::<Decimal128Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal256(_, _), Decimal256(_, _)) => decimal_op::<Decimal256Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => match (l_t, r_t) {
+            (Duration(_) | Interval(_), Date32 | Date64 | Timestamp(_, _)) if op.commutative() => {
+                arithmetic_op(op, rhs, lhs)
+            }
+            _ => Err(ArrowError::InvalidArgumentError(
+              format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+            ))
+        }
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs
+macro_rules! op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.unary(|$r| $op),
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.unary(|$l| $op),
+            },
+        }
+    };
+}
+
+/// Same as `op` but with a type hint for the returned array
+macro_rules! op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform a fallible binary operation on potentially scalar inputs
+macro_rules! try_op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.try_unary(|$r| $op)?,
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.try_unary(|$l| $op)?,
+            },
+        }
+    };
+}
+
+/// Same as `try_op` but with a type hint for the returned array
+macro_rules! try_op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform an arithmetic operation on integers
+fn integer_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)),
+        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
+        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.mod_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Perform an arithmetic operation on floats
+fn float_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::SubWrapping | Op::Sub => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::MulWrapping | Op::Mul => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Div => op!(l, l_s, r, r_s, l.div_wrapping(r)),
+        Op::Rem => op!(l, l_s, r, r_s, l.mod_wrapping(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Arithmetic trait for timestamp arrays
+trait TimestampOp: ArrowTimestampType {
+    type Duration: ArrowPrimitiveType<Native = i64>;
+
+    fn add_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn add_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn add_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+
+    fn sub_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn sub_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn sub_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+}
+
+macro_rules! timestamp {
+    ($t:ty, $d:ty) => {
+        impl TimestampOp for $t {
+            type Duration = $d;
+
+            fn add_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::add_year_months(left, right)
+            }
+
+            fn add_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::add_day_time(left, right)
+            }
+
+            fn add_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::add_month_day_nano(left, right)
+            }
+
+            fn sub_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::subtract_year_months(left, right)
+            }
+
+            fn sub_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::subtract_day_time(left, right)
+            }
+
+            fn sub_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::subtract_month_day_nano(left, right)
+            }
+        }
+    };
+}
+timestamp!(TimestampSecondType, DurationSecondType);
+timestamp!(TimestampMillisecondType, DurationMillisecondType);
+timestamp!(TimestampMicrosecondType, DurationMicrosecondType);
+timestamp!(TimestampNanosecondType, DurationNanosecondType);
+
+/// Perform arithmetic operation on a timestamp array
+fn timestamp_op<T: TimestampOp>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+
+    // Note: interval arithmetic should account for timezones (#4457)
+    let l = l.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match (op, r.data_type()) {
+        (Op::Sub | Op::SubWrapping, Timestamp(unit, _)) if unit == &T::UNIT => {
+            let r = r.as_primitive::<T>();
+            return Ok(try_op_ref!(T::Duration, l, l_s, r, r_s, l.sub_checked(r)));

Review Comment:
   The docs on add_wrapping state that it only performs wrapping overflow for integers, i.e. not for termporal, decimal, etc... This is because the overflow behaviour is not very well defined, and at least in the temporal case has never existed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1251956660


##########
arrow-arith/src/arithmetic.rs:
##########
@@ -3866,16 +3304,8 @@ mod tests {
 
     #[test]
     fn test_timestamp_microsecond_subtract_timestamp_overflow() {
-        let a = TimestampMicrosecondArray::from(vec![
-            <TimestampMicrosecondType as ArrowPrimitiveType>::Native::MAX,
-        ]);
-        let b = TimestampMicrosecondArray::from(vec![
-            <TimestampMicrosecondType as ArrowPrimitiveType>::Native::MIN,
-        ]);
-
-        // unchecked
-        let result = subtract_dyn(&a, &b);

Review Comment:
   Temporal arithmetic is now always checked



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1253815308


##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform `lhs + rhs`, wrapping on overflow for integers
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, returning an error on overflow

Review Comment:
   It could be either, e.g. subtract negative number, I think overflow is the generic catch all



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1251978544


##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform `lhs + rhs`, wrapping on overflow for integers
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, returning an error on overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, wrapping on overflow for integers
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, returning an error on overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, wrapping on overflow for integers
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform `lhs / rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Perform `lhs % rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {

Review Comment:
   I opted for rem instead of mod to be consistent with the Rust nomenclature for this operation



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1253810776


##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform `lhs + rhs`, wrapping on overflow for integers
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, returning an error on overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, wrapping on overflow for integers
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, returning an error on overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, wrapping on overflow for integers
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform `lhs / rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Perform `lhs % rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+impl Op {
+    fn commutative(&self) -> bool {
+        matches!(self, Self::Add | Self::AddWrapping)
+    }
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Second), Duration(Second)) => duration_op::<DurationSecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Millisecond), Duration(Millisecond)) => duration_op::<DurationMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Microsecond), Duration(Microsecond)) => duration_op::<DurationMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Nanosecond), Duration(Nanosecond)) => duration_op::<DurationNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Interval(YearMonth), Interval(YearMonth)) => interval_op::<IntervalYearMonthType>(op, l, l_scalar, r, r_scalar),
+        (Interval(DayTime), Interval(DayTime)) => interval_op::<IntervalDayTimeType>(op, l, l_scalar, r, r_scalar),
+        (Interval(MonthDayNano), Interval(MonthDayNano)) => interval_op::<IntervalMonthDayNanoType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal128(_, _), Decimal128(_, _)) => decimal_op::<Decimal128Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal256(_, _), Decimal256(_, _)) => decimal_op::<Decimal256Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => match (l_t, r_t) {
+            (Duration(_) | Interval(_), Date32 | Date64 | Timestamp(_, _)) if op.commutative() => {
+                arithmetic_op(op, rhs, lhs)
+            }
+            _ => Err(ArrowError::InvalidArgumentError(
+              format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+            ))
+        }
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs
+macro_rules! op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.unary(|$r| $op),
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.unary(|$l| $op),
+            },
+        }
+    };
+}
+
+/// Same as `op` but with a type hint for the returned array
+macro_rules! op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform a fallible binary operation on potentially scalar inputs
+macro_rules! try_op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.try_unary(|$r| $op)?,
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.try_unary(|$l| $op)?,
+            },
+        }
+    };
+}
+
+/// Same as `try_op` but with a type hint for the returned array
+macro_rules! try_op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform an arithmetic operation on integers
+fn integer_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)),
+        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
+        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.mod_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Perform an arithmetic operation on floats
+fn float_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),

Review Comment:
   Correct



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1254430780


##########
arrow-arith/src/arithmetic.rs:
##########
@@ -335,279 +298,56 @@ where
 ///
 /// This doesn't detect overflow. Once overflowing, the result will wrap around.
 /// For an overflow-checking variant, use `add_checked` instead.
+#[deprecated(note = "Use arrow_arith::numeric::add_wrapping")]
 pub fn add<T: ArrowNumericType>(
     left: &PrimitiveArray<T>,
     right: &PrimitiveArray<T>,
 ) -> Result<PrimitiveArray<T>, ArrowError> {
-    math_op(left, right, |a, b| a.add_wrapping(b))
+    binary(left, right, |a, b| a.add_wrapping(b))
 }
 
 /// Perform `left + right` operation on two arrays. If either left or right value is null
 /// then the result is also null.
 ///
 /// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
 /// use `add` instead.
+#[deprecated(note = "Use arrow_arith::numeric::add")]
 pub fn add_checked<T: ArrowNumericType>(
     left: &PrimitiveArray<T>,
     right: &PrimitiveArray<T>,
 ) -> Result<PrimitiveArray<T>, ArrowError> {
-    math_checked_op(left, right, |a, b| a.add_checked(b))
+    try_binary(left, right, |a, b| a.add_checked(b))

Review Comment:
   The dyn kernels now call through to the datum kernels



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] alamb commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1254428516


##########
arrow-arith/src/arithmetic.rs:
##########
@@ -335,279 +298,56 @@ where
 ///
 /// This doesn't detect overflow. Once overflowing, the result will wrap around.
 /// For an overflow-checking variant, use `add_checked` instead.
+#[deprecated(note = "Use arrow_arith::numeric::add_wrapping")]
 pub fn add<T: ArrowNumericType>(
     left: &PrimitiveArray<T>,
     right: &PrimitiveArray<T>,
 ) -> Result<PrimitiveArray<T>, ArrowError> {
-    math_op(left, right, |a, b| a.add_wrapping(b))
+    binary(left, right, |a, b| a.add_wrapping(b))
 }
 
 /// Perform `left + right` operation on two arrays. If either left or right value is null
 /// then the result is also null.
 ///
 /// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
 /// use `add` instead.
+#[deprecated(note = "Use arrow_arith::numeric::add")]
 pub fn add_checked<T: ArrowNumericType>(
     left: &PrimitiveArray<T>,
     right: &PrimitiveArray<T>,
 ) -> Result<PrimitiveArray<T>, ArrowError> {
-    math_checked_op(left, right, |a, b| a.add_checked(b))
+    try_binary(left, right, |a, b| a.add_checked(b))

Review Comment:
   But aren't the tests in terms of the original kernels? If you don't call into the new kernels they aren't tested. 
   
   Or perhaps I am missing something



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1253812848


##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform `lhs + rhs`, wrapping on overflow for integers
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, returning an error on overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, wrapping on overflow for integers
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, returning an error on overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, wrapping on overflow for integers
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform `lhs / rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Perform `lhs % rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+impl Op {
+    fn commutative(&self) -> bool {
+        matches!(self, Self::Add | Self::AddWrapping)
+    }
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Second), Duration(Second)) => duration_op::<DurationSecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Millisecond), Duration(Millisecond)) => duration_op::<DurationMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Microsecond), Duration(Microsecond)) => duration_op::<DurationMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Nanosecond), Duration(Nanosecond)) => duration_op::<DurationNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Interval(YearMonth), Interval(YearMonth)) => interval_op::<IntervalYearMonthType>(op, l, l_scalar, r, r_scalar),
+        (Interval(DayTime), Interval(DayTime)) => interval_op::<IntervalDayTimeType>(op, l, l_scalar, r, r_scalar),
+        (Interval(MonthDayNano), Interval(MonthDayNano)) => interval_op::<IntervalMonthDayNanoType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal128(_, _), Decimal128(_, _)) => decimal_op::<Decimal128Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal256(_, _), Decimal256(_, _)) => decimal_op::<Decimal256Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => match (l_t, r_t) {
+            (Duration(_) | Interval(_), Date32 | Date64 | Timestamp(_, _)) if op.commutative() => {
+                arithmetic_op(op, rhs, lhs)
+            }
+            _ => Err(ArrowError::InvalidArgumentError(
+              format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+            ))
+        }
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs
+macro_rules! op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.unary(|$r| $op),
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.unary(|$l| $op),
+            },
+        }
+    };
+}
+
+/// Same as `op` but with a type hint for the returned array
+macro_rules! op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform a fallible binary operation on potentially scalar inputs
+macro_rules! try_op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.try_unary(|$r| $op)?,
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.try_unary(|$l| $op)?,
+            },
+        }
+    };
+}
+
+/// Same as `try_op` but with a type hint for the returned array
+macro_rules! try_op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform an arithmetic operation on integers
+fn integer_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)),
+        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
+        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.mod_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Perform an arithmetic operation on floats
+fn float_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::SubWrapping | Op::Sub => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::MulWrapping | Op::Mul => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Div => op!(l, l_s, r, r_s, l.div_wrapping(r)),
+        Op::Rem => op!(l, l_s, r, r_s, l.mod_wrapping(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Arithmetic trait for timestamp arrays
+trait TimestampOp: ArrowTimestampType {
+    type Duration: ArrowPrimitiveType<Native = i64>;
+
+    fn add_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn add_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn add_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+
+    fn sub_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn sub_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn sub_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+}
+
+macro_rules! timestamp {
+    ($t:ty, $d:ty) => {
+        impl TimestampOp for $t {
+            type Duration = $d;
+
+            fn add_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::add_year_months(left, right)
+            }
+
+            fn add_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::add_day_time(left, right)
+            }
+
+            fn add_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::add_month_day_nano(left, right)
+            }
+
+            fn sub_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::subtract_year_months(left, right)
+            }
+
+            fn sub_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::subtract_day_time(left, right)
+            }
+
+            fn sub_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::subtract_month_day_nano(left, right)
+            }
+        }
+    };
+}
+timestamp!(TimestampSecondType, DurationSecondType);
+timestamp!(TimestampMillisecondType, DurationMillisecondType);
+timestamp!(TimestampMicrosecondType, DurationMicrosecondType);
+timestamp!(TimestampNanosecondType, DurationNanosecondType);
+
+/// Perform arithmetic operation on a timestamp array
+fn timestamp_op<T: TimestampOp>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+
+    // Note: interval arithmetic should account for timezones (#4457)
+    let l = l.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match (op, r.data_type()) {
+        (Op::Sub | Op::SubWrapping, Timestamp(unit, _)) if unit == &T::UNIT => {
+            let r = r.as_primitive::<T>();
+            return Ok(try_op_ref!(T::Duration, l, l_s, r, r_s, l.sub_checked(r)));

Review Comment:
   The docs on add_wrapping state that it only performs wrapping overflow for integers, i.e. not for termporal, decimal, etc... This is because the overflow behaviour is not very well defined, and at least in the temporal case has never existed. Let me know if the existing docs are insufficient



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1253811142


##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {

Review Comment:
   I thought it was less confusing to make wrapping the special case, as it only impacts integers



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1253815484


##########
arrow-arith/src/aggregate.rs:
##########
@@ -897,54 +897,35 @@ mod tests {
 
     #[test]
     fn test_primitive_array_sum_large_64() {
-        let a: Int64Array = (1..=100)
-            .map(|i| if i % 3 == 0 { Some(i) } else { None })
-            .collect();
-        let b: Int64Array = (1..=100)
-            .map(|i| if i % 3 == 0 { Some(0) } else { Some(i) })
-            .collect();
         // create an array that actually has non-zero values at the invalid indices
-        let c = add(&a, &b).unwrap();
+        let validity = NullBuffer::new((1..=100).map(|x| x % 3 == 0).collect());

Review Comment:
   It was to avoid using a now deprecated kernel



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1253813907


##########
arrow-arith/src/arithmetic.rs:
##########
@@ -335,279 +298,56 @@ where
 ///
 /// This doesn't detect overflow. Once overflowing, the result will wrap around.
 /// For an overflow-checking variant, use `add_checked` instead.
+#[deprecated(note = "Use arrow_arith::numeric::add_wrapping")]
 pub fn add<T: ArrowNumericType>(
     left: &PrimitiveArray<T>,
     right: &PrimitiveArray<T>,
 ) -> Result<PrimitiveArray<T>, ArrowError> {
-    math_op(left, right, |a, b| a.add_wrapping(b))
+    binary(left, right, |a, b| a.add_wrapping(b))
 }
 
 /// Perform `left + right` operation on two arrays. If either left or right value is null
 /// then the result is also null.
 ///
 /// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
 /// use `add` instead.
+#[deprecated(note = "Use arrow_arith::numeric::add")]
 pub fn add_checked<T: ArrowNumericType>(
     left: &PrimitiveArray<T>,
     right: &PrimitiveArray<T>,
 ) -> Result<PrimitiveArray<T>, ArrowError> {
-    math_checked_op(left, right, |a, b| a.add_checked(b))
+    try_binary(left, right, |a, b| a.add_checked(b))

Review Comment:
   Theoretically yes, but I was trying to avoid changing the behaviour of the generic kernels



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#issuecomment-1622774487

   > how well covered is this code
   
   The existing tests of the dyn kernels which now call into this logic should give fairly good coverage, definitely could be improved though. Happy to do as a follow on
   
   > add_wrapping
   
   This was an attempt to encourage the checked logic by default, I can change it back if you feel strongly


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] alamb commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1253516425


##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray

Review Comment:
   ```suggestion
   //! Defines numeric kernels on [`PrimitiveArray`] such as [`add`]
   ```



##########
arrow-arith/src/aggregate.rs:
##########
@@ -897,54 +897,35 @@ mod tests {
 
     #[test]
     fn test_primitive_array_sum_large_64() {
-        let a: Int64Array = (1..=100)
-            .map(|i| if i % 3 == 0 { Some(i) } else { None })
-            .collect();
-        let b: Int64Array = (1..=100)
-            .map(|i| if i % 3 == 0 { Some(0) } else { Some(i) })
-            .collect();
         // create an array that actually has non-zero values at the invalid indices
-        let c = add(&a, &b).unwrap();
+        let validity = NullBuffer::new((1..=100).map(|x| x % 3 == 0).collect());

Review Comment:
   I assume these are updated because they were testing the `sum` kernel for two arrays rather than the aggregate `sum` (which is what is defined in this module)?



##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform `lhs + rhs`, wrapping on overflow for integers
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, returning an error on overflow

Review Comment:
   Is it underflow for sub? Or maybe that is overly pedantic
   ```suggestion
   /// Perform `lhs - rhs`, returning an error on underflow
   ```



##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform `lhs + rhs`, wrapping on overflow for integers
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, returning an error on overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, wrapping on overflow for integers
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, returning an error on overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, wrapping on overflow for integers
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform `lhs / rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Perform `lhs % rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+impl Op {
+    fn commutative(&self) -> bool {
+        matches!(self, Self::Add | Self::AddWrapping)
+    }
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Second), Duration(Second)) => duration_op::<DurationSecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Millisecond), Duration(Millisecond)) => duration_op::<DurationMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Microsecond), Duration(Microsecond)) => duration_op::<DurationMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Nanosecond), Duration(Nanosecond)) => duration_op::<DurationNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Interval(YearMonth), Interval(YearMonth)) => interval_op::<IntervalYearMonthType>(op, l, l_scalar, r, r_scalar),
+        (Interval(DayTime), Interval(DayTime)) => interval_op::<IntervalDayTimeType>(op, l, l_scalar, r, r_scalar),
+        (Interval(MonthDayNano), Interval(MonthDayNano)) => interval_op::<IntervalMonthDayNanoType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal128(_, _), Decimal128(_, _)) => decimal_op::<Decimal128Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal256(_, _), Decimal256(_, _)) => decimal_op::<Decimal256Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => match (l_t, r_t) {
+            (Duration(_) | Interval(_), Date32 | Date64 | Timestamp(_, _)) if op.commutative() => {
+                arithmetic_op(op, rhs, lhs)
+            }
+            _ => Err(ArrowError::InvalidArgumentError(
+              format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+            ))
+        }
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs
+macro_rules! op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.unary(|$r| $op),
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.unary(|$l| $op),
+            },
+        }
+    };
+}
+
+/// Same as `op` but with a type hint for the returned array
+macro_rules! op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform a fallible binary operation on potentially scalar inputs
+macro_rules! try_op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.try_unary(|$r| $op)?,
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.try_unary(|$l| $op)?,
+            },
+        }
+    };
+}
+
+/// Same as `try_op` but with a type hint for the returned array
+macro_rules! try_op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform an arithmetic operation on integers
+fn integer_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)),
+        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
+        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.mod_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Perform an arithmetic operation on floats
+fn float_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::SubWrapping | Op::Sub => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::MulWrapping | Op::Mul => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Div => op!(l, l_s, r, r_s, l.div_wrapping(r)),
+        Op::Rem => op!(l, l_s, r, r_s, l.mod_wrapping(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Arithmetic trait for timestamp arrays
+trait TimestampOp: ArrowTimestampType {
+    type Duration: ArrowPrimitiveType<Native = i64>;
+
+    fn add_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn add_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn add_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+
+    fn sub_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn sub_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn sub_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+}
+
+macro_rules! timestamp {
+    ($t:ty, $d:ty) => {
+        impl TimestampOp for $t {
+            type Duration = $d;
+
+            fn add_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::add_year_months(left, right)
+            }
+
+            fn add_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::add_day_time(left, right)
+            }
+
+            fn add_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::add_month_day_nano(left, right)
+            }
+
+            fn sub_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::subtract_year_months(left, right)
+            }
+
+            fn sub_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::subtract_day_time(left, right)
+            }
+
+            fn sub_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::subtract_month_day_nano(left, right)
+            }
+        }
+    };
+}
+timestamp!(TimestampSecondType, DurationSecondType);
+timestamp!(TimestampMillisecondType, DurationMillisecondType);
+timestamp!(TimestampMicrosecondType, DurationMicrosecondType);
+timestamp!(TimestampNanosecondType, DurationNanosecondType);
+
+/// Perform arithmetic operation on a timestamp array
+fn timestamp_op<T: TimestampOp>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+
+    // Note: interval arithmetic should account for timezones (#4457)
+    let l = l.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match (op, r.data_type()) {
+        (Op::Sub | Op::SubWrapping, Timestamp(unit, _)) if unit == &T::UNIT => {
+            let r = r.as_primitive::<T>();
+            return Ok(try_op_ref!(T::Duration, l, l_s, r, r_s, l.sub_checked(r)));

Review Comment:
   Do i read this as Op::SubWrapping will generate an error on underflow (only) for timestamp arithmetic?
   
   Given the other kernels seem to use `Op::SubWrapping` and `Op::Sub` distinguish between non-erroring erroring variants, is there a reason for the discrepancy in timestamp behavior?
   
   If this behavior will stay, I think it should be documented in `add`, `add_wrapping`, etc



##########
arrow-arith/src/arithmetic.rs:
##########
@@ -335,279 +298,56 @@ where
 ///
 /// This doesn't detect overflow. Once overflowing, the result will wrap around.
 /// For an overflow-checking variant, use `add_checked` instead.
+#[deprecated(note = "Use arrow_arith::numeric::add_wrapping")]
 pub fn add<T: ArrowNumericType>(
     left: &PrimitiveArray<T>,
     right: &PrimitiveArray<T>,
 ) -> Result<PrimitiveArray<T>, ArrowError> {
-    math_op(left, right, |a, b| a.add_wrapping(b))
+    binary(left, right, |a, b| a.add_wrapping(b))
 }
 
 /// Perform `left + right` operation on two arrays. If either left or right value is null
 /// then the result is also null.
 ///
 /// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
 /// use `add` instead.
+#[deprecated(note = "Use arrow_arith::numeric::add")]
 pub fn add_checked<T: ArrowNumericType>(
     left: &PrimitiveArray<T>,
     right: &PrimitiveArray<T>,
 ) -> Result<PrimitiveArray<T>, ArrowError> {
-    math_checked_op(left, right, |a, b| a.add_checked(b))
+    try_binary(left, right, |a, b| a.add_checked(b))

Review Comment:
   could this call the new `add_checked` kernel directly?



##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform `lhs + rhs`, wrapping on overflow for integers
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, returning an error on overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform `lhs - rhs`, wrapping on overflow for integers
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, returning an error on overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform `lhs * rhs`, wrapping on overflow for integers
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform `lhs / rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Perform `lhs % rhs`
+///
+/// Overflow or division by zero will result in an error, with exception to
+/// floating point numbers, which instead follow the IEEE 754 rules
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+impl Op {
+    fn commutative(&self) -> bool {
+        matches!(self, Self::Add | Self::AddWrapping)
+    }
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Second), Duration(Second)) => duration_op::<DurationSecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Millisecond), Duration(Millisecond)) => duration_op::<DurationMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Microsecond), Duration(Microsecond)) => duration_op::<DurationMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Duration(Nanosecond), Duration(Nanosecond)) => duration_op::<DurationNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Interval(YearMonth), Interval(YearMonth)) => interval_op::<IntervalYearMonthType>(op, l, l_scalar, r, r_scalar),
+        (Interval(DayTime), Interval(DayTime)) => interval_op::<IntervalDayTimeType>(op, l, l_scalar, r, r_scalar),
+        (Interval(MonthDayNano), Interval(MonthDayNano)) => interval_op::<IntervalMonthDayNanoType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal128(_, _), Decimal128(_, _)) => decimal_op::<Decimal128Type>(op, l, l_scalar, r, r_scalar),
+        (Decimal256(_, _), Decimal256(_, _)) => decimal_op::<Decimal256Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => match (l_t, r_t) {
+            (Duration(_) | Interval(_), Date32 | Date64 | Timestamp(_, _)) if op.commutative() => {
+                arithmetic_op(op, rhs, lhs)
+            }
+            _ => Err(ArrowError::InvalidArgumentError(
+              format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+            ))
+        }
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs
+macro_rules! op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.unary(|$r| $op),
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.unary(|$l| $op),
+            },
+        }
+    };
+}
+
+/// Same as `op` but with a type hint for the returned array
+macro_rules! op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform a fallible binary operation on potentially scalar inputs
+macro_rules! try_op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.try_unary(|$r| $op)?,
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.try_unary(|$l| $op)?,
+            },
+        }
+    };
+}
+
+/// Same as `try_op` but with a type hint for the returned array
+macro_rules! try_op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform an arithmetic operation on integers
+fn integer_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)),
+        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
+        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.mod_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Perform an arithmetic operation on floats
+fn float_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),

Review Comment:
   Add and AddWrapping call `add_wrapping` is because there is no such thing as "float overflow", right (when they exceed the range the turn into Nan or inf)?



##########
arrow-arith/src/numeric.rs:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Defines numeric kernels on PrimitiveArray
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+
+use crate::arity::{binary, try_binary};
+
+/// Perform `lhs + rhs`, returning an error on overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {

Review Comment:
   Rather than `add` maybe we could call this `add_checked` to:
   1. Make it explicit the user is choosing the checked variant
   2. Be consistent with https://docs.rs/num-traits/latest/num_traits/ops/wrapping/index.html ?
   
   I don't feel super strongly about this



##########
arrow-arith/src/lib.rs:
##########
@@ -18,8 +18,10 @@
 //! Arrow arithmetic and aggregation kernels
 
 pub mod aggregate;
+#[doc(hidden)] // Kernels to be removed in a future release

Review Comment:
   I think this should be tracked in another ticket perhaps



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#issuecomment-1625318909

   Filed tickets #4480 #4481


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1246624340


##########
arrow-arith/src/operation.rs:
##########
@@ -0,0 +1,419 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Arrow arithmetic operations
+
+use crate::arity::{binary, try_binary};
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+use std::sync::Arc;
+
+/// Perform addition between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform addition between two `Datum`
+///
+/// Unlike [`add`] this will not return an error for integer overflow
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform addition between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform subtraction between two `Datum`
+///
+/// Unlike [`sub`] this will not return an error for integer overflow
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform multiplication between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform multiplication between two `Datum`
+///
+/// Unlike [`mul`] this will not return an error for integer overflow
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform division between two `Datum`
+///
+/// An error will be returned if this results in overflow or would divide by zero
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Compute the remainder of division of two `Datum`
+///
+/// An error will be returned if this results in overflow or would divide by zero
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => Err(ArrowError::InvalidArgumentError(
+            format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+        ))
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs
+macro_rules! op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.unary(|$r| $op),
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.unary(|$l| $op),
+            },
+        }
+    };
+}
+
+/// Same as `op` but with a type hint for the returned array
+macro_rules! op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform a fallible binary operation on potentially scalar inputs
+macro_rules! try_op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.try_unary(|$r| $op)?,
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.try_unary(|$l| $op)?,
+            },
+        }
+    };
+}
+
+/// Same as `try_op` but with a type hint for the returned array
+macro_rules! try_op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform an arithmetic operation on integers
+fn integer_op<T: ArrowPrimitiveType>(

Review Comment:
   I'm quite pleased at how concise this is



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org