turns 0.1.2

Fixed-point angles modulo 2π backed by unsigned integers.
Documentation
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
#![cfg_attr(not(feature = "std"), no_std)]

//! Fixed-point angles modulo 2π, backed by unsigned integers.
//!
//! [`Angle<T>`] represents an angle as an unsigned integer where the full
//! range of `T` maps onto one full turn (2π radians / 360 degrees). Natural
//! integer overflow provides wraparound at 2π, so modular arithmetic is free.
//!
//! Type aliases [`Angle8`], [`Angle16`], [`Angle32`], [`Angle64`], and
//! [`Angle128`] cover the standard widths.
//!
//! # Precision
//!
//! Float conversions are generic over any `F: Float`. Expect precision loss
//! when the integer width exceeds the float mantissa (e.g. [`Angle128`] with
//! `f64` keeps ~53 of 128 bits). Non-finite inputs (`NaN`, infinities) are
//! coerced to zero rather than panicking.
//!
//! # Example
//!
//! ```
//! use turns::Angle8;
//! use core::f64::consts::PI;
//!
//! let pi = Angle8::from_radians(PI);
//! assert_eq!(pi + pi, Angle8::from_radians(0.0_f64));
//! ```

use core::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub};
use num_traits::{
    Bounded, CheckedDiv, CheckedMul, CheckedRem, Euclid, Float, FloatConst, NumCast, PrimInt,
    ToPrimitive, WrappingAdd, WrappingMul, WrappingNeg, WrappingSub, Zero,
};

/// Fixed-point angle modulo 2π, stored as an unsigned integer `T`.
///
/// The full range of `T` covers one turn: `T::MAX + 1` corresponds to 2π.
/// Intended to be instantiated with an unsigned primitive integer; the
/// type aliases [`Angle8`] through [`Angle128`] are the supported widths.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct Angle<T>(pub T);

impl<T: NumCast + ToPrimitive + Bounded + Zero> Angle<T> {
    /// Construct an angle from radians.
    ///
    /// Input is reduced modulo 2π. Non-finite values (`NaN`, `±∞`) map to
    /// the zero angle.
    #[must_use]
    pub fn from_radians<F: Float + FloatConst + Euclid>(radians: F) -> Self {
        if !radians.is_finite() {
            return Self(T::zero());
        }
        let scale = <F as NumCast>::from(T::max_value()).unwrap() + F::one();
        let normalized = radians.rem_euclid(&F::TAU()) / F::TAU();
        Self(NumCast::from(normalized * scale).unwrap_or_else(T::zero))
    }

    /// Convert the angle to radians in `[0, 2π)`.
    #[must_use]
    pub fn to_radians<F: Float + FloatConst>(self) -> F {
        let scale = <F as NumCast>::from(T::max_value()).unwrap() + F::one();
        <F as NumCast>::from(self.0).unwrap() / scale * F::TAU()
    }

    /// Construct an angle from degrees.
    ///
    /// Input is reduced modulo 360. Non-finite values map to zero.
    #[must_use]
    pub fn from_degrees<F: Float + Euclid>(degrees: F) -> Self {
        if !degrees.is_finite() {
            return Self(T::zero());
        }
        let scale = <F as NumCast>::from(T::max_value()).unwrap() + F::one();
        let full = <F as NumCast>::from(360).unwrap();
        let normalized = degrees.rem_euclid(&full) / full;
        Self(NumCast::from(normalized * scale).unwrap_or_else(T::zero))
    }

    /// Convert the angle to degrees in `[0, 360)`.
    #[must_use]
    pub fn to_degrees<F: Float>(self) -> F {
        let scale = <F as NumCast>::from(T::max_value()).unwrap() + F::one();
        let full = <F as NumCast>::from(360).unwrap();
        <F as NumCast>::from(self.0).unwrap() / scale * full
    }

    /// Construct an angle from the result of `atan2(y, x)`.
    ///
    /// Non-finite coordinates map to the zero angle (via [`Self::from_radians`]).
    #[must_use]
    pub fn from_atan2<F: Float + FloatConst + Euclid>(y: F, x: F) -> Self {
        Self::from_radians(y.atan2(x))
    }

    /// Sine of the angle.
    #[must_use]
    pub fn sin<F: Float + FloatConst>(self) -> F {
        self.to_radians::<F>().sin()
    }

    /// Cosine of the angle.
    #[must_use]
    pub fn cos<F: Float + FloatConst>(self) -> F {
        self.to_radians::<F>().cos()
    }

    /// Tangent of the angle.
    #[must_use]
    pub fn tan<F: Float + FloatConst>(self) -> F {
        self.to_radians::<F>().tan()
    }

    /// Sine and cosine computed together as `(sin, cos)`.
    #[must_use]
    pub fn sin_cos<F: Float + FloatConst>(self) -> (F, F) {
        self.to_radians::<F>().sin_cos()
    }

    /// Multiply the angle by a floating-point factor, wrapping mod 2π.
    ///
    /// A non-finite `factor` returns the zero angle.
    #[must_use]
    pub fn scale<F: Float + Euclid>(self, factor: F) -> Self {
        if !factor.is_finite() {
            return Self(T::zero());
        }
        let full = <F as NumCast>::from(T::max_value()).unwrap() + F::one();
        let wrapped = (<F as NumCast>::from(self.0).unwrap() * factor).rem_euclid(&full);
        Self(NumCast::from(wrapped).unwrap_or_else(T::zero))
    }
}

impl<T: ToPrimitive> Angle<T> {
    /// Ratio of two angles as a float: `self / other`.
    ///
    /// Division is on the underlying integer values; dividing by the zero
    /// angle produces `±∞` or `NaN` per IEEE-754.
    #[must_use]
    pub fn ratio<F: Float>(self, other: Self) -> F {
        <F as NumCast>::from(self.0).unwrap() / <F as NumCast>::from(other.0).unwrap()
    }
}

impl<T: PrimInt> Angle<T> {
    /// Express the angle as the reduced fraction `num·π/den`.
    ///
    /// Returns `(num, den)` such that the angle equals `num·π/den`, with the
    /// fraction reduced by their greatest common power of two (the only
    /// possible common factor, since `den` is always a power of two). The zero
    /// angle returns `(0, 1)`.
    #[must_use]
    pub fn to_frac(self) -> (T, T) {
        let one = T::one();
        if self.0.is_zero() {
            return (T::zero(), one);
        }
        let two = one + one;
        let num = self.0;
        let den = T::max_value() / two + one;
        let shift = num.trailing_zeros().min(den.trailing_zeros()) as usize;
        (num >> shift, den >> shift)
    }
}

impl<T: PrimInt + WrappingMul + WrappingAdd> Angle<T> {
    /// Construct an angle from the fraction `num·π/den`, reduced modulo 2π.
    ///
    /// Exact when `den` divides the raw value of π (i.e. `den` is a power of
    /// two up to `2^(N-1)`); this covers every `(num, den)` that [`to_frac`]
    /// can produce, so `from_frac(a.to_frac())` round-trips. For other `den`
    /// the result is rounded by truncation.
    ///
    /// [`to_frac`]: Self::to_frac
    ///
    /// # Panics
    ///
    /// Panics if `den` is zero.
    #[must_use]
    pub fn from_frac(num: T, den: T) -> Self {
        let two = T::one() + T::one();
        let pi = T::max_value() / two + T::one();
        let q = num / den;
        let r = num % den;
        Angle(q.wrapping_mul(&pi).wrapping_add(&(r * (pi / den))))
    }
}

impl<T: ToPrimitive + Shr<usize, Output = T>> Angle<T> {
    /// Re-encode the angle in a different integer width.
    ///
    /// Widening copies the source value into the top bits of the target;
    /// narrowing keeps the top bits of the source. The angle itself is
    /// preserved up to the target's resolution.
    #[must_use]
    pub fn cast<U: NumCast + Shl<usize, Output = U>>(self) -> Angle<U> {
        let src_bits = core::mem::size_of::<T>() * 8;
        let dst_bits = core::mem::size_of::<U>() * 8;
        if src_bits >= dst_bits {
            let shifted = self.0 >> (src_bits - dst_bits);
            Angle(<U as NumCast>::from(shifted).unwrap())
        } else {
            let widened: U = <U as NumCast>::from(self.0).unwrap();
            Angle(widened << (dst_bits - src_bits))
        }
    }
}

impl<T: WrappingAdd> Add for Angle<T> {
    type Output = Self;
    fn add(self, rhs: Self) -> Self {
        Angle(self.0.wrapping_add(&rhs.0))
    }
}

impl<T: Zero + WrappingAdd> Zero for Angle<T> {
    fn zero() -> Self {
        Angle(T::zero())
    }
    fn is_zero(&self) -> bool {
        self.0.is_zero()
    }
}

impl<T: WrappingSub> Sub for Angle<T> {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self {
        Angle(self.0.wrapping_sub(&rhs.0))
    }
}

impl<T: WrappingNeg> Neg for Angle<T> {
    type Output = Self;
    fn neg(self) -> Self {
        Angle(self.0.wrapping_neg())
    }
}

impl<T: WrappingMul> Mul<T> for Angle<T> {
    type Output = Self;
    fn mul(self, rhs: T) -> Self {
        Angle(self.0.wrapping_mul(&rhs))
    }
}

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

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

impl<T: Shl<usize, Output = T> + Zero> Shl<usize> for Angle<T> {
    type Output = Self;
    fn shl(self, rhs: usize) -> Self {
        if rhs >= core::mem::size_of::<T>() * 8 {
            Angle(T::zero())
        } else {
            Angle(self.0 << rhs)
        }
    }
}

impl<T: Shr<usize, Output = T> + Zero> Shr<usize> for Angle<T> {
    type Output = Self;
    fn shr(self, rhs: usize) -> Self {
        if rhs >= core::mem::size_of::<T>() * 8 {
            Angle(T::zero())
        } else {
            Angle(self.0 >> rhs)
        }
    }
}

impl<T: CheckedMul> Angle<T> {
    /// Multiply by an integer scalar, returning `None` on raw integer
    /// overflow.
    ///
    /// Unlike the wrapping [`Mul`] impl, this surfaces overflow instead of
    /// wrapping — useful when you need to know whether the operation
    /// crossed 2π.
    #[must_use]
    pub fn checked_mul(self, rhs: T) -> Option<Self> {
        self.0.checked_mul(&rhs).map(Angle)
    }
}

impl<T: CheckedDiv> Angle<T> {
    /// Divide by an integer scalar, returning `None` on division by zero.
    #[must_use]
    pub fn checked_div(self, rhs: T) -> Option<Self> {
        self.0.checked_div(&rhs).map(Angle)
    }
}

impl<T: CheckedRem> Angle<T> {
    /// Remainder by an integer scalar, returning `None` on division by zero.
    #[must_use]
    pub fn checked_rem(self, rhs: T) -> Option<Self> {
        self.0.checked_rem(&rhs).map(Angle)
    }
}

macro_rules! impl_consts {
    ($t:ty) => {
        impl Angle<$t> {
            /// The zero angle.
            pub const ZERO: Self = Angle(0);
            /// One full turn (2π). Wraps to zero in this representation.
            pub const TAU: Self = Angle(0);
            /// π (half turn).
            pub const PI: Self = Angle(<$t>::MAX / 2 + 1);
            /// π/2 (quarter turn).
            pub const FRAC_PI_2: Self = Angle(<$t>::MAX / 4 + 1);
            /// π/3 (truncated to the nearest representable value).
            pub const FRAC_PI_3: Self = Angle(<$t>::MAX / 6);
            /// π/4 (eighth turn).
            pub const FRAC_PI_4: Self = Angle(<$t>::MAX / 8 + 1);
            /// π/6 (truncated to the nearest representable value).
            pub const FRAC_PI_6: Self = Angle(<$t>::MAX / 12);
            /// π/8.
            pub const FRAC_PI_8: Self = Angle(<$t>::MAX / 16 + 1);
        }
    };
}

impl<T: PrimInt + core::fmt::Display> core::fmt::Display for Angle<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let (num, den) = self.to_frac();
        if num.is_zero() {
            return f.write_str("0");
        }
        let one = T::one();
        match (num == one, den == one) {
            (true, true) => f.write_str("π"),
            (_, true) => write!(f, "{}π", num),
            (true, _) => write!(f, "π/{}", den),
            _ => write!(f, "{}π/{}", num, den),
        }
    }
}

impl_consts!(u8);
impl_consts!(u16);
impl_consts!(u32);
impl_consts!(u64);
impl_consts!(u128);
impl_consts!(usize);

/// 8-bit angle: one full turn per 256 steps.
pub type Angle8 = Angle<u8>;
/// 16-bit angle: one full turn per 65,536 steps.
pub type Angle16 = Angle<u16>;
/// 32-bit angle: one full turn per 2³² steps.
pub type Angle32 = Angle<u32>;
/// 64-bit angle: one full turn per 2⁶⁴ steps.
pub type Angle64 = Angle<u64>;
/// 128-bit angle: one full turn per 2¹²⁸ steps.
pub type Angle128 = Angle<u128>;
/// Pointer-width angle: one full turn per `usize::MAX + 1` steps (platform-dependent).
pub type AngleSize = Angle<usize>;

/// Helpers for use with `#[serde(with = "...")]` on fields of type [`Angle<T>`].
///
/// Three submodules cover the common wire formats:
///
/// - [`raw`] — the inner integer as-is (lossless, compact).
/// - [`radians`] — an `f64` in `[0, 2π)`.
/// - [`degrees`] — an `f64` in `[0, 360)`.
///
/// # Example
///
/// ```
/// # #[cfg(feature = "serde")] {
/// use turns::Angle32;
///
/// #[derive(serde::Serialize, serde::Deserialize)]
/// struct Heading {
///     #[serde(with = "turns::serde::degrees")]
///     yaw: Angle32,
/// }
/// # }
/// ```
#[cfg(feature = "serde")]
pub mod serde {
    use crate::Angle;
    use num_traits::{Bounded, NumCast, ToPrimitive, Zero};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    /// Serialize/deserialize an [`Angle<T>`] as the raw inner integer.
    pub mod raw {
        use super::{Angle, Deserialize, Deserializer, Serialize, Serializer};

        pub fn serialize<T, S>(angle: &Angle<T>, serializer: S) -> Result<S::Ok, S::Error>
        where
            T: Serialize,
            S: Serializer,
        {
            angle.0.serialize(serializer)
        }

        pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Angle<T>, D::Error>
        where
            T: Deserialize<'de>,
            D: Deserializer<'de>,
        {
            T::deserialize(deserializer).map(Angle)
        }
    }

    /// Serialize/deserialize an [`Angle<T>`] as an `f64` radian value in `[0, 2π)`.
    ///
    /// Non-finite input on deserialization is coerced to the zero angle (see
    /// [`Angle::from_radians`]).
    pub mod radians {
        use super::{
            Angle, Bounded, Deserialize, Deserializer, NumCast, Serializer, ToPrimitive, Zero,
        };

        pub fn serialize<T, S>(angle: &Angle<T>, serializer: S) -> Result<S::Ok, S::Error>
        where
            T: Copy + NumCast + ToPrimitive + Bounded + Zero,
            S: Serializer,
        {
            serializer.serialize_f64(angle.to_radians::<f64>())
        }

        pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Angle<T>, D::Error>
        where
            T: Copy + NumCast + ToPrimitive + Bounded + Zero,
            D: Deserializer<'de>,
        {
            f64::deserialize(deserializer).map(Angle::<T>::from_radians)
        }
    }

    /// Serialize/deserialize an [`Angle<T>`] as an `f64` degree value in `[0, 360)`.
    ///
    /// Non-finite input on deserialization is coerced to the zero angle (see
    /// [`Angle::from_degrees`]).
    pub mod degrees {
        use super::{
            Angle, Bounded, Deserialize, Deserializer, NumCast, Serializer, ToPrimitive, Zero,
        };

        pub fn serialize<T, S>(angle: &Angle<T>, serializer: S) -> Result<S::Ok, S::Error>
        where
            T: Copy + NumCast + ToPrimitive + Bounded + Zero,
            S: Serializer,
        {
            serializer.serialize_f64(angle.to_degrees::<f64>())
        }

        pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Angle<T>, D::Error>
        where
            T: Copy + NumCast + ToPrimitive + Bounded + Zero,
            D: Deserializer<'de>,
        {
            f64::deserialize(deserializer).map(Angle::<T>::from_degrees)
        }
    }
}

#[cfg(test)]
extern crate alloc;

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::format;
    use core::f64::consts::{PI, TAU};

    #[test]
    fn pi_is_half_circle_u8() {
        assert_eq!(Angle8::from_radians(PI), Angle(0b1000_0000));
    }

    #[test]
    fn zero_and_tau_wrap_to_same() {
        assert_eq!(Angle16::from_radians(0.0_f64), Angle16::from_radians(TAU),);
    }

    #[test]
    fn roundtrip_u32_f64() {
        let a = Angle32::from_radians(1.2345_f64);
        let r: f64 = a.to_radians();
        assert!((r - 1.2345).abs() < 1e-8);
    }

    #[test]
    fn roundtrip_u16_f32() {
        let a = Angle16::from_radians(1.0_f32);
        let r: f32 = a.to_radians();
        assert!((r - 1.0).abs() < 1e-3);
    }

    #[test]
    fn widen_angle8_to_angle16_preserves_pi() {
        assert_eq!(Angle::<u8>(0x80).cast::<u16>(), Angle(0x8000_u16));
    }

    #[test]
    fn narrow_angle16_to_angle8_keeps_top_bits() {
        assert_eq!(Angle::<u16>(0x80FF).cast::<u8>(), Angle(0x80_u8));
    }

    #[test]
    fn identity_same_width() {
        assert_eq!(
            Angle::<u32>(0xDEAD_BEEF).cast::<u32>(),
            Angle(0xDEAD_BEEF_u32),
        );
    }

    #[test]
    fn degrees_180_is_half_circle_u8() {
        assert_eq!(Angle8::from_degrees(180.0_f64), Angle(0x80));
    }

    #[test]
    fn degrees_wrap_at_360() {
        assert_eq!(
            Angle16::from_degrees(0.0_f64),
            Angle16::from_degrees(360.0_f64),
        );
    }

    #[test]
    fn roundtrip_degrees_u32() {
        let a = Angle32::from_degrees(123.456_f64);
        let d: f64 = a.to_degrees();
        assert!((d - 123.456).abs() < 1e-6);
    }

    #[test]
    fn add_wraps_past_tau() {
        let pi: Angle8 = Angle(0x80);
        assert_eq!(pi + pi, Angle(0));
    }

    #[test]
    fn sub_wraps_below_zero() {
        let zero: Angle8 = Angle(0);
        let pi: Angle8 = Angle(0x80);
        assert_eq!(zero - pi, pi);
    }

    #[test]
    fn mul_three_pi_wraps_to_pi() {
        let pi: Angle8 = Angle(0x80);
        assert_eq!(pi * 3_u8, Angle(0x80));
    }

    #[test]
    fn div_halves_pi() {
        let pi: Angle8 = Angle(0x80);
        assert_eq!(pi / 2_u8, Angle(0x40));
    }

    #[test]
    fn checked_mul_detects_overflow() {
        let a: Angle8 = Angle(200);
        assert!(a.checked_mul(2).is_none());
        assert_eq!(a.checked_mul(1), Some(a));
    }

    #[test]
    fn checked_div_by_zero_is_none() {
        let a: Angle8 = Angle(0x80);
        assert!(a.checked_div(0).is_none());
        assert_eq!(a.checked_div(2), Some(Angle(0x40)));
    }

    #[test]
    fn scale_half_pi_gives_quarter_pi() {
        let pi: Angle8 = Angle(0x80);
        assert_eq!(pi.scale(0.5_f64), Angle(0x40));
    }

    #[test]
    fn scale_two_wraps_to_zero() {
        let pi: Angle8 = Angle(0x80);
        assert_eq!(pi.scale(2.0_f64), Angle(0));
    }

    #[test]
    fn constants_match_from_radians() {
        assert_eq!(Angle8::PI, Angle8::from_radians(PI));
        assert_eq!(Angle8::FRAC_PI_2, Angle8::from_radians(PI / 2.0));
        assert_eq!(Angle8::FRAC_PI_4, Angle8::from_radians(PI / 4.0));
        assert_eq!(Angle8::FRAC_PI_8, Angle8::from_radians(PI / 8.0));
        assert_eq!(Angle8::FRAC_PI_3, Angle8::from_radians(PI / 3.0));
        assert_eq!(Angle8::FRAC_PI_6, Angle8::from_radians(PI / 6.0));
        assert_eq!(Angle8::TAU, Angle8::ZERO);
        assert_eq!(Angle8::ZERO, Angle(0));
        assert_eq!(Angle8::PI, Angle(0x80));
        assert_eq!(Angle8::FRAC_PI_2, Angle(0x40));
    }

    #[test]
    fn neg_pi_is_pi() {
        let pi: Angle8 = Angle(0x80);
        assert_eq!(-pi, pi);
    }

    #[test]
    fn neg_frac_pi_2_is_three_quarter_turn() {
        let quarter: Angle8 = Angle(0x40);
        assert_eq!(-quarter, Angle(0xC0));
    }

    #[test]
    fn from_atan2_north_is_frac_pi_2() {
        let a = Angle64::from_atan2(1.0_f64, 0.0_f64);
        assert_eq!(a, Angle64::FRAC_PI_2);
    }

    #[test]
    fn tan_frac_pi_4_is_one() {
        let t: f64 = Angle64::FRAC_PI_4.tan();
        assert!((t - 1.0).abs() < 1e-9);
    }

    #[test]
    fn sin_cos_matches_individual() {
        let a: Angle32 = Angle::<u32>(0x1234_5678);
        let (s, c): (f64, f64) = a.sin_cos();
        assert!((s - a.sin::<f64>()).abs() < 1e-12);
        assert!((c - a.cos::<f64>()).abs() < 1e-12);
    }

    #[test]
    fn sin_pi_is_near_zero() {
        let pi: Angle8 = Angle(0x80);
        let s: f64 = pi.sin();
        assert!(s.abs() < 1e-9);
    }

    #[test]
    fn cos_zero_is_one() {
        let zero: Angle16 = Angle(0);
        let c: f64 = zero.cos();
        assert!((c - 1.0).abs() < 1e-9);
    }

    #[test]
    fn cos_pi_is_minus_one() {
        let pi: Angle8 = Angle(0x80);
        let c: f64 = pi.cos();
        assert!((c + 1.0).abs() < 1e-9);
    }

    #[test]
    fn from_radians_nan_is_zero() {
        assert_eq!(Angle8::from_radians(f64::NAN), Angle(0));
        assert_eq!(Angle8::from_radians(f64::INFINITY), Angle(0));
        assert_eq!(Angle8::from_radians(f64::NEG_INFINITY), Angle(0));
    }

    #[test]
    fn from_degrees_non_finite_is_zero() {
        assert_eq!(Angle16::from_degrees(f32::NAN), Angle(0));
        assert_eq!(Angle16::from_degrees(f32::INFINITY), Angle(0));
    }

    #[test]
    fn scale_non_finite_is_zero() {
        let pi: Angle8 = Angle(0x80);
        assert_eq!(pi.scale(f64::NAN), Angle(0));
        assert_eq!(pi.scale(f64::INFINITY), Angle(0));
    }

    #[test]
    fn scale_negative_wraps() {
        let half_pi: Angle8 = Angle(0x40);
        assert_eq!(half_pi.scale(-1.0_f64), Angle(0xC0));
    }

    #[test]
    fn ratio_pi_over_half_pi_is_two() {
        let pi: Angle8 = Angle(0x80);
        let half_pi: Angle8 = Angle(0x40);
        let r: f64 = pi.ratio(half_pi);
        assert!((r - 2.0).abs() < 1e-9);
    }

    #[test]
    fn shl_doubles_angle() {
        let eighth: Angle8 = Angle(0x20);
        assert_eq!(eighth << 1, Angle(0x40));
    }

    #[test]
    fn shr_halves_pi() {
        let pi: Angle8 = Angle(0x80);
        assert_eq!(pi >> 1, Angle(0x40));
    }

    #[test]
    fn shl_past_width_saturates_to_zero() {
        let a: Angle8 = Angle(0xFF);
        assert_eq!(a << 8, Angle(0));
        assert_eq!(a << 100, Angle(0));
    }

    #[test]
    fn shr_past_width_saturates_to_zero() {
        let a: Angle8 = Angle(0xFF);
        assert_eq!(a >> 8, Angle(0));
        assert_eq!(a >> 100, Angle(0));
    }

    #[test]
    fn widen_then_narrow_is_lossless() {
        let a: Angle8 = Angle(0b1010_1010);
        assert_eq!(a.cast::<u128>().cast::<u8>(), a);
    }

    #[test]
    fn display_three_pi_over_two() {
        assert_eq!(format!("{}", Angle::<u8>(0b1100_0000)), "3π/2");
    }

    #[test]
    fn display_zero() {
        assert_eq!(format!("{}", Angle8::ZERO), "0");
    }

    #[test]
    fn display_pi() {
        assert_eq!(format!("{}", Angle8::PI), "π");
    }

    #[test]
    fn display_frac_pi_2() {
        assert_eq!(format!("{}", Angle8::FRAC_PI_2), "π/2");
    }

    #[test]
    fn display_frac_pi_4() {
        assert_eq!(format!("{}", Angle8::FRAC_PI_4), "π/4");
    }

    #[test]
    fn display_three_pi_over_four() {
        assert_eq!(format!("{}", Angle::<u8>(0b0110_0000)), "3π/4");
    }

    #[test]
    fn display_angle16_small_numerator() {
        assert_eq!(format!("{}", Angle::<u16>(1)), "π/32768");
    }

    #[test]
    fn to_frac_three_pi_over_two() {
        assert_eq!(Angle::<u8>(0b1100_0000).to_frac(), (3, 2));
    }

    #[test]
    fn to_frac_zero() {
        assert_eq!(Angle8::ZERO.to_frac(), (0, 1));
    }

    #[test]
    fn to_frac_pi() {
        assert_eq!(Angle8::PI.to_frac(), (1, 1));
    }

    #[test]
    fn to_frac_odd_numerator_keeps_full_denominator() {
        assert_eq!(Angle::<u16>(1).to_frac(), (1, 32768));
    }

    #[test]
    fn from_frac_three_pi_over_two() {
        assert_eq!(Angle8::from_frac(3, 2), Angle(0xC0));
    }

    #[test]
    fn from_frac_pi_is_half_circle() {
        assert_eq!(Angle8::from_frac(1, 1), Angle8::PI);
    }

    #[test]
    fn from_frac_zero() {
        assert_eq!(Angle8::from_frac(0, 1), Angle8::ZERO);
    }

    #[test]
    fn from_frac_wraps_past_two_pi() {
        assert_eq!(Angle8::from_frac(3, 1), Angle8::PI);
        assert_eq!(Angle8::from_frac(5, 2), Angle8::FRAC_PI_2);
    }

    #[test]
    fn from_frac_quarter_turn() {
        assert_eq!(Angle8::from_frac(1, 2), Angle8::FRAC_PI_2);
    }

    #[test]
    fn from_frac_roundtrips_to_frac() {
        let cases: [Angle8; 6] = [
            Angle8::ZERO,
            Angle8::PI,
            Angle8::FRAC_PI_2,
            Angle8::FRAC_PI_4,
            Angle8::FRAC_PI_8,
            Angle(0b1010_0000),
        ];
        for a in cases {
            let (n, d) = a.to_frac();
            assert_eq!(Angle8::from_frac(n, d), a);
        }
    }
}

#[cfg(all(test, feature = "serde"))]
mod serde_tests {
    use super::{Angle, Angle8, Angle32};
    use ::serde::{Deserialize, Serialize};
    use core::f64::consts::PI;

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    #[serde(crate = "::serde")]
    struct Raw {
        #[serde(with = "crate::serde::raw")]
        a: Angle8,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    #[serde(crate = "::serde")]
    struct Rads {
        #[serde(with = "crate::serde::radians")]
        a: Angle32,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    #[serde(crate = "::serde")]
    struct Degs {
        #[serde(with = "crate::serde::degrees")]
        a: Angle32,
    }

    #[test]
    fn raw_serializes_as_inner_integer() {
        let v = Raw { a: Angle8::PI };
        assert_eq!(serde_json::to_string(&v).unwrap(), r#"{"a":128}"#);
    }

    #[test]
    fn raw_roundtrip_is_exact() {
        let v = Raw { a: Angle(0xA5) };
        let s = serde_json::to_string(&v).unwrap();
        assert_eq!(serde_json::from_str::<Raw>(&s).unwrap(), v);
    }

    #[test]
    fn radians_roundtrip_within_precision() {
        let v = Rads {
            a: Angle32::from_radians(1.2345_f64),
        };
        let s = serde_json::to_string(&v).unwrap();
        let r: Rads = serde_json::from_str(&s).unwrap();
        let delta: f64 = (r.a - v.a).to_radians();
        let delta = delta.min(core::f64::consts::TAU - delta);
        assert!(delta < 1e-8, "delta = {delta}");
    }

    #[test]
    fn radians_serializes_pi() {
        let v = Rads {
            a: Angle32::from_radians(PI),
        };
        let s = serde_json::to_string(&v).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&s).unwrap();
        let f = parsed["a"].as_f64().unwrap();
        assert!((f - PI).abs() < 1e-9);
    }

    #[test]
    fn degrees_roundtrip_within_precision() {
        let v = Degs {
            a: Angle32::from_degrees(123.456_f64),
        };
        let s = serde_json::to_string(&v).unwrap();
        let r: Degs = serde_json::from_str(&s).unwrap();
        let delta: f64 = (r.a - v.a).to_degrees();
        let delta = delta.min(360.0 - delta);
        assert!(delta < 1e-6, "delta = {delta}");
    }

    #[test]
    fn degrees_serializes_180() {
        let v = Degs {
            a: Angle32::from_degrees(180.0_f64),
        };
        assert_eq!(serde_json::to_string(&v).unwrap(), r#"{"a":180.0}"#);
    }
}