-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathfraction.rs
More file actions
59 lines (53 loc) · 1.62 KB
/
fraction.rs
File metadata and controls
59 lines (53 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use derive_more::{AsRef, Deref, Display, Error, Into};
use std::{
convert::{TryFrom, TryInto},
num::ParseFloatError,
str::FromStr,
};
/// Floating-point value that is greater than or equal to 0 and less than 1.
#[derive(Debug, Display, Default, Clone, Copy, PartialEq, PartialOrd, AsRef, Deref, Into)]
pub struct Fraction(f32);
/// Error that occurs when calling [`Fraction::new`].
#[derive(Debug, Display, Error, Clone, Copy, PartialEq, Eq)]
pub enum ConversionError {
/// Provided value is greater than or equal to 1.
#[display("greater than or equal to 1")]
UpperBound,
/// Provided value is less than 0.
#[display("less than 0")]
LowerBound,
}
impl Fraction {
/// Create a [`Fraction`].
pub fn new(value: f32) -> Result<Self, ConversionError> {
use ConversionError::*;
if value >= 1.0 {
return Err(UpperBound);
}
if value < 0.0 {
return Err(LowerBound);
}
Ok(Fraction(value))
}
}
impl TryFrom<f32> for Fraction {
type Error = ConversionError;
fn try_from(value: f32) -> Result<Self, Self::Error> {
Fraction::new(value)
}
}
/// Error that occurs when parsing a string as [`Fraction`].
#[derive(Debug, Display, Error, Clone, PartialEq, Eq)]
pub enum FromStrError {
ParseFloatError(ParseFloatError),
Conversion(ConversionError),
}
impl FromStr for Fraction {
type Err = FromStrError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
text.parse::<f32>()
.map_err(FromStrError::ParseFloatError)?
.try_into()
.map_err(FromStrError::Conversion)
}
}