libhaystack 3.2.2

Rust implementation of the Haystack 4 data types, defs, filter, units, and encodings
Documentation
// Copyright (C) 2020 - 2022, J2 Innovations

//! Haystack Units module

pub mod unit;
pub mod unit_dimension;
#[cfg(feature = "units-db")]
pub mod units_generated;

use std::borrow::Cow;

pub use unit::Unit;
pub use unit_dimension::UnitDimensions;

/// The dimensionless default unit
pub static DEFAULT_UNIT: Unit = Unit {
    quantity: None,
    ids: Cow::Borrowed(&[]),
    dimensions: None,
    scale: 0.0,
    offset: 0.0,
};

/// Get unit by name, if it is defined in the units database
#[allow(unused_variables)]
pub fn get_unit(unit: &str) -> Option<&'static Unit> {
    #[cfg(feature = "units-db")]
    {
        units_generated::UNITS.get(unit).copied()
    }
    #[cfg(not(feature = "units-db"))]
    return None;
}

/// Tries to get the unit by name, if none is found, return a default unit
pub fn get_unit_or_default(unit: &str) -> &'static Unit {
    get_unit(unit).unwrap_or(&DEFAULT_UNIT)
}

/// Match units for the dimension
///
/// Returns each distinct unit (by identity) whose dimension and scale match. A unit that is
/// registered under more than one name/symbol (e.g. `square_inch` is keyed by both
/// `"square_inch"` and `"in²"`) previously appeared multiple times in the result -- once per
/// alias -- causing callers (e.g. [`crate::units::unit::Unit`]'s `Mul`/`Div` operators) to
/// spuriously treat an unambiguous match as ambiguous. Matches are now deduplicated by pointer
/// identity so each unit is returned at most once regardless of how many aliases it has.
#[allow(unused_variables)]
pub fn match_units(dim: UnitDimensions, scale: f64) -> Vec<&'static Unit> {
    #[cfg(feature = "units-db")]
    {
        let mut matches: Vec<&'static Unit> = Vec::new();
        for u in units_generated::UNITS.values() {
            if u.dimensions.as_ref() == Some(&dim)
                && approx_eq(u.scale, scale)
                && !matches.iter().any(|m| std::ptr::eq(*m, *u))
            {
                matches.push(u);
            }
        }
        matches
    }
    #[cfg(not(feature = "units-db"))]
    return Vec::default();
}

#[cfg(feature = "units-db")]
fn approx_eq(a: f64, b: f64) -> bool {
    if a == b {
        return true;
    }
    let min_precision = f64::min(f64::abs(a / 1e3), f64::abs(b / 1e3));
    f64::abs(a - b) <= min_precision
}