ifc_lite_core/unit_labels.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Unit *labels* and the scales they resolve to.
6//!
7//! Two readers need the same answer to "what does this unit label mean in
8//! metres": [`crate::units`], reading an `IfcSIUnit`/`IfcConversionBasedUnit`
9//! declaration, and [`crate::georef`], reading the free-text
10//! `ePSet_ProjectedCRS.MapUnit` of the IFC2x3 georeferencing convention. Both
11//! tables and the MapUnit label rules live here so the two cannot drift; the
12//! `units::` paths are preserved as re-exports.
13
14/// One member of the `IfcSIPrefix` EXPRESS enumeration.
15#[derive(Clone, Copy, Debug, PartialEq)]
16#[non_exhaustive]
17pub struct SiPrefix {
18 /// The enumeration token without dots (`"MILLI"`).
19 pub name: &'static str,
20 /// The display symbol that prepends a unit symbol (`"m"`, `"\u{00B5}"`).
21 pub symbol: &'static str,
22 /// The multiplier (`1e-3`).
23 pub factor: f64,
24}
25
26const fn prefix(name: &'static str, symbol: &'static str, factor: f64) -> SiPrefix {
27 SiPrefix { name, symbol, factor }
28}
29
30/// The one `IfcSIPrefix` table (CORE-26, XCUT-6): the multiplier readers
31/// ([`try_si_prefix_multiplier`]), the display symbols
32/// ([`crate::project_units::symbols::si_prefix_symbol`]) and the exporters'
33/// prefix-name checks all derive from these sixteen rows.
34pub const SI_PREFIXES: [SiPrefix; 16] = [
35 prefix("ATTO", "a", 1e-18),
36 prefix("FEMTO", "f", 1e-15),
37 prefix("PICO", "p", 1e-12),
38 prefix("NANO", "n", 1e-9),
39 prefix("MICRO", "\u{00B5}", 1e-6), // micro sign
40 prefix("MILLI", "m", 1e-3), // Most common: millimeters
41 prefix("CENTI", "c", 1e-2), // Centimeters
42 prefix("DECI", "d", 1e-1), // Decimeters
43 prefix("DECA", "da", 1e1), // Dekameters
44 prefix("HECTO", "h", 1e2), // Hectometers
45 prefix("KILO", "k", 1e3), // Kilometers
46 prefix("MEGA", "M", 1e6),
47 prefix("GIGA", "G", 1e9),
48 prefix("TERA", "T", 1e12),
49 prefix("PETA", "P", 1e15),
50 prefix("EXA", "E", 1e18),
51];
52
53/// The [`SI_PREFIXES`] row for a member of the `IfcSIPrefix` EXPRESS
54/// enumeration (exact token, no dots), or `None`.
55pub fn si_prefix(prefix: &str) -> Option<&'static SiPrefix> {
56 SI_PREFIXES.iter().find(|row| row.name == prefix)
57}
58
59/// SI Prefix multiplier for a member of the `IfcSIPrefix` EXPRESS
60/// enumeration, or `None` when the string is not one of its sixteen members.
61///
62/// The checked form exists because callers that need to tell "no prefix" from
63/// "a prefix I do not recognise" cannot use [`get_si_prefix_multiplier`],
64/// which collapses both onto 1.0. Resolving an `ePSet_ProjectedCRS.MapUnit`
65/// label is one such caller: answering 1.0 for an unrecognised spelling is a
66/// silent wrong answer, where declining to answer defers to the project
67/// length unit, which is the documented convention.
68#[inline]
69pub fn try_si_prefix_multiplier(prefix: &str) -> Option<f64> {
70 si_prefix(prefix).map(|row| row.factor)
71}
72
73/// SI Prefix multipliers as defined in IFC specification.
74/// Maps IfcSIPrefix enum values to their numeric multipliers; an absent or
75/// unrecognised prefix means the base unit (metres), i.e. 1.0. Callers that
76/// must distinguish those two cases want [`try_si_prefix_multiplier`].
77#[inline]
78pub fn get_si_prefix_multiplier(prefix: &str) -> f64 {
79 try_si_prefix_multiplier(prefix).unwrap_or(1.0)
80}
81
82/// Known conversion factors for imperial/conversion-based units to meters
83/// These are the standard conversions defined in IFC specification
84#[inline]
85pub fn get_conversion_based_unit_factor(name: &str) -> Option<f64> {
86 match name.to_uppercase().as_str() {
87 // Length units to meters
88 // The quoted spellings are the doubled-quote STEP escaping: a name
89 // attribute written `''FEET''` in the file decodes to the
90 // four-character string `'FEET'` and is matched here verbatim. Keep
91 // this arm in step with CONVERSION_BASED_UNIT_FACTORS in
92 // packages/parser/src/unit-extractor.ts — two length-unit readers that
93 // disagree put the model and its map coordinates on different scales.
94 "FOOT" | "FEET" | "'FOOT'" | "'FEET'" => Some(0.3048),
95 "INCH" | "'INCH'" => Some(0.0254),
96 "YARD" | "'YARD'" => Some(0.9144),
97 "MILE" | "'MILE'" => Some(1609.344),
98 _ => None,
99 }
100}
101
102/// 1200/3937 m, exactly: the US survey foot, distinct from the international
103/// 0.3048. The one definition (CORE-26, EXPORT-STEP-20): the former core copy
104/// was truncated to `0.3048006096` (4e-12 relative).
105pub const US_SURVEY_FOOT_M: f64 = 1200.0 / 3937.0;
106
107/// Is `key` — an already-folded (alphanumeric, upper-cased) label — one of the
108/// glued US-survey-foot spellings? Shared with the exporters' map-unit
109/// normaliser so the spelling list has one home.
110pub fn is_us_survey_foot_key(key: &str) -> bool {
111 matches!(
112 key,
113 "USSURVEYFOOT" | "USSURVEYFEET" | "USSURVEYFT" | "USFOOT" | "USFEET" | "USFT" | "FTUS"
114 )
115}
116
117/// The foot/feet spellings a US-survey qualifier may be attached to.
118const FOOT_TOKENS: [&str; 3] = ["FOOT", "FEET", "FT"];
119
120/// Order-insensitive recogniser for the separated US-survey foot spellings —
121/// `foot (US survey)`, `SURVEY FEET (US)`, `US survey foot`. The glued
122/// spellings (`USSURVEYFOOT`, `FTUS`, ...) are matched exactly in
123/// [`resolve_exact_unit_label`]; once an exporter puts separators in, the
124/// word order varies and gluing alone cannot see it.
125///
126/// Accepts exactly one foot token plus either `US` (or the glued `USSURVEY`)
127/// or both `US` and `SURVEY`. A bare `SURVEY FOOT` without `US` is REFUSED:
128/// other national survey feet exist (the Indian and Clarke feet are different
129/// ratios), so the qualifier alone does not identify the value.
130///
131/// Twin of `isUsSurveyFootTokens` in
132/// packages/parser/src/georef-extractor.ts.
133pub fn is_us_survey_foot_tokens(tokens: &[String]) -> bool {
134 let feet = tokens
135 .iter()
136 .filter(|t| FOOT_TOKENS.contains(&t.as_str()))
137 .count();
138 if feet != 1 {
139 return false;
140 }
141 let rest: Vec<&str> = tokens
142 .iter()
143 .map(|t| t.as_str())
144 .filter(|t| !FOOT_TOKENS.contains(t))
145 .collect();
146 match rest.len() {
147 1 => rest[0] == "US" || rest[0] == "USSURVEY",
148 2 => rest.contains(&"US") && rest.contains(&"SURVEY"),
149 _ => false,
150 }
151}
152
153/// Exact lookup of an already-folded (alphanumeric, upper-cased) unit label.
154///
155/// The accepted set is DERIVED, not hand-written: the conversion-based length
156/// units of the shared table, the glued US-survey foot spellings, and the
157/// METRE/METER base spellings carrying any member of the `IfcSIPrefix`
158/// EXPRESS enumeration.
159fn resolve_exact_unit_label(key: &str) -> Option<f64> {
160 if key.is_empty() {
161 return None;
162 }
163
164 // The US survey foot is a different ratio from the international foot
165 // (1200/3937 vs 0.3048), and is spelled several ways in the wild. These
166 // are the accepted glued spellings, matched exactly rather than sniffed
167 // for; the separated ones go through `is_us_survey_foot_tokens`.
168 if is_us_survey_foot_key(key) {
169 return Some(US_SURVEY_FOOT_M);
170 }
171
172 // Conversion-based length units (FOOT/FEET/INCH/YARD/MILE), from the same
173 // table the native IfcConversionBasedUnit path uses.
174 if let Some(factor) = get_conversion_based_unit_factor(key) {
175 return Some(factor);
176 }
177
178 // SI: strip the base-unit spelling, then resolve what remains as an
179 // IfcSIPrefix member. An empty remainder is the unprefixed metre.
180 for spelling in ["METRE", "METER"] {
181 if let Some(prefix) = key.strip_suffix(spelling) {
182 if prefix.is_empty() {
183 return Some(1.0);
184 }
185 // `try_`, not `get_`: the infallible form answers 1.0 for an
186 // unrecognised prefix, which is the very approximation this
187 // function exists to refuse.
188 return try_si_prefix_multiplier(prefix);
189 }
190 }
191
192 None
193}
194
195/// Resolve an `ePSet_ProjectedCRS.MapUnit` free-text label to its metre scale.
196///
197/// `MapUnit` on the ePSet path is exporter free text, so the label is
198/// NORMALISED and then matched EXACTLY — never substring-matched.
199///
200/// What the normalisation accepts:
201/// - any case and any separators: `metres`, `Meters`, `US survey foot`,
202/// `MILLI-METRE` (letters and digits are kept, everything else dropped);
203/// - the two base spellings `METRE` and `METER`, each prefixed by any of the
204/// sixteen `IfcSIPrefix` members (`MILLIMETRE` ... `GIGAMETER`);
205/// - the conversion-based length units of the shared table (`FOOT`, `FEET`,
206/// `INCH`, `YARD`, `MILE`);
207/// - one English plural suffix on any of the above, stripped once and then
208/// re-matched exactly: `METRES`, `KILOMETERS`, `MILLIMETRES`, `INCHES`,
209/// `MILES`;
210/// - the US survey foot, glued (`USSURVEYFOOT`, `USFT`, `FTUS`, ...) or
211/// separated in any word order (see [`is_us_survey_foot_tokens`]).
212///
213/// What it still REFUSES (returns `None`, so the ePSet convention defers to
214/// the project length unit downstream):
215/// - an absent or blank label;
216/// - a label that merely CONTAINS a known unit: `SQUARE METRE` is an area,
217/// `BANANAMETRE` is not a unit, and neither may borrow the metre's scale;
218/// - abbreviations that are not in the table (`M`, `MM`, `MTR`);
219/// - a survey foot with no nationality (`SURVEY FOOT`);
220/// - anything else, including a plural whose singular is still unknown.
221///
222/// The exactness is the point. A `contains("METRE")` test is satisfied by
223/// MILLIMETRE, CENTIMETRE, KILOMETRE, DECAMETRE, HECTOMETRE and every other
224/// prefixed spelling, so a decametre map unit answered 1.0 — a silent 10x
225/// error in the CRS scale; the same shape scaled a projected CRS by 1000x in
226/// #3274. Normalising a recognisable spelling onto a table entry is not that:
227/// the answer is still one exact table hit, and `DECAMETRES` resolves to 10,
228/// not to 1. Where no exact answer exists after normalisation, decline rather
229/// than approximate: an absent MapUnit is honest and has a defined meaning, a
230/// wrong one relocates the model.
231///
232/// Twin of `inferMapUnitScaleFromLabel` in
233/// packages/parser/src/georef-extractor.ts; both are pinned to the shared
234/// vectors in rust/core/tests/fixtures/georef_vectors.json.
235pub(crate) fn infer_map_unit_scale(label: &str) -> Option<f64> {
236 let tokens: Vec<String> = label
237 .split(|c: char| !c.is_ascii_alphanumeric())
238 .filter(|t| !t.is_empty())
239 .map(|t| t.to_ascii_uppercase())
240 .collect();
241 if tokens.is_empty() {
242 return None;
243 }
244 if is_us_survey_foot_tokens(&tokens) {
245 return Some(US_SURVEY_FOOT_M);
246 }
247
248 let key: String = tokens.concat();
249 if let Some(scale) = resolve_exact_unit_label(&key) {
250 return Some(scale);
251 }
252
253 // One English plural suffix, removed once and re-matched exactly. `ES`
254 // covers INCHES, whose singular is not reachable by dropping a single `S`.
255 for suffix in ["S", "ES"] {
256 if let Some(stem) = key.strip_suffix(suffix) {
257 if let Some(scale) = resolve_exact_unit_label(stem) {
258 return Some(scale);
259 }
260 }
261 }
262
263 None
264}