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("h_P").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 ["pi", "h_P", "e", "k_B", "N_A"] {
83            let c = constant(name).unwrap_or_else(|| panic!("{name} missing"));
84            assert!(!c.source.is_empty() && !c.conditions.is_empty(), "{name}");
85            assert!(c.value().is_ok(), "{name}");
86            assert!(!c.name.is_empty(), "{name}: no full name");
87            assert!(reg.parse(c.unit).is_ok(), "{name}: unit {}", c.unit);
88            // A constant's name is never also a unit's (`h` is the hour).
89            let err = reg.parse(c.id).unwrap_err();
90            assert_eq!(err.code(), "unknown_unit", "{name} is also a unit");
91        }
92    }
93
94    #[test]
95    fn every_ambiguous_symbol_is_rejected_with_candidates() {
96        let reg = registry().unwrap();
97        for a in AMBIGUOUS {
98            let err = reg.parse(a.symbol).unwrap_err();
99            assert_eq!(err.code(), "ambiguous_symbol", "{}", a.symbol);
100            assert_eq!(err.candidates().len(), a.candidates.len() + a.planned.len());
101            for c in a.candidates {
102                assert!(
103                    reg.parse(c).is_ok(),
104                    "candidate {c} of {} must resolve",
105                    a.symbol
106                );
107            }
108        }
109        for sym in ["ton", "gal", "oz", "pt", "cal", "BTU", "mile", "ppm", "hp"] {
110            assert!(AMBIGUOUS.iter().any(|a| a.symbol == sym), "{sym}");
111        }
112    }
113}