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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use crate::types::NUM_SVNS;
use core::fmt;
use core::num::NonZeroU8;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct Svn(NonZeroU8);
impl Svn {
pub fn iter() -> impl Iterator<Item = Svn> {
(1..=NUM_SVNS)
.into_iter()
.map(|x| Svn::try_from(x).unwrap())
}
}
macro_rules! impl_conv {
($t: ty) => {
impl From<Svn> for $t {
fn from(svn: Svn) -> $t {
svn.0.get().try_into().unwrap()
}
}
impl TryFrom<$t> for Svn {
type Error = SvnError;
fn try_from(value: $t) -> Result<Svn, SvnError> {
let max = <$t>::try_from(NUM_SVNS).unwrap();
if (1..=max).contains(&value) {
let val = NonZeroU8::new(u8::try_from(value).unwrap()).unwrap();
Ok(Svn(val))
} else {
Err(SvnError {})
}
}
}
};
}
impl_conv!(u8);
impl_conv!(u16);
impl_conv!(u32);
impl_conv!(u64);
impl_conv!(u128);
impl_conv!(usize);
impl_conv!(i8);
impl_conv!(i16);
impl_conv!(i32);
impl_conv!(i64);
impl_conv!(i128);
impl_conv!(isize);
impl fmt::Display for Svn {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "E{:02}", self.0)
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct SvnError;
impl fmt::Display for SvnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
"SVN out of range 1-36".fmt(f)
}
}
#[cfg(feature = "std")]
impl std::error::Error for SvnError {}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn from_int() {
let error = Err(SvnError {});
for j in 1..=NUM_SVNS {
assert!(Svn::try_from(j).is_ok());
}
assert_eq!(Svn::try_from(0), error);
assert_eq!(Svn::try_from(37), error);
}
#[test]
fn format() {
assert_eq!(format!("{}", Svn::try_from(3).unwrap()), "E03");
assert_eq!(format!("{}", Svn::try_from(24).unwrap()), "E24");
}
#[test]
fn iterator() {
let mut n = 0;
for svn in Svn::iter() {
n += 1;
assert_eq!(usize::from(svn), n);
}
assert_eq!(n, 36);
}
}