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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
// Copyright © 2016–2024 Trevor Spiteri

// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option) any
// later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License and
// a copy of the GNU General Public License along with this program. If not, see
// <https://www.gnu.org/licenses/>.

use crate::ext::xmpq;
use crate::ext::xmpz;
use crate::integer::big as big_integer;
use crate::misc::{StringLike, VecLike};
use crate::ops::{NegAssign, SubFrom};
use crate::rational::arith::MulIncomplete;
use crate::rational::BorrowRational;
use crate::{Assign, Complete, Integer};
use az::{Cast, CheckedCast, UnwrappedAs, UnwrappedCast};
use core::cmp::Ordering;
use core::fmt::{Display, Formatter, Result as FmtResult};
use core::mem::{ManuallyDrop, MaybeUninit};
use core::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign};
use gmp_mpfr_sys::gmp;
use gmp_mpfr_sys::gmp::mpq_t;
#[cfg(feature = "std")]
use std::error::Error;

/**
An arbitrary-precision rational number.

A `Rational` number is made up of a numerator [`Integer`] and denominator
[`Integer`]. After `Rational` number functions, the number is always in
canonical form, that is the denominator is always greater than zero, and there
are no common factors. Zero is stored as 0/1.

# Examples

```rust
use rug::Rational;
let r = Rational::from((-12, 15));
let recip = Rational::from(r.recip_ref());
assert_eq!(recip, Rational::from((-5, 4)));
assert_eq!(recip, -1.25);
// The numerator and denominator are stored in canonical form.
let (num, den) = r.into_numer_denom();
assert_eq!(num, -4);
assert_eq!(den, 5);
```

When comparing `Rational` numbers, it is sometimes convenient to compare to a
pair of primitive integers, like in the comparison to `Rational::from((-5, 4))`
in the example above. `Rational::from((-5, 4))` requires memory allocation,
which can be an expensive operation. To avoid this allocation, when both the
numerator and denominator fit in a primitive integer, we can use
[`MiniRational`] instead, which does not require heap memory allocation.

```rust
use rug::rational::MiniRational;
use rug::Rational;
let r = Rational::from((-12, 15));
let recip = Rational::from(r.recip_ref());
assert_eq!(recip, MiniRational::from((-5, 4)));
```

The `Rational` number type supports various functions. Most methods have three
versions:

 1. The first method consumes the operand.
 2. The second method has a “`_mut`” suffix and mutates the operand.
 3. The third method has a “`_ref`” suffix and borrows the operand. The returned
    item is an [incomplete-computation value][icv] that can be assigned to a
    `Rational` number.

```rust
use rug::rational::MiniRational;
use rug::Rational;

// 1. consume the operand
let a = Rational::from((-15, 2));
let abs_a = a.abs();
assert_eq!(abs_a, MiniRational::from((15, 2)));

// 2. mutate the operand
let mut b = Rational::from((-17, 2));
b.abs_mut();
assert_eq!(b, MiniRational::from((17, 2)));

// 3. borrow the operand
let c = Rational::from((-19, 2));
let r = c.abs_ref();
let abs_c = Rational::from(r);
assert_eq!(abs_c, MiniRational::from((19, 2)));
// c was not consumed
assert_eq!(c, MiniRational::from((-19, 2)));
```

[`MiniRational`]: crate::rational::MiniRational
[icv]: crate#incomplete-computation-values
*/
#[repr(transparent)]
pub struct Rational {
    inner: mpq_t,
}

static_assert_same_layout!(Rational, mpq_t);
static_assert_same_layout!(BorrowRational<'_>, mpq_t);

static_assert_same_size!(Rational, Option<Rational>);

macro_rules! ref_rat_op_int {
    (
        $func:path;
        $(#[$attr_ref:meta])*
        struct $Incomplete:ident { $($param:ident: $T:ty),* }
    ) => {
         $(#[$attr_ref])*
        #[derive(Debug)]
        pub struct $Incomplete<'a> {
            ref_self: &'a Rational,
            $($param: $T,)*
        }

        impl Assign<$Incomplete<'_>> for Integer {
            #[inline]
            fn assign(&mut self, src: $Incomplete<'_>) {
                $func(self, src.ref_self, $(src.$param),*);
            }
        }

        impl From<$Incomplete<'_>> for Integer {
            #[inline]
            fn from(src: $Incomplete<'_>) -> Self {
                let mut dst = Self::default();
                dst.assign(src);
                dst
            }
        }

        impl Complete for $Incomplete<'_> {
            type Completed = Rational;
            #[inline]
            fn complete(self) -> Rational {
                Rational::from(self)
            }
        }
    };
}

macro_rules! ref_rat_op_rat_int {
    (
        $func:path;
        $(#[$attr_ref:meta])*
        struct $Incomplete:ident { $($param:ident: $T:ty),* }
    ) => {
         $(#[$attr_ref])*
        #[derive(Debug)]
        pub struct $Incomplete<'a> {
            ref_self: &'a Rational,
            $($param: $T,)*
        }

        impl Assign<$Incomplete<'_>> for (&mut Rational, & mut Integer) {
            #[inline]
            fn assign(&mut self, src: $Incomplete<'_>) {
                $func(self.0, self.1, src.ref_self, $(src.$param),*);
            }
        }

        impl Assign<$Incomplete<'_>> for (Rational, Integer) {
            #[inline]
            fn assign(&mut self, src: $Incomplete<'_>) {
                Assign::assign(&mut (&mut self.0, &mut self.1), src);
            }
        }

        from_assign! { $Incomplete<'_> => Rational, Integer }
    };
}

impl Rational {
    /// Zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// assert_eq!(*Rational::ZERO, 0);
    /// ```
    pub const ZERO: &'static Rational = {
        const INT: &Integer = &Integer::ZERO;
        const BORROW: BorrowRational = INT.as_rational();
        BorrowRational::const_deref(&BORROW)
    };

    /// One.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// assert_eq!(*Rational::ONE, 1);
    /// ```
    pub const ONE: &'static Rational = {
        const BORROW: BorrowRational = Integer::ONE.as_rational();
        BorrowRational::const_deref(&BORROW)
    };

    /// Negative one (&minus;1).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// assert_eq!(*Rational::NEG_ONE, -1);
    /// ```
    pub const NEG_ONE: &'static Rational = {
        const BORROW: BorrowRational = Integer::NEG_ONE.as_rational();
        BorrowRational::const_deref(&BORROW)
    };

    /// Constructs a new arbitrary-precision [`Rational`] number with value 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let r = Rational::new();
    /// assert_eq!(r, 0);
    /// ```
    #[inline]
    pub fn new() -> Self {
        unsafe {
            let mut ret = MaybeUninit::uninit();
            gmp::mpq_init(cast_ptr_mut!(ret.as_mut_ptr(), mpq_t));
            ret.assume_init()
        }
    }

    /// Creates a [`Rational`] number from an initialized [GMP rational
    /// number][mpq_t].
    ///
    /// # Safety
    ///
    ///   * The function must *not* be used to create a constant [`Rational`]
    ///     number, though it can be used to create a static [`Rational`]
    ///     number. This is because constant values are *copied* on use, leading
    ///     to undefined behavior when they are dropped.
    ///   * The value must be initialized as a valid [`mpq_t`].
    ///   * The [`mpq_t`] type can be considered as a kind of pointer, so there
    ///     can be multiple copies of it. Since this function takes over
    ///     ownership, no other copies of the passed value should exist.
    ///   * The numerator and denominator must be in canonical form, as the rest
    ///     of the library assumes that they are. Most GMP functions leave the
    ///     rational number in canonical form, but assignment functions do not.
    ///     Check the [GMP documentation][gmp mpq] for details.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use core::mem::MaybeUninit;
    /// use gmp_mpfr_sys::gmp;
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let r = unsafe {
    ///     let mut q = MaybeUninit::uninit();
    ///     gmp::mpq_init(q.as_mut_ptr());
    ///     let mut q = q.assume_init();
    ///     gmp::mpq_set_si(&mut q, -145, 10);
    ///     gmp::mpq_canonicalize(&mut q);
    ///     // q is initialized and unique
    ///     Rational::from_raw(q)
    /// };
    /// assert_eq!(r, MiniRational::from((-145, 10)));
    /// // since r is a Rational now, deallocation is automatic
    /// ```
    ///
    /// This can be used to create a static [`Rational`] number using
    /// [`MPZ_ROINIT_N`][gmp::MPZ_ROINIT_N] to initialize the raw numerator and
    /// denominator values. See the [GMP documentation][gmp roinit] for details.
    ///
    /// ```rust
    /// use gmp_mpfr_sys::gmp;
    /// use gmp_mpfr_sys::gmp::{limb_t, mpq_t};
    /// use rug::{Integer, Rational};
    /// const NUMER_LIMBS: [limb_t; 2] = [0, 5];
    /// const DENOM_LIMBS: [limb_t; 1] = [3];
    /// const MPQ: mpq_t = unsafe {
    ///     mpq_t {
    ///         num: gmp::MPZ_ROINIT_N(NUMER_LIMBS.as_ptr().cast_mut(), -2),
    ///         den: gmp::MPZ_ROINIT_N(DENOM_LIMBS.as_ptr().cast_mut(), 1),
    ///     }
    /// };
    /// // Must *not* be const, otherwise it would lead to undefined
    /// // behavior on use, as it would create a copy that is dropped.
    /// static R: Rational = unsafe { Rational::from_raw(MPQ) };
    /// let numer_check =
    ///     -((Integer::from(NUMER_LIMBS[1]) << gmp::NUMB_BITS) + NUMER_LIMBS[0]);
    /// let denom_check = Integer::from(DENOM_LIMBS[0]);
    /// assert_eq!(*R.numer(), numer_check);
    /// assert_eq!(*R.denom(), denom_check);
    /// let check = Rational::from((&numer_check, &denom_check));
    /// assert_eq!(R, check);
    /// assert_eq!(*R.numer(), *check.numer());
    /// assert_eq!(*R.denom(), *check.denom());
    /// ```
    ///
    /// [gmp mpq]: gmp_mpfr_sys::C::GMP::Rational_Number_Functions#index-Rational-number-functions
    /// [gmp roinit]: gmp_mpfr_sys::C::GMP::Integer_Functions#index-MPZ_005fROINIT_005fN
    #[inline]
    pub const unsafe fn from_raw(raw: mpq_t) -> Self {
        Rational { inner: raw }
    }

    /// Converts a [`Rational`] number into a [GMP rational number][mpq_t].
    ///
    /// The returned object should be freed to avoid memory leaks.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gmp_mpfr_sys::gmp;
    /// use rug::Rational;
    /// let r = Rational::from((-145, 10));
    /// let mut q = r.into_raw();
    /// unsafe {
    ///     let d = gmp::mpq_get_d(&q);
    ///     assert_eq!(d, -14.5);
    ///     // free object to prevent memory leak
    ///     gmp::mpq_clear(&mut q);
    /// }
    /// ```
    #[inline]
    pub const fn into_raw(self) -> mpq_t {
        let ret = self.inner;
        let _ = ManuallyDrop::new(self);
        ret
    }

    /// Returns a pointer to the inner [GMP rational number][mpq_t].
    ///
    /// The returned pointer will be valid for as long as `self` is valid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gmp_mpfr_sys::gmp;
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let r = Rational::from((-145, 10));
    /// let q_ptr = r.as_raw();
    /// unsafe {
    ///     let d = gmp::mpq_get_d(q_ptr);
    ///     assert_eq!(d, -14.5);
    /// }
    /// // r is still valid
    /// assert_eq!(r, MiniRational::from((-145, 10)));
    /// ```
    #[inline]
    pub const fn as_raw(&self) -> *const mpq_t {
        &self.inner
    }

    /// Returns an unsafe mutable pointer to the inner [GMP rational
    /// number][mpq_t].
    ///
    /// The returned pointer will be valid for as long as `self` is valid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gmp_mpfr_sys::gmp;
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let mut r = Rational::from((-145, 10));
    /// let q_ptr = r.as_raw_mut();
    /// unsafe {
    ///     gmp::mpq_inv(q_ptr, q_ptr);
    /// }
    /// assert_eq!(r, MiniRational::from((-10, 145)));
    /// ```
    #[inline]
    pub fn as_raw_mut(&mut self) -> *mut mpq_t {
        &mut self.inner
    }

    /// Creates a [`Rational`] number from an [`f32`] if it is
    /// [finite][f32::is_finite], losing no precision.
    ///
    /// This conversion can also be performed using
    ///   * <code>[Rational]::[try\_from]\(value)</code>
    ///   * <code>value.[checked\_as]::\<[Rational]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// // -17.125 can be stored exactly as f32
    /// let r = Rational::from_f32(-17.125).unwrap();
    /// assert_eq!(r, MiniRational::from((-17125, 1000)));
    /// let inf = Rational::from_f32(f32::INFINITY);
    /// assert!(inf.is_none());
    /// ```
    ///
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn from_f32(value: f32) -> Option<Self> {
        value.checked_cast()
    }

    /// Creates a [`Rational`] number from an [`f64`] if it is
    /// [finite][f64::is_finite], losing no precision.
    ///
    /// This conversion can also be performed using
    ///   * <code>[Rational]::[try\_from]\(value)</code>
    ///   * <code>value.[checked\_as]::\<[Rational]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// // -17.125 can be stored exactly as f64
    /// let r = Rational::from_f64(-17.125).unwrap();
    /// assert_eq!(r, MiniRational::from((-17125, 1000)));
    /// let inf = Rational::from_f64(f64::INFINITY);
    /// assert!(inf.is_none());
    /// ```
    ///
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn from_f64(value: f64) -> Option<Self> {
        value.checked_cast()
    }

    /// Parses a [`Rational`] number.
    ///
    /// # Panics
    ///
    /// Panics if `radix` is less than 2 or greater than 36.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let r1 = Rational::from_str_radix("ff/a", 16).unwrap();
    /// assert_eq!(r1, MiniRational::from((255, 10)));
    /// let r2 = Rational::from_str_radix("+ff0/a0", 16).unwrap();
    /// assert_eq!(r2, MiniRational::from((0xff0, 0xa0)));
    /// assert_eq!(*r2.numer(), 51);
    /// assert_eq!(*r2.denom(), 2);
    /// ```
    #[inline]
    pub fn from_str_radix(src: &str, radix: i32) -> Result<Self, ParseRationalError> {
        Ok(Rational::from(Rational::parse_radix(src, radix)?))
    }

    /// Parses a decimal string slice (<code>\&[str]</code>) or byte slice
    /// (<code>[\&\[][slice][u8][][\]][slice]</code>) into a [`Rational`]
    /// number.
    ///
    /// The following are implemented with the unwrapped returned
    /// [incomplete-computation value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// The string must contain a numerator, and may contain a denominator; the
    /// numerator and denominator are separated with a “`/`”. The numerator can
    /// start with an optional minus or plus sign.
    ///
    /// ASCII whitespace is ignored everywhere in the string. Underscores are
    /// ignored anywhere except before the first digit of the numerator and
    /// between the “`/`” and the the first digit of the denominator.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    ///
    /// assert_eq!(
    ///     Rational::parse("-12/23").unwrap().complete(),
    ///     MiniRational::from((-12, 23))
    /// );
    /// assert_eq!(
    ///     Rational::parse("+ 12 / 23").unwrap().complete(),
    ///     MiniRational::from((12, 23))
    /// );
    ///
    /// let invalid = Rational::parse("12/");
    /// assert!(invalid.is_err());
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn parse<S: AsRef<[u8]>>(src: S) -> Result<ParseIncomplete, ParseRationalError> {
        parse(src.as_ref(), 10)
    }

    /// Parses a string slice (<code>\&[str]</code>) or byte slice
    /// (<code>[\&\[][slice][u8][][\]][slice]</code>) into a [`Rational`]
    /// number.
    ///
    /// The following are implemented with the unwrapped returned
    /// [incomplete-computation value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// The string must contain a numerator, and may contain a denominator; the
    /// numerator and denominator are separated with a “`/`”. The numerator can
    /// start with an optional minus or plus sign.
    ///
    /// ASCII whitespace is ignored everywhere in the string. Underscores are
    /// ignored anywhere except before the first digit of the numerator and
    /// between the “`/`” and the the first digit of the denominator.
    ///
    /// If parsing is already done by an external function, the unsafe low-level
    /// <code>[Integer]::[assign\_bytes\_radix\_unchecked]</code> method can be
    /// used in conjunction with the [`mutate_numer_denom`] method.
    ///
    /// # Panics
    ///
    /// Panics if `radix` is less than 2 or greater than 36.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    ///
    /// let valid1 = Rational::parse_radix("12/23", 4);
    /// assert_eq!(
    ///     valid1.unwrap().complete(),
    ///     MiniRational::from((2 + 4 * 1, 3 + 4 * 2))
    /// );
    /// let valid2 = Rational::parse_radix("12 / yz", 36);
    /// assert_eq!(
    ///     valid2.unwrap().complete(),
    ///     MiniRational::from((2 + 36 * 1, 35 + 36 * 34))
    /// );
    ///
    /// let invalid = Rational::parse_radix("12/23", 3);
    /// assert!(invalid.is_err());
    /// ```
    ///
    /// If parsing is done externally, low-level code can be used.
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    ///
    /// let num_bytes = &[1, 2];
    /// let den_bytes = &[2, 3];
    /// let radix = 10;
    /// let neg = true;
    /// let mut r = Rational::new();
    /// // SAFETY: radix and the bytes are in the required ranges
    /// r.mutate_numer_denom(|num, den| unsafe {
    ///     num.assign_bytes_radix_unchecked(num_bytes, radix, neg);
    ///     den.assign_bytes_radix_unchecked(den_bytes, radix, false);
    /// });
    /// // -12/23
    /// assert_eq!(r, MiniRational::from((-12, 23)));
    /// ```
    ///
    /// [`mutate_numer_denom`]: Rational::mutate_numer_denom
    /// [assign\_bytes\_radix\_unchecked]: Integer::assign_bytes_radix_unchecked
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn parse_radix<S: AsRef<[u8]>>(
        src: S,
        radix: i32,
    ) -> Result<ParseIncomplete, ParseRationalError> {
        parse(src.as_ref(), radix)
    }

    /// Converts to an [`f32`], rounding towards zero.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&rational).[az][az::Az::az]::\<[f32]>()</code>
    ///   * <code>rational.[borrow]\().[az][az::Az::az]::\<[f32]>()</code>
    ///   * <code>rational.[az][az::Az::az]::\<[f32]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let min = Rational::from_f32(f32::MIN).unwrap();
    /// let minus_small = min - MiniRational::from((7, 2)).borrow_excl();
    /// // minus_small is truncated to f32::MIN
    /// assert_eq!(minus_small.to_f32(), f32::MIN);
    /// let times_three_two = minus_small * MiniRational::from((3, 2)).borrow_excl();
    /// // times_three_two is too small
    /// assert_eq!(times_three_two.to_f32(), f32::NEG_INFINITY);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    #[inline]
    pub fn to_f32(&self) -> f32 {
        self.cast()
    }

    /// Converts to an [`f64`], rounding towards zero.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&rational).[az][az::Az::az]::\<[f64]>()</code>
    ///   * <code>rational.[borrow]\().[az][az::Az::az]::\<[f64]>()</code>
    ///   * <code>rational.[az][az::Az::az]::\<[f64]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    ///
    /// // An `f64` has 53 bits of precision.
    /// let exact = 0x1f_1234_5678_9aff_u64;
    /// let den = 0x1000_u64;
    /// let r = Rational::from((exact, den));
    /// assert_eq!(r.to_f64(), exact as f64 / den as f64);
    ///
    /// // large has 56 ones
    /// let large = 0xff_1234_5678_9aff_u64;
    /// // trunc has 53 ones followed by 3 zeros
    /// let trunc = 0xff_1234_5678_9af8_u64;
    /// let j = Rational::from((large, den));
    /// assert_eq!(j.to_f64(), trunc as f64 / den as f64);
    ///
    /// let max = Rational::from_f64(f64::MAX).unwrap();
    /// let plus_small = max + MiniRational::from((7, 2)).borrow_excl();
    /// // plus_small is truncated to f64::MAX
    /// assert_eq!(plus_small.to_f64(), f64::MAX);
    /// let times_three_two = plus_small * MiniRational::from((3, 2)).borrow_excl();
    /// // times_three_two is too large
    /// assert_eq!(times_three_two.to_f64(), f64::INFINITY);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    #[inline]
    pub fn to_f64(&self) -> f64 {
        self.cast()
    }

    /// Returns a string representation for the specified `radix`.
    ///
    /// # Panics
    ///
    /// Panics if `radix` is less than 2 or greater than 36.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let r1 = Rational::from(0);
    /// assert_eq!(r1.to_string_radix(10), "0");
    /// let r2 = Rational::from((15, 5));
    /// assert_eq!(r2.to_string_radix(10), "3");
    /// let r3 = Rational::from((10, -6));
    /// assert_eq!(r3.to_string_radix(10), "-5/3");
    /// assert_eq!(r3.to_string_radix(5), "-10/3");
    /// ```
    #[cfg(feature = "std")]
    #[inline]
    pub fn to_string_radix(&self, radix: i32) -> String {
        let mut s = StringLike::new_string();
        append_to_string(&mut s, self, radix, false);
        s.unwrap_string()
    }

    /// Assigns from an [`f32`] if it is [finite][f32::is_finite], losing no
    /// precision.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let mut r = Rational::new();
    /// let ret = r.assign_f32(12.75);
    /// assert!(ret.is_ok());
    /// assert_eq!(r, MiniRational::from((1275, 100)));
    /// let ret = r.assign_f32(f32::NAN);
    /// assert!(ret.is_err());
    /// assert_eq!(r, MiniRational::from((1275, 100)));
    /// ```
    #[inline]
    #[allow(clippy::result_unit_err)]
    pub fn assign_f32(&mut self, val: f32) -> Result<(), ()> {
        self.assign_f64(val.into())
    }

    /// Assigns from an [`f64`] if it is [finite][f64::is_finite], losing no
    /// precision.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let mut r = Rational::new();
    /// let ret = r.assign_f64(12.75);
    /// assert!(ret.is_ok());
    /// assert_eq!(r, MiniRational::from((1275, 100)));
    /// let ret = r.assign_f64(1.0 / 0.0);
    /// assert!(ret.is_err());
    /// assert_eq!(r, MiniRational::from((1275, 100)));
    /// ```
    #[inline]
    #[allow(clippy::result_unit_err)]
    pub fn assign_f64(&mut self, val: f64) -> Result<(), ()> {
        if val.is_finite() {
            xmpq::set_f64(self, val);
            Ok(())
        } else {
            Err(())
        }
    }

    /// Creates a new [`Rational`] number from a numerator and denominator
    /// without canonicalizing aftwerwards.
    ///
    /// # Safety
    ///
    /// This function is unsafe because it does not canonicalize the
    /// [`Rational`] number. The caller must ensure that the numerator and
    /// denominator are in canonical form, as the rest of the library assumes
    /// that they are.
    ///
    /// There are a few methods that can be called on [`Rational`] numbers that
    /// are not in canonical form:
    ///
    ///   * [`numer`] and [`denom`], which treat the numerator and denominator
    ///     separately
    ///   * assignment methods, which overwrite the previous value and leave the
    ///     number in canonical form
    ///   * [`mutate_numer_denom`], which treats the numerator and denominator
    ///     seprarately, and leaves the number in canoncial form
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    ///
    /// // -3/5 is in canonical form
    /// let r = unsafe { Rational::from_canonical(-3, 5) };
    /// assert_eq!(r, MiniRational::from((-3, 5)));
    /// ```
    ///
    /// [`denom`]: `Rational::denom`
    /// [`mutate_numer_denom`]: `Rational::mutate_numer_denom`
    /// [`numer`]: `Rational::numer`
    pub unsafe fn from_canonical<Num, Den>(num: Num, den: Den) -> Self
    where
        Integer: From<Num> + From<Den>,
    {
        let (num, den) = (Integer::from(num), Integer::from(den));
        let mut dst = MaybeUninit::uninit();
        unsafe {
            xmpq::write_num_den_unchecked(&mut dst, num, den);
            dst.assume_init()
        }
    }

    /// Assigns to the numerator and denominator without canonicalizing
    /// aftwerwards.
    ///
    /// # Safety
    ///
    /// This function is unsafe because it does not canonicalize the
    /// [`Rational`] number after the assignment. The caller must ensure that
    /// the numerator and denominator are in canonical form, as the rest of the
    /// library assumes that they are.
    ///
    /// There are a few methods that can be called on [`Rational`] numbers that
    /// are not in canonical form:
    ///
    ///   * [`numer`] and [`denom`], which treat the numerator and denominator
    ///     separately
    ///   * assignment methods, which overwrite the previous value and leave the
    ///     number in canonical form
    ///   * [`mutate_numer_denom`], which treats the numerator and denominator
    ///     seprarately, and leaves the number in canoncial form
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    ///
    /// let mut r = Rational::new();
    /// // -3/5 is in canonical form
    /// unsafe {
    ///     r.assign_canonical(-3, 5);
    /// }
    /// assert_eq!(r, MiniRational::from((-3, 5)));
    /// ```
    ///
    /// [`denom`]: `Rational::denom`
    /// [`mutate_numer_denom`]: `Rational::mutate_numer_denom`
    /// [`numer`]: `Rational::numer`
    pub unsafe fn assign_canonical<Num, Den>(&mut self, num: Num, den: Den)
    where
        Integer: Assign<Num> + Assign<Den>,
    {
        unsafe {
            let (dst_num, dst_den) = self.as_mut_numer_denom_no_canonicalization();
            dst_num.assign(num);
            dst_den.assign(den);
        }
    }

    /// Borrows the numerator as an [`Integer`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let r = Rational::from((12, -20));
    /// // r will be canonicalized to -3/5
    /// assert_eq!(*r.numer(), -3)
    /// ```
    #[inline]
    pub const fn numer(&self) -> &Integer {
        xmpq::numref_const(self)
    }

    /// Borrows the denominator as an [`Integer`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let r = Rational::from((12, -20));
    /// // r will be canonicalized to -3/5
    /// assert_eq!(*r.denom(), 5);
    /// ```
    #[inline]
    pub const fn denom(&self) -> &Integer {
        xmpq::denref_const(self)
    }

    /// Calls a function with mutable references to the numerator and
    /// denominator, then canonicalizes the number.
    ///
    /// The denominator must not be zero when the function returns.
    ///
    /// # Panics
    ///
    /// Panics if the denominator is zero when the function returns.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let mut r = Rational::from((3, 5));
    /// r.mutate_numer_denom(|num, den| {
    ///     // change r from 3/5 to 4/8, which is equal to 1/2
    ///     *num += 1;
    ///     *den += 3;
    /// });
    /// assert_eq!(*r.numer(), 1);
    /// assert_eq!(*r.denom(), 2);
    /// ```
    ///
    /// This method does not check that the numerator and denominator are in
    /// canonical form before calling `func`. This means that this method can be
    /// used to canonicalize the number after some unsafe methods that do not
    /// leave the number in cononical form.
    ///
    /// ```rust
    /// use rug::Rational;
    /// let mut r = Rational::from((3, 5));
    /// unsafe {
    ///     // leave r in non-canonical form
    ///     *r.as_mut_numer_denom_no_canonicalization().0 += 1;
    ///     *r.as_mut_numer_denom_no_canonicalization().1 -= 13;
    /// }
    /// // At this point, r is still not canonical: 4 / -8
    /// assert_eq!(*r.numer(), 4);
    /// assert_eq!(*r.denom(), -8);
    /// r.mutate_numer_denom(|_, _| {});
    /// // Now r is in canonical form: -1 / 2
    /// assert_eq!(*r.numer(), -1);
    /// assert_eq!(*r.denom(), 2);
    /// ```
    pub fn mutate_numer_denom<F>(&mut self, func: F)
    where
        F: FnOnce(&mut Integer, &mut Integer),
    {
        struct CanonicalizeOnDrop<'a>(&'a mut Rational);

        impl Drop for CanonicalizeOnDrop<'_> {
            fn drop(&mut self) {
                xmpq::canonicalize(self.0);
            }
        }

        let guard = CanonicalizeOnDrop(self);
        unsafe {
            let (num, den) = xmpq::numref_denref(guard.0);
            func(num, den);
        }
    }

    /// Borrows the numerator and denominator mutably without canonicalizing
    /// aftwerwards.
    ///
    /// # Safety
    ///
    /// This function is unsafe because it does not canonicalize the
    /// [`Rational`] number when the borrow ends. The caller must ensure that
    /// the numerator and denominator are left in canonical form, as the rest of
    /// the library assumes that they are.
    ///
    /// There are a few methods that can be called on [`Rational`] numbers that
    /// are not in canonical form:
    ///
    ///   * [`numer`][Rational::numer] and [`denom`][Rational::denom], which
    ///     treat the numerator and denominator separately
    ///   * assignment methods, which overwrite the previous value and leave the
    ///     number in canonical form
    ///   * [`mutate_numer_denom`][Rational::mutate_numer_denom], which treats
    ///     the numerator and denominator seprarately, and leaves the number in
    ///     canoncial form
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    ///
    /// let mut r = Rational::from((3, 5));
    /// {
    ///     let (num, den) = unsafe { r.as_mut_numer_denom_no_canonicalization() };
    ///     // Add one to r by adding den to num. Since num and den
    ///     // are relatively prime, r remains in canonical form.
    ///     *num += &*den;
    /// }
    /// assert_eq!(r, MiniRational::from((8, 5)));
    /// ```
    ///
    /// This method can also be used to group some operations before
    /// canonicalization. This is usually not beneficial, as early
    /// canonicalization usually means subsequent arithmetic operations have
    /// less work to do.
    ///
    /// ```rust
    /// use rug::Rational;
    /// let mut r = Rational::from((3, 5));
    /// unsafe {
    ///     // first operation: add 1 to numerator
    ///     *r.as_mut_numer_denom_no_canonicalization().0 += 1;
    ///     // second operation: subtract 13 from denominator
    ///     *r.as_mut_numer_denom_no_canonicalization().1 -= 13;
    /// }
    /// // At this point, r is still not canonical: 4 / -8
    /// assert_eq!(*r.numer(), 4);
    /// assert_eq!(*r.denom(), -8);
    /// r.mutate_numer_denom(|_, _| {});
    /// // Now r is in canonical form: -1 / 2
    /// assert_eq!(*r.numer(), -1);
    /// assert_eq!(*r.denom(), 2);
    /// ```
    #[inline]
    pub unsafe fn as_mut_numer_denom_no_canonicalization(
        &mut self,
    ) -> (&mut Integer, &mut Integer) {
        unsafe { xmpq::numref_denref(self) }
    }

    /// Converts into numerator and denominator [`Integer`] values.
    ///
    /// This function reuses the allocated memory and does not allocate any new
    /// memory.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let r = Rational::from((12, -20));
    /// // r will be canonicalized to -3/5
    /// let (num, den) = r.into_numer_denom();
    /// assert_eq!(num, -3);
    /// assert_eq!(den, 5);
    /// ```
    #[inline]
    pub const fn into_numer_denom(self) -> (Integer, Integer) {
        let raw = self.into_raw();
        // Safety: raw contains two valid Integers.
        unsafe { (Integer::from_raw(raw.num), Integer::from_raw(raw.den)) }
    }

    /// Borrows a negated copy of the [`Rational`] number.
    ///
    /// The returned object implements <code>[Deref]\<[Target][Deref::Target] = [Rational]></code>.
    ///
    /// This method performs a shallow copy and negates it, and
    /// negation does not change the allocated data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let r = Rational::from((7, 11));
    /// let neg_r = r.as_neg();
    /// assert_eq!(*neg_r, MiniRational::from((-7, 11)));
    /// // methods taking &self can be used on the returned object
    /// let reneg_r = neg_r.as_neg();
    /// assert_eq!(*reneg_r, MiniRational::from((7, 11)));
    /// assert_eq!(*reneg_r, r);
    /// ```
    ///
    /// [Deref::Target]: core::ops::Deref::Target
    /// [Deref]: core::ops::Deref
    pub const fn as_neg(&self) -> BorrowRational<'_> {
        let mut raw = self.inner;
        raw.num.size = match raw.num.size.checked_neg() {
            Some(s) => s,
            None => panic!("overflow"),
        };
        // Safety: the lifetime of the return type is equal to the lifetime of self.
        // Safety: the number is in canonical form as only the sign of the numerator was changed.
        unsafe { BorrowRational::from_raw(raw) }
    }

    /// Borrows an absolute copy of the [`Rational`] number.
    ///
    /// The returned object implements <code>[Deref]\<[Target][Deref::Target] = [Rational]></code>.
    ///
    /// This method performs a shallow copy and possibly negates it, and
    /// negation does not change the allocated data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let r = Rational::from((-7, 11));
    /// let abs_r = r.as_abs();
    /// assert_eq!(*abs_r, MiniRational::from((7, 11)));
    /// // methods taking &self can be used on the returned object
    /// let reabs_r = abs_r.as_abs();
    /// assert_eq!(*reabs_r, MiniRational::from((7, 11)));
    /// assert_eq!(*reabs_r, *abs_r);
    /// ```
    ///
    /// [Deref::Target]: core::ops::Deref::Target
    /// [Deref]: core::ops::Deref
    pub const fn as_abs(&self) -> BorrowRational<'_> {
        let mut raw = self.inner;
        raw.num.size = match raw.num.size.checked_abs() {
            Some(s) => s,
            None => panic!("overflow"),
        };
        // Safety: the lifetime of the return type is equal to the lifetime of self.
        // Safety: the number is in canonical form as only the sign of the numerator was changed.
        unsafe { BorrowRational::from_raw(raw) }
    }

    /// Borrows a reciprocal copy of the [`Rational`] number.
    ///
    /// The returned object implements <code>[Deref]\<[Target][Deref::Target] = [Rational]></code>.
    ///
    /// This method performs some shallow copying, swapping numerator and
    /// denominator and making sure the sign is in the numerator.
    ///
    /// # Panics
    ///
    /// Panics if the value is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let r = Rational::from((-7, 11));
    /// let recip_r = r.as_recip();
    /// assert_eq!(*recip_r, MiniRational::from((-11, 7)));
    /// // methods taking &self can be used on the returned object
    /// let rerecip_r = recip_r.as_recip();
    /// assert_eq!(*rerecip_r, MiniRational::from((-7, 11)));
    /// assert_eq!(*rerecip_r, r);
    /// ```
    ///
    /// [Deref::Target]: core::ops::Deref::Target
    /// [Deref]: core::ops::Deref
    pub const fn as_recip(&self) -> BorrowRational<'_> {
        assert!(!self.is_zero(), "division by zero");
        let mut raw = mpq_t {
            num: self.inner.den,
            den: self.inner.num,
        };
        if raw.den.size < 0 {
            raw.den.size = raw.den.size.wrapping_neg();
            raw.num.size = match raw.num.size.checked_neg() {
                Some(s) => s,
                None => panic!("overflow"),
            };
        }
        // Safety: the lifetime of the return type is equal to the lifetime of self.
        // Safety: the number is in canonical form as the numerator and denominator are
        // still mutually prime, and the denominator was made positive.
        unsafe { BorrowRational::from_raw(raw) }
    }

    /// Returns [`true`] if the number is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// assert!(Rational::from(0).is_zero());
    /// assert!(!(Rational::from((1, 2)).is_zero()));
    /// ```
    #[inline]
    pub const fn is_zero(&self) -> bool {
        matches!(self.cmp0(), Ordering::Equal)
    }

    /// Returns [`true`] if the number is positive and [`false`] if the number
    /// is zero or negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// assert!(Rational::from((1, 2)).is_positive());
    /// assert!(!(Rational::from((-1, 2)).is_positive()));
    /// ```
    #[inline]
    pub const fn is_positive(&self) -> bool {
        matches!(self.cmp0(), Ordering::Greater)
    }

    /// Returns [`true`] if the number is negative and [`false`] if the number
    /// is zero or positive.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// assert!(Rational::from((-1, 2)).is_negative());
    /// assert!(!(Rational::from((1, 2)).is_negative()));
    /// ```
    #[inline]
    pub const fn is_negative(&self) -> bool {
        matches!(self.cmp0(), Ordering::Less)
    }

    /// Returns the same result as
    /// <code>self.[cmp][Ord::cmp]\(\&0.[into][Into::into]\())</code>, but is
    /// faster.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use core::cmp::Ordering;
    /// use rug::Rational;
    /// assert_eq!(Rational::from((-5, 7)).cmp0(), Ordering::Less);
    /// assert_eq!(Rational::from(0).cmp0(), Ordering::Equal);
    /// assert_eq!(Rational::from((5, 7)).cmp0(), Ordering::Greater);
    /// ```
    #[inline]
    pub const fn cmp0(&self) -> Ordering {
        self.numer().cmp0()
    }

    /// Compares the absolute values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use core::cmp::Ordering;
    /// use rug::Rational;
    /// let a = Rational::from((-23, 10));
    /// let b = Rational::from((-47, 5));
    /// assert_eq!(a.cmp(&b), Ordering::Greater);
    /// assert_eq!(a.cmp_abs(&b), Ordering::Less);
    /// ```
    #[inline]
    pub fn cmp_abs(&self, other: &Self) -> Ordering {
        self.as_abs().cmp(&*other.as_abs())
    }

    /// Returns [`true`] if the number is an integer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// assert!(!(Rational::from((5, 2)).is_integer()));
    /// assert!(Rational::from(3).is_integer());
    /// ```
    #[inline]
    pub const fn is_integer(&self) -> bool {
        xmpq::is_integer(self)
    }

    /// Adds a list of [`Rational`] values.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///   * <code>[AddAssign]\<Src> for [Rational]</code>
    ///   * <code>[Add]\<Src> for [Rational]</code>,
    ///     <code>[Add]\<[Rational]> for Src</code>
    ///   * <code>[SubAssign]\<Src> for [Rational]</code>,
    ///     <code>[SubFrom]\<Src> for [Rational]</code>
    ///   * <code>[Sub]\<Src> for [Rational]</code>,
    ///     <code>[Sub]\<[Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    ///
    /// let values = [
    ///     Rational::from((5, 2)),
    ///     Rational::from((-100_000, 7)),
    ///     Rational::from(-4),
    /// ];
    ///
    /// let sum = Rational::sum(values.iter()).complete();
    /// let expected = MiniRational::from((5 * 7 - 100_000 * 2 - 4 * 14, 14));
    /// assert_eq!(sum, expected);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn sum<'a, I>(values: I) -> SumIncomplete<'a, I>
    where
        I: Iterator<Item = &'a Self>,
    {
        SumIncomplete { values }
    }

    /// Finds the dot product of a list of [`Rational`] value pairs.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///   * <code>[AddAssign]\<Src> for [Rational]</code>
    ///   * <code>[Add]\<Src> for [Rational]</code>,
    ///     <code>[Add]\<[Rational]> for Src</code>
    ///   * <code>[SubAssign]\<Src> for [Rational]</code>,
    ///     <code>[SubFrom]\<Src> for [Rational]</code>
    ///   * <code>[Sub]\<Src> for [Rational]</code>,
    ///     <code>[Sub]\<[Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    ///
    /// let a = [Rational::from((270, 7)), Rational::from((-11, 10))];
    /// let b = [Rational::from(7), Rational::from((1, 2))];
    ///
    /// let dot = Rational::dot(a.iter().zip(b.iter())).complete();
    /// let expected = MiniRational::from((270 * 20 - 11, 20));
    /// assert_eq!(dot, expected);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn dot<'a, I>(values: I) -> DotIncomplete<'a, I>
    where
        I: Iterator<Item = (&'a Self, &'a Self)>,
    {
        DotIncomplete { values }
    }

    /// Multiplies a list of [`Rational`] values.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///   * <code>[MulAssign]\<Src> for [Rational]</code>
    ///   * <code>[Mul]\<Src> for [Rational]</code>,
    ///     <code>[Mul]\<[Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    ///
    /// let values = [
    ///     Rational::from((5, 2)),
    ///     Rational::from((-100_000, 7)),
    ///     Rational::from(-4),
    /// ];
    ///
    /// let product = Rational::product(values.iter()).complete();
    /// let expected = MiniRational::from((5 * -100_000 * -4, 2 * 7));
    /// assert_eq!(product, expected);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn product<'a, I>(values: I) -> ProductIncomplete<'a, I>
    where
        I: Iterator<Item = &'a Self>,
    {
        ProductIncomplete { values }
    }

    /// Computes the absolute value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let r = Rational::from((-100, 17));
    /// let abs = r.abs();
    /// assert_eq!(abs, MiniRational::from((100, 17)));
    /// ```
    #[inline]
    #[must_use]
    pub fn abs(mut self) -> Self {
        self.abs_mut();
        self
    }

    /// Computes the absolute value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let mut r = Rational::from((-100, 17));
    /// r.abs_mut();
    /// assert_eq!(r, MiniRational::from((100, 17)));
    /// ```
    #[inline]
    pub fn abs_mut(&mut self) {
        xmpq::abs(self, ());
    }

    /// Computes the absolute value.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    /// let r = Rational::from((-100, 17));
    /// let abs = r.abs_ref().complete();
    /// assert_eq!(abs, MiniRational::from((100, 17)));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn abs_ref(&self) -> AbsIncomplete<'_> {
        AbsIncomplete { ref_self: self }
    }

    /// Computes the signum.
    ///
    ///   * 0 if the value is zero
    ///   * 1 if the value is positive
    ///   * &minus;1 if the value is negative
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let r = Rational::from((-100, 17));
    /// let signum = r.signum();
    /// assert_eq!(signum, -1);
    /// ```
    #[inline]
    #[must_use]
    pub fn signum(mut self) -> Self {
        self.signum_mut();
        self
    }

    /// Computes the signum.
    ///
    ///   * 0 if the value is zero
    ///   * 1 if the value is positive
    ///   * &minus;1 if the value is negative
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let mut r = Rational::from((-100, 17));
    /// r.signum_mut();
    /// assert_eq!(r, -1);
    /// ```
    #[inline]
    pub fn signum_mut(&mut self) {
        xmpq::signum(self);
    }

    /// Computes the signum.
    ///
    ///   * 0 if the value is zero
    ///   * 1 if the value is positive
    ///   * &minus;1 if the value is negative
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Integer, Rational};
    /// let r = Rational::from((-100, 17));
    /// let r_ref = r.signum_ref();
    /// let signum = Integer::from(r_ref);
    /// assert_eq!(signum, -1);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn signum_ref(&self) -> SignumIncomplete<'_> {
        SignumIncomplete { ref_self: self }
    }

    /// Clamps the value within the specified bounds.
    ///
    /// # Panics
    ///
    /// Panics if the maximum value is less than the minimum value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let min = MiniRational::from((-3, 2));
    /// let max = MiniRational::from((3, 2));
    /// let min_borrow = &*min.borrow();
    /// let max_borrow = &*max.borrow();
    /// let too_small = Rational::from((-5, 2));
    /// let clamped1 = too_small.clamp(min_borrow, max_borrow);
    /// assert_eq!(clamped1, MiniRational::from((-3, 2)));
    /// let in_range = Rational::from((1, 2));
    /// let clamped2 = in_range.clamp(min_borrow, max_borrow);
    /// assert_eq!(clamped2, MiniRational::from((1, 2)));
    /// ```
    #[inline]
    #[must_use]
    pub fn clamp<Min, Max>(mut self, min: &Min, max: &Max) -> Self
    where
        Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
    {
        self.clamp_mut(min, max);
        self
    }

    /// Clamps the value within the specified bounds.
    ///
    /// # Panics
    ///
    /// Panics if the maximum value is less than the minimum value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let min = MiniRational::from((-3, 2));
    /// let max = MiniRational::from((3, 2));
    /// let min_borrow = &*min.borrow();
    /// let max_borrow = &*max.borrow();
    /// let mut too_small = Rational::from((-5, 2));
    /// too_small.clamp_mut(min_borrow, max_borrow);
    /// assert_eq!(too_small, MiniRational::from((-3, 2)));
    /// let mut in_range = Rational::from((1, 2));
    /// in_range.clamp_mut(min_borrow, max_borrow);
    /// assert_eq!(in_range, MiniRational::from((1, 2)));
    /// ```
    pub fn clamp_mut<Min, Max>(&mut self, min: &Min, max: &Max)
    where
        Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
    {
        if (*self).lt(min) {
            self.assign(min);
            assert!(!(*self).gt(max), "minimum larger than maximum");
        } else if (*self).gt(max) {
            self.assign(max);
            assert!(!(*self).lt(min), "minimum larger than maximum");
        }
    }

    /// Clamps the value within the specified bounds.
    ///
    /// The following are implemented with the returned
    /// [incomplete-computation value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Panics
    ///
    /// Panics if the maximum value is less than the minimum value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Assign, Complete, Rational};
    /// let min = MiniRational::from((-3, 2));
    /// let max = MiniRational::from((3, 2));
    /// let min_borrow = &*min.borrow();
    /// let max_borrow = &*max.borrow();
    /// let too_small = Rational::from((-5, 2));
    /// let mut clamped = too_small.clamp_ref(min_borrow, max_borrow).complete();
    /// assert_eq!(clamped, MiniRational::from((-3, 2)));
    /// let in_range = Rational::from((1, 2));
    /// clamped.assign(in_range.clamp_ref(min_borrow, max_borrow));
    /// assert_eq!(clamped, MiniRational::from((1, 2)));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn clamp_ref<'min, 'max, Min, Max>(
        &self,
        min: &'min Min,
        max: &'max Max,
    ) -> ClampIncomplete<'_, 'min, 'max, Min, Max>
    where
        Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
    {
        ClampIncomplete {
            ref_self: self,
            min,
            max,
        }
    }

    /// Computes the reciprocal.
    ///
    /// # Panics
    ///
    /// Panics if the value is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let r = Rational::from((-100, 17));
    /// let recip = r.recip();
    /// assert_eq!(recip, MiniRational::from((-17, 100)));
    /// ```
    #[inline]
    #[must_use]
    pub fn recip(mut self) -> Self {
        self.recip_mut();
        self
    }

    /// Computes the reciprocal.
    ///
    /// This method never reallocates or copies the heap data. It simply swaps
    /// the allocated data of the numerator and denominator and makes sure the
    /// denominator is stored as positive.
    ///
    /// # Panics
    ///
    /// Panics if the value is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let mut r = Rational::from((-100, 17));
    /// r.recip_mut();
    /// assert_eq!(r, MiniRational::from((-17, 100)));
    /// ```
    #[inline]
    pub fn recip_mut(&mut self) {
        xmpq::inv(self, ());
    }

    /// Computes the reciprocal.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    /// let r = Rational::from((-100, 17));
    /// assert_eq!(r.recip_ref().complete(), MiniRational::from((-17, 100)));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn recip_ref(&self) -> RecipIncomplete<'_> {
        RecipIncomplete { ref_self: self }
    }

    /// Rounds the number towards zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// // -3.7
    /// let r1 = Rational::from((-37, 10));
    /// let trunc1 = r1.trunc();
    /// assert_eq!(trunc1, -3);
    /// // 3.3
    /// let r2 = Rational::from((33, 10));
    /// let trunc2 = r2.trunc();
    /// assert_eq!(trunc2, 3);
    /// ```
    #[inline]
    #[must_use]
    pub fn trunc(mut self) -> Self {
        self.trunc_mut();
        self
    }

    /// Rounds the number towards zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Rational};
    /// // -3.7
    /// let mut r = Rational::from((-37, 10));
    /// r.trunc_mut();
    /// assert_eq!(r, -3);
    /// // 3.3
    /// r.assign((33, 10));
    /// r.trunc_mut();
    /// assert_eq!(r, 3);
    /// ```
    #[inline]
    pub fn trunc_mut(&mut self) {
        xmpq::trunc(self);
    }

    /// Rounds the number towards zero.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer, Rational};
    /// let mut trunc = Integer::new();
    /// // -3.7
    /// let r1 = Rational::from((-37, 10));
    /// trunc.assign(r1.trunc_ref());
    /// assert_eq!(trunc, -3);
    /// // 3.3
    /// let r2 = Rational::from((33, 10));
    /// trunc.assign(r2.trunc_ref());
    /// assert_eq!(trunc, 3);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn trunc_ref(&self) -> TruncIncomplete<'_> {
        TruncIncomplete { ref_self: self }
    }

    /// Computes the fractional part of the number.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// // -100/17 = -5 - 15/17
    /// let r = Rational::from((-100, 17));
    /// let rem = r.rem_trunc();
    /// assert_eq!(rem, MiniRational::from((-15, 17)));
    /// ```
    #[inline]
    #[must_use]
    pub fn rem_trunc(mut self) -> Self {
        self.rem_trunc_mut();
        self
    }

    /// Computes the fractional part of the number.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// // -100/17 = -5 - 15/17
    /// let mut r = Rational::from((-100, 17));
    /// r.rem_trunc_mut();
    /// assert_eq!(r, MiniRational::from((-15, 17)));
    /// ```
    #[inline]
    pub fn rem_trunc_mut(&mut self) {
        xmpq::trunc_fract(self, ());
    }

    /// Computes the fractional part of the number.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    /// // -100/17 = -5 - 15/17
    /// let r = Rational::from((-100, 17));
    /// assert_eq!(r.rem_trunc_ref().complete(), MiniRational::from((-15, 17)));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn rem_trunc_ref(&self) -> RemTruncIncomplete<'_> {
        RemTruncIncomplete { ref_self: self }
    }

    /// Computes the fractional and truncated parts of the number.
    ///
    /// The initial value of `trunc` is ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Integer, Rational};
    /// // -100/17 = -5 - 15/17
    /// let r = Rational::from((-100, 17));
    /// let (fract, trunc) = r.fract_trunc(Integer::new());
    /// assert_eq!(fract, MiniRational::from((-15, 17)));
    /// assert_eq!(trunc, -5);
    /// ```
    #[inline]
    pub fn fract_trunc(mut self, mut trunc: Integer) -> (Self, Integer) {
        self.fract_trunc_mut(&mut trunc);
        (self, trunc)
    }

    /// Computes the fractional and truncated parts of the number.
    ///
    /// The initial value of `trunc` is ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Integer, Rational};
    /// // -100/17 = -5 - 15/17
    /// let mut r = Rational::from((-100, 17));
    /// let mut whole = Integer::new();
    /// r.fract_trunc_mut(&mut whole);
    /// assert_eq!(r, MiniRational::from((-15, 17)));
    /// assert_eq!(whole, -5);
    /// ```
    #[inline]
    pub fn fract_trunc_mut(&mut self, trunc: &mut Integer) {
        xmpq::trunc_fract_whole(self, trunc, ());
    }

    /// Computes the fractional and truncated parts of the number.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Rational][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Rational], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Rational][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Rational][], [Integer][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Assign, Integer, Rational};
    /// // -100/17 = -5 - 15/17
    /// let r = Rational::from((-100, 17));
    /// let r_ref = r.fract_trunc_ref();
    /// let (mut fract, mut trunc) = (Rational::new(), Integer::new());
    /// (&mut fract, &mut trunc).assign(r_ref);
    /// assert_eq!(fract, MiniRational::from((-15, 17)));
    /// assert_eq!(trunc, -5);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn fract_trunc_ref(&self) -> FractTruncIncomplete<'_> {
        FractTruncIncomplete { ref_self: self }
    }

    /// Rounds the number upwards (towards plus infinity).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// // -3.7
    /// let r1 = Rational::from((-37, 10));
    /// let ceil1 = r1.ceil();
    /// assert_eq!(ceil1, -3);
    /// // 3.3
    /// let r2 = Rational::from((33, 10));
    /// let ceil2 = r2.ceil();
    /// assert_eq!(ceil2, 4);
    /// ```
    #[inline]
    #[must_use]
    pub fn ceil(mut self) -> Self {
        self.ceil_mut();
        self
    }

    /// Rounds the number upwards (towards plus infinity).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Rational};
    /// // -3.7
    /// let mut r = Rational::from((-37, 10));
    /// r.ceil_mut();
    /// assert_eq!(r, -3);
    /// // 3.3
    /// r.assign((33, 10));
    /// r.ceil_mut();
    /// assert_eq!(r, 4);
    /// ```
    #[inline]
    pub fn ceil_mut(&mut self) {
        xmpq::ceil(self);
    }

    /// Rounds the number upwards (towards plus infinity).
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer, Rational};
    /// let mut ceil = Integer::new();
    /// // -3.7
    /// let r1 = Rational::from((-37, 10));
    /// ceil.assign(r1.ceil_ref());
    /// assert_eq!(ceil, -3);
    /// // 3.3
    /// let r2 = Rational::from((33, 10));
    /// ceil.assign(r2.ceil_ref());
    /// assert_eq!(ceil, 4);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn ceil_ref(&self) -> CeilIncomplete<'_> {
        CeilIncomplete { ref_self: self }
    }

    /// Computes the non-positive remainder after rounding up.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// // 100/17 = 6 - 2/17
    /// let r = Rational::from((100, 17));
    /// let rem = r.rem_ceil();
    /// assert_eq!(rem, MiniRational::from((-2, 17)));
    /// ```
    #[inline]
    #[must_use]
    pub fn rem_ceil(mut self) -> Self {
        self.rem_ceil_mut();
        self
    }

    /// Computes the non-positive remainder after rounding up.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// // 100/17 = 6 - 2/17
    /// let mut r = Rational::from((100, 17));
    /// r.rem_ceil_mut();
    /// assert_eq!(r, MiniRational::from((-2, 17)));
    /// ```
    #[inline]
    pub fn rem_ceil_mut(&mut self) {
        xmpq::ceil_fract(self, ());
    }

    /// Computes the non-positive remainder after rounding up.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    /// // 100/17 = 6 - 2/17
    /// let r = Rational::from((100, 17));
    /// assert_eq!(r.rem_ceil_ref().complete(), MiniRational::from((-2, 17)));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn rem_ceil_ref(&self) -> RemCeilIncomplete<'_> {
        RemCeilIncomplete { ref_self: self }
    }

    /// Computes the fractional and ceil parts of the number.
    ///
    /// The fractional part cannot greater than zero.
    ///
    /// The initial value of `ceil` is ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Integer, Rational};
    /// // 100/17 = 6 - 2/17
    /// let r = Rational::from((100, 17));
    /// let (fract, ceil) = r.fract_ceil(Integer::new());
    /// assert_eq!(fract, MiniRational::from((-2, 17)));
    /// assert_eq!(ceil, 6);
    /// ```
    #[inline]
    pub fn fract_ceil(mut self, mut ceil: Integer) -> (Self, Integer) {
        self.fract_ceil_mut(&mut ceil);
        (self, ceil)
    }

    /// Computes the fractional and ceil parts of the number.
    ///
    /// The fractional part cannot be greater than zero.
    ///
    /// The initial value of `ceil` is ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Integer, Rational};
    /// // 100/17 = 6 - 2/17
    /// let mut r = Rational::from((100, 17));
    /// let mut ceil = Integer::new();
    /// r.fract_ceil_mut(&mut ceil);
    /// assert_eq!(r, MiniRational::from((-2, 17)));
    /// assert_eq!(ceil, 6);
    /// ```
    #[inline]
    pub fn fract_ceil_mut(&mut self, ceil: &mut Integer) {
        xmpq::ceil_fract_whole(self, ceil, ());
    }

    /// Computes the fractional and ceil parts of the number.
    ///
    /// The fractional part cannot be greater than zero.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Rational][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Rational], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Rational][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Rational][], [Integer][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Assign, Integer, Rational};
    /// // 100/17 = 6 - 2/17
    /// let r = Rational::from((100, 17));
    /// let r_ref = r.fract_ceil_ref();
    /// let (mut fract, mut ceil) = (Rational::new(), Integer::new());
    /// (&mut fract, &mut ceil).assign(r_ref);
    /// assert_eq!(fract, MiniRational::from((-2, 17)));
    /// assert_eq!(ceil, 6);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn fract_ceil_ref(&self) -> FractCeilIncomplete<'_> {
        FractCeilIncomplete { ref_self: self }
    }

    /// Rounds the number downwards (towards minus infinity).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// // -3.7
    /// let r1 = Rational::from((-37, 10));
    /// let floor1 = r1.floor();
    /// assert_eq!(floor1, -4);
    /// // 3.3
    /// let r2 = Rational::from((33, 10));
    /// let floor2 = r2.floor();
    /// assert_eq!(floor2, 3);
    /// ```
    #[inline]
    #[must_use]
    pub fn floor(mut self) -> Self {
        self.floor_mut();
        self
    }

    /// Rounds the number downwards (towards minus infinity).
    ///
    /// ```rust
    /// use rug::{Assign, Rational};
    /// // -3.7
    /// let mut r = Rational::from((-37, 10));
    /// r.floor_mut();
    /// assert_eq!(r, -4);
    /// // 3.3
    /// r.assign((33, 10));
    /// r.floor_mut();
    /// assert_eq!(r, 3);
    /// ```
    #[inline]
    pub fn floor_mut(&mut self) {
        xmpq::floor(self);
    }

    /// Rounds the number downwards (towards minus infinity).
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer, Rational};
    /// let mut floor = Integer::new();
    /// // -3.7
    /// let r1 = Rational::from((-37, 10));
    /// floor.assign(r1.floor_ref());
    /// assert_eq!(floor, -4);
    /// // 3.3
    /// let r2 = Rational::from((33, 10));
    /// floor.assign(r2.floor_ref());
    /// assert_eq!(floor, 3);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn floor_ref(&self) -> FloorIncomplete<'_> {
        FloorIncomplete { ref_self: self }
    }

    /// Computes the non-negative remainder after rounding down.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// // -100/17 = -6 + 2/17
    /// let r = Rational::from((-100, 17));
    /// let rem = r.rem_floor();
    /// assert_eq!(rem, MiniRational::from((2, 17)));
    /// ```
    #[inline]
    #[must_use]
    pub fn rem_floor(mut self) -> Self {
        self.rem_floor_mut();
        self
    }

    /// Computes the non-negative remainder after rounding down.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// // -100/17 = -6 + 2/17
    /// let mut r = Rational::from((-100, 17));
    /// r.rem_floor_mut();
    /// assert_eq!(r, MiniRational::from((2, 17)));
    /// ```
    #[inline]
    pub fn rem_floor_mut(&mut self) {
        xmpq::floor_fract(self, ());
    }

    /// Computes the non-negative remainder after rounding down.
    ///
    /// The following are implemented with the returned
    /// [incomplete-computation value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    /// // -100/17 = -6 + 2/17
    /// let r = Rational::from((-100, 17));
    /// assert_eq!(r.rem_floor_ref().complete(), MiniRational::from((2, 17)));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn rem_floor_ref(&self) -> RemFloorIncomplete<'_> {
        RemFloorIncomplete { ref_self: self }
    }

    /// Computes the fractional and floor parts of the number.
    ///
    /// The fractional part cannot be negative.
    ///
    /// The initial value of `floor` is ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Integer, Rational};
    /// // -100/17 = -6 + 2/17
    /// let r = Rational::from((-100, 17));
    /// let (fract, floor) = r.fract_floor(Integer::new());
    /// assert_eq!(fract, MiniRational::from((2, 17)));
    /// assert_eq!(floor, -6);
    /// ```
    #[inline]
    pub fn fract_floor(mut self, mut floor: Integer) -> (Self, Integer) {
        self.fract_floor_mut(&mut floor);
        (self, floor)
    }

    /// Computes the fractional and floor parts of the number.
    ///
    /// The fractional part cannot be negative.
    ///
    /// The initial value of `floor` is ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Integer, Rational};
    /// // -100/17 = -6 + 2/17
    /// let mut r = Rational::from((-100, 17));
    /// let mut floor = Integer::new();
    /// r.fract_floor_mut(&mut floor);
    /// assert_eq!(r, MiniRational::from((2, 17)));
    /// assert_eq!(floor, -6);
    /// ```
    #[inline]
    pub fn fract_floor_mut(&mut self, floor: &mut Integer) {
        xmpq::floor_fract_whole(self, floor, ());
    }

    /// Computes the fractional and floor parts of the number.
    ///
    /// The fractional part cannot be negative.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Rational][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Rational], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Rational][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Rational][], [Integer][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Assign, Integer, Rational};
    /// // -100/17 = -6 + 2/17
    /// let r = Rational::from((-100, 17));
    /// let r_ref = r.fract_floor_ref();
    /// let (mut fract, mut floor) = (Rational::new(), Integer::new());
    /// (&mut fract, &mut floor).assign(r_ref);
    /// assert_eq!(fract, MiniRational::from((2, 17)));
    /// assert_eq!(floor, -6);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn fract_floor_ref(&self) -> FractFloorIncomplete<'_> {
        FractFloorIncomplete { ref_self: self }
    }

    /// Rounds the number to the nearest integer.
    ///
    /// When the number lies exactly between two integers, it is rounded away
    /// from zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// // -3.5
    /// let r1 = Rational::from((-35, 10));
    /// let round1 = r1.round();
    /// assert_eq!(round1, -4);
    /// // 3.7
    /// let r2 = Rational::from((37, 10));
    /// let round2 = r2.round();
    /// assert_eq!(round2, 4);
    /// ```
    #[inline]
    #[must_use]
    pub fn round(mut self) -> Self {
        self.round_mut();
        self
    }

    /// Rounds the number to the nearest integer.
    ///
    /// When the number lies exactly between two integers, it is rounded away
    /// from zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Rational};
    /// // -3.5
    /// let mut r = Rational::from((-35, 10));
    /// r.round_mut();
    /// assert_eq!(r, -4);
    /// // 3.7
    /// r.assign((37, 10));
    /// r.round_mut();
    /// assert_eq!(r, 4);
    /// ```
    #[inline]
    pub fn round_mut(&mut self) {
        xmpq::round(self);
    }

    /// Rounds the number to the nearest integer.
    ///
    /// When the number lies exactly between two integers, it is rounded away
    /// from zero.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer`]</code>
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer, Rational};
    /// let mut round = Integer::new();
    /// // -3.5
    /// let r1 = Rational::from((-35, 10));
    /// round.assign(r1.round_ref());
    /// assert_eq!(round, -4);
    /// // 3.7
    /// let r2 = Rational::from((37, 10));
    /// round.assign(r2.round_ref());
    /// assert_eq!(round, 4);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn round_ref(&self) -> RoundIncomplete<'_> {
        RoundIncomplete { ref_self: self }
    }

    /// Computes the remainder after rounding to the nearest integer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// // -3.5 = -4 + 0.5 = -4 + 1/2
    /// let r1 = Rational::from((-35, 10));
    /// let rem1 = r1.rem_round();
    /// assert_eq!(rem1, MiniRational::from((1, 2)));
    /// // 3.7 = 4 - 0.3 = 4 - 3/10
    /// let r2 = Rational::from((37, 10));
    /// let rem2 = r2.rem_round();
    /// assert_eq!(rem2, MiniRational::from((-3, 10)));
    /// ```
    #[inline]
    #[must_use]
    pub fn rem_round(mut self) -> Self {
        self.rem_round_mut();
        self
    }

    /// Computes the remainder after rounding to the nearest integer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// // -3.5 = -4 + 0.5 = -4 + 1/2
    /// let mut r1 = Rational::from((-35, 10));
    /// r1.rem_round_mut();
    /// assert_eq!(r1, MiniRational::from((1, 2)));
    /// // 3.7 = 4 - 0.3 = 4 - 3/10
    /// let mut r2 = Rational::from((37, 10));
    /// r2.rem_round_mut();
    /// assert_eq!(r2, MiniRational::from((-3, 10)));
    /// ```
    #[inline]
    pub fn rem_round_mut(&mut self) {
        xmpq::round_fract(self, ());
    }

    /// Computes the remainder after rounding to the nearest integer.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Assign, Complete, Rational};
    /// // -3.5 = -4 + 0.5 = -4 + 1/2
    /// let r1 = Rational::from((-35, 10));
    /// let mut rem = r1.rem_round_ref().complete();
    /// assert_eq!(rem, MiniRational::from((1, 2)));
    /// // 3.7 = 4 - 0.3 = 4 - 3/10
    /// let r2 = Rational::from((37, 10));
    /// rem.assign(r2.rem_round_ref());
    /// assert_eq!(rem, MiniRational::from((-3, 10)));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn rem_round_ref(&self) -> RemRoundIncomplete<'_> {
        RemRoundIncomplete { ref_self: self }
    }

    /// Computes the fractional and rounded parts of the number.
    ///
    /// The fractional part is positive when the number is rounded down and
    /// negative when the number is rounded up. When the number lies exactly
    /// between two integers, it is rounded away from zero.
    ///
    /// The initial value of `round` is ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Integer, Rational};
    /// // -3.5 = -4 + 0.5 = -4 + 1/2
    /// let r1 = Rational::from((-35, 10));
    /// let (fract1, round1) = r1.fract_round(Integer::new());
    /// assert_eq!(fract1, MiniRational::from((1, 2)));
    /// assert_eq!(round1, -4);
    /// // 3.7 = 4 - 0.3 = 4 - 3/10
    /// let r2 = Rational::from((37, 10));
    /// let (fract2, round2) = r2.fract_round(Integer::new());
    /// assert_eq!(fract2, MiniRational::from((-3, 10)));
    /// assert_eq!(round2, 4);
    /// ```
    #[inline]
    pub fn fract_round(mut self, mut round: Integer) -> (Self, Integer) {
        self.fract_round_mut(&mut round);
        (self, round)
    }

    /// Computes the fractional and round parts of the number.
    ///
    /// The fractional part is positive when the number is rounded down and
    /// negative when the number is rounded up. When the number lies exactly
    /// between two integers, it is rounded away from zero.
    ///
    /// The initial value of `round` is ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Integer, Rational};
    /// // -3.5 = -4 + 0.5 = -4 + 1/2
    /// let mut r1 = Rational::from((-35, 10));
    /// let mut round1 = Integer::new();
    /// r1.fract_round_mut(&mut round1);
    /// assert_eq!(r1, MiniRational::from((1, 2)));
    /// assert_eq!(round1, -4);
    /// // 3.7 = 4 - 0.3 = 4 - 3/10
    /// let mut r2 = Rational::from((37, 10));
    /// let mut round2 = Integer::new();
    /// r2.fract_round_mut(&mut round2);
    /// assert_eq!(r2, MiniRational::from((-3, 10)));
    /// assert_eq!(round2, 4);
    /// ```
    #[inline]
    pub fn fract_round_mut(&mut self, round: &mut Integer) {
        xmpq::round_fract_whole(self, round, ());
    }

    /// Computes the fractional and round parts of the number.
    ///
    /// The fractional part is positive when the number is rounded down and
    /// negative when the number is rounded up. When the number lies exactly
    /// between two integers, it is rounded away from zero.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Rational][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Rational], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Rational][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Rational][], [Integer][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Assign, Integer, Rational};
    /// // -3.5 = -4 + 0.5 = -4 + 1/2
    /// let r1 = Rational::from((-35, 10));
    /// let r_ref1 = r1.fract_round_ref();
    /// let (mut fract1, mut round1) = (Rational::new(), Integer::new());
    /// (&mut fract1, &mut round1).assign(r_ref1);
    /// assert_eq!(fract1, MiniRational::from((1, 2)));
    /// assert_eq!(round1, -4);
    /// // 3.7 = 4 - 0.3 = 4 - 3/10
    /// let r2 = Rational::from((37, 10));
    /// let r_ref2 = r2.fract_round_ref();
    /// let (mut fract2, mut round2) = (Rational::new(), Integer::new());
    /// (&mut fract2, &mut round2).assign(r_ref2);
    /// assert_eq!(fract2, MiniRational::from((-3, 10)));
    /// assert_eq!(round2, 4);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn fract_round_ref(&self) -> FractRoundIncomplete<'_> {
        FractRoundIncomplete { ref_self: self }
    }

    /// Computes the square.
    ///
    /// This method cannot be replaced by a multiplication using the `*`
    /// operator: `r * r` and `r * &r` are both errors.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let r = Rational::from((-13, 2));
    /// let square = r.square();
    /// assert_eq!(square, MiniRational::from((169, 4)));
    /// ```
    #[inline]
    #[must_use]
    pub fn square(mut self) -> Self {
        self.square_mut();
        self
    }

    /// Computes the square.
    ///
    /// This method cannot be replaced by a compound multiplication and
    /// assignment using the `*=` operataor: `r *= r;` and `r *= &r;` are both
    /// errors.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::Rational;
    /// let mut r = Rational::from((-13, 2));
    /// r.square_mut();
    /// assert_eq!(r, MiniRational::from((169, 4)));
    /// ```
    #[inline]
    pub fn square_mut(&mut self) {
        xmpq::mul(self, (), ());
    }

    /// Computes the square.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Rational]</code>
    ///   * <code>[From]\<Src> for [Rational]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Rational]> for Src</code>
    ///
    /// `r.square_ref()` produces the exact same result as `&r * &r`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rational::MiniRational;
    /// use rug::{Complete, Rational};
    /// let r = Rational::from((-13, 2));
    /// assert_eq!(r.square_ref().complete(), MiniRational::from((169, 4)));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn square_ref(&self) -> MulIncomplete<'_> {
        self * self
    }
}

#[derive(Debug)]
pub struct SumIncomplete<'a, I>
where
    I: Iterator<Item = &'a Rational>,
{
    values: I,
}

impl<'a, I> Assign<SumIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    fn assign(&mut self, mut src: SumIncomplete<'a, I>) {
        if let Some(first) = src.values.next() {
            self.assign(first);
        } else {
            self.assign(0u32);
            return;
        }
        self.add_assign(src);
    }
}

impl<'a, I> From<SumIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    fn from(mut src: SumIncomplete<'a, I>) -> Self {
        let mut dst = match src.values.next() {
            Some(first) => first.clone(),
            None => return Rational::new(),
        };
        dst.add_assign(src);
        dst
    }
}

impl<'a, I> Complete for SumIncomplete<'a, I>
where
    I: Iterator<Item = &'a Rational>,
{
    type Completed = Rational;
    #[inline]
    fn complete(self) -> Rational {
        Rational::from(self)
    }
}

impl<'a, I> Add<SumIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    type Output = Self;
    #[inline]
    fn add(mut self, rhs: SumIncomplete<'a, I>) -> Self {
        self.add_assign(rhs);
        self
    }
}

impl<'a, I> Add<Rational> for SumIncomplete<'a, I>
where
    I: Iterator<Item = &'a Rational>,
{
    type Output = Rational;
    #[inline]
    fn add(self, mut rhs: Rational) -> Rational {
        rhs.add_assign(self);
        rhs
    }
}

impl<'a, I> AddAssign<SumIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    fn add_assign(&mut self, src: SumIncomplete<'a, I>) {
        for i in src.values {
            self.add_assign(i);
        }
    }
}

impl<'a, I> Sub<SumIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    type Output = Self;
    #[inline]
    fn sub(mut self, rhs: SumIncomplete<'a, I>) -> Self {
        self.sub_assign(rhs);
        self
    }
}

impl<'a, I> Sub<Rational> for SumIncomplete<'a, I>
where
    I: Iterator<Item = &'a Rational>,
{
    type Output = Rational;
    #[inline]
    fn sub(self, mut rhs: Rational) -> Rational {
        rhs.neg_assign();
        rhs.add_assign(self);
        rhs
    }
}

impl<'a, I> SubAssign<SumIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    fn sub_assign(&mut self, src: SumIncomplete<'a, I>) {
        for i in src.values {
            self.sub_assign(i);
        }
    }
}

impl<'a, I> SubFrom<SumIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    fn sub_from(&mut self, src: SumIncomplete<'a, I>) {
        self.neg_assign();
        self.add_assign(src);
    }
}

#[derive(Debug)]
pub struct DotIncomplete<'a, I>
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    values: I,
}

impl<'a, I> Assign<DotIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    fn assign(&mut self, mut src: DotIncomplete<'a, I>) {
        if let Some(first) = src.values.next() {
            self.assign(first.0 * first.1);
        } else {
            self.assign(0u32);
            return;
        }
        self.add_assign(src);
    }
}

impl<'a, I> From<DotIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    fn from(mut src: DotIncomplete<'a, I>) -> Self {
        let mut dst = match src.values.next() {
            Some(first) => Rational::from(first.0 * first.1),
            None => return Rational::new(),
        };
        dst.add_assign(src);
        dst
    }
}

impl<'a, I> Complete for DotIncomplete<'a, I>
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    type Completed = Rational;
    #[inline]
    fn complete(self) -> Rational {
        Rational::from(self)
    }
}

impl<'a, I> Add<DotIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    type Output = Self;
    #[inline]
    fn add(mut self, rhs: DotIncomplete<'a, I>) -> Self {
        self.add_assign(rhs);
        self
    }
}

impl<'a, I> Add<Rational> for DotIncomplete<'a, I>
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    type Output = Rational;
    #[inline]
    fn add(self, mut rhs: Rational) -> Rational {
        rhs.add_assign(self);
        rhs
    }
}

impl<'a, I> AddAssign<DotIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    fn add_assign(&mut self, src: DotIncomplete<'a, I>) {
        let mut mul = Rational::new();
        for i in src.values {
            #[allow(clippy::suspicious_op_assign_impl)]
            mul.assign(i.0 * i.1);
            AddAssign::add_assign(self, &mul);
        }
    }
}

impl<'a, I> Sub<DotIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    type Output = Self;
    #[inline]
    fn sub(mut self, rhs: DotIncomplete<'a, I>) -> Self {
        self.sub_assign(rhs);
        self
    }
}

impl<'a, I> Sub<Rational> for DotIncomplete<'a, I>
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    type Output = Rational;
    #[inline]
    fn sub(self, mut rhs: Rational) -> Rational {
        rhs.neg_assign();
        rhs.add_assign(self);
        rhs
    }
}

impl<'a, I> SubAssign<DotIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    fn sub_assign(&mut self, src: DotIncomplete<'a, I>) {
        let mut mul = Rational::new();
        for i in src.values {
            #[allow(clippy::suspicious_op_assign_impl)]
            mul.assign(i.0 * i.1);
            SubAssign::sub_assign(self, &mul);
        }
    }
}

impl<'a, I> SubFrom<DotIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = (&'a Rational, &'a Rational)>,
{
    fn sub_from(&mut self, src: DotIncomplete<'a, I>) {
        self.neg_assign();
        self.add_assign(src);
    }
}

#[derive(Debug)]
pub struct ProductIncomplete<'a, I>
where
    I: Iterator<Item = &'a Rational>,
{
    values: I,
}

impl<'a, I> Assign<ProductIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    fn assign(&mut self, mut src: ProductIncomplete<'a, I>) {
        if let Some(first) = src.values.next() {
            self.assign(first);
        } else {
            self.assign(1u32);
            return;
        }
        self.mul_assign(src);
    }
}

impl<'a, I> From<ProductIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    fn from(mut src: ProductIncomplete<'a, I>) -> Self {
        let mut dst = match src.values.next() {
            Some(first) => first.clone(),
            None => return Rational::from(1),
        };
        dst.mul_assign(src);
        dst
    }
}

impl<'a, I> Complete for ProductIncomplete<'a, I>
where
    I: Iterator<Item = &'a Rational>,
{
    type Completed = Rational;
    #[inline]
    fn complete(self) -> Rational {
        Rational::from(self)
    }
}

impl<'a, I> Mul<ProductIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    type Output = Self;
    #[inline]
    fn mul(mut self, rhs: ProductIncomplete<'a, I>) -> Self {
        self.mul_assign(rhs);
        self
    }
}

impl<'a, I> Mul<Rational> for ProductIncomplete<'a, I>
where
    I: Iterator<Item = &'a Rational>,
{
    type Output = Rational;
    #[inline]
    fn mul(self, mut rhs: Rational) -> Rational {
        rhs.mul_assign(self);
        rhs
    }
}

impl<'a, I> MulAssign<ProductIncomplete<'a, I>> for Rational
where
    I: Iterator<Item = &'a Self>,
{
    fn mul_assign(&mut self, mut src: ProductIncomplete<'a, I>) {
        let mut other = match src.values.next() {
            Some(next) => Rational::from(&*self * next),
            None => return,
        };
        loop {
            if let Some(next) = src.values.next() {
                self.assign(&other * next);
            } else {
                self.assign(other);
                return;
            }
            match src.values.next() {
                Some(next) => {
                    other.assign(&*self * next);
                }
                None => {
                    return;
                }
            }
            if self.is_zero() {
                return;
            }
        }
    }
}

ref_math_op1! { Rational; xmpq::abs; struct AbsIncomplete {} }
ref_rat_op_int! { xmpq::signum_int; struct SignumIncomplete {} }

#[derive(Debug)]
pub struct ClampIncomplete<'s, 'min, 'max, Min, Max>
where
    Rational: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
{
    ref_self: &'s Rational,
    min: &'min Min,
    max: &'max Max,
}

impl<Min, Max> Assign<ClampIncomplete<'_, '_, '_, Min, Max>> for Rational
where
    Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
{
    #[inline]
    fn assign(&mut self, src: ClampIncomplete<Min, Max>) {
        if src.ref_self.lt(src.min) {
            self.assign(src.min);
            assert!(!(*self).gt(src.max), "minimum larger than maximum");
        } else if src.ref_self.gt(src.max) {
            self.assign(src.max);
            assert!(!(*self).lt(src.min), "minimum larger than maximum");
        } else {
            self.assign(src.ref_self);
        }
    }
}

impl<Min, Max> From<ClampIncomplete<'_, '_, '_, Min, Max>> for Rational
where
    Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
{
    #[inline]
    fn from(src: ClampIncomplete<Min, Max>) -> Self {
        let mut dst = Rational::new();
        dst.assign(src);
        dst
    }
}

impl<Min, Max> Complete for ClampIncomplete<'_, '_, '_, Min, Max>
where
    Rational: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
{
    type Completed = Rational;
    #[inline]
    fn complete(self) -> Rational {
        Rational::from(self)
    }
}

ref_math_op1! { Rational; xmpq::inv; struct RecipIncomplete {} }
ref_rat_op_int! { xmpq::trunc_int; struct TruncIncomplete {} }
ref_math_op1! { Rational; xmpq::trunc_fract; struct RemTruncIncomplete {} }
ref_rat_op_rat_int! { xmpq::trunc_fract_whole; struct FractTruncIncomplete {} }
ref_rat_op_int! { xmpq::ceil_int; struct CeilIncomplete {} }
ref_math_op1! { Rational; xmpq::ceil_fract; struct RemCeilIncomplete {} }
ref_rat_op_rat_int! { xmpq::ceil_fract_whole; struct FractCeilIncomplete {} }
ref_rat_op_int! { xmpq::floor_int; struct FloorIncomplete {} }
ref_math_op1! { Rational; xmpq::floor_fract; struct RemFloorIncomplete {} }
ref_rat_op_rat_int! { xmpq::floor_fract_whole; struct FractFloorIncomplete {} }
ref_rat_op_int! { xmpq::round_int; struct RoundIncomplete {} }
ref_math_op1! { Rational; xmpq::round_fract; struct RemRoundIncomplete {} }
ref_rat_op_rat_int! { xmpq::round_fract_whole; struct FractRoundIncomplete {} }

pub(crate) fn append_to_string(s: &mut StringLike, r: &Rational, radix: i32, to_upper: bool) {
    let (num, den) = (r.numer(), r.denom());
    let is_whole = *den == 1;
    if !is_whole {
        // 2 for '/' and nul
        let cap_for_den_nul = big_integer::req_chars(den, radix, 2);
        let cap = big_integer::req_chars(num, radix, cap_for_den_nul);
        s.reserve(cap);
    };
    let reserved_ptr = s.as_str().as_ptr();
    big_integer::append_to_string(s, num, radix, to_upper);
    if !is_whole {
        s.push_str("/");
        big_integer::append_to_string(s, den, radix, to_upper);
        debug_assert_eq!(reserved_ptr, s.as_str().as_ptr());
    }
}

#[derive(Debug)]
pub struct ParseIncomplete {
    is_negative: bool,
    digits: VecLike<u8>,
    den_start: usize,
    radix: i32,
}

impl Assign<ParseIncomplete> for Rational {
    fn assign(&mut self, src: ParseIncomplete) {
        let num_len = src.den_start;
        if num_len == 0 {
            xmpq::set_0(self);
            return;
        }
        let den_len = src.digits.as_slice().len() - num_len;
        let num_str = src.digits.as_slice().as_ptr();
        unsafe {
            let (num, den) = self.as_mut_numer_denom_no_canonicalization();
            xmpz::realloc_for_mpn_set_str(num, num_len, src.radix);
            let size = gmp::mpn_set_str(num.inner_mut().d.as_ptr(), num_str, num_len, src.radix);
            num.inner_mut().size = (if src.is_negative { -size } else { size }).unwrapped_cast();

            if den_len == 0 {
                // The number is in canonical form if the denominator is 1.
                xmpz::set_1(den);
                return;
            }
            let den_str = num_str.offset(num_len.unwrapped_cast());
            xmpz::realloc_for_mpn_set_str(den, den_len, src.radix);
            let size = gmp::mpn_set_str(den.inner_mut().d.as_ptr(), den_str, den_len, src.radix);
            den.inner_mut().size = size.unwrapped_cast();
            xmpq::canonicalize(self);
        }
    }
}

from_assign! { ParseIncomplete => Rational }

fn parse(bytes: &[u8], radix: i32) -> Result<ParseIncomplete, ParseRationalError> {
    use self::{ParseErrorKind as Kind, ParseRationalError as Error};

    assert!((2..=36).contains(&radix), "radix out of range");
    let bradix = radix.unwrapped_as::<u8>();

    let mut digits = VecLike::new();
    digits.reserve(bytes.len() + 1);
    let mut has_sign = false;
    let mut is_negative = false;
    let mut has_digits = false;
    let mut den_start = None;
    for &b in bytes {
        if b == b'/' {
            if den_start.is_some() {
                return Err(Error {
                    kind: Kind::TooManySlashes,
                });
            }
            if !has_digits {
                return Err(Error {
                    kind: Kind::NumerNoDigits,
                });
            }
            has_digits = false;
            den_start = Some(digits.as_slice().len());
            continue;
        }
        let digit = match b {
            b'+' if den_start.is_none() && !has_sign && !has_digits => {
                has_sign = true;
                continue;
            }
            b'-' if den_start.is_none() && !has_sign && !has_digits => {
                is_negative = true;
                has_sign = true;
                continue;
            }
            b'_' if has_digits => continue,
            b' ' | b'\t' | b'\n' | 0x0b | 0x0c | 0x0d => continue,

            b'0'..=b'9' => b - b'0',
            b'a'..=b'z' => b - b'a' + 10,
            b'A'..=b'Z' => b - b'A' + 10,

            // error
            _ => bradix,
        };
        if digit >= bradix {
            return Err(Error {
                kind: Kind::InvalidDigit,
            });
        }
        has_digits = true;
        if digit > 0
            || (!digits.as_slice().is_empty() && den_start != Some(digits.as_slice().len()))
        {
            digits.push(digit);
        }
    }
    if !has_digits {
        return Err(Error {
            kind: if den_start.is_some() {
                Kind::DenomNoDigits
            } else {
                Kind::NoDigits
            },
        });
    }
    if den_start == Some(digits.as_slice().len()) {
        return Err(Error {
            kind: Kind::DenomZero,
        });
    }
    let den_start = den_start.unwrap_or(digits.as_slice().len());
    Ok(ParseIncomplete {
        is_negative,
        digits,
        den_start,
        radix,
    })
}

/**
An error which can be returned when parsing a [`Rational`] number.

See the <code>[Rational]::[parse\_radix][Rational::parse_radix]</code> method
for details on what strings are accepted.

# Examples

```rust
use rug::rational::ParseRationalError;
use rug::Rational;
// This string is not a rational number.
let s = "something completely different (_!_!_)";
let error: ParseRationalError = match Rational::parse_radix(s, 4) {
    Ok(_) => unreachable!(),
    Err(error) => error,
};
println!("Parse error: {}", error);
```
*/
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ParseRationalError {
    kind: ParseErrorKind,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ParseErrorKind {
    InvalidDigit,
    NoDigits,
    NumerNoDigits,
    DenomNoDigits,
    TooManySlashes,
    DenomZero,
}

impl ParseRationalError {
    fn desc(&self) -> &str {
        use self::ParseErrorKind::*;
        match self.kind {
            InvalidDigit => "invalid digit found in string",
            NoDigits => "string has no digits",
            NumerNoDigits => "string has no digits for numerator",
            DenomNoDigits => "string has no digits for denominator",
            TooManySlashes => "more than one / found in string",
            DenomZero => "string has zero denominator",
        }
    }
}

impl Display for ParseRationalError {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        Display::fmt(self.desc(), f)
    }
}

#[cfg(feature = "std")]
impl Error for ParseRationalError {
    #[allow(deprecated)]
    fn description(&self) -> &str {
        self.desc()
    }
}