Skip to content
This repository has been archived by the owner on Nov 23, 2024. It is now read-only.

Commit

Permalink
feat: add convenience .to_int() and .to_uint() methods
Browse files Browse the repository at this point in the history
  • Loading branch information
bgeron committed Mar 6, 2020
1 parent cf842f1 commit 6b40b49
Showing 1 changed file with 27 additions and 17 deletions.
44 changes: 27 additions & 17 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,9 +459,10 @@ impl Eq for Int {}

// -- Basic stuff between different signedness --

impl From<Uint> for Int {
fn from(v: Uint) -> Self {
match v.0 {
impl Uint {
/// Convert to [`Int`].
pub fn into_int(self) -> Int {
match self.0 {
Left(x) => {
if let Ok(x1) = x.try_into() {
Int(Left(x1))
Expand All @@ -473,29 +474,38 @@ impl From<Uint> for Int {
}
}
}
/// An alias for `.into_uint()`.
impl From<Uint> for Int {
fn from(v: Uint) -> Self {
v.into_int()
}
}

impl Int {
/// Convert to [`Uint`] if nonnegative, otherwise None.
pub fn into_uint(self) -> Option<Uint> {
match self.0 {
Left(x) => {
if let Ok(x1) = x.try_into() {
Some(Uint(Left(x1)))
} else {
Some(Uint(Right(Box::new(x.to_biguint()?))))
}
}
Right(x) => Some(Uint(Right(Box::new(x.to_biguint()?)))),
}
}
}
#[non_exhaustive]
#[derive(Debug)]
pub struct IntIsNegativeError();

/// An alias for `.into_int()`.
impl TryFrom<Int> for Uint {
type Error = IntIsNegativeError;
/// Fails on negative numbers.
fn try_from(v: Int) -> Result<Self, Self::Error> {
match v.0 {
Left(x) => {
if let Ok(x1) = x.try_into() {
Ok(Uint(Left(x1)))
} else {
Ok(Uint(Right(Box::new(
x.to_biguint().ok_or(IntIsNegativeError())?,
))))
}
}
Right(x) => Ok(Uint(Right(Box::new(
x.to_biguint().ok_or(IntIsNegativeError())?,
)))),
}
v.into_uint().ok_or(IntIsNegativeError())
}
}

Expand Down

0 comments on commit 6b40b49

Please sign in to comment.