Skip to content

Commit 4966407

Browse files
authored
Limb: optimize constant-time comparisons (#413)
Optimizes `ConstantTimeGreater`/`ConstantTimeLess` impls by using borrowing subtraction and checking whether a borrow occurred. ops/ct_lt time: [900.95 ps 909.83 ps 922.37 ps] change: [-76.095% -75.752% -75.373%] (p = 0.00 < 0.05) Performance has improved. ops/ct_gt time: [902.46 ps 938.83 ps 1.0134 ns] change: [-55.763% -53.637% -50.192%] (p = 0.00 < 0.05) Performance has improved.
1 parent 1ab049f commit 4966407

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/limb/cmp.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,19 +44,26 @@ impl ConstantTimeEq for Limb {
4444
fn ct_eq(&self, other: &Self) -> Choice {
4545
self.0.ct_eq(&other.0)
4646
}
47+
48+
#[inline]
49+
fn ct_ne(&self, other: &Self) -> Choice {
50+
self.0.ct_ne(&other.0)
51+
}
4752
}
4853

4954
impl ConstantTimeGreater for Limb {
5055
#[inline]
5156
fn ct_gt(&self, other: &Self) -> Choice {
52-
self.0.ct_gt(&other.0)
57+
let borrow = other.sbb(*self, Limb::ZERO).1;
58+
Choice::from(borrow.0 as u8 & 1)
5359
}
5460
}
5561

5662
impl ConstantTimeLess for Limb {
5763
#[inline]
5864
fn ct_lt(&self, other: &Self) -> Choice {
59-
self.0.ct_lt(&other.0)
65+
let borrow = self.sbb(*other, Limb::ZERO).1;
66+
Choice::from(borrow.0 as u8 & 1)
6067
}
6168
}
6269

0 commit comments

Comments
 (0)