| Crates.io | unitscale_core |
| lib.rs | unitscale_core |
| version | 0.1.7 |
| created_at | 2025-04-11 02:09:24.174247+00 |
| updated_at | 2025-04-15 20:24:03.611786+00 |
| description | UnitScale core and traits for simplifying conversions over bus communication |
| homepage | |
| repository | https://gitlab.com/goosegrid/unitscale |
| max_upload_size | |
| id | 1629124 |
| size | 20,907 |
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.
UnitScale: Specifies the scale factor (e.g. 0.01, 1.0) used for encoding/decoding values.Scaled<U>: Abstracts access to the underlying value.UnitScaleError: Error type returned by TryFrom<f64> implementations.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
}
}