Skip to content

Commit

Permalink
impl FromStr for IntegerOrFloat
Browse files Browse the repository at this point in the history
  • Loading branch information
ctrlcctrlv committed Jan 11, 2022
1 parent 181536b commit 13c42f9
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/from_str.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use core::num::ParseFloatError;
use core::str::FromStr;

use super::IntegerOrFloat::{self, *};

impl FromStr for IntegerOrFloat {
type Err = ParseFloatError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(
match s.parse::<i32>() {
Ok(i) => Integer(i),
Err(_) => Float(s.parse::<f32>()?),
}
)
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use serde::{Serialize, Deserialize};
mod hash;

pub mod encode;
mod from_str;

/// The UFO data type "integer or float".
#[cfg_attr(feature = "default", derive(Serialize, Deserialize))]
Expand Down
21 changes: 21 additions & 0 deletions tests/from_str.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use integer_or_float::IntegerOrFloat::{self, *};

#[test]
fn test_from_str() {
assert_eq!("12".parse::<IntegerOrFloat>().unwrap(), Integer(12));
assert_eq!("12.0".parse::<IntegerOrFloat>().unwrap(), Float(12.0));
}

#[test]
fn test_from_str_subnormal_nan() {
assert!(f32::from("NaN".parse::<IntegerOrFloat>().unwrap()).is_nan());
assert!(f32::from("INF".parse::<IntegerOrFloat>().unwrap()).is_infinite());
assert!(f64::from("NaN".parse::<IntegerOrFloat>().unwrap()).is_nan());
assert!(f64::from("INF".parse::<IntegerOrFloat>().unwrap()).is_infinite());
}

#[test]
fn test_from_str_fail() {
assert!("12.v0".parse::<IntegerOrFloat>().is_err());
assert!("nanners".parse::<IntegerOrFloat>().is_err());
}

0 comments on commit 13c42f9

Please sign in to comment.