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
use std::convert::From;
macro_rules! impl_from {
( $type : tt ) => {
impl From<$type> for IntSanitizer<$type> {
fn from(content: $type) -> Self {
Self::new(content)
}
}
};
}
pub struct IntSanitizer<T: PartialOrd + Copy>(T);
impl<T: PartialOrd + Copy> IntSanitizer<T> {
pub(crate) fn new(int: T) -> Self {
Self(int)
}
pub fn get(self) -> T {
self.0
}
pub fn clamp(&mut self, min: T, max: T) -> &mut Self {
self.0 = num_traits::clamp(self.0, min, max);
self
}
pub fn call<F>(&mut self, func: F) -> &mut Self
where
F: FnOnce(T) -> T,
{
self.0 = func(self.0);
self
}
}
impl_from!(u8);
impl_from!(u16);
impl_from!(u32);
impl_from!(u64);
impl_from!(usize);
impl_from!(isize);
impl_from!(i64);
impl_from!(i32);
impl_from!(i16);
impl_from!(i8);
#[cfg(test)]
mod test {
use super::*;
#[test]
fn basic_cap_min() {
let int: u8 = 50;
let mut instance = IntSanitizer::from(int);
instance.clamp(99, 101);
assert_eq!(99, instance.get());
}
#[test]
fn basic_cap_max() {
let int: u8 = 200;
let mut instance = IntSanitizer::from(int);
instance.clamp(99, 101);
assert_eq!(101, instance.get());
}
}