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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to