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
use crate::errors::*;
use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Prefix {
Nano,
Micro,
Milli,
One,
OneButBinary,
Kilo,
Kibi,
Mega,
Mebi,
Giga,
Gibi,
Tera,
Tebi,
}
const MUL: [f64; 13] = [
1e-9,
1e-6,
1e-3,
1.0,
1.0,
1e3,
1024.0,
1e6,
1024.0 * 1024.0,
1e9,
1024.0 * 1024.0 * 1024.0,
1e12,
1024.0 * 1024.0 * 1024.0 * 1024.0,
];
impl Prefix {
pub fn min_available() -> Self {
Self::Nano
}
pub fn max_available() -> Self {
Self::Tera
}
pub fn max(self, other: Self) -> Self {
if other > self {
other
} else {
self
}
}
pub fn apply(self, value: f64) -> f64 {
value / MUL[self as usize]
}
pub fn eng(number: f64) -> Self {
if number == 0.0 {
Self::One
} else {
match number.abs().log10().div_euclid(3.) as i32 {
i32::MIN..=-3 => Prefix::Nano,
-2 => Prefix::Micro,
-1 => Prefix::Milli,
0 => Prefix::One,
1 => Prefix::Kilo,
2 => Prefix::Mega,
3 => Prefix::Giga,
4..=i32::MAX => Prefix::Tera,
}
}
}
pub fn eng_binary(number: f64) -> Self {
if number == 0.0 {
Self::One
} else {
match number.abs().log2().div_euclid(10.) as i32 {
i32::MIN..=0 => Prefix::OneButBinary,
1 => Prefix::Kibi,
2 => Prefix::Mebi,
3 => Prefix::Gibi,
4..=i32::MAX => Prefix::Tebi,
}
}
}
pub fn is_binary(&self) -> bool {
matches!(
self,
Self::OneButBinary | Self::Kibi | Self::Mebi | Self::Gibi | Self::Tebi
)
}
}
impl fmt::Display for Prefix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
Self::Nano => "n",
Self::Micro => "u",
Self::Milli => "m",
Self::One | Self::OneButBinary => "",
Self::Kilo => "K",
Self::Kibi => "Ki",
Self::Mega => "M",
Self::Mebi => "Mi",
Self::Giga => "G",
Self::Gibi => "Gi",
Self::Tera => "T",
Self::Tebi => "Ti",
})
}
}
impl FromStr for Prefix {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"n" => Ok(Prefix::Nano),
"u" => Ok(Prefix::Micro),
"m" => Ok(Prefix::Milli),
"1" => Ok(Prefix::One),
"1i" => Ok(Prefix::OneButBinary),
"K" => Ok(Prefix::Kilo),
"Ki" => Ok(Prefix::Kibi),
"M" => Ok(Prefix::Mega),
"Mi" => Ok(Prefix::Mebi),
"G" => Ok(Prefix::Giga),
"Gi" => Ok(Prefix::Gibi),
"T" => Ok(Prefix::Tera),
"Ti" => Ok(Prefix::Tebi),
x => Err(Error::new(format!("Unknown prefix: '{x}'"))),
}
}
}