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
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 byTryFrom<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
}
}Enums§
- Unit
Scale Error - Errors relating to data conversion
Traits§
- Scaled
- Trait for custom data type for data transfers over various bus interfaces
- Scaled
Primitive Byte Size - Unit
Scale - Trait for setting a scale of a custom data type for data transfers