Skip to content

Commit f02bf45

Browse files
authored
Merge pull request #53 from Lucretiel/master
OrderedFloat and NotNan now implement FromStr
2 parents 7786afd + 5f9dff5 commit f02bf45

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/lib.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ use core::hash::{Hash, Hasher};
1414
use core::fmt;
1515
use core::mem;
1616
use core::hint::unreachable_unchecked;
17+
use core::str::FromStr;
18+
1719
use num_traits::{Bounded, Float, FromPrimitive, Num, NumCast, One, Signed, ToPrimitive,
1820
Zero};
1921

@@ -166,6 +168,23 @@ impl<T: Float> Bounded for OrderedFloat<T> {
166168
}
167169
}
168170

171+
impl<T: Float + FromStr> FromStr for OrderedFloat<T> {
172+
type Err = T::Err;
173+
174+
/// Convert a &str to `OrderedFloat`. Returns an error if the string fails to parse.
175+
///
176+
/// ```
177+
/// use ordered_float::OrderedFloat;
178+
///
179+
/// assert!("-10".parse::<OrderedFloat<f32>>().is_ok());
180+
/// assert!("abc".parse::<OrderedFloat<f32>>().is_err());
181+
/// assert!("NaN".parse::<OrderedFloat<f32>>().is_ok());
182+
/// ```
183+
fn from_str(s: &str) -> Result<Self, Self::Err> {
184+
T::from_str(s).map(OrderedFloat)
185+
}
186+
}
187+
169188
/// A wrapper around Floats providing an implementation of Ord and Hash.
170189
///
171190
/// A NaN value cannot be stored in this type.
@@ -614,6 +633,26 @@ impl<T: Float> Bounded for NotNan<T> {
614633
}
615634
}
616635

636+
impl<T: Float + FromStr> FromStr for NotNan<T> {
637+
type Err = ParseNotNanError<T::Err>;
638+
639+
/// Convert a &str to `NotNan`. Returns an error if the string fails to parse,
640+
/// or if the resulting value is NaN
641+
///
642+
/// ```
643+
/// use ordered_float::NotNan;
644+
///
645+
/// assert!("-10".parse::<NotNan<f32>>().is_ok());
646+
/// assert!("abc".parse::<NotNan<f32>>().is_err());
647+
/// assert!("NaN".parse::<NotNan<f32>>().is_err());
648+
/// ```
649+
fn from_str(src: &str) -> Result<Self, Self::Err> {
650+
src.parse()
651+
.map_err(ParseNotNanError::ParseFloatError)
652+
.and_then(|f| NotNan::new(f).map_err(|_| ParseNotNanError::IsNaN))
653+
}
654+
}
655+
617656
impl<T: Float + FromPrimitive> FromPrimitive for NotNan<T> {
618657
fn from_i64(n: i64) -> Option<Self> { T::from_i64(n).and_then(|n| NotNan::new(n).ok()) }
619658
fn from_u64(n: u64) -> Option<Self> { T::from_u64(n).and_then(|n| NotNan::new(n).ok()) }

0 commit comments

Comments
 (0)