irox_units/units/
speed.rs1use core::fmt::{Display, Formatter};
7
8use crate::units::{FromUnits, Unit};
9
10#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
13#[non_exhaustive]
14pub enum SpeedUnits {
15 #[default]
17 MetersPerSecond,
18
19 MilesPerHour,
21
22 KilometersPerHour,
24
25 Knots,
27}
28
29macro_rules! from_units_speed {
30 ($type:ident) => {
31 impl crate::units::FromUnits<$type> for SpeedUnits {
32 fn from(&self, value: $type, units: Self) -> $type {
33 match self {
34 SpeedUnits::MetersPerSecond => match units {
36 SpeedUnits::MetersPerSecond => value as $type,
38 SpeedUnits::MilesPerHour => value * MPH_TO_MPS as $type,
39 SpeedUnits::KilometersPerHour => value * KPH_TO_MPS as $type,
40 SpeedUnits::Knots => value * KNOT_TO_MPS as $type,
41 },
42 _ => todo!(),
43 }
44 }
45 }
46 };
47}
48basic_unit!(Speed, SpeedUnits, MetersPerSecond);
49from_units_speed!(f32);
50from_units_speed!(f64);
51
52impl Speed {
53 #[must_use]
54 pub fn as_meters_per_second(&self) -> Speed {
55 self.as_unit(SpeedUnits::MetersPerSecond)
56 }
57
58 #[must_use]
59 pub fn new_meters_per_second(value: f64) -> Speed {
60 Speed::new(value, SpeedUnits::MetersPerSecond)
61 }
62}
63
64impl Display for Speed {
65 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
66 write!(f, "{:0.3}m/s", self.as_meters_per_second().value)
67 }
68}
69
70pub const FPS_TO_MPS: f64 = 8.466_667E-5;
71pub const MPS_TO_FPS: f64 = 1.0 / FPS_TO_MPS;
72pub const KPH_TO_MPS: f64 = 2.777_778E-1;
73pub const MPS_TO_KPH: f64 = 1.0 / KPH_TO_MPS;
74pub const KNOT_TO_MPS: f64 = 5.144_444E-1;
75pub const MPS_TO_KNOT: f64 = 1.0 / KNOT_TO_MPS;
76pub const MPH_TO_MPS: f64 = 4.4704E-1;
77pub const MPS_TO_MPH: f64 = 1.0 / MPH_TO_MPS;