Skip to content

Commit c714e43

Browse files
authored
Add SquareRoot trait (#508)
1 parent f2dde0d commit c714e43

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

src/traits.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ pub trait Integer:
138138
+ for<'a> Sub<&'a Self, Output = Self>
139139
+ SubMod<Output = Self>
140140
+ Sync
141+
+ SquareRoot
141142
+ WrappingAdd
142143
+ WrappingSub
143144
+ WrappingMul
@@ -463,6 +464,15 @@ pub trait SquareAssign {
463464
fn square_assign(&mut self);
464465
}
465466

467+
/// Support for calucaling square roots.
468+
pub trait SquareRoot {
469+
/// Computes `floor(sqrt(self))`.
470+
fn sqrt(&self) -> Self;
471+
472+
/// Computes `floor(sqrt(self))`, variable time in `self`.
473+
fn sqrt_vartime(&self) -> Self;
474+
}
475+
466476
/// Support for optimized division by a single limb.
467477
pub trait DivRemLimb: Sized {
468478
/// Computes `self / rhs` using a pre-made reciprocal,

src/uint/boxed/sqrt.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
use subtle::{ConstantTimeEq, ConstantTimeGreater, CtOption};
44

5-
use crate::{BoxedUint, ConstantTimeSelect, NonZero};
5+
use crate::{BoxedUint, ConstantTimeSelect, NonZero, SquareRoot};
66

77
impl BoxedUint {
88
/// Computes √(`self`) in constant time.
@@ -121,6 +121,16 @@ impl BoxedUint {
121121
}
122122
}
123123

124+
impl SquareRoot for BoxedUint {
125+
fn sqrt(&self) -> Self {
126+
self.sqrt()
127+
}
128+
129+
fn sqrt_vartime(&self) -> Self {
130+
self.sqrt_vartime()
131+
}
132+
}
133+
124134
#[cfg(test)]
125135
mod tests {
126136
use crate::{BoxedUint, Limb};

src/uint/sqrt.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! [`Uint`] square root operations.
22
3-
use crate::Uint;
3+
use crate::{SquareRoot, Uint};
44
use subtle::{ConstantTimeEq, CtOption};
55

66
impl<const LIMBS: usize> Uint<LIMBS> {
@@ -113,6 +113,16 @@ impl<const LIMBS: usize> Uint<LIMBS> {
113113
}
114114
}
115115

116+
impl<const LIMBS: usize> SquareRoot for Uint<LIMBS> {
117+
fn sqrt(&self) -> Self {
118+
self.sqrt()
119+
}
120+
121+
fn sqrt_vartime(&self) -> Self {
122+
self.sqrt_vartime()
123+
}
124+
}
125+
116126
#[cfg(test)]
117127
mod tests {
118128
use crate::{Limb, U192, U256};

0 commit comments

Comments
 (0)