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
135
136
137
138
139
140
const SIZE: usize = 7;
const IDX_PERCENT_DECIMAL: usize = SIZE - 3;
#[derive(Debug, Clone, Copy, Hash, PartialEq)]
pub struct NicePercent {
inner: [u8; SIZE],
from: usize,
}
crate::impl_nice_int!(NicePercent);
impl Default for NicePercent {
#[inline]
fn default() -> Self {
Self {
inner: [0, 0, 0, b'.', 0, 0, b'%'],
from: SIZE,
}
}
}
macro_rules! impl_from {
($type:ty) => {
impl From<$type> for NicePercent {
fn from(mut num: $type) -> Self {
if num <= 0.0 {
return Self {
inner: *b"000.00%",
from: SIZE - 5,
};
}
else if 1.0 <= num {
return Self {
inner: *b"100.00%",
from: SIZE - 7,
};
}
let mut out = Self {
inner: *b"000.00%",
from: SIZE - 4,
};
let ptr = out.inner.as_mut_ptr();
num *= 100.0;
let base = num.trunc() as usize;
if base >= 10 {
out.from -= 2;
unsafe { super::write_u8_2(ptr.add(out.from), base); }
}
else {
out.from -= 1;
unsafe { super::write_u8_1(ptr.add(out.from), base); }
}
unsafe {
super::write_u8_2(
ptr.add(IDX_PERCENT_DECIMAL),
<$type>::floor(num.fract() * 100.0) as usize
);
}
out
}
}
};
}
impl_from!(f32);
impl_from!(f64);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn t_nice_percent() {
for i in 0..1_000 {
let fraction = i as f32 / 1000_f32;
let num = fraction * 100_f32;
let base = f32::floor(num);
assert_eq!(
NicePercent::from(fraction).as_str(),
format!("{}.{:02}%", base, f32::floor((num - base) * 100_f32)),
);
}
assert_eq!(NicePercent::from(0_f64).as_str(), "0.00%");
assert_eq!(NicePercent::from(-10_f64).as_str(), "0.00%");
assert_eq!(NicePercent::from(1.03_f64).as_str(), "100.00%");
assert_eq!(NicePercent::from(10_f64).as_str(), "100.00%");
}
}