You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@arrow.apache.org by tu...@apache.org on 2023/03/26 10:27:37 UTC

[arrow-rs] branch master updated: Fix checked i256 arithmetic (#3942) (#3941) (#3943)

This is an automated email from the ASF dual-hosted git repository.

tustvold pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git


The following commit(s) were added to refs/heads/master by this push:
     new 86b384fa8 Fix checked i256 arithmetic (#3942) (#3941) (#3943)
86b384fa8 is described below

commit 86b384fa81d3fd747e4facd20cdcd47f1581e3b9
Author: Raphael Taylor-Davies <17...@users.noreply.github.com>
AuthorDate: Sun Mar 26 11:27:31 2023 +0100

    Fix checked i256 arithmetic (#3942) (#3941) (#3943)
    
    * Fix checked i256 arithmetic (#3942) (#3941)
    
    * Tweak
    
    * Add is_positive
    
    * Make const
---
 arrow-buffer/src/bigint.rs | 75 ++++++++++++++++++++++++++++++++--------------
 1 file changed, 53 insertions(+), 22 deletions(-)

diff --git a/arrow-buffer/src/bigint.rs b/arrow-buffer/src/bigint.rs
index 4b446e19b..4625d24c1 100644
--- a/arrow-buffer/src/bigint.rs
+++ b/arrow-buffer/src/bigint.rs
@@ -243,9 +243,9 @@ impl i256 {
     /// Performs checked addition
     #[inline]
     pub fn checked_add(self, other: Self) -> Option<Self> {
-        let (low, carry) = self.low.overflowing_add(other.low);
-        let high = self.high.checked_add(other.high)?.checked_add(carry as _)?;
-        Some(Self { low, high })
+        let r = self.wrapping_add(other);
+        ((other.is_negative() && r < self) || (!other.is_negative() && r >= self))
+            .then_some(r)
     }
 
     /// Performs wrapping subtraction
@@ -259,9 +259,9 @@ impl i256 {
     /// Performs checked subtraction
     #[inline]
     pub fn checked_sub(self, other: Self) -> Option<Self> {
-        let (low, carry) = self.low.overflowing_sub(other.low);
-        let high = self.high.checked_sub(other.high)?.checked_sub(carry as _)?;
-        Some(Self { low, high })
+        let r = self.wrapping_sub(other);
+        ((other.is_negative() && r > self) || (!other.is_negative() && r <= self))
+            .then_some(r)
     }
 
     /// Performs wrapping multiplication
@@ -282,10 +282,14 @@ impl i256 {
     /// Performs checked multiplication
     #[inline]
     pub fn checked_mul(self, other: Self) -> Option<Self> {
+        if self == i256::ZERO || other == i256::ZERO {
+            return Some(i256::ZERO);
+        }
+
         // Shift sign bit down to construct mask of all set bits if negative
         let l_sa = self.high >> 127;
         let r_sa = other.high >> 127;
-        let out_sa = l_sa ^ r_sa;
+        let out_sa = (l_sa ^ r_sa) as u128;
 
         // Compute absolute values
         let l_abs = self.wrapping_abs();
@@ -303,13 +307,15 @@ impl i256 {
         let hl = (l_abs.high as u128).checked_mul(r_abs.low)?;
         let lh = l_abs.low.checked_mul(r_abs.high as u128)?;
 
-        let high: i128 = high.checked_add(hl)?.checked_add(lh)?.try_into().ok()?;
+        let high = high.checked_add(hl)?.checked_add(lh)?;
 
         // Reverse absolute value, if necessary
-        let (low, c) = (low ^ out_sa as u128).overflowing_sub(out_sa as u128);
-        let high = (high ^ out_sa).wrapping_sub(out_sa).wrapping_sub(c as i128);
+        let (low, c) = (low ^ out_sa).overflowing_sub(out_sa);
+        let high = (high ^ out_sa).wrapping_sub(out_sa).wrapping_sub(c as u128) as i128;
 
-        Some(Self { low, high })
+        // Check for overflow in final conversion
+        (high.is_negative() == (self.is_negative() ^ other.is_negative()))
+            .then_some(Self { low, high })
     }
 
     /// Performs wrapping division
@@ -398,6 +404,12 @@ impl i256 {
         // needless overflow.
         acc.wrapping_mul(base)
     }
+
+    /// Returns `true` if this [`i256`] is negative
+    #[inline]
+    pub const fn is_negative(self) -> bool {
+        self.high.is_negative()
+    }
 }
 
 /// Temporary workaround due to lack of stable const array slicing
@@ -709,7 +721,7 @@ mod tests {
         let checked = il.checked_add(ir);
         match overflow {
             true => assert!(checked.is_none()),
-            false => assert_eq!(checked.unwrap(), actual),
+            false => assert_eq!(checked, Some(actual)),
         }
 
         // Subtraction
@@ -721,7 +733,7 @@ mod tests {
         let checked = il.checked_sub(ir);
         match overflow {
             true => assert!(checked.is_none()),
-            false => assert_eq!(checked.unwrap(), actual),
+            false => assert_eq!(checked, Some(actual), "{bl} - {br} = {expected}"),
         }
 
         // Multiplication
@@ -737,14 +749,14 @@ mod tests {
                 "{il} * {ir} = {actual} vs {bl} * {br} = {expected}"
             ),
             false => assert_eq!(
-                checked.unwrap(),
-                actual,
+                checked,
+                Some(actual),
                 "{il} * {ir} = {actual} vs {bl} * {br} = {expected}"
             ),
         }
 
         // Exponentiation
-        for exp in vec![0, 1, 3, 8, 100].into_iter() {
+        for exp in vec![0, 1, 2, 3, 8, 100].into_iter() {
             let actual = il.wrapping_pow(exp);
             let (expected, overflow) =
                 i256::from_bigint_with_overflow(bl.clone().pow(exp));
@@ -757,9 +769,9 @@ mod tests {
                     "{il} ^ {exp} = {actual} vs {bl} * {exp} = {expected}"
                 ),
                 false => assert_eq!(
-                    checked.unwrap(),
-                    actual,
-                    "{il} ^ {exp} = {actual} vs {bl} * {exp} = {expected}"
+                    checked,
+                    Some(actual),
+                    "{il} ^ {exp} = {actual} vs {bl} ^ {exp} = {expected}"
                 ),
             }
         }
@@ -791,14 +803,33 @@ mod tests {
     #[test]
     fn test_i256() {
         let candidates = [
-            i256::from_parts(0, 0),
-            i256::from_parts(0, 1),
-            i256::from_parts(0, -1),
+            i256::ZERO,
+            i256::ONE,
+            i256::MINUS_ONE,
+            i256::from_i128(2),
+            i256::from_i128(-2),
             i256::from_parts(u128::MAX, 1),
             i256::from_parts(u128::MAX, -1),
             i256::from_parts(0, 1),
             i256::from_parts(0, -1),
+            i256::from_parts(1, -1),
+            i256::from_parts(1, 1),
+            i256::from_parts(0, i128::MAX),
+            i256::from_parts(0, i128::MIN),
+            i256::from_parts(1, i128::MAX),
+            i256::from_parts(1, i128::MIN),
+            i256::from_parts(u128::MAX, i128::MIN),
             i256::from_parts(100, 32),
+            i256::MIN,
+            i256::MAX,
+            i256::MIN >> 1,
+            i256::MAX >> 1,
+            i256::ONE << 127,
+            i256::ONE << 128,
+            i256::ONE << 129,
+            i256::MINUS_ONE << 127,
+            i256::MINUS_ONE << 128,
+            i256::MINUS_ONE << 129,
         ];
 
         for il in candidates {