Skip to main content

tpt_math_units/
lib.rs

1#![no_std]
2//! Compile-time typed units, a thin wrap over [`uom`].
3//!
4//! `uom` provides quantities (length, mass, time, …) whose units are checked
5//! at compile time: `Length<f64>` multiplied by `Time<f64>` is a
6//! `Velocity<f64>`, and you cannot accidentally add a `Mass` to a `Length`.
7//!
8//! This crate re-exports the whole [`uom`] API under [`uom`], plus a set of
9//! `f64`-backed quantity type aliases and a [`prelude`] that brings the common
10//! SI unit markers into scope.
11//!
12//! # Examples
13//!
14//! ```
15//! use tpt_math_units::prelude::*;
16//! use tpt_math_units::si::length::kilometer;
17//! use tpt_math_units::si::time::second;
18//!
19//! let distance = Length::new::<kilometer>(3.0);
20//! let duration = Time::new::<second>(90.0);
21//! let speed = distance / duration;
22//! assert!((speed.get::<tpt_math_units::si::velocity::kilometer_per_hour>() - 120.0).abs() < 1e-9);
23//! ```
24//!
25//! # no_std
26//!
27//! `uom` is built with its `std` feature disabled; the `f32`/`f64`
28//! transcendental math is provided through [`uom`]'s `libm` backend. The
29//! crate therefore compiles for `no_std` targets.
30
31pub use uom;
32
33/// Re-export of [`uom`]'s `si` module (systems, quantities, units).
34pub mod si {
35    pub use uom::si::*;
36}
37
38/// `f64`-backed aliases for the most common SI quantities.
39pub mod q {
40    pub use uom::si::area::Area;
41    pub use uom::si::length::Length;
42    pub use uom::si::mass::Mass;
43    pub use uom::si::ratio::Ratio;
44    pub use uom::si::thermodynamic_temperature::ThermodynamicTemperature;
45    pub use uom::si::time::Time;
46    pub use uom::si::velocity::Velocity;
47    pub use uom::si::volume::Volume;
48}
49
50/// Brings the `f64` SI unit markers and base quantities into scope.
51pub mod prelude {
52    pub use uom::si::f64::*;
53}
54
55#[cfg(test)]
56mod tests {
57    use super::prelude::*;
58    use super::si::length::meter;
59    use super::si::mass::kilogram;
60    use super::si::time::second;
61
62    #[test]
63    fn dimensions_are_checked_at_compile_time() {
64        let m = Mass::new::<kilogram>(2.0);
65        let a = Length::new::<meter>(10.0);
66        // velocity = length / time, not mass + length
67        let _v = a / Time::new::<second>(2.0);
68        assert_eq!(m.get::<kilogram>(), 2.0);
69    }
70
71    #[test]
72    fn unit_conversion() {
73        let km = Length::new::<super::si::length::kilometer>(1.0);
74        assert!((km.get::<meter>() - 1000.0).abs() < 1e-9);
75    }
76}