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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use anyhow::{format_err, Error};
use derive_more::{Add, Display, FromStr, Into};
use serde::{
de::{self, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
use std::{
convert::{From, TryFrom},
fmt::{self, Formatter},
io::Write,
};
const MM_PER_INCH: f64 = 25.4;
#[derive(
Into,
Clone,
Copy,
Display,
FromStr,
Debug,
Serialize,
Deserialize,
Add,
Default,
PartialEq,
PartialOrd,
)]
#[serde(into = "f64", try_from = "f64")]
pub struct Precipitation(f64);
impl TryFrom<f64> for Precipitation {
type Error = Error;
fn try_from(item: f64) -> Result<Self, Self::Error> {
if item < 0.0 {
Err(format_err!("{} is not a valid precipitation amount", item))
} else {
Ok(Self(item))
}
}
}
impl Precipitation {
pub fn from_millimeters(precip: f64) -> Result<Self, Error> {
Self::try_from(precip)
}
pub fn from_inches(precip: f64) -> Result<Self, Error> {
Self::try_from(precip * MM_PER_INCH)
}
#[inline]
pub fn millimeters(self) -> f64 {
self.0
}
#[inline]
pub fn inches(self) -> f64 {
self.0 / MM_PER_INCH
}
}
#[cfg(test)]
mod test {
use anyhow::Error;
use std::convert::TryFrom;
use crate::precipitation::{Precipitation, MM_PER_INCH};
#[test]
fn test_precipitation() -> Result<(), Error> {
let p = Precipitation::try_from(1.0)?;
assert_eq!(p.millimeters(), 1.0);
assert_eq!(p.inches(), 1.0 / MM_PER_INCH);
let p2 = Precipitation::from_millimeters(1.0)?;
assert_eq!(p, p2);
let p = Precipitation::from_inches(1.0)?;
assert_eq!(p.inches(), 1.0);
let h = Precipitation::try_from(-1.0);
assert!(h.is_err());
assert_eq!(
h.err().unwrap().to_string(),
format!("{} is not a valid precipitation amount", -1.0)
);
Ok(())
}
}