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
use std::fmt;
use std::str::FromStr;
use failure::Fail;
#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct ProjectId {
val: u64,
}
#[derive(Debug, Fail, PartialEq, Eq, PartialOrd, Ord)]
pub enum ProjectIdParseError {
#[fail(display = "invalid value for project id")]
InvalidValue,
#[fail(display = "empty or missing project id")]
EmptyValue,
}
impl fmt::Display for ProjectId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.val)
}
}
impl fmt::Debug for ProjectId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
macro_rules! impl_from {
($ty:ty) => {
impl From<$ty> for ProjectId {
fn from(val: $ty) -> ProjectId {
ProjectId { val: val as u64 }
}
}
};
}
impl_from!(usize);
impl_from!(u8);
impl_from!(u16);
impl_from!(u32);
impl_from!(u64);
impl_from!(i8);
impl_from!(i16);
impl_from!(i32);
impl_from!(i64);
impl FromStr for ProjectId {
type Err = ProjectIdParseError;
fn from_str(s: &str) -> Result<ProjectId, ProjectIdParseError> {
if s.is_empty() {
return Err(ProjectIdParseError::EmptyValue);
}
match s.parse::<u64>() {
Ok(val) => Ok(ProjectId { val }),
Err(_) => Err(ProjectIdParseError::InvalidValue),
}
}
}
impl_str_serde!(ProjectId);
#[cfg(test)]
mod test {
use super::*;
use serde_json;
#[test]
fn test_basic_api() {
let id: ProjectId = "42".parse().unwrap();
assert_eq!(id, ProjectId::from(42));
assert_eq!(
"42xxx".parse::<ProjectId>(),
Err(ProjectIdParseError::InvalidValue)
);
assert_eq!(
"".parse::<ProjectId>(),
Err(ProjectIdParseError::EmptyValue)
);
assert_eq!(ProjectId::from(42).to_string(), "42");
assert_eq!(
serde_json::to_string(&ProjectId::from(42)).unwrap(),
"\"42\""
);
assert_eq!(
serde_json::from_str::<ProjectId>("\"42\"").unwrap(),
ProjectId::from(42)
);
}
}