|
| 1 | +//! Types and constants for handling angles |
| 2 | +
|
| 3 | +use super::measurement::*; |
| 4 | +use ::std::f64::consts::PI; |
| 5 | + |
| 6 | +/// The 'Angle' struct can be used to deal with angles in a common way. |
| 7 | +/// |
| 8 | +/// # Example |
| 9 | +/// |
| 10 | +/// ``` |
| 11 | +/// use measurements::Angle; |
| 12 | +/// |
| 13 | +/// let whole_cake = Angle::from_degrees(360.0); |
| 14 | +/// let pieces = 6.0; |
| 15 | +/// let slice = whole_cake / pieces; |
| 16 | +/// println!("Each slice will be {} degrees", slice.as_degrees()); |
| 17 | +/// ``` |
| 18 | +#[derive(Copy, Clone, Debug)] |
| 19 | +pub struct Angle { |
| 20 | + radians: f64, |
| 21 | +} |
| 22 | + |
| 23 | +/// Number of degrees in a radian |
| 24 | +pub const RADIAN_DEGREE_FACTOR: f64 = 180.0 / PI; |
| 25 | + |
| 26 | +impl Angle { |
| 27 | + |
| 28 | + /// Create a new Angle from a floating point value in degrees |
| 29 | + pub fn from_degrees(degrees: f64) -> Self { |
| 30 | + Angle::from_radians(degrees / RADIAN_DEGREE_FACTOR) |
| 31 | + } |
| 32 | + |
| 33 | + /// Create a new Angle from a floating point value in radians |
| 34 | + pub fn from_radians(radians: f64) -> Self { |
| 35 | + Angle { radians: radians } |
| 36 | + } |
| 37 | + |
| 38 | + /// Convert this Angle to a floating point value in degrees |
| 39 | + pub fn as_degrees(&self) -> f64 { |
| 40 | + self.radians * RADIAN_DEGREE_FACTOR |
| 41 | + } |
| 42 | + |
| 43 | + /// Convert this Angle to a floating point value in radians |
| 44 | + pub fn as_radians(&self) -> f64 { |
| 45 | + self.radians |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl Measurement for Angle { |
| 50 | + fn as_base_units(&self) -> f64 { |
| 51 | + self.radians |
| 52 | + } |
| 53 | + |
| 54 | + fn from_base_units(units: f64) -> Self { |
| 55 | + Self::from_radians(units) |
| 56 | + } |
| 57 | + |
| 58 | + fn as_base_units_name(&self) -> &'static str { |
| 59 | + "rad" |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +implement_measurement! { Angle } |
| 64 | + |
| 65 | +#[cfg(test)] |
| 66 | +mod test { |
| 67 | + use angle::*; |
| 68 | + use test_utils::assert_almost_eq; |
| 69 | + |
| 70 | + #[test] |
| 71 | + fn radians() { |
| 72 | + let i1 = Angle::from_degrees(360.0); |
| 73 | + let r1 = i1.as_radians(); |
| 74 | + let i2 = Angle::from_radians(PI); |
| 75 | + let r2 = i2.as_degrees(); |
| 76 | + assert_almost_eq(r1, 2.0 * PI); |
| 77 | + assert_almost_eq(r2, 180.0); |
| 78 | + } |
| 79 | +} |
0 commit comments