From 021454c43876fb256ed91a96796bbf8d20dbcbb7 Mon Sep 17 00:00:00 2001 From: EvilMuffinHa Date: Thu, 4 Aug 2022 22:22:23 -0400 Subject: [PATCH] fix add --- src/lib.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 091e8b6..4c7289a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -126,8 +126,6 @@ impl Add for SmallUint { match i.overflowing_add(j) { (t, false) => Self(SmallUintType::Inline(t)), (t, true) => { - - let mut res = [0, 0, 0, 0, 1]; let mut v = t; @@ -138,7 +136,9 @@ impl Add for SmallUint { v >>= 32; } - Self(SmallUintType::Heap((>::from(res).as_mut_ptr(), 5))) + let mut slice = ManuallyDrop::new(>::from(res)); + + Self(SmallUintType::Heap((slice.as_mut_ptr(), 5))) } } @@ -146,7 +146,7 @@ impl Add for SmallUint { (&SmallUintType::Heap((r, s)), &SmallUintType::Inline(i)) | (&SmallUintType::Inline(i), &SmallUintType::Heap((r, s))) => { let slice1 = unsafe { core::slice::from_raw_parts(r, s) }; - let mut res = [0, 0, 0, 0, 1]; + let mut res = [0, 0, 0, 0]; let mut v = i; #[allow(clippy::needless_range_loop)] @@ -155,6 +155,7 @@ impl Add for SmallUint { v >>= 32; } + let result = add_two_slices(slice1, &res[..]); let size = result.len(); @@ -181,6 +182,7 @@ impl Add for SmallUint { } } + impl Drop for SmallInt { fn drop(&mut self) { if let Self(SmallIntType::Heap((r, s))) = self { @@ -429,7 +431,7 @@ mod conversion_tests { use crate::SmallUint; #[cfg(feature = "num-bigint")] - use num_bigint::{BigInt, Sign, BigUint, }; + use num_bigint::{BigInt, Sign, BigUint}; macro_rules! conversion_tests { ($t:ty, $i:ident) => { @@ -461,11 +463,19 @@ mod conversion_tests { #[cfg(feature = "num-bigint")] fn test_op_add_u_u() { let i = SmallUint::from(u128::MAX); - let k = SmallUint::from(&BigUint::new(vec![5, 4, 9, 3, 2, 1, 5])); + let k = SmallUint::from(u128::MAX); let q = i + k; - println!("{:?}", BigUint::from(&q)); - println!("{:?}", BigUint::new(vec![5, 4, 9, 3, 2, 1, 5]) + u128::MAX); + assert_eq!(BigUint::from(&q), BigUint::from(u128::MAX) + u128::MAX); + let i = SmallUint::from(u128::MAX); + let k = SmallUint::from(&BigUint::new(vec![5, 4, 9, 3, 1, 81])); + let q = i + k; + assert_eq!(BigUint::from(&q), BigUint::new(vec![5, 4, 9, 3, 1, 81]) + u128::MAX); + + let i = SmallUint::from(&BigUint::new(vec![3, 9, 8])); + let k = SmallUint::from(&BigUint::new(vec![5, 4, 9, 3, 1, 81])); + let q = i + k; + assert_eq!(BigUint::from(&q), BigUint::new(vec![3, 9, 8]) + BigUint::new(vec![5, 4, 9, 3, 1, 81])); } #[test]