Skip to main content

shared/
unit.rs

1use core::fmt::{self, Debug, Display};
2
3pub struct Suffix {
4    pub name: &'static str,
5    pub symbol: &'static str,
6}
7
8pub type PrefixTuple = (i32, &'static str, &'static str);
9
10pub const BYTES_SUFFIX: Suffix = Suffix {
11    name: "bytes",
12    symbol: "B",
13};
14pub const BITS_SUFFIX: Suffix = Suffix {
15    name: "bits",
16    symbol: "b",
17};
18pub const FREQUENCY_SUFFIX: Suffix = Suffix {
19    name: "hertz",
20    symbol: "Hz",
21};
22
23pub const PREFIXES: &[PrefixTuple] = &[
24    (30, "quetta", "Q"),
25    (27, "ronna", "R"),
26    (24, "yotta", "Y"),
27    (21, "zetta", "Z"),
28    (18, "exa", "E"),
29    (15, "peta", "P"),
30    (12, "tera", "T"),
31    (9, "giga", "G"),
32    (6, "mega", "M"),
33    (3, "kilo", "k"),
34    (2, "hecto", "h"),
35    (1, "deca", "da"),
36    (0, "", ""),
37    (-1, "deci", "d"),
38    (-2, "centi", "c"),
39    (-3, "milli", "m"),
40    (-6, "micro", "µ"),
41    (-9, "nano", "n"),
42    (-12, "pico", "p"),
43    (-15, "femto", "f"),
44    (-18, "atto", "a"),
45    (-21, "zepto", "z"),
46    (-24, "yocto", "y"),
47    (-27, "ronto", "r"),
48    (-30, "quecto", "q"),
49];
50
51pub struct Unit<'a, T> {
52    pub value: T,
53    pub prefix: PrefixTuple,
54    pub suffix: &'a str,
55}
56
57/// Exact power of ten for prefix exponents. Multiplication is exact for the
58/// prefix range, and one division rounds to the nearest double, unlike a
59/// libm `powi`, which can shift a boundary comparison such as `0.001`.
60fn power_of_ten(exponent: i32) -> f64 {
61    let mut result = 1.0;
62
63    for _ in 0..exponent.unsigned_abs() {
64        result *= 10.0;
65    }
66
67    if exponent < 0 { 1.0 / result } else { result }
68}
69
70fn get_prefix<T>(value: T) -> PrefixTuple
71where
72    T: Copy + PartialOrd + TryInto<f64>,
73{
74    let target_value: f64 = value.try_into().ok().unwrap_or(0.0).abs();
75
76    // Find the largest prefix where the value is >= prefix_value
77    for &prefix @ (exponent, _, _) in PREFIXES {
78        let prefix_value: f64 = power_of_ten(exponent);
79
80        if target_value >= prefix_value {
81            return prefix;
82        }
83    }
84
85    // Default to base unit if no prefix matches
86    (0, "", "")
87}
88
89impl<'a, T> Unit<'a, T>
90where
91    T: Copy + PartialOrd + TryInto<f64>,
92{
93    pub fn new(value: T, suffix: &'a str) -> Self {
94        let prefix = get_prefix(value);
95        Self {
96            value,
97            prefix,
98            suffix,
99        }
100    }
101
102    pub fn with_custom_prefix(value: T, prefix: PrefixTuple, suffix: &'a str) -> Self {
103        Self {
104            value,
105            prefix,
106            suffix,
107        }
108    }
109
110    pub fn get_prefix(&self) -> PrefixTuple {
111        self.prefix
112    }
113
114    pub fn format(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
115        let (exponent, _, symbol) = self.prefix;
116
117        let scaled_value: f64 = self.value.try_into().ok().unwrap_or(0.0) / power_of_ten(exponent);
118
119        // Check if the value has a fractional part
120        if scaled_value % 1.0 == 0.0 {
121            write!(fmt, "{} {}{}", scaled_value, symbol, self.suffix)
122        } else {
123            write!(fmt, "{:.2} {}{}", scaled_value, symbol, self.suffix)
124        }
125    }
126
127    pub fn format_full_name(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
128        let (exponent, name, _) = self.prefix;
129
130        let scaled_value: f64 = self.value.try_into().ok().unwrap_or(0.0) / power_of_ten(exponent);
131
132        // Check if the value has a fractional part
133        if scaled_value % 1.0 == 0.0 {
134            write!(fmt, "{} {}{}", scaled_value, name, self.suffix)
135        } else {
136            write!(fmt, "{:.2} {}{}", scaled_value, name, self.suffix)
137        }
138    }
139}
140
141impl<T> Debug for Unit<'_, T>
142where
143    T: Debug,
144{
145    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
146        formatter
147            .debug_struct("Unit")
148            .field("value", &self.value)
149            .field("suffix", &self.suffix)
150            .finish()
151    }
152}
153
154impl<T> Display for Unit<'_, T>
155where
156    T: Display + Copy + PartialOrd + TryInto<f64>,
157{
158    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
159        self.format(formatter)
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    extern crate alloc;
166
167    use alloc::format;
168
169    use super::*;
170
171    #[test]
172    fn test_unit_new() {
173        let unit = Unit::new(1000.0, "m");
174        assert_eq!(unit.value, 1000.0);
175        assert_eq!(unit.suffix, "m");
176    }
177
178    #[test]
179    fn test_get_prefix_base() {
180        let prefix = get_prefix(1.0);
181        assert_eq!(prefix, (0, "", ""));
182    }
183
184    #[test]
185    fn test_get_prefix_kilo() {
186        let prefix = get_prefix(1000.0);
187        assert_eq!(prefix, (3, "kilo", "k"));
188    }
189
190    #[test]
191    fn test_get_prefix_mega() {
192        let prefix = get_prefix(1_000_000.0);
193        assert_eq!(prefix, (6, "mega", "M"));
194    }
195
196    #[test]
197    fn test_get_prefix_giga() {
198        let prefix = get_prefix(1_000_000_000.0);
199        assert_eq!(prefix, (9, "giga", "G"));
200    }
201
202    #[test]
203    fn test_get_prefix_milli() {
204        let prefix = get_prefix(0.001);
205        assert_eq!(prefix, (-3, "milli", "m"));
206    }
207
208    #[test]
209    fn test_get_prefix_micro() {
210        let prefix = get_prefix(0.000001);
211        assert_eq!(prefix, (-6, "micro", "µ"));
212    }
213
214    #[test]
215    fn test_get_prefix_nano() {
216        let prefix = get_prefix(0.000000001);
217        assert_eq!(prefix, (-9, "nano", "n"));
218    }
219
220    #[test]
221    fn test_unit_format() {
222        let unit = Unit::new(1500.0, "m");
223        assert_eq!(format!("{}", unit), "1.50 km");
224    }
225
226    #[test]
227    fn test_unit_format_base() {
228        let unit = Unit::new(5.0, "g");
229        assert_eq!(format!("{}", unit), "5 g");
230    }
231
232    #[test]
233    fn test_unit_format_milli() {
234        let unit = Unit::new(0.005, "A");
235        assert_eq!(format!("{}", unit), "5 mA");
236    }
237
238    #[test]
239    fn test_unit_format_mega() {
240        let unit = Unit::new(2_500_000.0, "B");
241        assert_eq!(format!("{}", unit), "2.50 MB");
242    }
243
244    #[test]
245    fn test_unit_debug() {
246        let unit = Unit::new(42.0, "Hz");
247        let debug_str = format!("{:?}", unit);
248        assert!(debug_str.contains("value"));
249        assert!(debug_str.contains("suffix"));
250    }
251
252    #[test]
253    fn test_get_prefix_tera() {
254        let prefix = get_prefix(1_000_000_000_000.0);
255        assert_eq!(prefix, (12, "tera", "T"));
256    }
257
258    #[test]
259    fn test_get_prefix_pico() {
260        let prefix = get_prefix(0.000000000001);
261        assert_eq!(prefix, (-12, "pico", "p"));
262    }
263
264    #[test]
265    fn test_unit_format_small_value() {
266        let unit = Unit::new(0.0000025, "F");
267        assert_eq!(format!("{}", unit), "2.50 µF");
268    }
269
270    #[test]
271    fn test_unit_format_large_value() {
272        let unit = Unit::new(5_000_000_000.0, "Hz");
273        assert_eq!(format!("{}", unit), "5 GHz");
274    }
275}