Skip to content

Commit

Permalink
safegcd: remove branch in iterations calculation (#656)
Browse files Browse the repository at this point in the history
  • Loading branch information
tarcieri authored Aug 16, 2024
1 parent ae30093 commit 2952c76
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/modular/safegcd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,13 +341,9 @@ const fn de<const LIMBS: usize>(
// TODO(tarcieri): improved bounds using https://github.com/sipa/safegcd-bounds
pub(crate) const fn iterations(f_bits: u32, g_bits: u32) -> usize {
// Select max of `f_bits`, `g_bits`
let d = ConstChoice::from_u32_lt(f_bits, g_bits).select_u32(f_bits, g_bits) as usize;

if d < 46 {
(49 * d + 80) / 17
} else {
(49 * d + 57) / 17
}
let d = ConstChoice::from_u32_lt(f_bits, g_bits).select_u32(f_bits, g_bits);
let addend = ConstChoice::from_u32_lt(d, 46).select_u32(57, 80);
((49 * d + addend) / 17) as usize
}

/// "Bigint"-like (62 * LIMBS)-bit signed integer type, whose variables store numbers in the two's
Expand Down Expand Up @@ -560,6 +556,7 @@ impl<const LIMBS: usize> UnsatInt<LIMBS> {

#[cfg(test)]
mod tests {
use super::iterations;
use crate::{Inverter, PrecomputeInverter, U256};

type UnsatInt = super::UnsatInt<4>;
Expand All @@ -586,6 +583,13 @@ mod tests {
);
}

#[test]
fn iterations_boundary_conditions() {
assert_eq!(iterations(0, 0), 4);
assert_eq!(iterations(0, 45), 134);
assert_eq!(iterations(0, 46), 135);
}

#[test]
fn unsatint_add() {
assert_eq!(UnsatInt::ZERO, UnsatInt::ZERO.add(&UnsatInt::ZERO));
Expand Down

0 comments on commit 2952c76

Please sign in to comment.