|
| 1 | +use super::measurement::*; |
| 2 | +use super::Speed; |
| 3 | +use std::time::Duration; |
| 4 | + |
| 5 | +/// The `Acceleration` struct can be used to deal with Accelerations in a common way. |
| 6 | +/// Common metric and imperial units are supported. |
| 7 | +/// |
| 8 | +/// # Example |
| 9 | +/// |
| 10 | +/// ``` |
| 11 | +/// use measurements::{Acceleration, Length, Speed}; |
| 12 | +/// use std::time::Duration; |
| 13 | +/// |
| 14 | +/// // Standing quarter mile in 10.0 dead, at 120.0 mph |
| 15 | +/// let track = Length::from_miles(0.25); |
| 16 | +/// let finish = Speed::from_miles_per_hour(120.0); |
| 17 | +/// let time = Duration::new(10, 0); |
| 18 | +/// let accel = finish / time; |
| 19 | +/// println!("You accelerated over {} at an average of {}", track, accel); |
| 20 | +/// ``` |
| 21 | +#[derive(Copy, Clone, Debug)] |
| 22 | +pub struct Acceleration { |
| 23 | + meters_per_second_per_second: f64, |
| 24 | +} |
| 25 | + |
| 26 | +impl Acceleration { |
| 27 | + pub fn from_meters_per_second_per_second(meters_per_second_per_second: f64) -> Acceleration { |
| 28 | + Acceleration { meters_per_second_per_second: meters_per_second_per_second } |
| 29 | + } |
| 30 | + |
| 31 | + pub fn from_metres_per_second_per_second(metres_per_second_per_second: f64) -> Acceleration { |
| 32 | + Acceleration::from_meters_per_second_per_second(metres_per_second_per_second) |
| 33 | + } |
| 34 | + |
| 35 | + pub fn as_meters_per_second_per_second(&self) -> f64 { |
| 36 | + self.meters_per_second_per_second |
| 37 | + } |
| 38 | + |
| 39 | + pub fn as_metres_per_second_per_second(&self) -> f64 { |
| 40 | + self.as_meters_per_second_per_second() |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +/// Acceleration * Time = Speed |
| 45 | +impl ::std::ops::Mul<Duration> for Acceleration { |
| 46 | + type Output = Speed; |
| 47 | + |
| 48 | + fn mul(self, rhs: Duration) -> Speed { |
| 49 | + // It would be useful if Duration had a method that did this... |
| 50 | + let seconds: f64 = rhs.as_secs() as f64 + ((rhs.subsec_nanos() as f64) * 1e-9); |
| 51 | + Speed::from_meters_per_second(self.as_meters_per_second_per_second() * seconds) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +/// Time * Acceleration = Speed |
| 56 | +impl ::std::ops::Mul<Acceleration> for Duration { |
| 57 | + type Output = Speed; |
| 58 | + |
| 59 | + fn mul(self, rhs: Acceleration) -> Speed { |
| 60 | + rhs * self |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +impl Measurement for Acceleration { |
| 65 | + fn get_base_units(&self) -> f64 { |
| 66 | + self.meters_per_second_per_second |
| 67 | + } |
| 68 | + |
| 69 | + fn from_base_units(units: f64) -> Self { |
| 70 | + Self::from_meters_per_second_per_second(units) |
| 71 | + } |
| 72 | + |
| 73 | + fn get_base_units_name(&self) -> &'static str { |
| 74 | + "m/s\u{00B2}" |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +implement_measurement! { Acceleration } |
0 commit comments