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
use core::{
    fmt::{self, Alignment},
    ops::{Add, AddAssign, Div, Mul, Sub, SubAssign},
};
use num::NumCast;

const ONE_MHZ: u64 = 1_000_000;
const ONE_GHZ: u64 = ONE_MHZ * 1000;

#[repr(transparent)]
#[derive(Default, Clone, Copy)]
pub struct Frequency {
    hz: u64,
}

impl Frequency {
    pub fn from_hz<T: NumCast>(val: T) -> Self {
        Self {
            hz: val.to_u64().unwrap(),
        }
    }

    pub fn from_mhz<T: NumCast>(val: T) -> Self {
        Self {
            hz: (val.to_f64().unwrap() * ONE_MHZ as f64) as u64,
        }
    }

    pub fn to_hz<T: NumCast>(&self) -> T {
        T::from(self.hz).unwrap()
    }

    pub fn to_mhz<T: NumCast>(&self) -> T {
        T::from(self.hz as f64 / ONE_MHZ as f64).unwrap()
    }
}

impl Add for Frequency {
    type Output = Frequency;

    fn add(self, rhs: Self) -> Self::Output {
        Self {
            hz: self.hz + rhs.hz,
        }
    }
}
impl AddAssign for Frequency {
    fn add_assign(&mut self, rhs: Self) {
        self.hz += rhs.hz;
    }
}

impl Sub for Frequency {
    type Output = Frequency;

    fn sub(self, rhs: Self) -> Self::Output {
        Self {
            hz: self.hz - rhs.hz,
        }
    }
}

impl SubAssign for Frequency {
    fn sub_assign(&mut self, rhs: Self) {
        self.hz -= rhs.hz;
    }
}

impl<N: NumCast> Mul<N> for Frequency {
    type Output = Frequency;

    fn mul(self, rhs: N) -> Self::Output {
        Self {
            hz: self.hz * rhs.to_u64().unwrap(),
        }
    }
}

impl<N: NumCast> Div<N> for Frequency {
    type Output = Frequency;
    fn div(self, rhs: N) -> Self::Output {
        Self {
            hz: self.hz / rhs.to_u64().unwrap(),
        }
    }
}

impl Div<Frequency> for Frequency {
    type Output = f64;

    fn div(self, rhs: Frequency) -> Self::Output {
        self.hz as f64 / rhs.hz as f64
    }
}

impl PartialEq for Frequency {
    fn eq(&self, other: &Self) -> bool {
        self.hz == other.hz
    }
}

impl PartialOrd for Frequency {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.hz.partial_cmp(&other.hz)
    }
}

impl std::fmt::Display for Frequency {
    /// Formats the value using the given formatter.
    /// 
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut value = self.hz as f64;
        let mut unit = " Hz";
        let mut precision = f.precision().unwrap_or(3);

        if self.hz >= ONE_GHZ {
            value = value / ONE_GHZ as f64;
            unit = "GHz";
        } else if self.hz >= ONE_MHZ {
            value = value / ONE_MHZ as f64;
            unit = "MHz";
        } else {
            precision = 0;
        }

        if let Some(width) = f.width() {
            if f.align().unwrap_or(Alignment::Left) == Alignment::Left {
                write!(f, "{:<width$.precision$}", value)?;
            } else {
                write!(f, "{:>width$.precision$}", value)?;
            }
        } else {
            f.write_fmt(format_args!("{:.precision$}", value))?;
        }

        f.write_str(&unit)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_freq() {
        let freq = Frequency::from_mhz(1.0);
        let a: f64 = freq.to_mhz();
        let b: i32 = freq.to_hz();

        assert_eq!(a, 1.0);
        assert_eq!(b, 1_000_000);

        println!("{}", freq);
    }

    #[test]
    fn test_freq_add() {
        let freq = Frequency::from_mhz(1.0);
        let freq2 = Frequency::from_mhz(2.0);
        let freq3 = freq + freq2;

        let a: f64 = freq3.to_mhz();

        assert_eq!(a, 3.0);
    }

    #[test]
    fn test_freq_div() {
        let freq = Frequency::from_mhz(1.0);
        let freq2 = Frequency::from_mhz(2.0);
        let p = freq / freq2;

        assert_eq!(p, 0.5);
    }
    #[test]
    fn test_print() {
        let freq = Frequency::from_mhz(12.3456789);

        assert_eq!(format!("{:<10.2}", freq), "12.35     MHz");

        let freq = Frequency::from_hz(12);

        println!("{:<10.2}", freq);
    }
}