relp-num 0.2.1

Number types for the relp crate
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
use std::cmp::Ordering;
use std::iter::Sum;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
use std::ops::Neg;

use crate::Negateable;
use crate::non_zero::NonZero;
use crate::non_zero::NonZeroSign;
use crate::rational::small::{Rational128, Rational16, Rational32, Rational64, Rational8, RationalUsize};
use crate::rational::small::{NonZeroRational128, NonZeroRational16, NonZeroRational32, NonZeroRational64, NonZeroRational8, NonZeroRationalUsize};
use crate::rational::small::ops::building_blocks::{add128, add16, add32, add64, add8, add_usize};
use crate::rational::small::ops::building_blocks::{sub128, sub16, sub32, sub64, sub8, sub_usize};
use crate::rational::small::ops::building_blocks::{mul128, mul16, mul32, mul64, mul8, mul_usize};
use crate::rational::small::ops::building_blocks::SignChange;
use crate::sign::Sign;

pub(crate) mod building_blocks;
mod with_int;
mod with_one;
mod with_zero;

#[cfg(test)]
mod test;

macro_rules! rational {
    ($name:ident, $add_name:ident, $sub_name:ident, $mul_name:ident) => {
        impl AddAssign<&$name> for $name {
            #[inline]
            fn add_assign(&mut self, rhs: &Self) {
                match (self.sign, rhs.sign) {
                    (Sign::Positive, Sign::Positive) | (Sign::Negative, Sign::Negative) => {
                        $add_name(
                            &mut self.numerator,
                            &mut self.denominator,
                            rhs.numerator,
                            rhs.denominator,
                        )
                    }
                    (Sign::Positive, Sign::Negative) | (Sign::Negative, Sign::Positive) => {
                        let sign_change = $sub_name(
                            &mut self.numerator,
                            &mut self.denominator,
                            rhs.numerator,
                            rhs.denominator,
                        );
                        match sign_change {
                            SignChange::None => {}
                            SignChange::Flip => self.sign.negate(),
                            SignChange::Zero => self.sign = Sign::Zero,
                        }
                    }
                    (_, Sign::Zero) => {},
                    (Sign::Zero, _) => {
                        *self = Self {
                            sign: rhs.sign,
                            numerator: rhs.numerator,
                            denominator: rhs.denominator,
                        };
                    },
                }
            }
        }

        impl SubAssign<&$name> for $name {
            #[inline]
            fn sub_assign(&mut self, rhs: &Self) {
                match (self.sign, rhs.sign) {
                    (Sign::Positive, Sign::Positive) | (Sign::Negative, Sign::Negative) => {
                        let sign_change = $sub_name(
                            &mut self.numerator,
                            &mut self.denominator,
                            rhs.numerator,
                            rhs.denominator,
                        );
                        match sign_change {
                            SignChange::None => {}
                            SignChange::Flip => self.sign.negate(),
                            SignChange::Zero => self.sign = Sign::Zero,
                        }
                    }
                    (Sign::Positive, Sign::Negative) | (Sign::Negative, Sign::Positive) => {
                        $add_name(
                            &mut self.numerator,
                            &mut self.denominator,
                            rhs.numerator,
                            rhs.denominator,
                        )
                    }
                    (_, Sign::Zero) => {}
                    (Sign::Zero, _) => {
                        *self = Self {
                            sign: !rhs.sign,
                            numerator: rhs.numerator,
                            denominator: rhs.denominator,
                        };
                    }
                }
            }
        }

        impl Sum for $name {
            fn sum<I: Iterator<Item=Self>>(mut iter: I) -> Self {
                let first_value = iter.next();
                match first_value {
                    None => <Self as num_traits::Zero>::zero(),
                    Some(mut total) => {

                        while let Some(next_value) = iter.next() {
                            total += next_value;
                        }

                        total
                    }
                }
            }
        }

        impl MulAssign<&$name> for $name {
            #[inline]
            fn mul_assign(&mut self, rhs: &Self) {
                match (self.sign, rhs.sign) {
                    (Sign::Positive | Sign::Negative, Sign::Positive | Sign::Negative) => {
                        self.sign *= rhs.sign;
                        $mul_name(&mut self.numerator, &mut self.denominator, rhs.numerator, rhs.denominator);
                    }
                    (Sign::Zero, _) => {}
                    (_, Sign::Zero) => <Self as num_traits::Zero>::set_zero(self),
                }
            }
        }

        // The sign of a quotient is the product of the signs, so `*` is correct here.
        #[allow(clippy::suspicious_arithmetic_impl)]
        impl Div<$name> for &$name {
            type Output = $name;

            #[inline]
            fn div(self, mut rhs: $name) -> Self::Output {
                match (self.sign, rhs.sign) {
                    (Sign::Positive | Sign::Negative, Sign::Positive | Sign::Negative) => {
                        let sign = self.sign * rhs.sign;
                        $mul_name(&mut rhs.numerator, &mut rhs.denominator, self.denominator, self.numerator);
                        Self::Output {
                            sign,
                            numerator: rhs.denominator,
                            denominator: rhs.numerator,
                        }
                    }
                    (_, Sign::Zero) => panic!(),
                    (Sign::Zero, _) => {
                        <$name as num_traits::Zero>::set_zero(&mut rhs);
                        rhs
                    }
                }
            }
        }

        // The sign of a quotient is the product of the signs, so `*` is correct here.
        #[allow(clippy::suspicious_op_assign_impl)]
        impl DivAssign<&$name> for $name {
            #[inline]
            fn div_assign(&mut self, rhs: &Self) {
                match (self.sign, rhs.sign) {
                    (Sign::Positive | Sign::Negative, Sign::Positive | Sign::Negative) => {
                        self.sign *= rhs.sign;
                        $mul_name(&mut self.numerator, &mut self.denominator, rhs.denominator, rhs.numerator);
                    }
                    (_, Sign::Zero) => panic!(),
                    (Sign::Zero, _) => {}
                }
            }
        }
    }
}

rational!(Rational8, add8, sub8, mul8);
rational!(Rational16, add16, sub16, mul16);
rational!(Rational32, add32, sub32, mul32);
rational!(Rational64, add64, sub64, mul64);
rational!(Rational128, add128, sub128, mul128);
rational!(RationalUsize, add_usize, sub_usize, mul_usize);

macro_rules! rational_non_zero {
    ($name:ident, $add_name:ident, $sub_name:ident, $mul_name:ident) => {
        impl AddAssign<&$name> for $name {
            #[inline]
            fn add_assign(&mut self, rhs: &Self) {
                match (self.sign, rhs.sign) {
                    (NonZeroSign::Positive, NonZeroSign::Positive) | (NonZeroSign::Negative, NonZeroSign::Negative) => {
                        $add_name(
                            &mut self.numerator,
                            &mut self.denominator,
                            rhs.numerator,
                            rhs.denominator,
                        )
                    }
                    (NonZeroSign::Positive, NonZeroSign::Negative) | (NonZeroSign::Negative, NonZeroSign::Positive) => {
                        let sign_change = $sub_name(
                            &mut self.numerator,
                            &mut self.denominator,
                            rhs.numerator,
                            rhs.denominator,
                        );
                        match sign_change {
                            SignChange::None => {}
                            SignChange::Flip => self.sign.negate(),
                            // Adding opposite signs subtracts the magnitudes, which can cancel
                            // exactly. That is not an overflow: the result is zero, which this
                            // type deliberately cannot represent.
                            SignChange::Zero => panic!(concat!(
                                "the result of this addition is zero, which ", stringify!($name),
                                " cannot represent",
                            )),
                        }
                    }
                }
            }
        }
        impl SubAssign<&$name> for $name {
            #[inline]
            fn sub_assign(&mut self, rhs: &Self) {
                match (self.sign, rhs.sign) {
                    (NonZeroSign::Positive, NonZeroSign::Positive) | (NonZeroSign::Negative, NonZeroSign::Negative) => {
                        let sign_change = $sub_name(
                            &mut self.numerator,
                            &mut self.denominator,
                            rhs.numerator,
                            rhs.denominator,
                        );
                        match sign_change {
                            SignChange::None => {}
                            SignChange::Flip => self.sign.negate(),
                            // Equal values subtract to zero, which this type cannot represent.
                            SignChange::Zero => panic!(concat!(
                                "the result of this subtraction is zero, which ", stringify!($name),
                                " cannot represent",
                            )),
                        }
                    }
                    (NonZeroSign::Positive, NonZeroSign::Negative) | (NonZeroSign::Negative, NonZeroSign::Positive) => {
                        $add_name(
                            &mut self.numerator,
                            &mut self.denominator,
                            rhs.numerator,
                            rhs.denominator,
                        )
                    }
                }
            }
        }
        impl MulAssign<&$name> for $name {
            #[inline]
            fn mul_assign(&mut self, rhs: &Self) {
                self.sign *= rhs.sign;
                $mul_name(&mut self.numerator, &mut self.denominator, rhs.numerator, rhs.denominator);
            }
        }
        // The sign of a quotient is the product of the signs, so `*` is correct here.
        #[allow(clippy::suspicious_arithmetic_impl)]
        impl Div<$name> for &$name {
            type Output = $name;

            #[inline]
            fn div(self, mut rhs: $name) -> Self::Output {
                let sign = self.sign * rhs.sign;
                $mul_name(&mut rhs.numerator, &mut rhs.denominator, self.denominator, self.numerator);
                Self::Output {
                    sign,
                    numerator: rhs.denominator,
                    denominator: rhs.numerator,
                }
            }
        }
        // The sign of a quotient is the product of the signs, so `*` is correct here.
        #[allow(clippy::suspicious_op_assign_impl)]
        impl DivAssign<&$name> for $name {
            #[inline]
            fn div_assign(&mut self, rhs: &Self) {
                self.sign *= rhs.sign;
                $mul_name(&mut self.numerator, &mut self.denominator, rhs.denominator, rhs.numerator);
            }
        }

        impl Neg for $name {
            type Output = Self;

            #[inline]
            fn neg(mut self) -> Self::Output {
                self.sign.negate();
                self
            }
        }

        impl Neg for &$name {
            type Output = $name;

            #[inline]
            fn neg(self) -> Self::Output {
                Self::Output {
                    sign: !self.sign,
                    numerator: self.numerator,
                    denominator: self.denominator,
                }
            }
        }
    }
}
rational_non_zero!(NonZeroRational8, add8, sub8, mul8);
rational_non_zero!(NonZeroRational16, add16, sub16, mul16);
rational_non_zero!(NonZeroRational32, add32, sub32, mul32);
rational_non_zero!(NonZeroRational64, add64, sub64, mul64);
rational_non_zero!(NonZeroRational128, add128, sub128, mul128);
rational_non_zero!(NonZeroRationalUsize, add_usize, sub_usize, mul_usize);

/// Compare two ratios by cross multiplication.
///
/// `$widening_mul` computes the exact product of two magnitudes as a tuple that orders like the
/// number it represents: the most significant half first. Comparing the two tuples
/// lexicographically therefore compares `a * d` against `b * c` exactly, which is the comparison
/// of `a / b` against `c / d` because both denominators are positive.
macro_rules! rational_ord {
    ($name:ident, $sign:ident, $widening_mul:expr) => {
        impl PartialOrd for $name {
            #[inline]
            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
                Some(self.cmp(other))
            }
        }

        impl Ord for $name {
            #[inline]
            #[allow(unreachable_patterns)]
            fn cmp(&self, other: &Self) -> Ordering {
                match self.sign.cmp(&other.sign) {
                    Ordering::Less => return Ordering::Less,
                    Ordering::Greater => return Ordering::Greater,
                    // Both zero, or both nonzero with the same sign; compare the magnitudes.
                    Ordering::Equal => {}
                }

                if !self.sign.is_not_zero() {
                    // Equal signs and the sign is zero, so both values are zero.
                    return Ordering::Equal;
                }

                let widening_mul = $widening_mul;

                let ad = widening_mul(self.numerator, other.denominator);
                let bc = widening_mul(self.denominator, other.numerator);

                match (ad.cmp(&bc), self.sign) {
                    (Ordering::Less, $sign::Positive) | (Ordering::Greater, $sign::Negative) => Ordering::Less,
                    (Ordering::Equal, _) => Ordering::Equal,
                    (Ordering::Greater, $sign::Positive) | (Ordering::Less, $sign::Negative) => Ordering::Greater,
                    _ => unreachable!("sign was checked to be nonzero"),
                }
            }
        }
    }
}

/// Order a ratio by cross multiplying its magnitudes.
///
/// The two products are the `(high, low)` pairs [`carrying_mul`](u64::carrying_mul) returns: with
/// a zero carry it is a widening multiply, which every width has, including the widest one, where
/// no doubled width integer exists to widen into.
///
/// Comparing by the continued fraction expansion of the two ratios would avoid the wide product
/// altogether, but it costs a division per term of the expansion rather than a single
/// multiplication, and the number of terms is not bounded by anything better than the width.
macro_rules! rational_cross_multiplying_ord {
    ($name:ident, $uty:ty, $sign:ident) => {
        rational_ord!($name, $sign, |left: $uty, right: $uty| {
            // `carrying_mul` returns the low half first.
            let (low, high) = left.carrying_mul(right, 0);
            (high, low)
        });
    }
}

rational_cross_multiplying_ord!(Rational8, u8, Sign);
rational_cross_multiplying_ord!(Rational16, u16, Sign);
rational_cross_multiplying_ord!(Rational32, u32, Sign);
rational_cross_multiplying_ord!(Rational64, u64, Sign);
rational_cross_multiplying_ord!(RationalUsize, usize, Sign);
rational_cross_multiplying_ord!(Rational128, u128, Sign);
rational_cross_multiplying_ord!(NonZeroRational8, u8, NonZeroSign);
rational_cross_multiplying_ord!(NonZeroRational16, u16, NonZeroSign);
rational_cross_multiplying_ord!(NonZeroRational32, u32, NonZeroSign);
rational_cross_multiplying_ord!(NonZeroRational64, u64, NonZeroSign);
rational_cross_multiplying_ord!(NonZeroRationalUsize, usize, NonZeroSign);
rational_cross_multiplying_ord!(NonZeroRational128, u128, NonZeroSign);

macro_rules! rational_forward {
    ($name:ident) => {
        impl<'a> Add<&'a $name> for &'a $name {
            type Output = $name;

            #[inline]
            fn add(self, rhs: Self) -> Self::Output {
                Add::add(self.clone(), rhs)
            }
        }

        impl Add for $name {
            type Output = Self;

            #[inline]
            fn add(mut self, rhs: Self) -> Self::Output {
                AddAssign::add_assign(&mut self, rhs);
                self
            }
        }

        impl Add<&$name> for $name {
            type Output = Self;

            #[inline]
            fn add(mut self, rhs: &Self) -> Self::Output {
                AddAssign::add_assign(&mut self, rhs);
                self
            }
        }

        impl Add<$name> for &$name {
            type Output = $name;

            #[inline]
            fn add(self, rhs: $name) -> Self::Output {
                Add::add(rhs, self)
            }
        }

        impl AddAssign for $name {
            #[inline]
            fn add_assign(&mut self, rhs: Self) {
                AddAssign::add_assign(self, &rhs);
            }
        }

        impl Sub for $name {
            type Output = Self;

            #[inline]
            fn sub(mut self, rhs: Self) -> Self::Output {
                SubAssign::sub_assign(&mut self, rhs);
                self
            }
        }

        impl<'a> Sub<&'a $name> for &'a $name {
            type Output = $name;

            #[inline]
            fn sub(self, rhs: Self) -> Self::Output {
                Sub::sub(self.clone(), rhs)
            }
        }

        impl Sub<&$name> for $name {
            type Output = Self;

            #[inline]
            fn sub(mut self, rhs: &Self) -> Self::Output {
                SubAssign::sub_assign(&mut self, rhs);
                self
            }
        }

        impl Sub<$name> for &$name {
            type Output = $name;

            #[inline]
            fn sub(self, rhs: $name) -> Self::Output {
                -Sub::sub(rhs, self)
            }
        }

        impl SubAssign for $name {
            #[inline]
            fn sub_assign(&mut self, rhs: Self) {
                SubAssign::sub_assign(self, &rhs)
            }
        }

        impl Mul<&$name> for $name {
            type Output = Self;

            #[inline]
            fn mul(mut self, rhs: &Self) -> Self::Output {
                MulAssign::mul_assign(&mut self, rhs);
                self
            }
        }

        impl<'a> Mul<&'a $name> for &'a $name {
            type Output = $name;

            #[inline]
            fn mul(self, rhs: Self) -> Self::Output {
                Mul::mul(self.clone(), rhs)
            }
        }

        impl Mul for $name {
            type Output = Self;

            #[inline]
            fn mul(mut self, rhs: Self) -> Self::Output {
                MulAssign::mul_assign(&mut self, rhs);
                self
            }
        }

        impl MulAssign for $name {
            #[inline]
            fn mul_assign(&mut self, rhs: Self) {
                MulAssign::mul_assign(self, &rhs);
            }
        }

        impl Mul<$name> for &$name {
            type Output = $name;

            #[inline]
            fn mul(self, rhs: $name) -> Self::Output {
                Mul::mul(rhs, self)
            }
        }

        impl Div for $name {
            type Output = Self;

            #[inline]
            fn div(mut self, rhs: Self) -> Self::Output {
                DivAssign::div_assign(&mut self, rhs);
                self
            }
        }

        impl Div<&$name> for $name {
            type Output = Self;

            #[inline]
            fn div(mut self, rhs: &Self) -> Self::Output {
                DivAssign::div_assign(&mut self, rhs);
                self
            }
        }

        impl<'a> Div<&'a $name> for &'a $name {
            type Output = $name;

            #[inline]
            fn div(self, rhs: Self) -> Self::Output {
                Div::div(self.clone(), rhs)
            }
        }

        impl DivAssign for $name {
            #[inline]
            fn div_assign(&mut self, rhs: Self) {
                DivAssign::div_assign(self, &rhs);
            }
        }
    }
}

rational_forward!(Rational8);
rational_forward!(Rational16);
rational_forward!(Rational32);
rational_forward!(Rational64);
rational_forward!(Rational128);
rational_forward!(RationalUsize);
rational_forward!(NonZeroRational8);
rational_forward!(NonZeroRational16);
rational_forward!(NonZeroRational32);
rational_forward!(NonZeroRational64);
rational_forward!(NonZeroRational128);
rational_forward!(NonZeroRationalUsize);

#[cfg(test)]
mod order_test {
    use std::cmp::Ordering;

    use crate::{Field, OrderedField};
    use crate::non_zero::NonZeroSign;
    use crate::rational::Ratio;
    use crate::rational::small::{NonZeroRational128, NonZeroRationalUsize, Rational128, RationalUsize};
    use crate::sign::Sign;

    /// Build a value directly, to reach magnitudes that the `new` constructors can't take.
    ///
    /// The caller is responsible for the invariants: lowest terms, nonzero denominator and a sign
    /// that is zero exactly when the numerator is.
    fn ratio128(sign: Sign, numerator: u128, denominator: u128) -> Rational128 {
        Ratio { sign, numerator, denominator }
    }

    fn ratio_usize(sign: Sign, numerator: usize, denominator: usize) -> RationalUsize {
        Ratio { sign, numerator, denominator }
    }

    /// The widest types used to have no total order, and so were not fields either.
    #[test]
    fn test_ordered_field() {
        fn assert_field<T: Field>() {}
        fn assert_ordered_field<T: OrderedField>() {}
        fn assert_ord<T: Ord>() {}

        assert_field::<Rational128>();
        assert_ordered_field::<Rational128>();
        assert_field::<RationalUsize>();
        assert_ordered_field::<RationalUsize>();

        assert_ord::<NonZeroRational128>();
        assert_ord::<NonZeroRationalUsize>();

        // `Abs` is implemented for ratios that are ordered.
        assert_eq!(crate::Abs::abs(ratio128(Sign::Negative, u128::MAX, 2)), ratio128(Sign::Positive, u128::MAX, 2));
        assert_eq!(crate::Abs::abs(ratio_usize(Sign::Negative, usize::MAX, 2)), ratio_usize(Sign::Positive, usize::MAX, 2));
    }

    /// All pairs and triples of a small range, against an exact `f64` reference.
    #[test]
    fn test_order_usize_brute_force() {
        let mut values = Vec::new();
        for numerator in -5_isize..=5 {
            for denominator in 1_usize..=5 {
                let value = RationalUsize::new(numerator, denominator).unwrap();
                values.push((value, numerator as f64 / denominator as f64));
            }
        }

        for &(left, left_float) in &values {
            for &(right, right_float) in &values {
                let expected = left_float.partial_cmp(&right_float).unwrap();

                assert_eq!(left.cmp(&right), expected, "{:?} <=> {:?}", left, right);
                assert_eq!(left.partial_cmp(&right), Some(expected));
                // Antisymmetry.
                assert_eq!(right.cmp(&left), expected.reverse(), "{:?} <=> {:?}", right, left);
                // Agreement with `PartialEq`.
                assert_eq!(left == right, expected == Ordering::Equal, "{:?} == {:?}", left, right);
            }
        }

        // Transitivity.
        for &(left, _) in &values {
            for &(middle, _) in &values {
                if left > middle {
                    continue;
                }

                for &(right, _) in &values {
                    if middle <= right {
                        assert!(left <= right, "{:?} <= {:?} <= {:?}", left, middle, right);
                    }
                }
            }
        }
    }

    /// Products that don't fit a `usize`, which is why the comparison multiplies into a `u128`.
    #[test]
    fn test_order_usize_wide_product() {
        // `(2 ^ (usize::BITS - 1) + 1) * 2` wraps to `2` in a `usize`, which is less than `1 * 3`,
        // so a comparison that multiplies at the width of the type gets this pair backwards.
        let large = ratio_usize(Sign::Positive, (1 << (usize::BITS - 1)) + 1, 1);
        let small = ratio_usize(Sign::Positive, 3, 2);
        assert!(large > small);
        assert!(small < large);
        assert!(-large < -small);

        // The difference between these two is in the low half of the product.
        let left = ratio_usize(Sign::Positive, usize::MAX, usize::MAX - 1);
        let right = ratio_usize(Sign::Positive, usize::MAX - 1, usize::MAX - 2);
        assert!(left < right);
        assert!(right > left);
        assert_eq!(left.cmp(&left), Ordering::Equal);
        assert_eq!(right.cmp(&right), Ordering::Equal);
        assert_eq!(left.cmp(&right).reverse(), right.cmp(&left));
    }

    /// Magnitudes above `u64::MAX`, whose products need more than the 128 bits of a `u128`.
    #[test]
    fn test_order_128_above_64_bits() {
        // `(2 ^ 127 + 1) * 2` wraps to `2` in a `u128`, which is less than `1 * 3`.
        let large = ratio128(Sign::Positive, (1 << 127) + 1, 1);
        let small = ratio128(Sign::Positive, 3, 2);
        assert!(large > small);
        assert!(small < large);
        assert!(-large < -small);

        // `1 + 1 / 2 ^ 64` against `1 + 1 / (2 ^ 64 + 1)`; both cross products exceed a `u128`.
        let left = ratio128(Sign::Positive, (1 << 64) + 1, 1 << 64);
        let right = ratio128(Sign::Positive, (1 << 64) + 2, (1 << 64) + 1);
        assert!(left > right);
        assert!(right < left);

        // The two products are `2 ^ 254 - 2 ^ 128` and `2 ^ 254 - 2 ^ 128 + 1`: they share their
        // high 128 bits and differ in the last bit of the low half.
        let left = ratio128(Sign::Positive, 1 << 127, (1 << 127) - 1);
        let right = ratio128(Sign::Positive, (1 << 127) - 1, (1 << 127) - 2);
        assert!(left < right);
        assert!(right > left);
        assert_eq!(left.cmp(&left), Ordering::Equal);
        assert_eq!(left.cmp(&right).reverse(), right.cmp(&left));

        // Large values that differ only in the last bit of the numerator.
        let left = ratio128(Sign::Positive, u128::MAX, 2);
        let right = ratio128(Sign::Positive, u128::MAX - 2, 2);
        assert!(left > right);
        assert!(-left < -right);
    }

    #[test]
    fn test_order_128_signs() {
        let zero = ratio128(Sign::Zero, 0, 1);
        let positive = ratio128(Sign::Positive, u128::MAX, u128::MAX - 1);
        let negative = ratio128(Sign::Negative, 1, u128::MAX);

        assert_eq!(zero.cmp(&zero), Ordering::Equal);
        assert_eq!(zero.cmp(&positive), Ordering::Less);
        assert_eq!(positive.cmp(&zero), Ordering::Greater);
        assert_eq!(zero.cmp(&negative), Ordering::Greater);
        assert_eq!(negative.cmp(&zero), Ordering::Less);
        assert_eq!(negative.cmp(&positive), Ordering::Less);
        assert_eq!(positive.cmp(&negative), Ordering::Greater);
        assert_eq!(positive.cmp(&positive), Ordering::Equal);
        assert_eq!(negative.cmp(&negative), Ordering::Equal);

        // Negation reverses the order of the magnitudes.
        let left = ratio128(Sign::Negative, (1 << 100) + 1, (1 << 100) - 1);
        let right = ratio128(Sign::Negative, (1 << 100) + 3, (1 << 100) - 1);
        assert!(left > right);
        assert!(-left < -right);
    }

    /// Compare `a / b` against `c / d` by their continued fraction expansions.
    ///
    /// This never computes a product, so it is independent of the implementation under test.
    fn euclidean_cmp(mut a: u128, mut b: u128, mut c: u128, mut d: u128) -> Ordering {
        let mut reversed = false;

        loop {
            let (left_quotient, left_remainder) = (a / b, a % b);
            let (right_quotient, right_remainder) = (c / d, c % d);

            let ordering = if left_quotient != right_quotient {
                left_quotient.cmp(&right_quotient)
            } else {
                match (left_remainder == 0, right_remainder == 0) {
                    (true, true) => Ordering::Equal,
                    (true, false) => Ordering::Less,
                    (false, true) => Ordering::Greater,
                    (false, false) => {
                        // Recurse on the reciprocals of the remainders, which flips the order.
                        a = b;
                        b = left_remainder;
                        c = d;
                        d = right_remainder;
                        reversed = !reversed;
                        continue;
                    }
                }
            };

            return if reversed { ordering.reverse() } else { ordering };
        }
    }

    #[test]
    fn test_order_128_against_continued_fractions() {
        fn gcd(mut left: u128, mut right: u128) -> u128 {
            while right != 0 {
                let remainder = left % right;
                left = right;
                right = remainder;
            }
            left
        }

        // A linear congruential generator, so that the values are reproducible.
        let mut state = 0x2545_f491_4f6c_dd1d_u64;
        let mut next = || {
            let mut value = 0_u128;
            for _ in 0..2 {
                state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
                value = (value << 64) | (state >> 1) as u128;
            }
            // Zero magnitudes are not representable in a nonzero ratio.
            value.max(1)
        };

        for _ in 0..200 {
            let (mut a, mut b, mut c, mut d) = (next(), next(), next(), next());
            let (left_gcd, right_gcd) = (gcd(a, b), gcd(c, d));
            a /= left_gcd;
            b /= left_gcd;
            c /= right_gcd;
            d /= right_gcd;

            let expected = euclidean_cmp(a, b, c, d);
            let left = ratio128(Sign::Positive, a, b);
            let right = ratio128(Sign::Positive, c, d);

            assert_eq!(left.cmp(&right), expected, "{} / {} <=> {} / {}", a, b, c, d);
            assert_eq!(right.cmp(&left), expected.reverse(), "{} / {} <=> {} / {}", c, d, a, b);
            assert_eq!((-left).cmp(&-right), expected.reverse());
            assert_eq!(left == right, expected == Ordering::Equal);
        }
    }

    /// Small values of the widest type, against an exact `f64` reference.
    #[test]
    fn test_order_128_brute_force() {
        let mut values = Vec::new();
        for numerator in -5_i128..=5 {
            for denominator in 1_u128..=5 {
                let value = Rational128::new(numerator, denominator).unwrap();
                values.push((value, numerator as f64 / denominator as f64));
            }
        }

        for &(left, left_float) in &values {
            for &(right, right_float) in &values {
                let expected = left_float.partial_cmp(&right_float).unwrap();

                assert_eq!(left.cmp(&right), expected, "{:?} <=> {:?}", left, right);
                assert_eq!(right.cmp(&left), expected.reverse());
                assert_eq!(left == right, expected == Ordering::Equal);
            }
        }
    }

    #[test]
    fn test_order_non_zero() {
        let left: NonZeroRational128 = Ratio { sign: NonZeroSign::Positive, numerator: (1 << 127) + 1, denominator: 1 };
        let right: NonZeroRational128 = Ratio { sign: NonZeroSign::Positive, numerator: 3, denominator: 2 };
        assert!(left > right);
        assert!(-left < -right);

        let left: NonZeroRationalUsize = Ratio { sign: NonZeroSign::Positive, numerator: usize::MAX, denominator: usize::MAX - 1 };
        let right: NonZeroRationalUsize = Ratio { sign: NonZeroSign::Positive, numerator: usize::MAX - 1, denominator: usize::MAX - 2 };
        assert!(left < right);
        assert_eq!(left.cmp(&left), Ordering::Equal);
        assert!(-left > -right);
    }
}