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
134
#[cfg(test)] mod tests;
use std::{fmt, ops::{Add, AddAssign, Mul, MulAssign}};
pub trait Percent {
fn percent(self) -> Percentage;
}
macro_rules! percent_impl {
($($ty:ty)*) => {
$(
impl Percent for $ty {
fn percent(self) -> Percentage {
Percentage(self as f64)
}
}
)*
};
}
percent_impl!{
usize u8 u16 u32 u64 u128
isize i8 i16 i32 i64 i128
f32 f64
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Percentage(pub f64);
impl Percentage {
pub fn get(&self) -> f64 {
self.0 / 100.0
}
}
impl Default for Percentage {
fn default() -> Self {
Self(0.0)
}
}
impl fmt::Display for Percentage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}%", self.0)
}
}
impl Add for Percentage {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self(self.0 + rhs.0)
}
}
impl AddAssign for Percentage {
fn add_assign(&mut self, rhs: Percentage) {
*self = self.clone() + rhs;
}
}
macro_rules! ops_percentage_impl {
($($type: ty)*) => {
$(
impl Add<Percentage> for $type {
type Output = Percentage;
fn add(self, rhs: Percentage) -> Self::Output {
((rhs.get() + self as f64)*100.0).percent()
}
}
impl Mul<Percentage> for $type {
type Output = f64;
fn mul(self, rhs: Percentage) -> Self::Output {
self as f64 * rhs.get()
}
}
impl MulAssign<Percentage> for $type {
fn mul_assign(&mut self, rhs: Percentage) {
*self = (*self * rhs) as $type;
}
}
)*
};
}
ops_percentage_impl!{
usize u8 u16 u32 u64 u128
isize i8 i16 i32 i64 i128
f32 f64
}