1#![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#[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#[must_use]
46pub fn constant(id: &str) -> Option<&'static ConstantDef> {
47 CONSTANTS.iter().find(|c| c.id == id)
48}
49
50pub fn registry() -> Result<Registry, Error> {
57 Registry::from_defs(UNITS, AMBIGUOUS)
58}
59
60#[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 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}