Skip to main content

Crate unitscale_core

Crate unitscale_core 

Source
Expand description

§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 UnitScaleF32: 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<f32> implementations.

§Example

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

struct Scale0_1;

impl UnitScaleF32 for Scale0_1 {
    const SCALE: f32 = 0.1;
}

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

impl<S, U> TryFrom<f32> for Volts<S, U>
where
    S: UnitScaleF32,
    U: FromPrimitive,
{
    type Error = UnitScaleError;
    fn try_from(value: f32) -> Result<Self, Self::Error> {
        let scaled_value = value / S::SCALE;
        if let Some(value) = U::from_f32(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: UnitScaleF32,
    U: Copy,
{
    fn scaled_value(&self) -> U {
        self.value
    }
}

Enums§

UnitScaleError
Errors relating to data conversion

Traits§

Scaled
Trait for custom data type for data transfers over various bus interfaces
ScaledPrimitiveByteSize
UnitScaleF32
Trait for setting a f32 scale of a custom data type for data transfers
UnitScaleF64
Trait for setting a f64 scale of a custom data type for data transfers