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
use std::fmt::Debug;
mod decimal;
mod binary;
#[cfg(test)]
pub(crate) mod test;
pub use decimal::Decimal;
pub use binary::Binary;
pub trait Prefix: Debug + Clone + Copy + PartialEq {
fn base(&self) -> i32;
fn exponent(&self) -> i32;
fn multiplier(&self) -> f64 {
let base = self.base() as f64;
let exp = self.exponent();
base.powi(exp)
}
fn scale_value<T: Into<f64>>(&self, value: T) -> f64 {
let x: f64 = value.into();
x / self.multiplier()
}
fn label(&self) -> &'static str;
}
pub trait PrefixFamily {
type Prefix: Prefix + 'static;
fn unit_prefix() -> Self::Prefix;
fn all_prefixes() -> &'static [&'static Self::Prefix];
fn autoscale(val: f64) -> (f64, Self::Prefix) {
if !val.is_finite() || !val.is_normal() {
return (val, Self::unit_prefix())
}
let pfxs = Self::all_prefixes();
let mut iter = pfxs.iter();
let mut cur = iter.next().unwrap();
while let Some(next) = iter.next() {
if next.scale_value(val).abs() < 1.0 {
break;
} else {
cur = next;
}
}
(cur.scale_value(val), **cur)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scale<F: PrefixFamily> {
Auto,
Native,
Fixed(F::Prefix),
}
impl From<Decimal> for Scale<Decimal> {
fn from(p: Decimal) -> Scale<Decimal> {
Scale::Fixed(p)
}
}
impl From<Binary> for Scale<Binary> {
fn from(p: Binary) -> Scale<Binary> {
Scale::Fixed(p)
}
}