danwi 0.4.2

Zero-cost dimensional analysis library with SI units, compile-time checking, and no_std support
Documentation
use super::Quantity;
use crate::{dimension::Dimensions, scalar::Scalar, unit::UnitDef};
use core::{fmt, marker::PhantomData};

/// `Display` for `Quantity` prints just the base-unit value; it does not
/// append a unit symbol. Use [`Quantity::display_as`] to format a specific
/// unit representation.
impl<S: Scalar, D: Dimensions, K> fmt::Display for Quantity<S, D, K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.value, f)
    }
}

/// A formatting adapter built by [`Quantity::display_as`]. It renders the
/// value converted to the unit `M`, followed by the unit's symbol
/// (`"10.5 kV"`, `"25 °C"`).
pub struct UnitDisplay<S, M>
where
    S: Scalar,
    M: UnitDef,
{
    pub(crate) value: S,
    pub(crate) _phantom: PhantomData<M>,
}

impl<S, M> Clone for UnitDisplay<S, M>
where
    S: Scalar,
    M: UnitDef,
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<S, M> Copy for UnitDisplay<S, M>
where
    S: Scalar,
    M: UnitDef,
{
}

#[cfg(feature = "f32")]
impl<M: UnitDef> fmt::Display for UnitDisplay<f32, M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let scaled = crate::scalar::from_base_f32(
            self.value,
            M::SCALE_NUM,
            M::SCALE_DEN,
            M::OFFSET_NUM,
            M::OFFSET_DEN,
        );
        // Delegate to the float's `Display` so the user's precision/width
        // format specifiers are preserved for the numeric portion.
        fmt::Display::fmt(&scaled, f)?;
        write!(f, " {}{}", M::PREFIX, M::SYMBOL)
    }
}

#[cfg(feature = "f64")]
impl<M: UnitDef> fmt::Display for UnitDisplay<f64, M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let scaled = crate::scalar::from_base_f64(
            self.value,
            M::SCALE_NUM,
            M::SCALE_DEN,
            M::OFFSET_NUM,
            M::OFFSET_DEN,
        );
        fmt::Display::fmt(&scaled, f)?;
        write!(f, " {}{}", M::PREFIX, M::SYMBOL)
    }
}