bern_units/
frequency.rs

1//! Units representing a frequency.
2
3use derive_more::{Add, Sub, Mul, Div};
4
5#[derive(PartialEq, PartialOrd, Clone, Copy, Debug, Add, Sub, Mul, Div)]
6pub struct MilliHertz(pub u32);
7
8#[derive(PartialEq, PartialOrd, Clone, Copy, Debug, Add, Sub, Mul, Div)]
9pub struct Hertz(pub u32);
10
11#[derive(PartialEq, PartialOrd, Clone, Copy, Debug, Add, Sub, Mul, Div)]
12pub struct KiloHertz(pub u32);
13
14#[derive(PartialEq, PartialOrd, Clone, Copy, Debug, Add, Sub, Mul, Div)]
15pub struct MegaHertz(pub u32);
16
17
18/// MilliHertz is implemented specifically because const trait implementations are not
19/// stable yet.
20#[allow(non_snake_case)]
21impl MilliHertz {
22    pub const fn from_Hz(hz: u32) -> Self {
23        MilliHertz(hz * 1_000)
24    }
25
26    pub const fn from_kHz(khz: u32) -> Self {
27        MilliHertz(khz * 1_000 * 1_000)
28    }
29
30    pub const fn from_MHz(mhz: u32) -> Self {
31        MilliHertz(mhz * 1_000 * 1_000 * 1_000)
32    }
33}
34
35/// Extension trait that adds convenience methods to the `u32` type
36#[allow(non_snake_case)]
37pub trait ExtMilliHertz {
38    /// Wrap in `MilliHertz`
39    fn mHz(self) -> MilliHertz;
40
41    /// Wrap in `Hertz`
42    fn Hz(self) -> Hertz;
43
44    /// Wrap in `KiloHertz`
45    fn kHz(self) -> KiloHertz;
46
47    /// Wrap in `MegaHertz`
48    fn MHz(self) -> MegaHertz;
49}
50
51#[allow(non_snake_case)]
52impl ExtMilliHertz for u32 {
53    fn mHz(self) -> MilliHertz {
54        MilliHertz(self)
55    }
56
57    fn Hz(self) -> Hertz {
58        Hertz(self)
59    }
60
61    fn kHz(self) -> KiloHertz {
62        KiloHertz(self)
63    }
64
65    fn MHz(self) -> MegaHertz {
66        MegaHertz(self)
67    }
68}
69
70
71impl From<u32> for MilliHertz {
72    fn from(mhz: u32) -> Self {
73        mhz.mHz()
74    }
75}
76
77
78impl From<Hertz> for MilliHertz {
79    fn from(hz: Hertz) -> Self {
80        Self(hz.0 * 1_000)
81    }
82}
83
84
85impl From<KiloHertz> for MilliHertz {
86    fn from(khz: KiloHertz) -> Self {
87        Self(khz.0 * 1_000 * 1_000)
88    }
89}
90
91impl From<KiloHertz> for Hertz {
92    fn from(khz: KiloHertz) -> Self {
93        Self(khz.0 * 1_000)
94    }
95}
96
97
98impl From<MegaHertz> for MilliHertz {
99    fn from(mhz: MegaHertz) -> Self {
100        Self(mhz.0 * 1_000 * 1_000 * 1_000)
101    }
102}
103
104impl From<MegaHertz> for Hertz {
105    fn from(mhz: MegaHertz) -> Self {
106        Self(mhz.0 * 1_000 * 1_000)
107    }
108}
109
110impl From<MegaHertz> for KiloHertz {
111    fn from(mhz: MegaHertz) -> Self {
112        Self(mhz.0 * 1_000)
113    }
114}