Skip to content

Commit

Permalink
🔎editoast_common: units: new staff to review
Browse files Browse the repository at this point in the history
Signed-off-by: Tristram Gräbener <[email protected]>
  • Loading branch information
Tristramg committed Dec 18, 2024
1 parent 1a3663f commit 97fb3f0
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions editoast/editoast_common/src/units.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
//! impl Train {
//! fn from_meter_per_seconds(mps: f64) -> Self {
//! Self {
//! max_speed: meter_per_second::new(f64),
//! max_speed: meter_per_second::new(mps),
//! }
//! }
//!
Expand All @@ -37,6 +37,7 @@
/// Re-export the Quantities that are used in OSRD
pub use uom::si::f64::{Acceleration, Length, Velocity};

// Todo: maybe replace with https://crates.io/crates/casey
macro_rules! quantity_to_path {
(Length, $unit:ident) => {
uom::si::length::$unit
Expand All @@ -55,6 +56,7 @@ macro_rules! define_unit {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use uom::si::f64::*;
type Unit = quantity_to_path!($quantity, $unit);
pub type ReprType = f64;

pub fn serialize<S>(value: &$quantity, serializer: S) -> Result<S::Ok, S::Error>
where
Expand All @@ -67,20 +69,25 @@ macro_rules! define_unit {
where
D: Deserializer<'de>,
{
let value = f64::deserialize(deserializer)?;
let value = ReprType::deserialize(deserializer)?;
Ok($quantity::new::<Unit>(value))
}

pub fn new(value: f64) -> $quantity {
pub fn new(value: ReprType) -> $quantity {
$quantity::new::<Unit>(value)
}

pub fn from(qty: $quantity) -> f64 {
pub fn from(qty: $quantity) -> ReprType {
qty.get::<Unit>()
}

pub fn hash<H: std::hash::Hasher>(value: &$quantity, state: &mut H) {
crate::hash_float::<5, H>(&from(*value), state);
}

pub mod option {
use super::*;
pub type ReprType = Option<super::ReprType>;

pub fn serialize<S>(
value: &Option<$quantity>,
Expand All @@ -99,6 +106,18 @@ macro_rules! define_unit {
let value = Option::deserialize(deserializer)?;
Ok(value.map(|value| $quantity::new::<Unit>(value)))
}

pub fn new(value: ReprType) -> Option<$quantity> {
value.map(|v| $quantity::new::<Unit>(v))
}

pub fn from(qty: Option<$quantity>) -> ReprType {
qty.map(|q| q.get::<Unit>())
}

pub fn hash<H: std::hash::Hasher>(value: &Option<$quantity>, state: &mut H) {
super::hash(&value.unwrap_or_default(), state);
}
}
}
};
Expand Down

0 comments on commit 97fb3f0

Please sign in to comment.