tpt_math_units_dyn/lib.rs
1//! Runtime dimension-checked units for dynamic/config payloads.
2//!
3//! [`tpt_math_units`] (a wrapper around [`uom`](tpt_math_units::uom)) checks
4//! units *at compile time*, which is the right tool whenever the units are
5//! known while the code is written. It cannot help when the unit is only
6//! known at runtime — a YAML file that says `speed_limit: "90 km/h"`, a JSON
7//! payload with `{"value": 12, "unit": "kWh"}`, a spreadsheet column header,
8//! a plugin that reports whatever unit its sensor uses. This crate fills that
9//! gap:
10//!
11//! * [`Dimension`] — the seven SI base-dimension exponents as a `Copy` value
12//! that multiplies, divides and compares like the quantity it describes.
13//! * [`UnitDef`] / [`UnitRegistry`] — a symbol table mapping unit names such
14//! as `"km"`, `"min"` or `"kWh"` onto a dimension plus the conversion to
15//! the SI base unit, with a large built-in table and room for custom units.
16//! * [`DynQuantity`] — a value stored in SI base units, tagged with its
17//! dimension, whose arithmetic is dimension-checked at runtime.
18//! * [`interop`] — conversions to and from the compile-time quantities of
19//! [`tpt_math_units`], so dynamic input can be validated once at the
20//! boundary and be statically typed everywhere else.
21//!
22//! # Examples
23//!
24//! ```
25//! use tpt_math_units_dyn::prelude::*;
26//!
27//! // Values that arrived as (number, unit) pairs from a config file.
28//! let distance = DynQuantity::parse(1.0, "km")?;
29//! let extra = DynQuantity::parse(200.0, "m")?;
30//!
31//! // Same dimension: addition is allowed, and unit conversion is implicit
32//! // because everything is stored in SI base units.
33//! let total = distance.try_add(&extra)?;
34//! assert!((total.convert_to("km")? - 1.2).abs() < 1e-12);
35//!
36//! // Different dimensions: multiplication composes them ...
37//! let duration = DynQuantity::parse(30.0, "min")?;
38//! let speed = total.try_div(&duration)?;
39//! assert_eq!(*speed.dim(), Dimension::VELOCITY);
40//! assert!((speed.convert_to("km/h")? - 2.4).abs() < 1e-12);
41//!
42//! // ... but addition is rejected.
43//! let mass = DynQuantity::parse(70.0, "kg")?;
44//! assert!(total.try_add(&mass).is_err());
45//! # Ok::<(), UnitError>(())
46//! ```
47//!
48//! # Design notes
49//!
50//! * A [`DynQuantity`] always stores its magnitude in SI base units, so no
51//! conversion bookkeeping is needed during arithmetic and comparisons are
52//! exact for values that came from the same unit.
53//! * `Add`/`Sub` **panic** on a dimension mismatch (a mismatch is a bug in
54//! the same way indexing out of bounds is); use the `try_*` methods to get
55//! a [`UnitError`] instead. `Mul`/`Div` never mismatch — they compose
56//! dimensions.
57//! * Unit symbols are case sensitive, as SI requires: `"m"` is metre, `"T"`
58//! is tesla and `"t"` is tonne.
59//! * Degrees Celsius and Fahrenheit are supported through the affine
60//! `offset` field of [`UnitDef`].
61
62#![warn(missing_docs)]
63#![warn(missing_debug_implementations)]
64#![warn(clippy::all)]
65
66pub mod dimension;
67pub mod error;
68pub mod interop;
69pub mod quantity;
70pub mod solve;
71pub mod unit;
72
73pub use crate::dimension::{BaseDimension, Dimension, BASE_COUNT};
74pub use crate::error::{Result, UnitError};
75pub use crate::quantity::DynQuantity;
76pub use crate::unit::{
77 builtin_registry, builtin_units, convert, lookup, lookup_unit, UnitDef, UnitRegistry,
78 BUILTIN_UNITS,
79};
80
81/// The types most users need.
82///
83/// ```
84/// use tpt_math_units_dyn::prelude::*;
85///
86/// let energy = DynQuantity::parse(2.5, "kWh").unwrap();
87/// assert_eq!(*energy.dim(), Dimension::ENERGY);
88/// ```
89pub mod prelude {
90 pub use crate::dimension::{BaseDimension, Dimension};
91 pub use crate::error::UnitError;
92 pub use crate::quantity::DynQuantity;
93 pub use crate::unit::{convert, lookup, lookup_unit, UnitDef, UnitRegistry};
94}