unitscale_core

Crates.iounitscale_core
lib.rsunitscale_core
version0.1.7
created_at2025-04-11 02:09:24.174247+00
updated_at2025-04-15 20:24:03.611786+00
descriptionUnitScale core and traits for simplifying conversions over bus communication
homepage
repositoryhttps://gitlab.com/goosegrid/unitscale
max_upload_size
id1629124
size20,907
David Kalliecharan (ddkn)

documentation

https://docs.rs/unitscale_core

README

unitscale_core

Overview

unitscale_core provides foundational traits and error types for working with statically-scaled numeric units in embedded protocols, like CAN bus or OBD2. This crate is designed to be lightweight, stable, and usable without procedural macros. It can be used on its own, or in combination with unitscale_macros to generate scalable unit types.

Key Exports

  • trait UnitScale: Specifies the scale factor (e.g. 0.01, 1.0) used for encoding/decoding values.
  • trait Scaled<U>: Abstracts access to the underlying value.
  • struct UnitScaleError: Error type returned by TryFrom<f64> implementations.

Example

use unitscale_core::{UnitScale, Scaled, UnitScaleError};
use num_traits::FromPrimitive;
use core::marker::PhantomData;

struct Scale0_1;

impl UnitScale for Scale0_1 {
    const SCALE: f64 = 0.1;
}

struct Volts<S, U> {
    value: U,
    _scale: std::marker::PhantomData<S>,
}

impl<S, U> TryFrom<f64> for Volts<S, U>
where
    S: UnitScale,
    U: FromPrimitive,
{
    type Error = UnitScaleError;
    fn try_from(value: f64) -> Result<Self, Self::Error> {
        let scaled_value = value / S::SCALE;
        if let Some(value) = U::from_f64(scaled_value) {
            Ok(Self {
                value,
                _scale: PhantomData,
            })
        } else {
            Err(UnitScaleError::Conversion(format!(
                "Scaled {} is outside of {} bounds",
                scaled_value,
                std::any::type_name::<U>()
            )))
        }
    }
}

impl<S, U> Scaled<U> for Volts<S, U>
where
    S: UnitScale,
    U: Copy,
{
    fn scaled_value(&self) -> U {
        self.value
    }
}
Commit count: 24

cargo fmt