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
use std::fmt;
use std::str::FromStr;

use super::prefix::Prefix;
use crate::errors::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unit {
    /// `B`
    Bytes,
    /// `b`
    Bits,
    /// `%`
    Percents,
    /// `deg`
    Degrees,
    /// `s`
    Seconds,
    /// `W`
    Watts,
    /// `Hz`
    Hertz,
    /// ``
    None,
}

impl fmt::Display for Unit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self {
            Self::Bytes => "B",
            Self::Bits => "b",
            Self::Percents => "%",
            Self::Degrees => "°",
            Self::Seconds => "s",
            Self::Watts => "W",
            Self::Hertz => "Hz",
            Self::None => "",
        })
    }
}

impl FromStr for Unit {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "B" => Ok(Unit::Bytes),
            "b" => Ok(Unit::Bits),
            "%" => Ok(Unit::Percents),
            "deg" => Ok(Unit::Degrees),
            "s" => Ok(Unit::Seconds),
            "W" => Ok(Unit::Watts),
            "Hz" => Ok(Unit::Hertz),
            "" => Ok(Unit::None),
            x => Err(Error::new(format!("Unknown unit: '{x}'"))),
        }
    }
}

impl Unit {
    pub fn convert(self, value: f64, unit: Self) -> Result<f64> {
        match (self, unit) {
            (x, y) if x == y => Ok(value),
            (Self::Bytes, Self::Bits) => Ok(value * 8.),
            (Self::Bits, Self::Bytes) => Ok(value / 8.),
            _ => Err(Error::new(format!("Failed to convert '{self}' to '{unit}"))),
        }
    }

    pub fn clamp_prefix(self, prefix: Prefix) -> Prefix {
        match self {
            Self::Bytes | Self::Bits => prefix.max(Prefix::One),
            Self::Percents | Self::Degrees | Self::None => Prefix::One,
            _ => prefix,
        }
    }
}