Skip to main content

ifc_properties/
convert.rs

1//! Conversion between units (#469): exact factors, dimensional analysis and
2//! length formatting.
3//!
4//! A [`ConversionUnit`] is a unit reduced to what conversion needs: its SI
5//! dimensional exponents and its factor into SI base units, split as an
6//! integer power of ten and a mantissa. It comes from a model
7//! ([`crate::resolve_unit`], which follows `IfcSIUnit` prefixes,
8//! `IfcConversionBasedUnit` factors and `IfcDerivedUnit` exponents through
9//! the exact, release-bound resolver), or without one from an SI name and
10//! prefix ([`ConversionUnit::si`]), a named conversion-based unit
11//! ([`ConversionUnit::named`], IFC4 Table 673 with exact factors) or text
12//! ([`ConversionUnit::parse`]). [`ConversionUnit::coherent_si`] is the
13//! coherent SI unit of given dimensions, the source of a conversion from SI
14//! values.
15//!
16//! [`unit_conversion`] between two units checks that their dimensions are
17//! equal and gives the [`UnitConversion`] that takes a value from one to the
18//! other. Units that differ only by prefixes convert by an exact power of
19//! ten: millimetres to metres divides by 1000, which `value * 0.001` does
20//! not (0.001 is not a binary fraction).
21//!
22//! # Refused
23//!
24//! - Units of different dimensions ([`UnitConversionError::DimensionMismatch`]):
25//!   an area does not convert to a length.
26//! - Monetary units ([`UnitConversionError::MonetaryUnit`]): currencies have
27//!   no fixed rate.
28//! - Context-dependent units ([`UnitConversionError::ContextDependentUnit`]):
29//!   they state no SI factor.
30//! - Conversion-based units with an offset (`IfcConversionBasedUnitWithOffset`,
31//!   degree Fahrenheit by name): where IFC4 applies the offset contradicts
32//!   its own example, so nothing applies one until buildingSMART settles it
33//!   (IFC4.x-development#1193, tracked in #110).
34//!
35//! The SI `DEGREE_CELSIUS` is the one offset unit converted: SI defines it
36//! as kelvin less 273.15, and `IfcSIUnit` states no offset to dispute. A
37//! conversion to or from it is affine ([`UnitConversion::offset`]) and is
38//! for absolute temperatures, not temperature differences.
39
40mod 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/// A unit reduced to its dimensions and its exact factor into SI base units.
56///
57/// `value_si = value * mantissa * 10^decimal_exponent + offset`.
58#[derive(Debug, Clone, PartialEq)]
59#[non_exhaustive]
60pub struct ConversionUnit {
61    /// How the unit was named: `MILLI METRE`, `foot`, or the model entity's
62    /// type and name.
63    pub name: Arc<str>,
64    /// Its `IfcUnitEnum` or `IfcDerivedUnitEnum` constant, when it has one.
65    pub unit_type: Option<Arc<str>>,
66    /// SI dimensional exponents `[L, M, T, I, Θ, N, J]`.
67    pub dimensions: [i32; 7],
68    /// See the type note.
69    pub mantissa: f64,
70    /// See the type note.
71    pub decimal_exponent: i32,
72    /// Added after scaling; nonzero only for the SI `DEGREE_CELSIUS`.
73    pub offset: f64,
74}
75
76impl ConversionUnit {
77    /// An `IfcSIUnit` by name and optional prefix, e.g. `(Some("MILLI"),
78    /// "METRE")` or `(None, "SQUARE_METRE")`.
79    ///
80    /// Names and dimensions are IFC4 ADD2 TC1's `IfcDimensionsForSiUnit`
81    /// (IFC4X3 ADD2 agrees); the unprefixed mass unit is the gram, as
82    /// `IfcSIUnit` defines it.
83    ///
84    /// # Errors
85    ///
86    /// [`UnitConversionError::UnknownPrefix`] or
87    /// [`UnitConversionError::UnknownUnit`].
88    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    /// A named conversion-based unit: an IFC4 Table 673 designation
118    /// (`inch`, `foot`, `square foot`, `gallon US`, `pound`, `degree` ...,
119    /// case-insensitive) or `US survey foot`, with the exact factors of
120    /// [`named_units`].
121    ///
122    /// # Errors
123    ///
124    /// [`UnitConversionError::OffsetUnit`] for degree Fahrenheit (#110),
125    /// [`UnitConversionError::UnknownUnit`] for any other name.
126    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    /// A unit from text: an SI unit, with its prefix written before it
140    /// (`METRE`, `MILLIMETRE`, `MILLI METRE`, `MILLI_METRE`, `square
141    /// millimetre`, `CUBIC_METRE`, `KILOGRAM`; `METER` spellings accepted),
142    /// or a named conversion-based unit ([`Self::named`]). Case-insensitive.
143    ///
144    /// A prefix joined to a square or cubic name applies before the power,
145    /// as in IFC: `MILLI SQUARE_METRE` and `SQUARE_MILLIMETRE` are both
146    /// mm².
147    ///
148    /// # Errors
149    ///
150    /// As [`Self::si`] and [`Self::named`].
151    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    /// The coherent SI unit of `dimensions`: factor 1 into SI base units, no
175    /// offset. A value in it is the SI value itself, so
176    /// [`unit_conversion`] from it takes SI input into any unit of the same
177    /// dimensions.
178    #[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    /// The factor into SI base units, `mantissa * 10^decimal_exponent`.
191    #[must_use]
192    pub fn scale(&self) -> f64 {
193        shift(self.mantissa, self.decimal_exponent)
194    }
195
196    /// Whether this is a length unit (dimensions `[1, 0, 0, 0, 0, 0, 0]`).
197    #[must_use]
198    pub fn is_length(&self) -> bool {
199        self.dimensions == [1, 0, 0, 0, 0, 0, 0]
200    }
201}
202
203/// The `IfcUnitEnum` constant an SI name belongs to when that is unique.
204fn 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
239/// `IfcSIPrefix` constants. No constant is a prefix of another, so the
240/// order does not matter.
241const PREFIXES: [&str; 16] = [
242    "EXA", "PETA", "TERA", "GIGA", "MEGA", "KILO", "HECTO", "DECA", "DECI", "CENTI", "MILLI",
243    "MICRO", "NANO", "PICO", "FEMTO", "ATTO",
244];
245
246/// An SI unit as `(prefix, name)`, or `None` when the text is not one.
247fn 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    // `SQUARE_MILLIMETRE`, `CUBIC_CENTIMETRE`: the power first.
261    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/// How a value in one unit becomes a value in another:
283/// `to = from * numerator / denominator * 10^decimal_exponent + offset`.
284///
285/// The numerator and denominator are the two units' mantissas, kept apart
286/// so that a conversion to or from a unit whose mantissa is 1 (every SI
287/// unit) rounds once: millimetres to inches divides by 254 instead of
288/// multiplying by the rounded `1/254`.
289#[derive(Debug, Clone, Copy, PartialEq)]
290#[non_exhaustive]
291pub struct UnitConversion {
292    /// The mantissa of the unit converted from.
293    pub numerator: f64,
294    /// The mantissa of the unit converted to.
295    pub denominator: f64,
296    /// The power of ten between the two units.
297    pub decimal_exponent: i32,
298    /// Added after scaling; nonzero only to or from the SI
299    /// `DEGREE_CELSIUS`.
300    pub offset: f64,
301}
302
303impl UnitConversion {
304    /// The identity.
305    pub const IDENTITY: Self = Self {
306        numerator: 1.0,
307        denominator: 1.0,
308        decimal_exponent: 0,
309        offset: 0.0,
310    };
311
312    /// Convert one value. A power of ten up to 10^22 is exact in `f64`, so
313    /// it is applied as one correctly rounded multiplication or division.
314    #[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    /// The multiplicative factor, `numerator / denominator *
329    /// 10^decimal_exponent`.
330    #[must_use]
331    pub fn factor(&self) -> f64 {
332        self.apply(1.0) - self.offset
333    }
334
335    /// The conversion raised to an integer power: the factor between the
336    /// squares (`2`) or cubes (`3`) of two units. `None` when the
337    /// conversion has an offset, which has no power.
338    #[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    /// The conversion back.
349    #[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    /// Whether the conversion changes nothing.
363    #[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
369/// `(mantissa, exponent)` with the mantissa scaled to the smallest integer
370/// that still states the same `f64` (`0.3048, 0` becomes `3048, -4`), so
371/// that a factor read from a file and the same factor written as an integer
372/// convert into each other exactly. A mantissa whose decimal form does not
373/// terminate within 15 digits is kept as it is.
374pub(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
390/// `value * 10^exponent`, exactly rounded while `10^|exponent|` is exact.
391pub(crate) fn shift(value: f64, exponent: i32) -> f64 {
392    // 10^22 is the largest power of ten an f64 holds exactly.
393    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
401/// The conversion taking a value in `from` to a value in `to`.
402///
403/// # Errors
404///
405/// [`UnitConversionError::DimensionMismatch`] when the two units measure
406/// different quantities.
407pub 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    // value_si = v_from * s_from + o_from = v_to * s_to + o_to
419    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
432/// Convert `value` from one unit to another.
433///
434/// # Errors
435///
436/// As [`unit_conversion`], and [`UnitConversionError::NonFinite`] for a
437/// value that is not finite.
438pub 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/// Why a conversion was refused.
450#[derive(Debug, Clone, PartialEq)]
451#[non_exhaustive]
452pub enum UnitConversionError {
453    /// The model's unit could not be resolved exactly (missing, malformed,
454    /// cyclic, an `IfcConversionBasedUnitWithOffset` ...): see
455    /// [`ExactUnitError`].
456    Resolve(ExactUnitError),
457    /// The two units measure different quantities.
458    DimensionMismatch {
459        /// Dimensions of the unit converted from.
460        from: [i32; 7],
461        /// Dimensions of the unit converted to.
462        to: [i32; 7],
463    },
464    /// An `IfcMonetaryUnit`: currencies have no fixed conversion.
465    MonetaryUnit {
466        /// The unit entity.
467        unit: EntityId,
468    },
469    /// An `IfcContextDependentUnit`: it states no factor into SI.
470    ContextDependentUnit {
471        /// The unit entity.
472        unit: EntityId,
473    },
474    /// A conversion-based unit with an offset, refused until buildingSMART
475    /// settles where `ConversionOffset` applies (IFC4.x-development#1193,
476    /// tracked in #110).
477    OffsetUnit {
478        /// The unit as named.
479        name: Arc<str>,
480        /// The unit entity, for a unit read from a model.
481        unit: Option<EntityId>,
482    },
483    /// Text that names no SI unit and no named conversion-based unit.
484    UnknownUnit {
485        /// The text.
486        spec: Arc<str>,
487    },
488    /// An SI prefix that is not an `IfcSIPrefix` constant.
489    UnknownPrefix {
490        /// The prefix as given.
491        prefix: Arc<str>,
492    },
493    /// A value that is not finite.
494    NonFinite {
495        /// The value.
496        value: f64,
497    },
498    /// A formatting request that cannot be met, such as a zero fraction
499    /// denominator.
500    InvalidFormat {
501        /// Why.
502        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        // value * 0.001 is not always the correctly rounded quotient.
571        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        // The square of the foot-to-metre conversion is the square foot's.
638        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}