From d52b88b5257ea21a14ef7367d5e6557b8eb7efa0 Mon Sep 17 00:00:00 2001 From: carolcapps Date: Sat, 13 Mar 2021 15:19:43 +0000 Subject: [PATCH] Fix increment of Uint256 with carry --- src/util/uint.rs | 55 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/src/util/uint.rs b/src/util/uint.rs index 064ce121..c7a52265 100644 --- a/src/util/uint.rs +++ b/src/util/uint.rs @@ -516,13 +516,13 @@ impl Uint256 { #[inline] pub fn increment(&mut self) { let &mut Uint256(ref mut arr) = self; - arr[0] += 1; + arr[0] = arr[0].wrapping_add(1); if arr[0] == 0 { - arr[1] += 1; + arr[1] = arr[1].wrapping_add(1); if arr[1] == 0 { - arr[2] += 1; + arr[2] = arr[2].wrapping_add(1); if arr[2] == 0 { - arr[3] += 1; + arr[3] = arr[3].wrapping_add(1); } } } @@ -689,6 +689,53 @@ mod tests { 0x4AFCFF6F0375C608u64, 0x928D92B4D7F5DF33u64])); } + #[test] + pub fn increment_test() { + let mut val = Uint256([ + 0xFFFFFFFFFFFFFFFEu64, + 0xFFFFFFFFFFFFFFFFu64, + 0xFFFFFFFFFFFFFFFFu64, + 0xEFFFFFFFFFFFFFFFu64, + ]); + val.increment(); + assert_eq!( + val, + Uint256([ + 0xFFFFFFFFFFFFFFFFu64, + 0xFFFFFFFFFFFFFFFFu64, + 0xFFFFFFFFFFFFFFFFu64, + 0xEFFFFFFFFFFFFFFFu64, + ]) + ); + val.increment(); + assert_eq!( + val, + Uint256([ + 0x0000000000000000u64, + 0x0000000000000000u64, + 0x0000000000000000u64, + 0xF000000000000000u64, + ]) + ); + + let mut val = Uint256([ + 0xFFFFFFFFFFFFFFFFu64, + 0xFFFFFFFFFFFFFFFFu64, + 0xFFFFFFFFFFFFFFFFu64, + 0xFFFFFFFFFFFFFFFFu64, + ]); + val.increment(); + assert_eq!( + val, + Uint256([ + 0x0000000000000000u64, + 0x0000000000000000u64, + 0x0000000000000000u64, + 0x0000000000000000u64, + ]) + ); + } + #[test] pub fn uint256_bitslice_test() { let init = Uint256::from_u64(0xDEADBEEFDEADBEEF).unwrap();