From af77c788bf45d66a5dbfb3bbcb5f1919bc3215ca Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 14 Dec 2021 21:46:25 +0100 Subject: [PATCH 1/2] Optimize twos_complement --- src/bigint/convert.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/bigint/convert.rs b/src/bigint/convert.rs index ff8e04ef..8f5d0ea5 100644 --- a/src/bigint/convert.rs +++ b/src/bigint/convert.rs @@ -460,10 +460,8 @@ where { let mut carry = true; for d in digits { - *d = !*d; - if carry { - *d = d.wrapping_add(1); - carry = d.is_zero(); - } + let (val, tmp_carry) = (!*d).overflowing_add(carry as u8); + *d = val; + carry = tmp_carry; } } From d8746daa127616ab26d6102274f4f27678e3bd00 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 14 Dec 2021 21:47:11 +0100 Subject: [PATCH 2/2] Remove extra alloc in from_signed_bytes_be --- src/bigint/convert.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/bigint/convert.rs b/src/bigint/convert.rs index 8f5d0ea5..0fbb323c 100644 --- a/src/bigint/convert.rs +++ b/src/bigint/convert.rs @@ -377,9 +377,10 @@ pub(super) fn from_signed_bytes_be(digits: &[u8]) -> BigInt { if sign == Sign::Minus { // two's-complement the content to retrieve the magnitude - let mut digits = Vec::from(digits); - twos_complement_be(&mut digits); - BigInt::from_biguint(sign, BigUint::from_bytes_be(&*digits)) + let mut digits = digits.to_vec(); + digits.reverse(); + twos_complement_le(&mut digits); + BigInt::from_biguint(sign, BigUint::from_bytes_le(&digits)) } else { BigInt::from_biguint(sign, BigUint::from_bytes_be(digits)) } @@ -395,9 +396,9 @@ pub(super) fn from_signed_bytes_le(digits: &[u8]) -> BigInt { if sign == Sign::Minus { // two's-complement the content to retrieve the magnitude - let mut digits = Vec::from(digits); + let mut digits = digits.to_vec(); twos_complement_le(&mut digits); - BigInt::from_biguint(sign, BigUint::from_bytes_le(&*digits)) + BigInt::from_biguint(sign, BigUint::from_bytes_le(&digits)) } else { BigInt::from_biguint(sign, BigUint::from_bytes_le(digits)) }