Skip to content

Commit

Permalink
FromStr for Rational
Browse files Browse the repository at this point in the history
  • Loading branch information
ooovi committed Sep 4, 2023
1 parent 59f5522 commit 410427e
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/dp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use num_bigint::{BigInt, BigUint, TryFromBigIntError};
use num_rational::{BigRational, Ratio};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::{fmt, str::FromStr};

/// Errors propagated by methods in this module.
#[derive(Debug, thiserror::Error)]
Expand Down Expand Up @@ -49,6 +49,20 @@ impl fmt::Display for Rational {
}
}

/// An error indicating a string could not be parsed as Rational.
#[derive(Debug)]
pub struct RationalParseError;

impl FromStr for Rational {
type Err = RationalParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match Ratio::<BigUint>::from_str(s) {
Ok(r) => Ok(Rational(r)),
Err(_) => Err(RationalParseError),
}
}
}

impl Rational {
/// Construct a [`Rational`] number from numerator `n` and denominator `d`. Errors if denominator is zero.
pub fn from_unsigned<T>(n: T, d: T) -> Result<Self, DpError>
Expand Down

0 comments on commit 410427e

Please sign in to comment.