From 7588b211ff51d58315b402a0e54e627764a49294 Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Thu, 18 Jun 2020 18:36:09 +0200 Subject: [PATCH 1/2] Adding Rem op (%) to Uint128 & Uint256 types --- src/util/uint.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/util/uint.rs b/src/util/uint.rs index 9456df0a..e05e9b99 100644 --- a/src/util/uint.rs +++ b/src/util/uint.rs @@ -166,6 +166,15 @@ macro_rules! construct_uint { } } + impl ::std::ops::Rem<$name> for $name { + type Output = $name; + + fn rem(self, other: $name) -> $name { + let times = self / other; + self - (times * other) + } + } + impl $crate::util::BitArray for $name { #[inline] fn bit(&self, index: usize) -> bool { @@ -479,6 +488,14 @@ mod tests { Uint256::from_u64(21).unwrap()); let div = mult / Uint256::from_u64(300).unwrap(); assert_eq!(div, Uint256([0x9F30411021524112u64, 0x0001BD5B7DDFBD5A, 0, 0])); + + assert_eq!(Uint256::from_u64(105).unwrap() % Uint256::from_u64(5).unwrap(), + Uint256::from_u64(0).unwrap()); + assert_eq!(Uint256::from_u64(35498456).unwrap() % Uint256::from_u64(3435).unwrap(), + Uint256::from_u64(1166).unwrap()); + let rem_src = mult * Uint256::from_u64(39842).unwrap() + Uint256::from_u64(9054).unwrap(); + assert_eq!(rem_src % Uint256::from_u64(39842).unwrap(), + Uint256::from_u64(9054).unwrap()); // TODO: bit inversion } From 19f88212afcdffbf6c14c21441e3474faebb5650 Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Tue, 21 Jul 2020 14:54:56 +0200 Subject: [PATCH 2/2] Fuzz tests for u128 modulo division --- fuzz/fuzz_targets/uint128_fuzz.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/fuzz/fuzz_targets/uint128_fuzz.rs b/fuzz/fuzz_targets/uint128_fuzz.rs index ce00c350..11b2b620 100644 --- a/fuzz/fuzz_targets/uint128_fuzz.rs +++ b/fuzz/fuzz_targets/uint128_fuzz.rs @@ -40,6 +40,7 @@ fn do_test(data: &[u8]) { check_eq!(a_native.wrapping_sub(b_native), a - b); if b_native != 0 { check_eq!(a_native.wrapping_div(b_native), a / b); + check_eq!(a_native.wrapping_rem(b_native), a % b); } check_eq!(a_native.wrapping_mul(b_native), a * b); check_eq!(a_native & b_native, a & b);