divecomputer_core/
units.rs1const METRES_PER_FOOT: f64 = 0.3048;
10const BAR_PER_PSI: f64 = 0.068_947_572_9;
12
13macro_rules! unit {
14 ($(#[$doc:meta])* $name:ident, $from:ident, $get:ident, $unit:literal) => {
15 $(#[$doc])*
16 #[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
17 #[cfg_attr(feature = "serde", derive(serde::Serialize), serde(transparent))]
18 pub struct $name(f64);
19
20 impl $name {
21 #[doc = concat!("A value in ", $unit, ".")]
22 #[must_use]
23 pub const fn $from(value: f64) -> Self {
24 Self(value)
25 }
26
27 #[doc = concat!("The value in ", $unit, ".")]
28 #[must_use]
29 pub const fn $get(self) -> f64 {
30 self.0
31 }
32 }
33 };
34}
35
36unit!(
37 Depth,
39 from_metres,
40 metres,
41 "metres"
42);
43unit!(
44 Temperature,
46 from_celsius,
47 celsius,
48 "degrees Celsius"
49);
50unit!(
51 Pressure,
53 from_bar,
54 bar,
55 "bar"
56);
57unit!(
58 GasFraction,
60 from_percent,
61 percent,
62 "percent"
63);
64
65impl Depth {
66 #[must_use]
68 pub const fn from_feet(feet: f64) -> Self {
69 Self(feet * METRES_PER_FOOT)
70 }
71}
72
73impl Temperature {
74 #[must_use]
76 pub const fn from_fahrenheit(fahrenheit: f64) -> Self {
77 Self((fahrenheit - 32.0) * 5.0 / 9.0)
78 }
79}
80
81impl Pressure {
82 #[must_use]
84 pub const fn from_millibar(millibar: f64) -> Self {
85 Self(millibar / 1000.0)
86 }
87
88 #[must_use]
90 pub const fn from_psi(psi: f64) -> Self {
91 Self(psi * BAR_PER_PSI)
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98
99 #[test]
100 fn converts_imperial_units() {
101 assert!((Depth::from_feet(10.0).metres() - 3.048).abs() < 1e-9);
102 assert!((Temperature::from_fahrenheit(212.0).celsius() - 100.0).abs() < 1e-9);
103 assert!((Pressure::from_psi(14.503_773_8).bar() - 1.0).abs() < 1e-6);
104 assert!((Pressure::from_millibar(1013.0).bar() - 1.013).abs() < 1e-9);
105 }
106}