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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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 {
    // fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    //     if self.hz >= ONE_GHZ {
    //         let ghz = self.hz as f64 / ONE_GHZ as f64;
    //         write!(f, "{:.2} GHz", ghz)
    //     } else if self.hz >= ONE_MHZ {
    //         let mhz = self.hz as f64 / ONE_MHZ as f64;
    //         write!(f, "{:.2} MHz", mhz)
    //     } else {
    //         write!(f, "{} Hz", self.hz)
    //     }
    // }

    /// Formats the value using the given formatter.
    ///
    /// # Examples
    ///
    /// ```
    /// use byte_unit::{Byte, Unit};
    ///
    /// let byte = Byte::from_u64_with_unit(1555, Unit::KB).unwrap();
    ///
    /// assert_eq!("1555000", byte.to_string());
    /// ```
    ///
    /// ```
    /// use byte_unit::{Byte, UnitType};
    ///
    /// let byte_based_2 = Byte::from_u64(10240);
    /// let byte_based_10 = Byte::from_u64(10000);
    ///
    /// assert_eq!("10240", format!("{byte_based_2}"));
    /// assert_eq!("10000", format!("{byte_based_10}"));
    ///
    /// // with an exact unit
    /// assert_eq!("10 KiB", format!("{byte_based_2:#}"));
    /// assert_eq!("10 KB", format!("{byte_based_10:#}"));
    ///
    /// // with an exact unit, no spaces between the value and the unit
    /// assert_eq!("10KiB", format!("{byte_based_2:-#}"));
    /// assert_eq!("10KB", format!("{byte_based_10:-#}"));
    ///
    /// // with a width, left alignment
    /// assert_eq!("10     KiB", format!("{byte_based_2:#10}"));
    /// assert_eq!("10      KB", format!("{byte_based_10:#10}"));
    ///
    /// // with a width, right alignment
    /// assert_eq!("    10 KiB", format!("{byte_based_2:>#10}"));
    /// assert_eq!("     10 KB", format!("{byte_based_10:>#10}"));
    ///
    /// // with a width, right alignment, more spaces between the value and the unit
    /// assert_eq!("    10 KiB", format!("{byte_based_2:>+#10}"));
    /// assert_eq!("    10  KB", format!("{byte_based_10:>+#10}"));
    /// ```
    ///
    /// ```
    /// use byte_unit::{Byte, UnitType};
    ///
    /// let byte = Byte::from_u64(3211776);
    ///
    /// assert_eq!("3211776", format!("{byte}"));
    ///
    /// // with a unit, still precisely
    /// assert_eq!("3136.5 KiB", format!("{byte:#}"));
    ///
    /// // with a unit and a larger precision (default is 3), still precisely
    /// assert_eq!("3.211776 MB", format!("{byte:#.6}"));
    ///
    /// // with a unit and a smaller precision (default is 3), still precisely
    /// assert_eq!("3211776 B", format!("{byte:#.0}"));
    /// ```
    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);
    }
}