1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! Library for representing and manipulating angular quantities.
//! Provides type-safe wrapper types for each unit as well as helper
//! traits for abstracting over the concrete types.
//! Conversions between types is easy and safe, allowing highly flexible manipulation.
//!
//! ## Details
//!
//! ### Arithmetic
//!
//! Each angle type defines basic arithmetic operators. Multiplication and
//! division are between an angle and a scalar. Addition and subtraction
//! are between two angles and the two angles do not have to be represented using
//! the same units for example, the following is valid:
//!
//! ```
//! # use angular_units::*;
//! let angle = Turns(0.25) + Deg(30.0) - ArcMinutes(15.0);
//! ```
//!
//! When combining units like this, the left-hand side type will be the result.
//!
//! ### Normalization
//!
//! For performance, most operations do not normalize the results or inputs automatically.
//! This is mathematically sound, but it is often more convenient to have a single
//! value to represent each angle. Thus, for methods that expect an angle within
//! the standard domain, `normalize()` should be used to create an equivalent
//! angle that is less than one period.


extern crate num_traits as num;
#[macro_use]
#[cfg(feature = "approx")]
extern crate approx;
#[cfg(feature = "serde")]
#[macro_use]
extern crate serde;

use std::ops::*;
use std::f64::consts;
use std::fmt;
use std::convert::From;
use num::{Float, NumCast};

/// An angular quantity measured in degrees.
///
/// Degrees are uniquely defined from 0..360.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Hash)]
#[repr(transparent)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Deg<T>(pub T);
/// An angular quantity measured in gons.
///
/// Gons, or gradians, are uniquely defined from 0..400.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Hash)]
#[repr(transparent)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Gon<T>(pub T);
/// An angular quantity measured in degrees.
///
/// Radians are uniquely defined from 0..2π.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Hash)]
#[repr(transparent)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Rad<T>(pub T);
/// An angular quantity measured in "turns", or full rotations.
///
/// Turns are uniquely defined from 0..1.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Hash)]
#[repr(transparent)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Turns<T>(pub T);
/// An angular quantity measured in arc minutes, which are
/// 1/60th of a degree.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Hash)]
#[repr(transparent)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ArcMinutes<T>(pub T);
/// An angular quantity measured in arc seconds, which are
/// 1/60th of an arc minute.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Hash)]
#[repr(transparent)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ArcSeconds<T>(pub T);

/// Construct `Self` from an angle.
///
/// Analogous to the traits in the standard library,
/// FromAngle and IntoAngle provide a way to convert between angle
/// types and to mix various angle types in a single operation.
pub trait FromAngle<T>
    where T: Angle
{
    /// Construct `Self` by converting a `T`.
    fn from_angle(from: T) -> Self;
}

/// Construct an angle by converting from another type.
///
/// IntoAngle is provided automatically based on FromAngle.
pub trait IntoAngle<To>
    where To: Angle<Scalar = Self::OutputScalar>
{
    type OutputScalar: Float;
    /// Construct an angle from `self`.
    fn into_angle(self) -> To;
}

/// Base functionality for all angle types.
pub trait Angle: Clone + FromAngle<Self> + PartialEq + PartialOrd + num::Zero {
    /// Internal type storing the angle value.
    type Scalar: Float;

    /// Construct a new angle.
    ///
    /// Equivalent to constructing the tuple struct directly, eg. `Deg(value)`,
    /// but usable in a generic context.
    fn new(value: Self::Scalar) -> Self;

    /// The length of a full rotation.
    fn period() -> Self::Scalar;
    /// Return the scalar (unitless) value.
    ///
    /// Equivalent to `self.0` or to doing `let Deg(val) = self`
    fn scalar(&self) -> Self::Scalar;
    /// Set the internal scalar value of the angle.
    fn set_scalar(&mut self, value: Self::Scalar);
    /// Normalize the angle, wrapping it back into the standard domain.
    ///
    /// After normalization, an angle will be in the range `[0, self.period())`.
    ///
    /// For performance reasons, normalization does not happen automatically
    /// during most operations. Thus, when passing an angle to a method that
    /// expects it to be within the standard domain, first normalize the angle.
    fn normalize(self) -> Self;
    /// Whether the angle is in the standard domain.
    fn is_normalized(&self) -> bool;

    /// Compute the sine of an angle.
    fn sin(self) -> Self::Scalar;
    /// Compute the cosine of an angle.
    fn cos(self) -> Self::Scalar;
    /// Compute the tangent of an angle.
    fn tan(self) -> Self::Scalar;
    /// Simultaneously compute sine and cosine.
    fn sin_cos(self) -> (Self::Scalar, Self::Scalar);

    /// Compute the arcsine of a value, returning an angle.
    fn asin(value: Self::Scalar) -> Self;
    /// Compute the arccosine of a value, returning an angle.
    fn acos(value: Self::Scalar) -> Self;
    /// Compute the arctangent of a value, returning an angle.
    fn atan(value: Self::Scalar) -> Self;
    /// Compute the arctangent of a value, using information from
    /// the numerator and denominator in order to increase the domain.
    fn atan2(x: Self::Scalar, y: Self::Scalar) -> Self;

    /// Return one full rotation in some unit.
    ///
    /// Equivalent to `Self(Self::period())`.
    fn full_turn() -> Self;
    /// Return one half of a full rotation in some unit.
    fn half_turn() -> Self;
    /// Return one quarter of a full rotation in some unit.
    fn quarter_turn() -> Self;

    /// Return the inverse of an angle.
    ///
    /// The inverse is equivalent to adding half a rotation
    /// or inverting the unit vector pointing from the origin along the
    /// angle.
    fn invert(self) -> Self;
    /// Return the reflection of an angle over the x axis.
    ///
    /// Equivalent to `full_turn() - self`.
    fn reflect_x(self) -> Self;
}

/// A trait for linear interpolation between angles.
pub trait Interpolate: Angle {
    /// Perform a linear interpolation between two angles.
    ///
    /// This method will always follow the shortest past between
    /// the two angles. This means it will go backward if the
    /// angles are more than a half turn apart. To force the interpolation
    /// to go forward, use `interpolate_forward`.
    /// The output is not normalized, and may exceed a
    /// full turn if it interpolates backward,
    /// even if both inputs are normalized.
    /// The angles may be represented in different units.
    fn interpolate<U>(&self, right: &U, pos: Self::Scalar) -> Self
        where U: Clone + IntoAngle<Self, OutputScalar = Self::Scalar>;

    /// Perform a linear interpolation between two angles,
    /// going forward from `self` to `right`.
    ///
    /// Unlike `interpolate` this will always go forward from `self` to `right`,
    /// even if going backward would take a shorter path. The output is not
    /// normalized, but should remain normalized if both `self` and `right` are.
    /// The angles may be represented in different units.
    fn interpolate_forward<U>(&self, right: &U, pos: Self::Scalar) -> Self
        where U: Clone + IntoAngle<Self, OutputScalar = Self::Scalar>;
}

macro_rules! impl_angle {
    ($Struct: ident, $period: expr) => {
        impl<T: Float> Angle for $Struct<T>
        {
            type Scalar = T;

            fn new(value: T) -> $Struct<T> {
                $Struct(value)
            }

            fn period() -> T {
                cast($period).unwrap()
            }

            fn scalar(&self) -> T {
                self.0
            }
            fn set_scalar(&mut self, value: T) {
                self.0 = value;
            }
            fn is_normalized(&self) -> bool {
                self.0 >= T::zero() && self.0 < Self::period()
            }

            fn normalize(self) -> $Struct<T> {
                if !self.is_normalized() {
                    let shifted = self.0 % Self::period();
                    if shifted < T::zero() {
                        $Struct(shifted + Self::period())
                    } else {
                        $Struct(shifted)
                    }
                } else {
                    self
                }
            }

            fn sin(self) -> T {
                Rad::from_angle(self).0.sin()
            }
            fn cos(self) -> T {
                Rad::from_angle(self).0.cos()
            }
            fn tan(self) -> T {
                Rad::from_angle(self).0.tan()
            }
            fn sin_cos(self) -> (T, T) {
                Rad::from_angle(self).0.sin_cos()
            }
            fn asin(value: T) -> $Struct<T> {
                $Struct::from_angle(Rad(value.asin()))
            }
            fn acos(value: T) -> $Struct<T> {
                $Struct::from_angle(Rad(value.acos()))
            }
            fn atan(value: T) -> $Struct<T> {
                $Struct::from_angle(Rad(value.atan()))
            }
            fn atan2(y: T, x: T) -> $Struct<T> {
                $Struct::from_angle(Rad(y.atan2(x)))
            }

            fn full_turn() -> Self {
                $Struct(Self::period())
            }
            fn half_turn() -> Self {
                $Struct(cast::<_, Self::Scalar>(0.5).unwrap() * Self::period())
            }
            fn quarter_turn() -> Self {
                $Struct(cast::<_, Self::Scalar>(0.25).unwrap() * Self::period())
            }
            fn invert(self) -> Self {
                self + Self::half_turn()
            }
            fn reflect_x(self) -> Self {
                Self::full_turn() - self
            }
        }

        impl<T: Float> Interpolate for $Struct<T> {
            fn interpolate<U>(&self, right: &U, pos: Self::Scalar) -> Self
                where U: Clone + IntoAngle<Self, OutputScalar=Self::Scalar>
            {
                let end = right.clone().into_angle();
                let forward_distance = (end.0 - self.0).abs();
                let inv_pos = cast::<_, Self::Scalar>(1.0).unwrap() - pos;
                
                if forward_distance > Self::half_turn().0 {
                    if *self > end {
                        $Struct(self.0 * inv_pos + (end.0 + Self::period()) * pos)
                    } else {
                        $Struct((self.0 + Self::period()) * inv_pos + end.0 * pos)
                    }
                } else {
                    $Struct(self.0 * inv_pos + end.0 * pos)
                }
            }

            fn interpolate_forward<U>(&self, right: &U, pos: Self::Scalar) -> Self
                where U: Clone + IntoAngle<Self, OutputScalar = Self::Scalar>
            {
                let inv_pos = cast::<_, Self::Scalar>(1.0).unwrap() - pos;
                $Struct(self.0 * inv_pos + right.clone().into_angle().0 * pos)
            }
        }

        #[cfg(feature = "approx")]
        impl<T: Float + approx::AbsDiffEq> approx::AbsDiffEq for $Struct<T>
            where T::Epsilon: Clone,
        {
            type Epsilon = T::Epsilon;

            fn default_epsilon() -> Self::Epsilon {
                T::default_epsilon()
            }

            fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool
            {
                let inv_self = self.clone().reflect_x();

                self.0.abs_diff_eq(&other.0, epsilon.clone())
                || self.0.abs_diff_eq(&other.clone().reflect_x().0,
                      epsilon.clone())
                || inv_self.0.abs_diff_eq(&other.0, epsilon)
            }
        }

        #[cfg(feature = "approx")]
        impl<T: Float + approx::RelativeEq> approx::RelativeEq for $Struct<T>
            where T::Epsilon: Clone,
        {
            fn default_max_relative() -> Self::Epsilon {
                T::default_max_relative()
            }

            fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, 
                           max_relative: Self::Epsilon) -> bool {
                let inv_self = self.clone().reflect_x();

                self.0.relative_eq(&other.0, epsilon.clone(), max_relative.clone())
                || self.0.relative_eq(&other.clone().reflect_x().0, 
                      epsilon.clone(), max_relative.clone())
                || inv_self.0.relative_eq(&other.0, epsilon, max_relative)
            }
        }

        #[cfg(feature = "approx")]
        impl<T: Float + approx::UlpsEq> approx::UlpsEq for $Struct<T>
        where T::Epsilon: Clone,
        {
            fn default_max_ulps() -> u32 {
                T::default_max_ulps()
            }
            fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
                let inv_self = self.clone().reflect_x();

                self.0.ulps_eq(&other.0, epsilon.clone(), max_ulps)
                || self.0.ulps_eq(&other.clone().reflect_x().0, epsilon.clone(), max_ulps)
                || inv_self.0.ulps_eq(&other.0, epsilon, max_ulps)
            }
        }

        impl<T: Rem<T, Output=T>> Rem for $Struct<T> {
            type Output=$Struct<T>;
            fn rem(self, rhs: $Struct<T>) -> $Struct<T> {
                $Struct(self.0 % rhs.0)
            }
        }

        impl<T: RemAssign> RemAssign for $Struct<T> {
            fn rem_assign(&mut self, rhs: $Struct<T>) {
                self.0 %= rhs.0;
            }
        }

        impl<U, T> Add<U> for $Struct<T> 
            where T: Float + Add<T, Output=T>,
                  U: IntoAngle<$Struct<T>, OutputScalar=T>
        {
            type Output=$Struct<T>;
            fn add(self, rhs: U) -> $Struct<T> {
                $Struct(self.0 + rhs.into_angle().0)
            }
        }

        impl<U, T> AddAssign<U> for $Struct<T> 
            where T: Float + AddAssign<T>,
                  U: IntoAngle<$Struct<T>, OutputScalar=T>
        {
            fn add_assign(&mut self, rhs: U) {
                self.0 += rhs.into_angle().0;
            }
        }

        impl<U, T> Sub<U> for $Struct<T> 
            where T: Float + Sub<T, Output=T>,
                  U: IntoAngle<$Struct<T>, OutputScalar=T>
        {
            type Output=$Struct<T>;
            fn sub(self, rhs: U) -> $Struct<T> {
                $Struct(self.0 - rhs.into_angle().0)
            }
        }

        impl<U, T> SubAssign<U> for $Struct<T> 
            where T: Float + SubAssign<T>,
                  U: IntoAngle<$Struct<T>, OutputScalar=T>
        {
            fn sub_assign(&mut self, rhs: U) {
                self.0 -= rhs.into_angle().0;
            }
        }
        
        impl<T: Mul<T, Output=T>> Mul<T> for $Struct<T> {
            type Output=$Struct<T>;
            fn mul(self, rhs: T) -> $Struct<T> {
                $Struct(self.0 * rhs)
            }
        }

        impl<T: MulAssign<T>> MulAssign<T> for $Struct<T> {
            fn mul_assign(&mut self, rhs: T) {
                self.0 *= rhs;
            }
        }

        impl<T: Div<T, Output=T>> Div<T> for $Struct<T> {
            type Output=$Struct<T>;
            fn div(self, rhs: T) -> $Struct<T> {
                $Struct(self.0 / rhs)
            }
        }

        impl<T: DivAssign<T>> DivAssign<T> for $Struct<T> {
            fn div_assign(&mut self, rhs: T) {
                self.0 /= rhs;
            }
        }

        impl<T: Neg<Output=T>> Neg for $Struct<T> {
            type Output=$Struct<T>;
            fn neg(self) -> $Struct<T> {
                $Struct(-self.0)
            }
        }

        impl<T: Float> num::Zero for $Struct<T> {
            fn zero() -> $Struct<T> {
                $Struct(T::zero())
            }
            fn is_zero(&self) -> bool {
                self.0 == T::zero()
            }
        }

        impl<T: num::Zero> Default for $Struct<T> {
            fn default() -> $Struct<T> {
                $Struct(T::zero())
            }
        }

        impl<T, U> FromAngle<U> for $Struct<T>
            where U: Angle<Scalar=T>,
                  T: Float,
        {
            fn from_angle(from: U) -> $Struct<T> {
                $Struct(from.scalar() * $Struct::period() / U::period())
            }
        }
    }
}

macro_rules! impl_from_for_angle {
    ($from: ty, $to: ty) => {
        impl<T: Float> From<$from> for $to {
            fn from(from: $from) -> $to {Self::from_angle(from)}
        }
    }
}

impl_angle!(Deg, 360.0);
impl_angle!(Gon, 400.0);
impl_angle!(Rad, consts::PI * 2.0);
impl_angle!(Turns, 1.0);
impl_angle!(ArcMinutes, 360.0 * 60.0);
impl_angle!(ArcSeconds, 360.0 * 3600.0);

impl_from_for_angle!(Deg<T>, Rad<T>);
impl_from_for_angle!(Deg<T>, Turns<T>);
impl_from_for_angle!(Deg<T>, Gon<T>);

impl_from_for_angle!(Gon<T>, Deg<T>);
impl_from_for_angle!(Gon<T>, Rad<T>);
impl_from_for_angle!(Gon<T>, Turns<T>);

impl_from_for_angle!(Rad<T>, Deg<T>);
impl_from_for_angle!(Rad<T>, Gon<T>);
impl_from_for_angle!(Rad<T>, Turns<T>);

impl_from_for_angle!(Turns<T>, Deg<T>);
impl_from_for_angle!(Turns<T>, Gon<T>);
impl_from_for_angle!(Turns<T>, Rad<T>);

impl_from_for_angle!(ArcMinutes<T>, Deg<T>);
impl_from_for_angle!(ArcSeconds<T>, Deg<T>);
impl_from_for_angle!(ArcSeconds<T>, ArcMinutes<T>);

impl<T: Float> Deg<T> {
    /// Construct a `Deg` instance from base degrees, minutes and seconds.
    ///
    /// The opposite of decompose. Equivalent to adding the components together:
    ///
    /// ```
    /// #   use angular_units::*;
    ///     let angle = Deg(50.0) + ArcMinutes(30.0) + ArcSeconds(10.0);
    ///     assert_eq!(angle, Deg::from_components(Deg(50.0),
    ///         ArcMinutes(30.0), ArcSeconds(10.0)));
    /// ```
    pub fn from_components(degs: Deg<T>, mins: ArcMinutes<T>, secs: ArcSeconds<T>) -> Self {
        degs + mins + secs
    }

    /// Split an angle in degrees into base degrees, minutes and seconds.
    ///
    /// If the decomposition would not be perfect, seconds will be
    /// a fractional value.
    pub fn decompose(self) -> (Deg<T>, ArcMinutes<T>, ArcSeconds<T>) {
        let sixty: T = cast(60.0).unwrap();
        let degs = self.0.floor();
        let rem = self.0 - degs;
        let mins = (rem * sixty).floor();
        let rem_s = rem * sixty - mins;
        let seconds = rem_s * sixty;

        (Deg(degs), ArcMinutes(mins), ArcSeconds(seconds))
    }
}

impl<T: Float> Rad<T> {
    pub fn pi() -> Rad<T> {
        Rad(cast(consts::PI).unwrap())
    }
    pub fn pi_over_2() -> Rad<T> {
        Rad(cast(consts::PI / 2.0).unwrap())
    }
    pub fn pi_over_3() -> Rad<T> {
        Rad(cast(consts::PI / 3.0).unwrap())
    }
    pub fn pi_over_4() -> Rad<T> {
        Rad(cast(consts::PI / 4.0).unwrap())
    }
}

impl<T, U> IntoAngle<U> for T
    where U: Angle<Scalar = T::Scalar> + FromAngle<T>,
          T: Angle
{
    type OutputScalar = T::Scalar;
    fn into_angle(self) -> U {
        U::from_angle(self)
    }
}
impl<T: fmt::Display> fmt::Display for Deg<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}°", self.0)
    }
}
impl<T: fmt::Display> fmt::Display for Gon<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}gon", self.0)
    }
}
impl<T: fmt::Display> fmt::Display for Rad<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}r", self.0)
    }
}
impl<T: fmt::Display> fmt::Display for Turns<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}
impl<T: fmt::Display> fmt::Display for ArcMinutes<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}'", self.0)
    }
}
impl<T: fmt::Display> fmt::Display for ArcSeconds<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}\"", self.0)
    }
}

/// Compute the mean of a collection of angles.
///
/// Note that because angles are circular, a standard summation and dividing by `len()`
/// is _not_ valid, even if all angles are normalized.
pub fn mean<T, Scalar, Out>(iter: T) -> Out
    where T: IntoIterator,
          T::Item: IntoAngle<Rad<Scalar>, OutputScalar=Scalar>,
          Scalar: Float + AddAssign,
          Out: Angle<Scalar=Scalar> + FromAngle<Rad<Scalar>>,
{
    let mut sum_of_sines: Scalar = cast(0.0).unwrap();
    let mut sum_of_cosines: Scalar = cast(0.0).unwrap();

    for angle in iter.into_iter() {
        let intermediate_angle: Rad<Scalar> = angle.into_angle();
        let (sin, cos) = intermediate_angle.sin_cos();
        sum_of_sines += sin;
        sum_of_cosines += cos;
    }

    Out::atan2(sum_of_sines, sum_of_cosines).normalize()
}

fn cast<T: NumCast, U: NumCast>(from: T) -> Option<U> {
    U::from(from)
}

#[cfg(test)]
mod test {
    #[cfg(feature = "serde")]
    extern crate serde_test;

    use std::f64::consts;
    use std::f64;
    use super::*;

    #[test]
    fn test_construct() {
        assert_relative_eq!(Deg(50.0), Deg::new(50.0));
        let mut a1 = Deg(100.0);
        let scalar = a1.scalar();
        a1.set_scalar(scalar + 150.0);
        assert_relative_eq!(a1, Deg(250.0));
    }

    #[test]
    fn test_convert() {
        assert_relative_eq!(ArcMinutes(120.0).into_angle(), Deg(2.0), epsilon=1e-6);
        assert_relative_eq!(ArcMinutes(120.0).into_angle(), Gon(2.222222), epsilon=1e-6);
        assert_relative_eq!(ArcSeconds(30.0).into_angle(), ArcMinutes(0.5), epsilon=1e-6);
        assert_relative_eq!(Deg(30.0) + ArcMinutes(30.0) + ArcSeconds(30.0), 
            Deg(30.50833333333), epsilon=1e-6);
        assert_relative_eq!(Rad(consts::PI).into_angle(), Deg(180.0), epsilon=1e-6);
        assert_relative_eq!(Turns(0.25).into_angle(), Deg(90.0), epsilon=1e-6);
        assert_relative_eq!(Turns(0.25).into_angle(), Rad(consts::PI / 2.0), epsilon=1e-6);
        assert_relative_eq!(ArcMinutes(600.0).into_angle(), Deg(10.0), epsilon=1e-6);
        assert_relative_eq!(ArcMinutes(5400.0).into_angle(), Rad(consts::PI / 2.0), epsilon=1e-6);
        assert_relative_eq!(Gon(100.0).into_angle(), Deg(90.0), epsilon=1e-6);
        assert_relative_eq!(Gon(50.0).into_angle(), Rad(consts::PI / 4.0), epsilon=1e-6);
    }

    #[test]
    fn test_arithmetic() {
        {
            let a1 = Rad(2.0);
            let a2 = Deg(100.0);

            let a3 = a2 + a1;
            assert_relative_eq!(a3.0, 214.59, epsilon=1e-2);

            let a4 = Deg(50.0);
            let a5 = a2 + a4;
            assert_ulps_eq!(a5.0, 150.0);

            let mut a6 = Deg(123.0);
            a6 += Deg(10.0);
            a6 += Rad::pi();
            assert_ulps_eq!(a6.0, 313.0);

            let a7 = Deg(50.0);
            assert_ulps_eq!(a7 * 2.0, Deg(100.0));
        }
        {
            let a1 = Rad(2.0);
            let a2 = a1 % Rad(1.5);
            assert_ulps_eq!(a2, Rad(0.5));
            assert_ulps_eq!(Rad(1.0) * 2.0, Rad(2.0));
            assert_ulps_eq!(Rad(consts::PI * 2.0) / 2.0, Rad(consts::PI));
        }
        {
            let a10 = Gon(15.0);
            let a11 = Deg(43.0);
            let a12 = a11 + a10;
            assert_relative_eq!(a12.0, 56.5, epsilon=1e-2);
            let a13 = a10 + a11;
            assert_relative_eq!(a13.0, 62.7778, epsilon=1e-2);
        }
    }

    #[test]
    fn test_trig() {
        assert_ulps_eq!(Deg(0.0).sin(), 0.0);
        assert_ulps_eq!(Gon(0.0).sin(), 0.0);
        assert_ulps_eq!(Rad(consts::PI / 2.0).sin(), 1.0);
        assert_ulps_eq!(Deg(90.0).sin(), 1.0);
        assert_ulps_eq!(Deg(45.0).tan(), 1.0);
        assert_relative_eq!(Deg(405.0).tan(), 1.0, epsilon=1e-6);
        assert_relative_eq!(Gon(450.0).tan(), 1.0, epsilon=1e-6);
        let a1 = Rad(consts::PI * 1.25);
        assert_relative_eq!(a1.cos(), -f64::sqrt(2.0) / 2.0, epsilon=1e-6);
        assert_relative_eq!(a1.cos(), Deg(135.0).cos(), epsilon=1e-6);
        assert_relative_eq!(a1.cos(), Gon(150.0).cos(), epsilon=1e-6);

        assert_relative_eq!(Deg::acos(1.0), Deg(0.0));
        assert_relative_eq!(Deg::acos(0.0), Deg(90.0));
        assert_relative_eq!(Deg::acos(0.0), Deg::from(Gon(100.0)));
        assert_relative_eq!(Rad::acos(0.0), Rad::pi_over_2());
    }

    #[test]
    fn test_equality() {
        let a1 = Rad(2.0);
        assert_ulps_eq!(a1, Rad(2.0));
        assert_ulps_eq!(Deg(200.0), Deg(200.0));
        assert!(!(Deg(200.0) == Deg(100.0)));

        assert!(Deg(200.0) < Deg(300.0));
        assert!(Deg(250.0) > Deg(100.0));

        assert_relative_eq!(Deg(359.999999), Deg(0.0), epsilon=1e-4);
        assert_ulps_eq!(Deg(359.999999), Deg(0.0), epsilon=1e-4);
        assert_ulps_eq!(Deg(359.99999), Deg(0.0), epsilon=1e-4);
    }

    #[test]
    fn test_normalize() {
        let mut a1 = Deg(200.0);
        a1 += Deg(300.0);
        assert_ulps_eq!(a1, Deg(500.0));
        a1 = a1.normalize();
        assert_ulps_eq!(a1, Deg(140.0));
        assert_ulps_eq!(a1.normalize(), a1);

        let a2 = Deg(50.0);
        assert_ulps_eq!(a2 - Deg(150.0), Deg(-100.0));
        let a3 = a2 - Deg(100.0);
        assert!(!a3.is_normalized());
        assert_ulps_eq!(a3.normalize(), Deg(310.0));
        assert_ulps_eq!(a3.normalize().normalize(), a3.normalize());
        assert!(a3.normalize().is_normalized());

        let a4 = Rad(consts::PI);
        let a5 = a4 + Rad(consts::PI * 2.0);
        assert_ulps_eq!(a5, Rad(consts::PI * 3.0));
        assert!(!a3.is_normalized());
        assert_ulps_eq!(a5.normalize(), Rad(consts::PI));
        let a6 = a4 - Rad(consts::PI * 2.0);
        assert_ulps_eq!(a6, Rad(consts::PI * -1.0));
        assert!(!a6.is_normalized());
        assert_ulps_eq!(a6.normalize(), a5.normalize());

        assert_ulps_eq!(Deg(360.0).normalize(), Deg(0.0));
        assert_ulps_eq!(Deg(-1.0).normalize(), Deg(359.0));
        assert_ulps_eq!(Deg(-360.0).normalize(), Deg(0.0));
        assert_relative_eq!(Deg(-359.9).normalize(), Deg(0.1), epsilon=1e-6);

        assert_relative_eq!(Gon(725.0).normalize().into_angle(), Deg(292.5), epsilon=1e-6);
        assert_relative_eq!(Gon(-275.0).normalize(), Gon(125.0), epsilon=1e-6);
    }

    #[test]
    fn decompose() {
        {
            let (deg, min, sec) = Deg(50.25).decompose();

            assert_ulps_eq!(deg, Deg(50.0));
            assert_ulps_eq!(min, ArcMinutes(15.0));
            assert_ulps_eq!(sec, ArcSeconds(0.0));
        }
        {
            let (deg, min, sec) = Deg(90.3131).decompose();

            assert_ulps_eq!(deg, Deg(90.0));
            assert_ulps_eq!(min, ArcMinutes(18.0));
            assert_relative_eq!(sec, ArcSeconds(47.16), epsilon=1e-6);
        }
    }

    #[test]
    fn test_interpolate() {
        assert_relative_eq!(Deg(60.0).interpolate(&Deg(120.0), 0.5), Deg(90.0));
        assert_relative_eq!(Deg(50.0).interpolate(&Rad(consts::PI), 0.75), 
                            Deg(147.5), epsilon=1e-6);
        assert_relative_eq!(Turns(0.50).interpolate(&Deg(30.0), 0.25), 
                            Turns(0.39583333333), epsilon=1e-6);

        assert_relative_eq!(Deg(100.0).interpolate(&Deg(310.0), 0.5).normalize(), Deg(25.0));
        assert_relative_eq!(Deg(100.0).interpolate_forward(&Deg(310.0), 0.5).normalize(), 
                            Deg(205.0));
        assert_relative_eq!(Gon(66.6666667).interpolate(&Deg(120.0), 0.5), Gon(100.0), epsilon=1e-6);
        assert_relative_eq!(Rad::pi_over_2().interpolate(&Rad(0.0), 0.5), Rad::pi_over_4());
    }

    #[test]
    fn test_constants() {
        assert_ulps_eq!(Deg::half_turn(), Deg(180.0));
        assert_ulps_eq!(Deg::quarter_turn(), Deg(90.0));
        assert_ulps_eq!(Rad::half_turn(), Rad(consts::PI));
        assert_ulps_eq!(Rad::<f32>::full_turn(), Rad(Rad::period()));
        assert_ulps_eq!(Gon::half_turn(), Gon(200.0));
        assert_ulps_eq!(Gon::quarter_turn(), Gon(100.0));
    }

    #[test]
    fn test_invert() {
        assert_ulps_eq!(Deg(0.0).invert(), Deg(180.0));
        assert_ulps_eq!(Deg(180.0).invert().normalize(), Deg(0.0));
        assert_ulps_eq!(Gon(200.0).invert().normalize(), Gon(0.0));
        assert_ulps_eq!(Deg(80.0).invert(), Deg(260.0));
        assert_ulps_eq!(Gon(80.0).invert(), Gon(280.0));
    }

    #[test]
    fn test_reflect_x() {
        assert_relative_eq!(Deg(359.9999999999).reflect_x(), 
            Deg(0.0000000000001), epsilon=1e-5);
        assert_relative_eq!(Deg(180.0).reflect_x(), Deg(180.0));
        assert_relative_eq!(Deg(90.0).reflect_x(), Deg(90.0));
        assert_relative_eq!(Deg(0.0).reflect_x(), Deg(0.0));
        assert_relative_eq!(Deg(45.0).reflect_x(), Deg(315.0));
        assert_relative_eq!(Deg(215.0).reflect_x(), Deg(145.0));
        assert_relative_eq!(Gon(50.0).reflect_x(), Gon(350.0));
        assert_relative_eq!(Gon(215.0).reflect_x(), Gon(185.0));
    }

    #[test]
    fn test_mean() {
        assert_relative_eq!(mean(vec![Deg(280.0), Deg(10.0)].into_iter()), Deg(325.0));
        assert_relative_eq!(mean(vec![Turns(0.5), Turns(0.0)].into_iter()), Deg(90.0));
        assert_relative_eq!(mean([Rad(0.0), Rad(0.0)].into_iter().cloned()), Rad(0.0));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serialize() {
        use self::serde_test::{Token, assert_tokens};

        assert_tokens(&Deg(90.0), &[Token::NewtypeStruct {name: "Deg"}, Token::F64(90.0)]);
        assert_tokens(&Rad(0.5f32), &[Token::NewtypeStruct {name: "Rad"}, Token::F32(0.5f32)]);
        assert_tokens(&Gon(300.0), &[Token::NewtypeStruct {name: "Gon"}, Token::F64(300.0)]);
        assert_tokens(&Turns(0.666), &[Token::NewtypeStruct {name: "Turns"}, Token::F64(0.666)]);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_deserialize() {
        use self::serde_test::{Token, assert_de_tokens};

        assert_de_tokens(&Deg(90.0), &[Token::NewtypeStruct {name: "Deg"}, Token::F64(90.0)]);
        assert_de_tokens(&Rad(0.5f32), &[Token::NewtypeStruct {name: "Rad"}, Token::F32(0.5f32)]);
        assert_de_tokens(&Gon(300.0), &[Token::NewtypeStruct {name: "Gon"}, Token::F64(300.0)]);
        assert_de_tokens(&Turns(0.666), &[Token::NewtypeStruct {name: "Turns"}, Token::F64(0.666)]);
    }
}