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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use crate::NiceWrapper;
const SIZE: usize = 7;
const IDX_PERCENT_DECIMAL: usize = SIZE - 3;
const ZERO: [u8; SIZE] = [b'0', b'0', b'0', b'.', b'0', b'0', b'%'];
pub type NicePercent = NiceWrapper<SIZE>;
impl Default for NicePercent {
fn default() -> Self { Self::min() }
}
macro_rules! nice_from {
($($float:ty),+ $(,)?) => ($(
impl From<$float> for NicePercent {
#[allow(unsafe_code)]
fn from(mut num: $float) -> Self {
if num <= 0.0 || ! num.is_normal() {
return Self::min();
}
else if 1.0 <= num {
return Self::max();
}
let mut out = Self {
inner: ZERO,
from: SIZE - 4,
};
let ptr = out.inner.as_mut_ptr();
num *= 100.0;
let base = num.trunc() as usize;
if 9 < base {
out.from -= 2;
unsafe {
std::ptr::copy_nonoverlapping(
crate::double_prt(base),
ptr.add(out.from),
2
);
}
}
else {
out.from -= 1;
unsafe { std::ptr::write(ptr.add(out.from), base as u8 + b'0'); }
}
unsafe {
std::ptr::copy_nonoverlapping(
crate::double_prt(<$float>::floor(num.fract() * 100.0) as usize),
ptr.add(IDX_PERCENT_DECIMAL),
2
);
}
out
}
}
)+);
}
nice_from!(f32, f64);
impl<T> TryFrom<(T, T)> for NicePercent
where T: num_traits::cast::AsPrimitive<f64> {
type Error = ();
fn try_from(src: (T, T)) -> Result<Self, Self::Error> {
crate::int_div_float(src.0, src.1)
.map(Self::from)
.ok_or(())
}
}
impl NicePercent {
#[must_use]
pub const fn min() -> Self {
Self {
inner: ZERO,
from: SIZE - 5,
}
}
#[must_use]
pub const fn max() -> Self {
Self {
inner: [b'1', b'0', b'0', b'.', b'0', b'0', b'%'],
from: SIZE - 7,
}
}
}
#[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%");
}
}