7 releases
Uses new Rust 2024
new 0.1.7 | Apr 15, 2025 |
---|---|
0.1.5 | Apr 14, 2025 |
#1333 in Embedded development
568 downloads per month
Used in 2 crates
8KB
114 lines
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
}
}
Dependencies
~225–670KB
~15K SLoC