Skip to main content

dimvexa_data/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The unit table of **dimvexa**, compiled from audited TOML at build time.
3//!
4//! The source of truth is `data/units/*.toml` and `data/constants/*.toml` (inside this crate): each unit carries an exact rational factor,
5//! an exactness flag (`defined` or `measured`), a cited source and a note, and has at least
6//! one golden test vector in `data/vectors/`. `cargo xtask validate-data` enforces this.
7//!
8//! ```
9//! let reg = dimvexa_data::registry()?;
10//! let c = reg.conversion("psi", "Pa")?;
11//! assert!((c.apply(1.0) - 6894.757_293_168_361).abs() < 1e-9);
12//! # Ok::<(), dimvexa_core::Error>(())
13//! ```
14#![forbid(unsafe_code)]
15#![doc(
16    html_logo_url = "https://raw.githubusercontent.com/welworx/dimvexa/main/docs/brand/icon-256.png",
17    html_favicon_url = "https://raw.githubusercontent.com/welworx/dimvexa/main/docs/brand/icon-32.png"
18)]
19
20use dimvexa_core::{
21    AmbiguousDef, ConstantDef, Error, Exactness, Kind, PrefixMode, Registry, Shape, Status, UnitDef,
22};
23
24// The ohm sign U+2126 alias is intentionally not NFC-normalised (it is a distinct code point users paste).
25#[allow(
26    clippy::unreadable_literal,
27    clippy::too_many_lines,
28    clippy::unicode_not_nfc,
29    missing_docs
30)]
31mod generated {
32    use super::{AmbiguousDef, ConstantDef, Exactness, Kind, PrefixMode, Shape, Status, UnitDef};
33    include!(concat!(env!("OUT_DIR"), "/units_generated.rs"));
34}
35
36pub use generated::{AMBIGUOUS, CONSTANTS, DATA_HASH, DATA_VERSION, PACKS, UNITS};
37
38/// The built-in constant with the identifier `id`, if there is one (ADR-018).
39///
40/// ```
41/// let h = dimvexa_data::constant("planck_constant").expect("built in");
42/// assert_eq!(h.unit, "J*s");
43/// assert!(dimvexa_data::constant("nope").is_none());
44/// ```
45#[must_use]
46pub fn constant(id: &str) -> Option<&'static ConstantDef> {
47    CONSTANTS.iter().find(|c| c.id == id)
48}
49
50/// Builds a [`Registry`] from the compiled seed table.
51///
52/// # Errors
53///
54/// Any definition error of the table. A table that passes `cargo xtask validate-data`
55/// never fails here; the error type exists so that no panic is possible.
56pub fn registry() -> Result<Registry, Error> {
57    Registry::from_defs(UNITS, AMBIGUOUS)
58}
59
60/// A printable identifier of the table: `v<version>+<hash>`.
61#[must_use]
62pub fn data_version() -> String {
63    format!("v{DATA_VERSION}+{DATA_HASH}")
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn table_loads_and_is_reasonably_sized() {
72        let reg = registry().unwrap();
73        assert!(reg.len() >= 50, "{}", reg.len());
74        assert_eq!(reg.len(), UNITS.len());
75        assert!(DATA_HASH.starts_with("fnv1a64:"));
76        assert!(PACKS.contains(&"base") && PACKS.contains(&"common"));
77    }
78
79    #[test]
80    fn constants_load_with_a_source_and_a_unit_that_parses() {
81        let reg = registry().unwrap();
82        for name in [
83            "pi",
84            "planck_constant",
85            "elementary_charge",
86            "boltzmann_constant",
87            "avogadro_constant",
88            "speed_of_light",
89            "molar_gas_constant",
90        ] {
91            let c = constant(name).unwrap_or_else(|| panic!("{name} missing"));
92            assert!(!c.source.is_empty() && !c.conditions.is_empty(), "{name}");
93            assert!(c.value().is_ok(), "{name}");
94            assert!(!c.name.is_empty(), "{name}: no full name");
95            assert!(reg.parse(c.unit).is_ok(), "{name}: unit {}", c.unit);
96            // A constant's name is never also a unit's (`h` is the hour).
97            let err = reg.parse(c.id).unwrap_err();
98            assert_eq!(err.code(), "unknown_unit", "{name} is also a unit");
99        }
100    }
101
102    #[test]
103    fn every_ambiguous_symbol_is_rejected_with_candidates() {
104        let reg = registry().unwrap();
105        for a in AMBIGUOUS {
106            let err = reg.parse(a.symbol).unwrap_err();
107            assert_eq!(err.code(), "ambiguous_symbol", "{}", a.symbol);
108            assert_eq!(err.candidates().len(), a.candidates.len() + a.planned.len());
109            for c in a.candidates {
110                assert!(
111                    reg.parse(c).is_ok(),
112                    "candidate {c} of {} must resolve",
113                    a.symbol
114                );
115            }
116        }
117        for sym in ["ton", "gal", "oz", "pt", "cal", "BTU", "mile", "hp"] {
118            assert!(AMBIGUOUS.iter().any(|a| a.symbol == sym), "{sym}");
119        }
120    }
121}