1mod format;
41mod named;
42
43use std::fmt;
44use std::sync::Arc;
45
46use ifc_model::EntityId;
47
48use crate::exact::ExactUnitError;
49use crate::unit::prefix_exponent;
50use crate::unit::si::{si_decimal_exponent, si_name_dimensions, si_to_base};
51
52pub use format::{format_length, LengthFormat};
53pub use named::{named_units, NamedUnit};
54
55#[derive(Debug, Clone, PartialEq)]
59#[non_exhaustive]
60pub struct ConversionUnit {
61 pub name: Arc<str>,
64 pub unit_type: Option<Arc<str>>,
66 pub dimensions: [i32; 7],
68 pub mantissa: f64,
70 pub decimal_exponent: i32,
72 pub offset: f64,
74}
75
76impl ConversionUnit {
77 pub fn si(prefix: Option<&str>, name: &str) -> Result<Self, UnitConversionError> {
89 let upper = name.trim().to_ascii_uppercase().replace("METER", "METRE");
90 let dimensions = si_name_dimensions(ifc_schema::SchemaVersion::Ifc4, &upper)
91 .ok_or_else(|| UnitConversionError::UnknownUnit { spec: name.into() })?;
92 let exponent = match prefix {
93 None => 0,
94 Some(prefix) => {
95 prefix_exponent(&prefix.trim().to_ascii_uppercase()).ok_or_else(|| {
96 UnitConversionError::UnknownPrefix {
97 prefix: prefix.into(),
98 }
99 })?
100 }
101 };
102 let (_, offset) = si_to_base(exponent, &upper);
103 let name = match prefix {
104 Some(prefix) => format!("{} {upper}", prefix.trim().to_ascii_uppercase()),
105 None => upper.clone(),
106 };
107 Ok(Self {
108 name: name.into(),
109 unit_type: si_unit_type(&upper).map(Into::into),
110 dimensions,
111 mantissa: 1.0,
112 decimal_exponent: si_decimal_exponent(exponent, &upper),
113 offset,
114 })
115 }
116
117 pub fn named(name: &str) -> Result<Self, UnitConversionError> {
127 if let Some(unit) = named::named_unit(name) {
128 return Ok(Self::from_named(unit));
129 }
130 if named::OFFSET_UNIT_NAMES.contains(&named::normalise(name).as_str()) {
131 return Err(UnitConversionError::OffsetUnit {
132 name: name.into(),
133 unit: None,
134 });
135 }
136 Err(UnitConversionError::UnknownUnit { spec: name.into() })
137 }
138
139 pub fn parse(spec: &str) -> Result<Self, UnitConversionError> {
152 if let Some((prefix, name)) = split_si(spec) {
153 return Self::si(prefix.as_deref(), &name);
154 }
155 Self::named(spec).map_err(|error| match error {
156 UnitConversionError::UnknownUnit { .. } => {
157 UnitConversionError::UnknownUnit { spec: spec.into() }
158 }
159 other => other,
160 })
161 }
162
163 pub(crate) fn from_named(unit: &NamedUnit) -> Self {
164 Self {
165 name: unit.name.into(),
166 unit_type: Some(unit.unit_type.into()),
167 dimensions: unit.dimensions,
168 mantissa: unit.mantissa,
169 decimal_exponent: unit.decimal_exponent,
170 offset: 0.0,
171 }
172 }
173
174 #[must_use]
179 pub fn coherent_si(dimensions: [i32; 7]) -> Self {
180 Self {
181 name: "coherent SI".into(),
182 unit_type: None,
183 dimensions,
184 mantissa: 1.0,
185 decimal_exponent: 0,
186 offset: 0.0,
187 }
188 }
189
190 #[must_use]
192 pub fn scale(&self) -> f64 {
193 shift(self.mantissa, self.decimal_exponent)
194 }
195
196 #[must_use]
198 pub fn is_length(&self) -> bool {
199 self.dimensions == [1, 0, 0, 0, 0, 0, 0]
200 }
201}
202
203fn si_unit_type(name: &str) -> Option<&'static str> {
205 Some(match name {
206 "METRE" => "LENGTHUNIT",
207 "SQUARE_METRE" => "AREAUNIT",
208 "CUBIC_METRE" => "VOLUMEUNIT",
209 "GRAM" => "MASSUNIT",
210 "SECOND" => "TIMEUNIT",
211 "AMPERE" => "ELECTRICCURRENTUNIT",
212 "KELVIN" | "DEGREE_CELSIUS" => "THERMODYNAMICTEMPERATUREUNIT",
213 "MOLE" => "AMOUNTOFSUBSTANCEUNIT",
214 "CANDELA" => "LUMINOUSINTENSITYUNIT",
215 "LUMEN" => "LUMINOUSFLUXUNIT",
216 "RADIAN" => "PLANEANGLEUNIT",
217 "STERADIAN" => "SOLIDANGLEUNIT",
218 "HERTZ" => "FREQUENCYUNIT",
219 "BECQUEREL" => "RADIOACTIVITYUNIT",
220 "NEWTON" => "FORCEUNIT",
221 "PASCAL" => "PRESSUREUNIT",
222 "JOULE" => "ENERGYUNIT",
223 "WATT" => "POWERUNIT",
224 "COULOMB" => "ELECTRICCHARGEUNIT",
225 "VOLT" => "ELECTRICVOLTAGEUNIT",
226 "FARAD" => "ELECTRICCAPACITANCEUNIT",
227 "OHM" => "ELECTRICRESISTANCEUNIT",
228 "SIEMENS" => "ELECTRICCONDUCTANCEUNIT",
229 "WEBER" => "MAGNETICFLUXUNIT",
230 "TESLA" => "MAGNETICFLUXDENSITYUNIT",
231 "HENRY" => "INDUCTANCEUNIT",
232 "LUX" => "ILLUMINANCEUNIT",
233 "GRAY" => "ABSORBEDDOSEUNIT",
234 "SIEVERT" => "DOSEEQUIVALENTUNIT",
235 _ => return None,
236 })
237}
238
239const PREFIXES: [&str; 16] = [
242 "EXA", "PETA", "TERA", "GIGA", "MEGA", "KILO", "HECTO", "DECA", "DECI", "CENTI", "MILLI",
243 "MICRO", "NANO", "PICO", "FEMTO", "ATTO",
244];
245
246fn split_si(spec: &str) -> Option<(Option<String>, String)> {
248 let normal: String = spec
249 .trim()
250 .to_ascii_uppercase()
251 .replace("METER", "METRE")
252 .split(|c: char| c.is_whitespace() || c == '_')
253 .filter(|part| !part.is_empty())
254 .collect::<Vec<_>>()
255 .join("_");
256 let is_si = |name: &str| si_name_dimensions(ifc_schema::SchemaVersion::Ifc4, name).is_some();
257 if is_si(&normal) {
258 return Some((None, normal));
259 }
260 for power in ["SQUARE_", "CUBIC_"] {
262 if let Some(rest) = normal.strip_prefix(power) {
263 if let Some((prefix, base)) = strip_prefix(rest) {
264 let name = format!("{power}{base}");
265 if is_si(&name) {
266 return Some((Some(prefix.to_owned()), name));
267 }
268 }
269 }
270 }
271 let (prefix, rest) = strip_prefix(&normal)?;
272 let rest = rest.trim_start_matches('_');
273 is_si(rest).then(|| (Some(prefix.to_owned()), rest.to_owned()))
274}
275
276fn strip_prefix(text: &str) -> Option<(&'static str, &str)> {
277 PREFIXES
278 .iter()
279 .find_map(|prefix| text.strip_prefix(prefix).map(|rest| (*prefix, rest)))
280}
281
282#[derive(Debug, Clone, Copy, PartialEq)]
290#[non_exhaustive]
291pub struct UnitConversion {
292 pub numerator: f64,
294 pub denominator: f64,
296 pub decimal_exponent: i32,
298 pub offset: f64,
301}
302
303impl UnitConversion {
304 pub const IDENTITY: Self = Self {
306 numerator: 1.0,
307 denominator: 1.0,
308 decimal_exponent: 0,
309 offset: 0.0,
310 };
311
312 #[must_use]
315 pub fn apply(&self, value: f64) -> f64 {
316 let mut scaled = value;
317 if self.numerator != self.denominator {
318 if self.numerator != 1.0 {
319 scaled *= self.numerator;
320 }
321 if self.denominator != 1.0 {
322 scaled /= self.denominator;
323 }
324 }
325 shift(scaled, self.decimal_exponent) + self.offset
326 }
327
328 #[must_use]
331 pub fn factor(&self) -> f64 {
332 self.apply(1.0) - self.offset
333 }
334
335 #[must_use]
339 pub fn powi(&self, exponent: i32) -> Option<Self> {
340 (self.offset == 0.0).then(|| Self {
341 numerator: self.numerator.powi(exponent),
342 denominator: self.denominator.powi(exponent),
343 decimal_exponent: self.decimal_exponent * exponent,
344 offset: 0.0,
345 })
346 }
347
348 #[must_use]
350 pub fn inverse(&self) -> Self {
351 Self {
352 numerator: self.denominator,
353 denominator: self.numerator,
354 decimal_exponent: -self.decimal_exponent,
355 offset: -shift(
356 self.offset * self.denominator / self.numerator,
357 -self.decimal_exponent,
358 ),
359 }
360 }
361
362 #[must_use]
364 pub fn is_identity(&self) -> bool {
365 self.numerator == self.denominator && self.decimal_exponent == 0 && self.offset == 0.0
366 }
367}
368
369pub(crate) fn normalise_decimal(mantissa: f64, exponent: i32) -> (f64, i32) {
375 if !mantissa.is_finite() || mantissa == 0.0 || mantissa.fract() == 0.0 {
376 return (mantissa, exponent);
377 }
378 for digits in 1..=15 {
379 let integer = shift(mantissa, digits).round();
380 if integer.abs() >= 9_007_199_254_740_992.0 {
381 break;
382 }
383 if shift(integer, -digits) == mantissa {
384 return (integer, exponent - digits);
385 }
386 }
387 (mantissa, exponent)
388}
389
390pub(crate) fn shift(value: f64, exponent: i32) -> f64 {
392 match exponent {
394 0 => value,
395 1..=22 => value * 10f64.powi(exponent),
396 -22..=-1 => value / 10f64.powi(-exponent),
397 _ => value * 10f64.powi(exponent),
398 }
399}
400
401pub fn unit_conversion(
408 from: &ConversionUnit,
409 to: &ConversionUnit,
410) -> Result<UnitConversion, UnitConversionError> {
411 if from.dimensions != to.dimensions {
412 return Err(UnitConversionError::DimensionMismatch {
413 from: from.dimensions,
414 to: to.dimensions,
415 });
416 }
417 let decimal_exponent = from.decimal_exponent - to.decimal_exponent;
418 let offset = if from.offset == to.offset {
420 0.0
421 } else {
422 (from.offset - to.offset) / to.scale()
423 };
424 Ok(UnitConversion {
425 numerator: from.mantissa,
426 denominator: to.mantissa,
427 decimal_exponent,
428 offset,
429 })
430}
431
432pub fn convert_value(
439 value: f64,
440 from: &ConversionUnit,
441 to: &ConversionUnit,
442) -> Result<f64, UnitConversionError> {
443 if !value.is_finite() {
444 return Err(UnitConversionError::NonFinite { value });
445 }
446 Ok(unit_conversion(from, to)?.apply(value))
447}
448
449#[derive(Debug, Clone, PartialEq)]
451#[non_exhaustive]
452pub enum UnitConversionError {
453 Resolve(ExactUnitError),
457 DimensionMismatch {
459 from: [i32; 7],
461 to: [i32; 7],
463 },
464 MonetaryUnit {
466 unit: EntityId,
468 },
469 ContextDependentUnit {
471 unit: EntityId,
473 },
474 OffsetUnit {
478 name: Arc<str>,
480 unit: Option<EntityId>,
482 },
483 UnknownUnit {
485 spec: Arc<str>,
487 },
488 UnknownPrefix {
490 prefix: Arc<str>,
492 },
493 NonFinite {
495 value: f64,
497 },
498 InvalidFormat {
501 reason: &'static str,
503 },
504}
505
506impl From<ExactUnitError> for UnitConversionError {
507 fn from(error: ExactUnitError) -> Self {
508 match error {
509 ExactUnitError::UnsupportedOffset { unit } => Self::OffsetUnit {
510 name: "IfcConversionBasedUnitWithOffset".into(),
511 unit: Some(unit),
512 },
513 other => Self::Resolve(other),
514 }
515 }
516}
517
518impl fmt::Display for UnitConversionError {
519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520 match self {
521 Self::Resolve(error) => write!(f, "{error}"),
522 Self::DimensionMismatch { from, to } => write!(
523 f,
524 "units of different dimensions do not convert: {from:?} to {to:?}"
525 ),
526 Self::MonetaryUnit { unit } => {
527 write!(
528 f,
529 "#{} is a monetary unit, which has no fixed conversion",
530 unit.0
531 )
532 }
533 Self::ContextDependentUnit { unit } => write!(
534 f,
535 "#{} is a context-dependent unit, which states no SI factor",
536 unit.0
537 ),
538 Self::OffsetUnit { name, .. } => write!(
539 f,
540 "{name} carries an offset, which is not applied until buildingSMART settles \
541 where it applies (IFC4.x-development#1193, openbimrs/ifc#110)"
542 ),
543 Self::UnknownUnit { spec } => write!(f, "{spec:?} names no unit this crate converts"),
544 Self::UnknownPrefix { prefix } => write!(f, "{prefix:?} is not an IfcSIPrefix"),
545 Self::NonFinite { value } => write!(f, "{value} is not a finite value"),
546 Self::InvalidFormat { reason } => write!(f, "invalid length format: {reason}"),
547 }
548 }
549}
550
551impl std::error::Error for UnitConversionError {}
552
553#[cfg(test)]
554mod tests {
555 use super::*;
556
557 fn parse(spec: &str) -> ConversionUnit {
558 ConversionUnit::parse(spec).unwrap_or_else(|error| panic!("{spec}: {error}"))
559 }
560
561 #[test]
562 fn prefixed_si_units_convert_by_an_exact_power_of_ten() {
563 let mm = parse("MILLIMETRE");
564 let m = parse("metre");
565 let conversion = unit_conversion(&mm, &m).unwrap();
566 assert_eq!(conversion.numerator, conversion.denominator);
567 assert_eq!(conversion.decimal_exponent, -3);
568 assert_eq!(conversion.apply(1234.0), 1.234);
569 assert_eq!(unit_conversion(&m, &mm).unwrap().apply(1.234), 1234.0);
570 assert_ne!(9.0 * 0.001, 0.009);
572 assert_eq!(conversion.apply(9.0), 0.009);
573 }
574
575 #[test]
576 fn the_coherent_si_unit_has_factor_one() {
577 let length = ConversionUnit::coherent_si([1, 0, 0, 0, 0, 0, 0]);
578 let to = |from: &ConversionUnit, spec: &str| unit_conversion(from, &parse(spec)).unwrap();
579 assert_eq!(to(&length, "MILLIMETRE").apply(1.234), 1234.0);
580 assert!(to(&length, "METRE").is_identity());
581 let mass = ConversionUnit::coherent_si([0, 1, 0, 0, 0, 0, 0]);
582 assert!(to(&mass, "KILOGRAM").is_identity());
583 assert_eq!(to(&mass, "GRAM").apply(2.5), 2500.0);
584 let kelvin = ConversionUnit::coherent_si([0, 0, 0, 0, 1, 0, 0]);
585 assert_eq!(
586 convert_value(273.15, &kelvin, &parse("DEGREE_CELSIUS")).unwrap(),
587 0.0
588 );
589 assert!(matches!(
590 unit_conversion(&length, &parse("SQUARE_METRE")),
591 Err(UnitConversionError::DimensionMismatch { .. })
592 ));
593 }
594
595 #[test]
596 fn spellings_of_an_si_unit_agree() {
597 let expected = parse("MILLIMETRE");
598 for spec in ["MILLI METRE", "milli_metre", "Millimeter", " MILLI METRE "] {
599 assert_eq!(
600 parse(spec).decimal_exponent,
601 expected.decimal_exponent,
602 "{spec}"
603 );
604 assert_eq!(parse(spec).dimensions, expected.dimensions, "{spec}");
605 }
606 let mm2 = parse("SQUARE_MILLIMETRE");
607 assert_eq!(mm2.dimensions, [2, 0, 0, 0, 0, 0, 0]);
608 assert_eq!(mm2.decimal_exponent, -6);
609 assert_eq!(
610 parse("MILLI SQUARE_METRE"),
611 ConversionUnit {
612 name: "MILLI SQUARE_METRE".into(),
613 ..mm2
614 }
615 );
616 assert_eq!(parse("cubic centimetre").decimal_exponent, -6);
617 assert_eq!(parse("KILOGRAM").decimal_exponent, 0);
618 assert_eq!(parse("GRAM").decimal_exponent, -3);
619 assert_eq!(parse("DECAMETRE").decimal_exponent, 1);
620 assert_eq!(parse("DECIMETRE").decimal_exponent, -1);
621 }
622
623 #[test]
624 fn imperial_units_convert_exactly() {
625 let inch = parse("inch");
626 let foot = parse("foot");
627 let mm = parse("MILLIMETRE");
628 assert_eq!(convert_value(1.0, &inch, &mm).unwrap(), 25.4);
629 assert_eq!(convert_value(1.0, &foot, &mm).unwrap(), 304.8);
630 assert_eq!(convert_value(12.0, &inch, &foot).unwrap(), 1.0);
631 assert_eq!(
632 convert_value(1.0, &parse("mile"), &parse("METRE")).unwrap(),
633 1609.344
634 );
635 let sq = unit_conversion(&parse("square foot"), &parse("SQUARE_METRE")).unwrap();
636 assert_eq!(sq.factor(), 0.09290304);
637 let length = unit_conversion(&foot, &parse("METRE")).unwrap();
639 assert_eq!(length.powi(2).unwrap().factor(), sq.factor());
640 }
641
642 #[test]
643 fn units_of_different_dimensions_are_refused() {
644 let error = unit_conversion(&parse("METRE"), &parse("SQUARE_METRE")).unwrap_err();
645 assert_eq!(normalise_decimal(0.3048, 0), (3048.0, -4));
646 assert_eq!(normalise_decimal(25.4, -3), (254.0, -4));
647 assert_eq!(normalise_decimal(1.0 / 3.0, 0), (1.0 / 3.0, 0));
648 assert_eq!(
649 error,
650 UnitConversionError::DimensionMismatch {
651 from: [1, 0, 0, 0, 0, 0, 0],
652 to: [2, 0, 0, 0, 0, 0, 0]
653 }
654 );
655 assert!(unit_conversion(&parse("pound"), &parse("NEWTON")).is_err());
656 assert!(unit_conversion(&parse("lbf"), &parse("KILONEWTON")).is_ok());
657 }
658
659 #[test]
660 fn offset_units_are_refused_by_name_and_celsius_is_affine() {
661 assert!(matches!(
662 ConversionUnit::parse("degree Fahrenheit"),
663 Err(UnitConversionError::OffsetUnit { .. })
664 ));
665 let celsius = parse("DEGREE_CELSIUS");
666 let kelvin = parse("KELVIN");
667 assert_eq!(convert_value(0.0, &celsius, &kelvin).unwrap(), 273.15);
668 assert_eq!(convert_value(273.15, &kelvin, &celsius).unwrap(), 0.0);
669 assert_eq!(unit_conversion(&celsius, &kelvin).unwrap().powi(2), None);
670 }
671
672 #[test]
673 fn unknown_text_is_refused() {
674 assert!(matches!(
675 ConversionUnit::parse("furlong"),
676 Err(UnitConversionError::UnknownUnit { .. })
677 ));
678 assert!(matches!(
679 ConversionUnit::si(Some("MICROSCOPIC"), "METRE"),
680 Err(UnitConversionError::UnknownPrefix { .. })
681 ));
682 assert!(matches!(
683 convert_value(f64::NAN, &parse("METRE"), &parse("METRE")),
684 Err(UnitConversionError::NonFinite { .. })
685 ));
686 }
687}