Skip to main content

divecomputer_core/
units.rs

1//! Units of measurement used by the dive model
2//! ([spec](https://michidk.github.io/divecomputer-rs/spec/conventions.html)).
3//!
4//! Each quantity is a newtype over `f64` in one fixed SI-style unit, so that parsers
5//! convert device units exactly once. With the `serde` feature each serializes as a
6//! plain number in that unit.
7
8/// Metres per foot.
9const METRES_PER_FOOT: f64 = 0.3048;
10/// Bar per psi.
11const 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    /// A depth below the surface, in metres.
38    Depth,
39    from_metres,
40    metres,
41    "metres"
42);
43unit!(
44    /// A temperature, in degrees Celsius.
45    Temperature,
46    from_celsius,
47    celsius,
48    "degrees Celsius"
49);
50unit!(
51    /// A pressure (tank, surface or partial pressure), in bar.
52    Pressure,
53    from_bar,
54    bar,
55    "bar"
56);
57unit!(
58    /// The share of one gas in a breathing mix, in percent (0–100).
59    GasFraction,
60    from_percent,
61    percent,
62    "percent"
63);
64
65impl Depth {
66    /// A depth in feet.
67    #[must_use]
68    pub const fn from_feet(feet: f64) -> Self {
69        Self(feet * METRES_PER_FOOT)
70    }
71}
72
73impl Temperature {
74    /// A temperature in degrees Fahrenheit.
75    #[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    /// A pressure in millibar.
83    #[must_use]
84    pub const fn from_millibar(millibar: f64) -> Self {
85        Self(millibar / 1000.0)
86    }
87
88    /// A pressure in pounds per square inch.
89    #[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}