danwi 0.4.2

Zero-cost dimensional analysis library with SI units, compile-time checking, and no_std support
Documentation
//! Rational scale/offset application as `const fn`s.
//!
//! Every unit conversion reduces to
//!
//! ```text
//! x_base = (SCALE_NUM / SCALE_DEN) * x_unit + (OFFSET_NUM / OFFSET_DEN)
//! ```
//!
//! The arguments are always const-known, so pure-scale units collapse at
//! monomorphization to a single multiply or divide; offset units such as
//! Celsius pay one extra add.
//!
//! Round-trip precision: multiplying and dividing by the same constant is
//! exact for scales with denominator 1 (`kV` and up); denominator scales
//! (`mV` and down) construct by division and can round one ulp.

// The `offset_num == 0` branches matter: IEEE 754 signed zero keeps LLVM
// from folding `x + 0.0`, so without them every prefix construction would
// emit a wasted fadd. Verified in `examples/asm_check.rs`.

#[cfg(feature = "f64")]
#[inline(always)]
pub const fn to_base_f64(
    x_unit: f64,
    scale_num: i128,
    scale_den: i128,
    offset_num: i128,
    offset_den: i128,
) -> f64 {
    let scaled = x_unit * (scale_num as f64) / (scale_den as f64);
    if offset_num == 0 {
        scaled
    } else {
        scaled + (offset_num as f64) / (offset_den as f64)
    }
}

#[cfg(feature = "f64")]
#[inline(always)]
pub const fn from_base_f64(
    x_base: f64,
    scale_num: i128,
    scale_den: i128,
    offset_num: i128,
    offset_den: i128,
) -> f64 {
    let shifted = if offset_num == 0 {
        x_base
    } else {
        x_base - (offset_num as f64) / (offset_den as f64)
    };
    shifted * (scale_den as f64) / (scale_num as f64)
}

#[cfg(feature = "f32")]
#[inline(always)]
pub const fn to_base_f32(
    x_unit: f32,
    scale_num: i128,
    scale_den: i128,
    offset_num: i128,
    offset_den: i128,
) -> f32 {
    let scaled = x_unit * (scale_num as f32) / (scale_den as f32);
    if offset_num == 0 {
        scaled
    } else {
        scaled + (offset_num as f32) / (offset_den as f32)
    }
}

#[cfg(feature = "f32")]
#[inline(always)]
pub const fn from_base_f32(
    x_base: f32,
    scale_num: i128,
    scale_den: i128,
    offset_num: i128,
    offset_den: i128,
) -> f32 {
    let shifted = if offset_num == 0 {
        x_base
    } else {
        x_base - (offset_num as f32) / (offset_den as f32)
    };
    shifted * (scale_den as f32) / (scale_num as f32)
}