1 unstable release

new 0.9.0 Feb 10, 2025

#312 in Build Utils

Download history 106/week @ 2025-02-09

106 downloads per month

MIT license

155KB
4K SLoC

absolute_unit

A unit system for Rust's type system to catch unit errors at build time.

Examples

Use the type system to ensure that you get the expected units out of a calculation.

let time = seconds!(10);
let velocity = meters_per_second!(100);
let position: Length<Meters> = velocity * time;
assert_eq!(position, meters!(100));

Use IDE type introspection to discover the type of a result. IDE Type Discovery

Check type correctness even when using approximation formulas that contain intermediate values with no inherent unit-based meaning. Runtime checks only happen in #[cfg(debug_assertions)], so there is no runtime cost in release builds.

let drag: Force<Newtons> = (coef_drag.as_dyn()
            * air_density.as_dyn()
            * (velocity_cg * velocity_cg).as_dyn()
            * meters2!(1_f64).as_dyn())
        .into();

Technical Details

The unit wrappers store the underlying value as f64. Values are wrapped in OrderedFloat and the unit values provide the same derivations as the underlying OrderedFloat(f64), enabling straightforward usage in most situations. All of the type info compiles away, leaving identical performance to bare f64.

Usage

Add absolute_unit to your Cargo.toml:

absolute_unit = "0.9"

Import the prelude to get access to everything, or import ala carte, if you know what you need.

use absolute_unit::prelude::*;

Dependencies

~9–14MB
~247K SLoC