Optimize `BigInt::from_biguint` and `BigInt::assign_from_slice`

It removes useless memory allocations.
This commit is contained in:
Nicolas Kirchner 2017-08-02 22:25:21 +02:00
parent 5106fcc95a
commit cbdaf8f6f9
1 changed files with 12 additions and 12 deletions

View File

@ -1376,13 +1376,13 @@ impl BigInt {
/// ///
/// The digits are in little-endian base 2^32. /// The digits are in little-endian base 2^32.
#[inline] #[inline]
pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt { pub fn from_biguint(mut sign: Sign, mut data: BigUint) -> BigInt {
if sign == NoSign || data.is_zero() { if sign == NoSign {
return BigInt { data.assign_from_slice(&[]);
sign: NoSign, } else if data.is_zero() {
data: Zero::zero(), sign = NoSign;
};
} }
BigInt { BigInt {
sign: sign, sign: sign,
data: data, data: data,
@ -1398,15 +1398,15 @@ impl BigInt {
/// Reinitializes a `BigInt`. /// Reinitializes a `BigInt`.
#[inline] #[inline]
pub fn assign_from_slice(&mut self, sign: Sign, slice: &[BigDigit]) { pub fn assign_from_slice(&mut self, sign: Sign, slice: &[BigDigit]) {
// Normalize: if sign == NoSign {
let slice = &slice[..slice.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; self.data.assign_from_slice(&[]);
if sign == NoSign || slice.len() == 0 {
self.sign = NoSign; self.sign = NoSign;
self.data = Zero::zero();
} else { } else {
self.sign = sign;
self.data.assign_from_slice(slice); self.data.assign_from_slice(slice);
self.sign = match self.data.is_zero() {
true => NoSign,
false => sign,
}
} }
} }