Skip to content

Commit

Permalink
Impl num_traits::Num for Uint (#720)
Browse files Browse the repository at this point in the history
Also adds the needed `Div` and `Rem` impls to meet the required bounds
  • Loading branch information
tarcieri authored Jan 7, 2025
1 parent e2fa911 commit f8c4ac7
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,15 @@ impl<const LIMBS: usize> Integer for Uint<LIMBS> {
}
}

impl<const LIMBS: usize> num_traits::Num for Uint<LIMBS> {
type FromStrRadixErr = crate::DecodeError;

/// ⚠️ WARNING: `from_str_radix` impl operates in variable-time with respect to the input.
fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
Self::from_str_radix_vartime(str, radix)
}
}

impl<const LIMBS: usize> ConstZero for Uint<LIMBS> {
const ZERO: Self = Self::ZERO;
}
Expand Down
36 changes: 36 additions & 0 deletions src/uint/div.rs
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,24 @@ impl<const LIMBS: usize> Div<&NonZero<Uint<LIMBS>>> for Wrapping<Uint<LIMBS>> {
}
}

impl<const LIMBS: usize> Div<Uint<LIMBS>> for &Uint<LIMBS> {
type Output = Uint<LIMBS>;

#[inline]
fn div(self, rhs: Uint<LIMBS>) -> Self::Output {
self / NonZero::new(rhs).expect("attempt to divide with a divisor of zero")
}
}

impl<const LIMBS: usize> Div<Uint<LIMBS>> for Uint<LIMBS> {
type Output = Uint<LIMBS>;

#[inline]
fn div(self, rhs: Uint<LIMBS>) -> Self::Output {
&self / rhs
}
}

impl<const LIMBS: usize> DivAssign<&NonZero<Uint<LIMBS>>> for Wrapping<Uint<LIMBS>> {
fn div_assign(&mut self, rhs: &NonZero<Uint<LIMBS>>) {
*self = Wrapping(self.0 / rhs);
Expand Down Expand Up @@ -847,6 +865,24 @@ impl<const LIMBS: usize> Rem<NonZero<Uint<LIMBS>>> for Uint<LIMBS> {
}
}

impl<const LIMBS: usize> Rem<Uint<LIMBS>> for &Uint<LIMBS> {
type Output = Uint<LIMBS>;

#[inline]
fn rem(self, rhs: Uint<LIMBS>) -> Self::Output {
self % NonZero::new(rhs).expect("attempt to calculate the remainder with a divisor of zero")
}
}

impl<const LIMBS: usize> Rem<Uint<LIMBS>> for Uint<LIMBS> {
type Output = Uint<LIMBS>;

#[inline]
fn rem(self, rhs: Uint<LIMBS>) -> Self::Output {
&self % rhs
}
}

impl<const LIMBS: usize> RemAssign<&NonZero<Uint<LIMBS>>> for Uint<LIMBS> {
fn rem_assign(&mut self, rhs: &NonZero<Uint<LIMBS>>) {
*self %= *rhs
Expand Down

0 comments on commit f8c4ac7

Please sign in to comment.