Skip to content

Commit

Permalink
Avoid allocations in BoxedUint::{add_mod, sub_mod} (#321)
Browse files Browse the repository at this point in the history
  • Loading branch information
tarcieri authored Nov 26, 2023
1 parent 7e9ea30 commit 7b437b9
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 8 deletions.
6 changes: 2 additions & 4 deletions src/boxed/uint/add_mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,12 @@ impl BoxedUint {

// Attempt to subtract the modulus, to ensure the result is in the field.
let (w, borrow) = w.sbb(p, Limb::ZERO);
let (_, borrow) = carry.sbb(Limb::ZERO, borrow);
let (_, mask) = carry.sbb(Limb::ZERO, borrow);

// If underflow occurred on the final limb, borrow = 0xfff...fff, otherwise
// borrow = 0x000...000. Thus, we use it as a mask to conditionally add the
// modulus.
let mask = Self::from_words(vec![borrow.0; p.nlimbs()]);

w.wrapping_add(&p.bitand(&mask))
w.wrapping_add(&p.bitand_limb(mask))
}
}

Expand Down
7 changes: 7 additions & 0 deletions src/boxed/uint/bit_and.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ impl BoxedUint {
Self::chain(self, rhs, Limb::ZERO, |a, b, z| (a.bitand(b), z)).0
}

/// Bitwise `AND` against the given limb.
pub fn bitand_limb(&self, rhs: Limb) -> Self {
Self {
limbs: self.limbs.iter().map(|limb| limb.bitand(rhs)).collect(),
}
}

/// Perform wrapping bitwise `AND`.
///
/// There's no way wrapping could ever happen.
Expand Down
6 changes: 2 additions & 4 deletions src/boxed/uint/sub_mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,11 @@ impl BoxedUint {
debug_assert!(self < p);
debug_assert!(rhs < p);

let (out, borrow) = self.sbb(rhs, Limb::ZERO);
let (out, mask) = self.sbb(rhs, Limb::ZERO);

// If underflow occurred on the final limb, borrow = 0xfff...fff, otherwise
// borrow = 0x000...000. Thus, we use it as a mask to conditionally add the modulus.
let mask = Self::from_words(vec![borrow.0; p.nlimbs()]);

out.wrapping_add(&p.bitand(&mask))
out.wrapping_add(&p.bitand_limb(mask))
}
}

Expand Down

0 comments on commit 7b437b9

Please sign in to comment.