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
|
#[macro_use]
extern crate derive_builder;
#[derive(Debug, Clone, Builder, PartialEq, Eq)]
#[builder(build_fn(validate = "LoremBuilder::validate"))]
pub struct Lorem {
/// A percentile. Must be between 0 and 100.
my_effort: u8,
/// A percentile. Must be less than or equal to `Lorem::my_effort`.
#[builder(default = "40")]
their_effort: u8,
/// A percentile. Must be between 0 and 100.
rivals_effort: u8,
}
impl LoremBuilder {
/// Performs bound checks.
fn validate(&self) -> Result<(), String> {
if let Some(ref my_effort) = self.my_effort {
if *my_effort > 100 {
return Err("Don't wear yourself out".to_string());
}
}
if let Some(ref their_effort) = self.their_effort {
if *their_effort > 100 {
return Err("The game has changed".to_string());
}
}
if let Some(ref rivals_effort) = self.rivals_effort {
if *rivals_effort > 100 {
return Err("Your rival is cheating".to_string());
}
}
Ok(())
}
}
#[test]
fn out_of_bounds() {
assert_eq!(
&LoremBuilder::default()
.my_effort(120)
.build()
.unwrap_err()
.to_string(),
"Don't wear yourself out"
);
assert_eq!(
&LoremBuilder::default()
.rivals_effort(120)
.build()
.unwrap_err()
.to_string(),
"Your rival is cheating"
);
}
#[test]
fn validation_pass() {
let lorem = LoremBuilder::default()
.my_effort(90)
.rivals_effort(89)
.build()
.expect("All validations should be passing");
assert_eq!(
lorem,
Lorem {
my_effort: 90,
rivals_effort: 89,
their_effort: 40,
}
);
}
|