You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/09/26 19:09:14 UTC

[GitHub] [arrow-rs] tustvold opened a new pull request, #2781: Add i256 (#2637)

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

   # 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.
   -->
   
   Part of #2637 
   
   # 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.
   -->
   
   This adds an i256 that can be used as the basis for a Decimal256Array, and implements common arithmetic for it.
   
   # 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 commented on a diff in pull request #2781: Add i256 (#2637)

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #2781:
URL: https://github.com/apache/arrow-rs/pull/2781#discussion_r985522101


##########
arrow-buffer/src/bigint.rs:
##########
@@ -0,0 +1,326 @@
+// 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.
+
+use num::BigInt;
+use std::cmp::Ordering;
+
+/// A signed 256-bit integer
+#[allow(non_camel_case_types)]
+#[derive(Copy, Clone, Default, Eq, PartialEq, Hash)]
+pub struct i256 {
+    low: u128,
+    high: i128,
+}
+
+impl std::fmt::Debug for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", self)
+    }
+}
+
+impl std::fmt::Display for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", BigInt::from_signed_bytes_le(&self.to_le_bytes()))
+    }
+}
+
+impl PartialOrd for i256 {
+    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+        Some(self.cmp(other))
+    }
+}
+
+impl Ord for i256 {
+    fn cmp(&self, other: &Self) -> Ordering {
+        // This is 25x faster than using a variable length encoding such
+        // as BigInt as it avoids allocation and branching
+        self.high.cmp(&other.high).then(self.low.cmp(&other.low))
+    }
+}
+
+impl i256 {
+    /// The additive identity for this integer type, i.e. `0`.
+    pub const ZERO: Self = i256 { low: 0, high: 0 };
+
+    /// The multiplicative identity for this integer type, i.e. `1`.
+    pub const ONE: Self = i256 { low: 1, high: 0 };
+
+    /// The multiplicative inverse for this integer type, i.e. `-1`.
+    pub const MINUS_ONE: Self = i256 {
+        low: u128::MAX,
+        high: -1,
+    };
+
+    /// Create an integer value from its representation as a byte array in little-endian.
+    #[inline]
+    pub fn from_le_bytes(b: [u8; 32]) -> Self {
+        Self {
+            high: i128::from_le_bytes(b[16..32].try_into().unwrap()),
+            low: u128::from_le_bytes(b[0..16].try_into().unwrap()),
+        }
+    }
+
+    /// Create an i256 from the provided low u128 and high i128
+    #[inline]
+    pub fn from_parts(low: u128, high: i128) -> Self {
+        Self { low, high }
+    }
+
+    /// Return the memory representation of this integer as a byte array in little-endian byte order.
+    #[inline]
+    pub fn to_le_bytes(self) -> [u8; 32] {
+        let mut t = [0; 32];
+        let t_low: &mut [u8; 16] = (&mut t[0..16]).try_into().unwrap();
+        *t_low = self.low.to_le_bytes();
+        let t_high: &mut [u8; 16] = (&mut t[16..32]).try_into().unwrap();
+        *t_high = self.high.to_le_bytes();
+        t
+    }
+
+    /// Create an i256 from the provided [`BigInt`] returning a bool indicating
+    /// if overflow occurred
+    fn from_bigint_with_overflow(v: BigInt) -> (Self, bool) {
+        let v_bytes = v.to_signed_bytes_le();
+        match v_bytes.len().cmp(&32) {
+            Ordering::Less => {
+                let mut bytes = if num::Signed::is_negative(&v) {
+                    [255_u8; 32]
+                } else {
+                    [0; 32]
+                };
+                bytes[0..v_bytes.len()].copy_from_slice(&v_bytes[..v_bytes.len()]);
+                (Self::from_le_bytes(bytes), false)
+            }
+            Ordering::Equal => (Self::from_le_bytes(v_bytes.try_into().unwrap()), false),
+            Ordering::Greater => {
+                (Self::from_le_bytes(v_bytes[..32].try_into().unwrap()), true)
+            }
+        }
+    }
+
+    /// Performs wrapping addition
+    #[inline]
+    pub fn wrapping_add(self, other: Self) -> Self {
+        let (low, carry) = self.low.overflowing_add(other.low);
+        let high = self.high.wrapping_add(other.high).wrapping_add(carry as _);
+        Self { low, high }
+    }
+
+    /// 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 })
+    }
+
+    /// Performs wrapping subtraction
+    #[inline]
+    pub fn wrapping_sub(self, other: Self) -> Self {
+        let (low, carry) = self.low.overflowing_sub(other.low);
+        let high = self.high.wrapping_sub(other.high).wrapping_sub(carry as _);
+        Self { low, high }
+    }
+
+    /// 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 })
+    }
+
+    /// Performs wrapping multiplication
+    #[inline]
+    pub fn wrapping_mul(self, other: Self) -> Self {
+        let (low, high) = mulx(self.low, other.low);
+
+        // Compute the high multiples, only impacting the high 128-bits
+        let hl = self.high.wrapping_mul(other.low as i128);
+        let lh = (self.low as i128).wrapping_mul(other.high);
+
+        Self {
+            low,
+            high: (high as i128).wrapping_add(hl).wrapping_add(lh),
+        }
+    }
+
+    /// Performs checked multiplication
+    #[inline]
+    pub fn checked_mul(self, other: Self) -> Option<Self> {
+        let (low, high) = mulx(self.low, other.low);
+
+        // Compute the high multiples, only impacting the high 128-bits
+        let hl = self.high.checked_mul(other.low as i128)?;
+        let lh = (self.low as i128).checked_mul(other.high)?;
+
+        Some(Self {
+            low,
+            high: (high as i128).checked_add(hl)?.checked_add(lh)?,
+        })
+    }
+
+    /// Performs wrapping division
+    #[inline]
+    pub fn wrapping_div(self, other: Self) -> Self {
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        Self::from_bigint_with_overflow(l / r).0
+    }
+
+    /// Performs checked division
+    #[inline]
+    pub fn checked_div(self, other: Self) -> Option<Self> {
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        let (val, overflow) = Self::from_bigint_with_overflow(l / r);
+        (!overflow).then(|| val)
+    }
+
+    /// Performs wrapping remainder
+    #[inline]
+    pub fn wrapping_rem(self, other: Self) -> Self {
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        Self::from_bigint_with_overflow(l % r).0
+    }
+
+    /// Performs checked remainder
+    #[inline]
+    pub fn checked_rem(self, other: Self) -> Option<Self> {
+        if other == Self::ZERO {
+            return None;
+        }
+
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        let (val, overflow) = Self::from_bigint_with_overflow(l % r);
+        (!overflow).then(|| val)
+    }
+}
+
+#[inline]
+fn mulx(a: u128, b: u128) -> (u128, u128) {
+    let split = |a: u128| (a & (u64::MAX as u128), a >> 64);
+
+    const MASK: u128 = u64::MAX as _;
+
+    let (a_low, a_high) = split(a);
+    let (b_low, b_high) = split(b);
+
+    // Carry stores the upper 64-bits of low and lower 64-bits of high
+    let (mut low, mut carry) = split(a_low * b_low);
+    carry += a_high * b_low;
+
+    // Update low and high with corresponding parts of carry
+    low += carry << 64;
+    let mut high = carry >> 64;
+
+    // Update carry with overflow from low
+    carry = low >> 64;
+    low &= MASK;
+
+    // Perform multiply including overflow from low
+    carry += b_high * a_low;
+
+    // Update low and high with values from carry
+    low += carry << 64;
+    high += carry >> 64;
+
+    // Perform 4th multiplication
+    high += a_high * b_high;
+
+    (low, high)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use num::BigInt;
+    use rand::{thread_rng, Rng};
+
+    #[test]
+    fn test_signed_cmp() {
+        let a = i256::from_parts(i128::MAX as u128, 12);
+        let b = i256::from_parts(i128::MIN as u128, 12);
+        assert!(a < b);
+
+        let a = i256::from_parts(i128::MAX as u128, 12);
+        let b = i256::from_parts(i128::MIN as u128, -12);
+        assert!(a > b);
+    }
+
+    #[test]
+    fn test_i256() {
+        let mut rng = thread_rng();
+
+        for _ in 0..1000 {
+            let mut l = [0_u8; 32];
+            let len = rng.gen_range(0..32);
+            l.iter_mut().take(len).for_each(|x| *x = rng.gen());
+
+            let mut r = [0_u8; 32];
+            let len = rng.gen_range(0..32);
+            r.iter_mut().take(len).for_each(|x| *x = rng.gen());
+
+            let il = i256::from_le_bytes(l);
+            let ir = i256::from_le_bytes(r);
+
+            let bl = BigInt::from_signed_bytes_le(&l);
+            let br = BigInt::from_signed_bytes_le(&r);
+
+            // Comparison
+            assert_eq!(il.cmp(&ir), bl.cmp(&br), "{} cmp {}", bl, br);
+
+            // Addition
+            let actual = il.wrapping_add(ir);
+            let (expected, overflow) =
+                i256::from_bigint_with_overflow(bl.clone() + br.clone());
+            assert_eq!(actual, expected);
+
+            let checked = il.checked_add(ir);
+            match overflow {
+                true => assert!(checked.is_none()),
+                false => assert_eq!(checked.unwrap(), actual),
+            }
+
+            // Subtraction
+            let actual = il.wrapping_sub(ir);
+            let (expected, overflow) =
+                i256::from_bigint_with_overflow(bl.clone() - br.clone());
+            assert_eq!(actual.to_string(), expected.to_string());
+
+            let checked = il.checked_sub(ir);
+            match overflow {
+                true => assert!(checked.is_none()),
+                false => assert_eq!(checked.unwrap(), actual),
+            }
+
+            // Multiplication
+            let actual = il.wrapping_mul(ir);
+            let (expected, overflow) =
+                i256::from_bigint_with_overflow(bl.clone() * br.clone());
+            assert_eq!(actual.to_string(), expected.to_string());
+
+            let checked = il.checked_mul(ir);
+            match overflow {
+                true => assert!(checked.is_none()),
+                false => assert_eq!(checked.unwrap(), actual),
+            }

Review Comment:
   Yeah I figured that would be a bit circular



-- 
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 #2781: Add i256 (#2637)

Posted by GitBox <gi...@apache.org>.
tustvold commented on PR #2781:
URL: https://github.com/apache/arrow-rs/pull/2781#issuecomment-1265427536

   There appears to be a mistake somewhere in this :cry: will look into https://github.com/apache/arrow-rs/actions/runs/3174304664/jobs/5170929134


-- 
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] liukun4515 commented on pull request #2781: Add i256 (#2637)

Posted by GitBox <gi...@apache.org>.
liukun4515 commented on PR #2781:
URL: https://github.com/apache/arrow-rs/pull/2781#issuecomment-1259544890

   I need more time to review it tomorrow.
   
   Thanks @tustvold 


-- 
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] liukun4515 commented on a diff in pull request #2781: Add i256 (#2637)

Posted by GitBox <gi...@apache.org>.
liukun4515 commented on code in PR #2781:
URL: https://github.com/apache/arrow-rs/pull/2781#discussion_r981274709


##########
arrow-buffer/src/bigint.rs:
##########
@@ -0,0 +1,253 @@
+use num::BigInt;
+use std::cmp::Ordering;
+
+/// A signed 256-bit integer
+#[allow(non_camel_case_types)]
+#[derive(Copy, Clone, Default, Eq, PartialEq, Hash)]
+pub struct i256([u8; 32]);
+
+impl std::fmt::Debug for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", self)
+    }
+}
+
+impl std::fmt::Display for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", BigInt::from_signed_bytes_le(&self.0))
+    }
+}
+
+impl PartialOrd for i256 {
+    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+        Some(self.cmp(other))
+    }
+}
+
+impl Ord for i256 {
+    fn cmp(&self, other: &Self) -> Ordering {

Review Comment:
   genius method.
   



-- 
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 #2781: Add i256 (#2637)

Posted by GitBox <gi...@apache.org>.
tustvold merged PR #2781:
URL: https://github.com/apache/arrow-rs/pull/2781


-- 
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 #2781: Add i256 (#2637)

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #2781:
URL: https://github.com/apache/arrow-rs/pull/2781#discussion_r980407193


##########
arrow-buffer/src/bigint.rs:
##########
@@ -0,0 +1,253 @@
+use num::BigInt;
+use std::cmp::Ordering;
+
+/// A signed 256-bit integer
+#[allow(non_camel_case_types)]
+#[derive(Copy, Clone, Default, Eq, PartialEq, Hash)]
+pub struct i256([u8; 32]);
+
+impl std::fmt::Debug for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", self)
+    }
+}
+
+impl std::fmt::Display for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", BigInt::from_signed_bytes_le(&self.0))
+    }
+}
+
+impl PartialOrd for i256 {
+    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+        Some(self.cmp(other))
+    }
+}
+
+impl Ord for i256 {
+    fn cmp(&self, other: &Self) -> Ordering {

Review Comment:
   This is related to #2360, performing the comparison this way is significantly faster than using memcmp, which is itself significantly faster than using BigInt.
   
   FYI @liukun4515 



-- 
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] ursabot commented on pull request #2781: Add i256 (#2637)

Posted by GitBox <gi...@apache.org>.
ursabot commented on PR #2781:
URL: https://github.com/apache/arrow-rs/pull/2781#issuecomment-1265405275

   Benchmark runs are scheduled for baseline = 9b590819baffb117383dfd026f92987f4f9f6950 and contender = 4df1f3c62f6d089d8cf02892168b9179e4c8c6fd. 4df1f3c62f6d089d8cf02892168b9179e4c8c6fd is a master commit associated with this PR. Results will be available as each benchmark for each run completes.
   Conbench compare runs links:
   [Skipped :warning: Benchmarking of arrow-rs-commits is not supported on ec2-t3-xlarge-us-east-2] [ec2-t3-xlarge-us-east-2](https://conbench.ursa.dev/compare/runs/b7529ce83ade4725b29f39e0f1c9ca4f...72fd91c771964004b3e5e9fdc44324dd/)
   [Skipped :warning: Benchmarking of arrow-rs-commits is not supported on test-mac-arm] [test-mac-arm](https://conbench.ursa.dev/compare/runs/2ecc2f908e2a4ae98573477df2fde980...50d0071b0d2a4747a73ac8ba223677e0/)
   [Skipped :warning: Benchmarking of arrow-rs-commits is not supported on ursa-i9-9960x] [ursa-i9-9960x](https://conbench.ursa.dev/compare/runs/13ed09c1f64d496b8081deddea7492bd...664b2124a9c04f4daca6b670744dbea0/)
   [Skipped :warning: Benchmarking of arrow-rs-commits is not supported on ursa-thinkcentre-m75q] [ursa-thinkcentre-m75q](https://conbench.ursa.dev/compare/runs/4de549be095349a3bd074f4c4352afd1...f8e510f90b2f4fd397a60df885853883/)
   Buildkite builds:
   Supported benchmarks:
   ec2-t3-xlarge-us-east-2: Supported benchmark langs: Python, R. Runs only benchmarks with cloud = True
   test-mac-arm: Supported benchmark langs: C++, Python, R
   ursa-i9-9960x: Supported benchmark langs: Python, R, JavaScript
   ursa-thinkcentre-m75q: Supported benchmark langs: C++, Java
   


-- 
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] viirya commented on a diff in pull request #2781: Add i256 (#2637)

Posted by GitBox <gi...@apache.org>.
viirya commented on code in PR #2781:
URL: https://github.com/apache/arrow-rs/pull/2781#discussion_r985329999


##########
arrow-buffer/src/bigint.rs:
##########
@@ -0,0 +1,326 @@
+// 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.
+
+use num::BigInt;
+use std::cmp::Ordering;
+
+/// A signed 256-bit integer
+#[allow(non_camel_case_types)]
+#[derive(Copy, Clone, Default, Eq, PartialEq, Hash)]
+pub struct i256 {
+    low: u128,
+    high: i128,
+}
+
+impl std::fmt::Debug for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", self)
+    }
+}
+
+impl std::fmt::Display for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", BigInt::from_signed_bytes_le(&self.to_le_bytes()))
+    }
+}
+
+impl PartialOrd for i256 {
+    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+        Some(self.cmp(other))
+    }
+}
+
+impl Ord for i256 {
+    fn cmp(&self, other: &Self) -> Ordering {
+        // This is 25x faster than using a variable length encoding such
+        // as BigInt as it avoids allocation and branching
+        self.high.cmp(&other.high).then(self.low.cmp(&other.low))
+    }
+}
+
+impl i256 {
+    /// The additive identity for this integer type, i.e. `0`.
+    pub const ZERO: Self = i256 { low: 0, high: 0 };
+
+    /// The multiplicative identity for this integer type, i.e. `1`.
+    pub const ONE: Self = i256 { low: 1, high: 0 };
+
+    /// The multiplicative inverse for this integer type, i.e. `-1`.
+    pub const MINUS_ONE: Self = i256 {
+        low: u128::MAX,
+        high: -1,
+    };
+
+    /// Create an integer value from its representation as a byte array in little-endian.
+    #[inline]
+    pub fn from_le_bytes(b: [u8; 32]) -> Self {
+        Self {
+            high: i128::from_le_bytes(b[16..32].try_into().unwrap()),
+            low: u128::from_le_bytes(b[0..16].try_into().unwrap()),
+        }
+    }
+
+    /// Create an i256 from the provided low u128 and high i128
+    #[inline]
+    pub fn from_parts(low: u128, high: i128) -> Self {
+        Self { low, high }
+    }
+
+    /// Return the memory representation of this integer as a byte array in little-endian byte order.
+    #[inline]
+    pub fn to_le_bytes(self) -> [u8; 32] {
+        let mut t = [0; 32];
+        let t_low: &mut [u8; 16] = (&mut t[0..16]).try_into().unwrap();
+        *t_low = self.low.to_le_bytes();
+        let t_high: &mut [u8; 16] = (&mut t[16..32]).try_into().unwrap();
+        *t_high = self.high.to_le_bytes();
+        t
+    }
+
+    /// Create an i256 from the provided [`BigInt`] returning a bool indicating
+    /// if overflow occurred
+    fn from_bigint_with_overflow(v: BigInt) -> (Self, bool) {
+        let v_bytes = v.to_signed_bytes_le();
+        match v_bytes.len().cmp(&32) {
+            Ordering::Less => {
+                let mut bytes = if num::Signed::is_negative(&v) {
+                    [255_u8; 32]
+                } else {
+                    [0; 32]
+                };
+                bytes[0..v_bytes.len()].copy_from_slice(&v_bytes[..v_bytes.len()]);
+                (Self::from_le_bytes(bytes), false)
+            }
+            Ordering::Equal => (Self::from_le_bytes(v_bytes.try_into().unwrap()), false),
+            Ordering::Greater => {
+                (Self::from_le_bytes(v_bytes[..32].try_into().unwrap()), true)
+            }
+        }
+    }
+
+    /// Performs wrapping addition
+    #[inline]
+    pub fn wrapping_add(self, other: Self) -> Self {
+        let (low, carry) = self.low.overflowing_add(other.low);
+        let high = self.high.wrapping_add(other.high).wrapping_add(carry as _);
+        Self { low, high }
+    }
+
+    /// 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 })
+    }
+
+    /// Performs wrapping subtraction
+    #[inline]
+    pub fn wrapping_sub(self, other: Self) -> Self {
+        let (low, carry) = self.low.overflowing_sub(other.low);
+        let high = self.high.wrapping_sub(other.high).wrapping_sub(carry as _);
+        Self { low, high }
+    }
+
+    /// 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 })
+    }
+
+    /// Performs wrapping multiplication
+    #[inline]
+    pub fn wrapping_mul(self, other: Self) -> Self {
+        let (low, high) = mulx(self.low, other.low);
+
+        // Compute the high multiples, only impacting the high 128-bits
+        let hl = self.high.wrapping_mul(other.low as i128);
+        let lh = (self.low as i128).wrapping_mul(other.high);
+
+        Self {
+            low,
+            high: (high as i128).wrapping_add(hl).wrapping_add(lh),
+        }
+    }
+
+    /// Performs checked multiplication
+    #[inline]
+    pub fn checked_mul(self, other: Self) -> Option<Self> {
+        let (low, high) = mulx(self.low, other.low);
+
+        // Compute the high multiples, only impacting the high 128-bits
+        let hl = self.high.checked_mul(other.low as i128)?;
+        let lh = (self.low as i128).checked_mul(other.high)?;
+
+        Some(Self {
+            low,
+            high: (high as i128).checked_add(hl)?.checked_add(lh)?,
+        })
+    }
+
+    /// Performs wrapping division
+    #[inline]
+    pub fn wrapping_div(self, other: Self) -> Self {
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        Self::from_bigint_with_overflow(l / r).0
+    }
+
+    /// Performs checked division
+    #[inline]
+    pub fn checked_div(self, other: Self) -> Option<Self> {
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        let (val, overflow) = Self::from_bigint_with_overflow(l / r);
+        (!overflow).then(|| val)
+    }
+
+    /// Performs wrapping remainder
+    #[inline]
+    pub fn wrapping_rem(self, other: Self) -> Self {
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        Self::from_bigint_with_overflow(l % r).0
+    }
+
+    /// Performs checked remainder
+    #[inline]
+    pub fn checked_rem(self, other: Self) -> Option<Self> {
+        if other == Self::ZERO {
+            return None;
+        }
+
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        let (val, overflow) = Self::from_bigint_with_overflow(l % r);
+        (!overflow).then(|| val)
+    }
+}
+
+#[inline]
+fn mulx(a: u128, b: u128) -> (u128, u128) {
+    let split = |a: u128| (a & (u64::MAX as u128), a >> 64);
+
+    const MASK: u128 = u64::MAX as _;
+
+    let (a_low, a_high) = split(a);
+    let (b_low, b_high) = split(b);
+
+    // Carry stores the upper 64-bits of low and lower 64-bits of high
+    let (mut low, mut carry) = split(a_low * b_low);
+    carry += a_high * b_low;
+
+    // Update low and high with corresponding parts of carry
+    low += carry << 64;
+    let mut high = carry >> 64;
+
+    // Update carry with overflow from low
+    carry = low >> 64;
+    low &= MASK;
+
+    // Perform multiply including overflow from low
+    carry += b_high * a_low;
+
+    // Update low and high with values from carry
+    low += carry << 64;
+    high += carry >> 64;
+
+    // Perform 4th multiplication
+    high += a_high * b_high;
+
+    (low, high)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use num::BigInt;
+    use rand::{thread_rng, Rng};
+
+    #[test]
+    fn test_signed_cmp() {
+        let a = i256::from_parts(i128::MAX as u128, 12);
+        let b = i256::from_parts(i128::MIN as u128, 12);
+        assert!(a < b);
+
+        let a = i256::from_parts(i128::MAX as u128, 12);
+        let b = i256::from_parts(i128::MIN as u128, -12);
+        assert!(a > b);
+    }
+
+    #[test]
+    fn test_i256() {
+        let mut rng = thread_rng();
+
+        for _ in 0..1000 {
+            let mut l = [0_u8; 32];
+            let len = rng.gen_range(0..32);
+            l.iter_mut().take(len).for_each(|x| *x = rng.gen());
+
+            let mut r = [0_u8; 32];
+            let len = rng.gen_range(0..32);
+            r.iter_mut().take(len).for_each(|x| *x = rng.gen());
+
+            let il = i256::from_le_bytes(l);
+            let ir = i256::from_le_bytes(r);
+
+            let bl = BigInt::from_signed_bytes_le(&l);
+            let br = BigInt::from_signed_bytes_le(&r);
+
+            // Comparison
+            assert_eq!(il.cmp(&ir), bl.cmp(&br), "{} cmp {}", bl, br);
+
+            // Addition
+            let actual = il.wrapping_add(ir);
+            let (expected, overflow) =
+                i256::from_bigint_with_overflow(bl.clone() + br.clone());
+            assert_eq!(actual, expected);
+
+            let checked = il.checked_add(ir);
+            match overflow {
+                true => assert!(checked.is_none()),
+                false => assert_eq!(checked.unwrap(), actual),
+            }
+
+            // Subtraction
+            let actual = il.wrapping_sub(ir);
+            let (expected, overflow) =
+                i256::from_bigint_with_overflow(bl.clone() - br.clone());
+            assert_eq!(actual.to_string(), expected.to_string());
+
+            let checked = il.checked_sub(ir);
+            match overflow {
+                true => assert!(checked.is_none()),
+                false => assert_eq!(checked.unwrap(), actual),
+            }
+
+            // Multiplication
+            let actual = il.wrapping_mul(ir);
+            let (expected, overflow) =
+                i256::from_bigint_with_overflow(bl.clone() * br.clone());
+            assert_eq!(actual.to_string(), expected.to_string());
+
+            let checked = il.checked_mul(ir);
+            match overflow {
+                true => assert!(checked.is_none()),
+                false => assert_eq!(checked.unwrap(), actual),
+            }

Review Comment:
   This doesn't include tests for div, rem because they are implemented using BigInt?



##########
arrow-buffer/src/bigint.rs:
##########
@@ -0,0 +1,326 @@
+// 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.
+
+use num::BigInt;
+use std::cmp::Ordering;
+
+/// A signed 256-bit integer
+#[allow(non_camel_case_types)]
+#[derive(Copy, Clone, Default, Eq, PartialEq, Hash)]
+pub struct i256 {
+    low: u128,
+    high: i128,
+}
+
+impl std::fmt::Debug for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", self)
+    }
+}
+
+impl std::fmt::Display for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", BigInt::from_signed_bytes_le(&self.to_le_bytes()))
+    }
+}
+
+impl PartialOrd for i256 {
+    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+        Some(self.cmp(other))
+    }
+}
+
+impl Ord for i256 {
+    fn cmp(&self, other: &Self) -> Ordering {
+        // This is 25x faster than using a variable length encoding such
+        // as BigInt as it avoids allocation and branching
+        self.high.cmp(&other.high).then(self.low.cmp(&other.low))
+    }
+}
+
+impl i256 {
+    /// The additive identity for this integer type, i.e. `0`.
+    pub const ZERO: Self = i256 { low: 0, high: 0 };
+
+    /// The multiplicative identity for this integer type, i.e. `1`.
+    pub const ONE: Self = i256 { low: 1, high: 0 };
+
+    /// The multiplicative inverse for this integer type, i.e. `-1`.
+    pub const MINUS_ONE: Self = i256 {
+        low: u128::MAX,
+        high: -1,
+    };
+
+    /// Create an integer value from its representation as a byte array in little-endian.
+    #[inline]
+    pub fn from_le_bytes(b: [u8; 32]) -> Self {
+        Self {
+            high: i128::from_le_bytes(b[16..32].try_into().unwrap()),
+            low: u128::from_le_bytes(b[0..16].try_into().unwrap()),
+        }
+    }
+
+    /// Create an i256 from the provided low u128 and high i128
+    #[inline]
+    pub fn from_parts(low: u128, high: i128) -> Self {
+        Self { low, high }
+    }
+
+    /// Return the memory representation of this integer as a byte array in little-endian byte order.
+    #[inline]
+    pub fn to_le_bytes(self) -> [u8; 32] {
+        let mut t = [0; 32];
+        let t_low: &mut [u8; 16] = (&mut t[0..16]).try_into().unwrap();
+        *t_low = self.low.to_le_bytes();
+        let t_high: &mut [u8; 16] = (&mut t[16..32]).try_into().unwrap();
+        *t_high = self.high.to_le_bytes();
+        t
+    }
+
+    /// Create an i256 from the provided [`BigInt`] returning a bool indicating
+    /// if overflow occurred
+    fn from_bigint_with_overflow(v: BigInt) -> (Self, bool) {
+        let v_bytes = v.to_signed_bytes_le();
+        match v_bytes.len().cmp(&32) {
+            Ordering::Less => {
+                let mut bytes = if num::Signed::is_negative(&v) {
+                    [255_u8; 32]
+                } else {
+                    [0; 32]
+                };
+                bytes[0..v_bytes.len()].copy_from_slice(&v_bytes[..v_bytes.len()]);
+                (Self::from_le_bytes(bytes), false)
+            }
+            Ordering::Equal => (Self::from_le_bytes(v_bytes.try_into().unwrap()), false),
+            Ordering::Greater => {
+                (Self::from_le_bytes(v_bytes[..32].try_into().unwrap()), true)
+            }
+        }
+    }
+
+    /// Performs wrapping addition
+    #[inline]
+    pub fn wrapping_add(self, other: Self) -> Self {
+        let (low, carry) = self.low.overflowing_add(other.low);
+        let high = self.high.wrapping_add(other.high).wrapping_add(carry as _);
+        Self { low, high }
+    }
+
+    /// 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 })
+    }
+
+    /// Performs wrapping subtraction
+    #[inline]
+    pub fn wrapping_sub(self, other: Self) -> Self {
+        let (low, carry) = self.low.overflowing_sub(other.low);
+        let high = self.high.wrapping_sub(other.high).wrapping_sub(carry as _);
+        Self { low, high }
+    }
+
+    /// 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 })
+    }
+
+    /// Performs wrapping multiplication
+    #[inline]
+    pub fn wrapping_mul(self, other: Self) -> Self {
+        let (low, high) = mulx(self.low, other.low);
+
+        // Compute the high multiples, only impacting the high 128-bits
+        let hl = self.high.wrapping_mul(other.low as i128);
+        let lh = (self.low as i128).wrapping_mul(other.high);
+
+        Self {
+            low,
+            high: (high as i128).wrapping_add(hl).wrapping_add(lh),
+        }
+    }
+
+    /// Performs checked multiplication
+    #[inline]
+    pub fn checked_mul(self, other: Self) -> Option<Self> {
+        let (low, high) = mulx(self.low, other.low);
+
+        // Compute the high multiples, only impacting the high 128-bits
+        let hl = self.high.checked_mul(other.low as i128)?;
+        let lh = (self.low as i128).checked_mul(other.high)?;
+
+        Some(Self {
+            low,
+            high: (high as i128).checked_add(hl)?.checked_add(lh)?,
+        })
+    }
+
+    /// Performs wrapping division
+    #[inline]
+    pub fn wrapping_div(self, other: Self) -> Self {
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        Self::from_bigint_with_overflow(l / r).0
+    }
+
+    /// Performs checked division
+    #[inline]
+    pub fn checked_div(self, other: Self) -> Option<Self> {
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        let (val, overflow) = Self::from_bigint_with_overflow(l / r);
+        (!overflow).then(|| val)
+    }
+
+    /// Performs wrapping remainder
+    #[inline]
+    pub fn wrapping_rem(self, other: Self) -> Self {
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        Self::from_bigint_with_overflow(l % r).0
+    }
+
+    /// Performs checked remainder
+    #[inline]
+    pub fn checked_rem(self, other: Self) -> Option<Self> {
+        if other == Self::ZERO {
+            return None;
+        }
+
+        let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
+        let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
+        let (val, overflow) = Self::from_bigint_with_overflow(l % r);
+        (!overflow).then(|| val)
+    }
+}
+
+#[inline]
+fn mulx(a: u128, b: u128) -> (u128, u128) {

Review Comment:
   A simple doc might be nicer.



-- 
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 #2781: Add i256 (#2637)

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #2781:
URL: https://github.com/apache/arrow-rs/pull/2781#discussion_r980409068


##########
arrow-buffer/src/bigint.rs:
##########
@@ -0,0 +1,253 @@
+use num::BigInt;
+use std::cmp::Ordering;
+
+/// A signed 256-bit integer
+#[allow(non_camel_case_types)]
+#[derive(Copy, Clone, Default, Eq, PartialEq, Hash)]
+pub struct i256([u8; 32]);
+
+impl std::fmt::Debug for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", self)
+    }
+}
+
+impl std::fmt::Display for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", BigInt::from_signed_bytes_le(&self.0))
+    }
+}
+
+impl PartialOrd for i256 {
+    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+        Some(self.cmp(other))
+    }
+}
+
+impl Ord for i256 {
+    fn cmp(&self, other: &Self) -> Ordering {
+        // This is 25x faster than using a variable length encoding such
+        // as BigInt as it avoids allocation and branching
+        let (left_low, left_high) = self.as_parts();
+        let (right_low, right_high) = other.as_parts();
+        left_high.cmp(&right_high).then(left_low.cmp(&right_low))
+    }
+}
+
+impl i256 {
+    /// Create an integer value from its representation as a byte array in little-endian.
+    #[inline]
+    pub fn from_le_bytes(b: [u8; 32]) -> Self {
+        Self(b)
+    }
+
+    /// Return the memory representation of this integer as a byte array in little-endian byte order.
+    #[inline]
+    pub fn to_le_bytes(self) -> [u8; 32] {
+        self.0
+    }
+
+    /// Returns this i256 as a low u128 and high i128
+    #[inline]
+    fn as_parts(self) -> (u128, i128) {
+        (
+            u128::from_le_bytes(self.0[0..16].try_into().unwrap()),
+            i128::from_le_bytes(self.0[16..32].try_into().unwrap()),
+        )
+    }
+
+    /// Create an i256 from the provided low and high i128
+    #[inline]
+    fn from_parts(low: u128, high: i128) -> Self {
+        let mut t = [0; 32];
+        let t_low: &mut [u8; 16] = (&mut t[0..16]).try_into().unwrap();
+        *t_low = low.to_le_bytes();
+        let t_high: &mut [u8; 16] = (&mut t[16..32]).try_into().unwrap();
+        *t_high = high.to_le_bytes();
+        Self(t)
+    }
+
+    /// Create an i256 from the provided [`BigInt`] returning a bool indicating
+    /// if overflow occurred
+    fn from_bigint_with_overflow(v: BigInt) -> (Self, bool) {
+        let v_bytes = v.to_signed_bytes_le();
+        match v_bytes.len().cmp(&32) {
+            Ordering::Less => {
+                let mut bytes = if num::Signed::is_negative(&v) {
+                    [255_u8; 32]
+                } else {
+                    [0; 32]
+                };
+                bytes[0..v_bytes.len()].copy_from_slice(&v_bytes[..v_bytes.len()]);
+                (Self(bytes), false)
+            }
+            Ordering::Equal => (Self(v_bytes.try_into().unwrap()), false),
+            Ordering::Greater => (Self(v_bytes[..32].try_into().unwrap()), true),
+        }
+    }
+
+    /// Performs wrapping addition
+    #[inline]
+    pub fn wrapping_add(self, other: Self) -> Self {
+        let (left_low, left_high) = self.as_parts();
+        let (right_low, right_high) = other.as_parts();
+
+        let (low, carry) = left_low.overflowing_add(right_low);
+        let high = left_high.wrapping_add(right_high).wrapping_add(carry as _);
+        Self::from_parts(low, high)
+    }
+
+    /// Performs checked addition
+    #[inline]
+    pub fn checked_add(self, other: Self) -> Option<Self> {
+        let (left_low, left_high) = self.as_parts();
+        let (right_low, right_high) = other.as_parts();
+
+        let (low, carry) = left_low.overflowing_add(right_low);
+        let high = left_high.checked_add(right_high)?.checked_add(carry as _)?;
+        Some(Self::from_parts(low, high))
+    }
+
+    /// Performs wrapping addition
+    #[inline]
+    pub fn wrapping_sub(self, other: Self) -> Self {
+        let (left_low, left_high) = self.as_parts();
+        let (right_low, right_high) = other.as_parts();
+
+        let (low, carry) = left_low.overflowing_sub(right_low);
+        let high = left_high.wrapping_sub(right_high).wrapping_sub(carry as _);
+        Self::from_parts(low, high)
+    }
+
+    /// Performs checked addition
+    #[inline]
+    pub fn checked_sub(self, other: Self) -> Option<Self> {
+        let (left_low, left_high) = self.as_parts();
+        let (right_low, right_high) = other.as_parts();
+
+        let (low, carry) = left_low.overflowing_sub(right_low);
+        let high = left_high.checked_sub(right_high)?.checked_sub(carry as _)?;
+        Some(Self::from_parts(low, high))
+    }
+
+    /// Performs wrapping multiplication
+    #[inline]
+    pub fn wrapping_mul(self, other: Self) -> Self {
+        let l = BigInt::from_signed_bytes_le(&self.0);
+        let r = BigInt::from_signed_bytes_le(&other.0);
+        Self::from_bigint_with_overflow(l * r).0
+    }
+
+    /// Performs checked multiplication
+    #[inline]
+    pub fn checked_mul(self, other: Self) -> Option<Self> {
+        let l = BigInt::from_signed_bytes_le(&self.0);
+        let r = BigInt::from_signed_bytes_le(&other.0);
+        let (val, overflow) = Self::from_bigint_with_overflow(l * r);
+        (!overflow).then(|| val)
+    }
+
+    /// Performs wrapping division
+    #[inline]
+    pub fn wrapping_div(self, other: Self) -> Self {
+        let l = BigInt::from_signed_bytes_le(&self.0);
+        let r = BigInt::from_signed_bytes_le(&other.0);
+        Self::from_bigint_with_overflow(l / r).0
+    }
+
+    /// Performs checked division
+    #[inline]
+    pub fn checked_div(self, other: Self) -> Option<Self> {
+        let l = BigInt::from_signed_bytes_le(&self.0);
+        let r = BigInt::from_signed_bytes_le(&other.0);
+        let (val, overflow) = Self::from_bigint_with_overflow(l / r);
+        (!overflow).then(|| val)
+    }
+
+    /// Performs wrapping remainder
+    #[inline]
+    pub fn wrapping_rem(self, other: Self) -> Self {
+        let l = BigInt::from_signed_bytes_le(&self.0);
+        let r = BigInt::from_signed_bytes_le(&other.0);
+        Self::from_bigint_with_overflow(l % r).0
+    }
+
+    /// Performs checked division
+    #[inline]
+    pub fn checked_rem(self, other: Self) -> Option<Self> {
+        if other.0 == [0; 32] {
+            return None;
+        }
+
+        let l = BigInt::from_signed_bytes_le(&self.0);
+        let r = BigInt::from_signed_bytes_le(&other.0);
+        let (val, overflow) = Self::from_bigint_with_overflow(l % r);
+        (!overflow).then(|| val)
+    }
+}

Review Comment:
   Theoretically these would all benefit from an implementation not using BigInt, as this elides allocations and branches, but unlike the addition and subtraction kernels these are significantly more complicated to implement. I leave this as a potential future optimisation for someone who really cares about decimal256 performance



-- 
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 #2781: Add i256 (#2637)

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #2781:
URL: https://github.com/apache/arrow-rs/pull/2781#discussion_r980407193


##########
arrow-buffer/src/bigint.rs:
##########
@@ -0,0 +1,253 @@
+use num::BigInt;
+use std::cmp::Ordering;
+
+/// A signed 256-bit integer
+#[allow(non_camel_case_types)]
+#[derive(Copy, Clone, Default, Eq, PartialEq, Hash)]
+pub struct i256([u8; 32]);
+
+impl std::fmt::Debug for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", self)
+    }
+}
+
+impl std::fmt::Display for i256 {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}", BigInt::from_signed_bytes_le(&self.0))
+    }
+}
+
+impl PartialOrd for i256 {
+    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+        Some(self.cmp(other))
+    }
+}
+
+impl Ord for i256 {
+    fn cmp(&self, other: &Self) -> Ordering {

Review Comment:
   This is related to #2360, performing the comparison this way is significantly faster than using memcmp, which is itself significantly faster than using BigInt.
   
   FYI @liukun4515 
   
   See https://rust.godbolt.org/z/h9fjEP1b4



-- 
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