1use crate::units::{FromUnits, Unit};
6use core::fmt::{Display, Formatter};
7
8#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
9pub enum FrequencyUnit {
10 #[default]
11 Hertz,
12 Kilohertz,
13 Megahertz,
14 Gigahertz,
15}
16impl FrequencyUnit {
17 pub fn abbreviation(&self) -> &'static str {
18 match self {
19 FrequencyUnit::Hertz => "Hz",
20 FrequencyUnit::Kilohertz => "KHz",
21 FrequencyUnit::Megahertz => "MHz",
22 FrequencyUnit::Gigahertz => "GHz",
23 }
24 }
25}
26
27macro_rules! from_units_freq {
28 ($type:ident) => {
29 impl crate::units::FromUnits<$type> for FrequencyUnit {
30 fn from(&self, value: $type, units: Self) -> $type {
31 match self {
32 FrequencyUnit::Hertz => {
34 match units {
36 FrequencyUnit::Hertz => value as $type,
37 FrequencyUnit::Kilohertz => value * KHZ_TO_HZ as $type,
38 FrequencyUnit::Megahertz => value * MHZ_TO_HZ as $type,
39 FrequencyUnit::Gigahertz => value * GHZ_TO_HZ as $type,
40 }
41 }
42 FrequencyUnit::Kilohertz => {
43 match units {
45 FrequencyUnit::Hertz => value * KHZ_TO_HZ as $type,
46 FrequencyUnit::Kilohertz => value as $type,
47 FrequencyUnit::Megahertz => value * MHZ_TO_HZ as $type,
48 FrequencyUnit::Gigahertz => value * GHZ_TO_HZ as $type,
49 }
50 }
51 FrequencyUnit::Megahertz => {
52 match units {
54 FrequencyUnit::Hertz => value * HZ_TO_MHZ as $type,
55 FrequencyUnit::Kilohertz => value * KHZ_TO_MHZ as $type,
56 FrequencyUnit::Megahertz => value as $type,
57 FrequencyUnit::Gigahertz => value * GHZ_TO_MHZ as $type,
58 }
59 }
60 FrequencyUnit::Gigahertz => {
61 match units {
63 FrequencyUnit::Hertz => value * HZ_TO_GHZ as $type,
64 FrequencyUnit::Kilohertz => value * KHZ_TO_GHZ as $type,
65 FrequencyUnit::Megahertz => value * MHZ_TO_GHZ as $type,
66 FrequencyUnit::Gigahertz => value as $type,
67 }
68 }
69 }
70 }
71 }
72 };
73}
74basic_unit!(Frequency, FrequencyUnit, Hertz);
75from_units_freq!(f64);
76
77impl Frequency {
78 pub fn new_hz(hz: u64) -> Self {
79 Self::new(hz as f64, FrequencyUnit::Hertz)
80 }
81 pub fn new_hz_f64(hz: f64) -> Self {
82 Self::new(hz, FrequencyUnit::Hertz)
83 }
84 pub fn new_khz(khz: f64) -> Self {
85 Self::new(khz, FrequencyUnit::Kilohertz)
86 }
87}
88impl Display for Frequency {
89 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
90 write!(f, "{:.3} {}", self.value, self.units.abbreviation())
91 }
92}
93
94pub const HZ_TO_KHZ: f64 = 1e-3;
95pub const HZ_TO_MHZ: f64 = 1e-6;
96pub const HZ_TO_GHZ: f64 = 1e-9;
97
98pub const GHZ_TO_HZ: f64 = 1e9;
99pub const MHZ_TO_HZ: f64 = 1e6;
100pub const KHZ_TO_HZ: f64 = 1e3;
101
102pub const KHZ_TO_MHZ: f64 = 1e-3;
103pub const MHZ_TO_KHZ: f64 = 1e3;
104
105pub const MHZ_TO_GHZ: f64 = 1e-3;
106pub const GHZ_TO_MHZ: f64 = 1e3;
107
108pub const GHZ_TO_KHZ: f64 = 1e6;
109pub const KHZ_TO_GHZ: f64 = 1e-6;