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
use derive_more::{AsRef, Deref, Display, Into};
use std::{
convert::{TryFrom, TryInto},
num::ParseFloatError,
str::FromStr,
};
#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, AsRef, Deref, Display, Into)]
pub struct Fraction(f32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
pub enum ConversionError {
#[display(fmt = "greater than or equal to 1")]
UpperBound,
#[display(fmt = "less than 0")]
LowerBound,
}
impl 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)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Display)]
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)
}
}