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
// Copyright © 2016–2018 University of Malta

// 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 <http://www.gnu.org/licenses/>.

use cast::cast;
use ext::gmp as xgmp;
use gmp_mpfr_sys::gmp::{self, mpq_t};
use inner::{Inner, InnerMut};
use integer::big as big_integer;
use misc;
use std::cmp::Ordering;
use std::error::Error;
use std::ffi::CString;
use std::i32;
use std::marker::PhantomData;
use std::mem;
use std::ops::Deref;
use std::ptr;
use {Assign, Integer};

/**
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, (-5, 4));
assert_eq!(recip.to_f32(), -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);
```

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;

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

// 2. mutate the operand
let mut b = Rational::from((-17, 2));
b.abs_mut();
assert_eq!(b, (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, (19, 2));
// c was not consumed
assert_eq!(c, (-19, 2));
```

[`Integer`]: struct.Integer.html
[icv]: index.html#incomplete-computation-values
*/
pub struct Rational {
    inner: mpq_t,
}

fn _static_assertions() {
    static_assert_size!(Rational, mpq_t);
}

macro_rules! rat_op_int {
    (
        $func:path;
        $(#[$attr:meta])*
        fn $method:ident($($param:ident: $T:ty),*);
        $(#[$attr_mut:meta])*
        fn $method_mut:ident;
        $(#[$attr_ref:meta])*
        fn $method_ref:ident -> $Incomplete:ident;
    ) => {
        $(#[$attr])*
        #[inline]
        pub fn $method(mut self, $($param: $T),*) -> Rational {
            self.$method_mut($($param),*);
            self
        }

        $(#[$attr_mut])*
        #[inline]
        pub fn $method_mut(&mut self, $($param: $T),*) {
            unsafe {
                let num_mut = gmp::mpq_numref(self.inner_mut());
                let den_mut = gmp::mpq_denref(self.inner_mut());
                $func(num_mut, self.inner(), $($param.into()),*);
                xgmp::mpz_set_1(den_mut);
            }
        }

        $(#[$attr_ref])*
        #[inline]
        pub fn $method_ref(&self, $($param: $T),*) -> $Incomplete {
            $Incomplete {
                ref_self: self,
                $($param,)*
            }
        }
    };
}

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<'a> Assign<$Incomplete<'a>> for Integer {
            #[inline]
            fn assign(&mut self, src: $Incomplete) {
                unsafe {
                    $func(
                        self.inner_mut(),
                        src.ref_self.inner(),
                        $(src.$param.into(),)*
                    );
                }
            }
        }

        from_assign! { $Incomplete<'r> => Integer }
    };
}

macro_rules! rat_op_rat_int {
    (
        $func:path;
        $(#[$attr:meta])*
        fn $method:ident($int:ident $(, $param:ident: $T:ty),*);
        $(#[$attr_mut:meta])*
        fn $method_mut:ident;
        $(#[$attr_ref:meta])*
        fn $method_ref:ident -> $Incomplete:ident;
    ) => {
        $(#[$attr])*
        #[inline]
        pub fn $method(
            mut self,
            mut $int: Integer,
            $($param: $T,)*
        ) -> (Self, Integer) {
            self.$method_mut(&mut $int);
            (self, $int)
        }

        $(#[$attr_mut])*
        #[inline]
        pub fn $method_mut(&mut self, $int: &mut Integer, $($param: $T),*) {
            unsafe {
                $func(
                    self.inner_mut(),
                    $int.inner_mut(),
                    self.inner(),
                    $($param.into()),*
                );
            }
        }

        $(#[$attr_ref])*
        #[inline]
        pub fn $method_ref(&self, $($param: $T),*) -> $Incomplete {
            $Incomplete {
                ref_self: self,
                $($param,)*
            }
        }
    };
}

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<'a, 'b, 'c>
            Assign<$Incomplete<'a>> for (&'b mut Rational, &'c mut Integer)
        {
            #[inline]
            fn assign(&mut self, src: $Incomplete) {
                unsafe {
                    $func(
                        self.0.inner_mut(),
                        self.1.inner_mut(),
                        src.ref_self.inner(),
                        $(src.$param.into(),)*
                    );
                }
            }
        }

        impl<'a> From<$Incomplete<'a>> for (Rational, Integer) {
            #[inline]
            fn from(src: $Incomplete) -> Self {
                let mut dst = <Self as Default>::default();
                <Self as Assign<$Incomplete>>::assign(&mut dst, src);
                dst
            }
        }
    };
}

impl Rational {
    /// Constructs a new arbitrary-precision [`Rational`] number with
    /// value 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let r = Rational::new();
    /// assert_eq!(r, 0);
    /// ```
    ///
    /// [`Rational`]: struct.Rational.html
    #[inline]
    pub fn new() -> Self {
        unsafe {
            let mut ret: Rational = mem::uninitialized();
            gmp::mpq_init(ret.inner_mut());
            ret
        }
    }

    /// Creates a [`Rational`] number from an [`f32`] if it is
    /// [finite][`f32::is_finite`], losing no precision.
    ///
    /// If the compiler supports [`TryFrom`], this conversion can also
    /// be performed using `Rational::try_from(value)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// use std::f32;
    /// let r = Rational::from_f32(-17125e-3).unwrap();
    /// assert_eq!(r, "-17125/1000".parse::<Rational>().unwrap());
    /// let inf = Rational::from_f32(f32::INFINITY);
    /// assert!(inf.is_none());
    /// ```
    ///
    /// [`Rational`]: struct.Rational.html
    /// [`TryFrom`]: https://doc.rust-lang.org/nightly/std/convert/trait.TryFrom.html
    /// [`f32::is_finite`]: https://doc.rust-lang.org/nightly/std/primitive.f32.html#method.is_finite
    /// [`f32`]: https://doc.rust-lang.org/nightly/std/primitive.f32.html
    #[inline]
    pub fn from_f32(value: f32) -> Option<Self> {
        Rational::from_f64(value.into())
    }

    /// Creates a [`Rational`] number from an [`f64`] if it is
    /// [finite][`f64::is_finite`], losing no precision.
    ///
    /// If the compiler supports [`TryFrom`], this conversion can also
    /// be performed using `Rational::try_from(value)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// use std::f64;
    /// let r = Rational::from_f64(-17125e-3).unwrap();
    /// assert_eq!(r, "-17125/1000".parse::<Rational>().unwrap());
    /// let inf = Rational::from_f64(f64::INFINITY);
    /// assert!(inf.is_none());
    /// ```
    ///
    /// [`Rational`]: struct.Rational.html
    /// [`TryFrom`]: https://doc.rust-lang.org/nightly/std/convert/trait.TryFrom.html
    /// [`f64::is_finite`]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_finite
    /// [`f64`]: https://doc.rust-lang.org/nightly/std/primitive.f64.html
    #[inline]
    pub fn from_f64(value: f64) -> Option<Self> {
        if value.is_finite() {
            let mut r = Rational::new();
            r.assign_f64(value).unwrap();
            Some(r)
        } else {
            None
        }
    }

    /// Parses a [`Rational`] number.
    ///
    /// # Panics
    ///
    /// Panics if `radix` is less than 2 or greater than 36.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let r1 = Rational::from_str_radix("ff/a", 16).unwrap();
    /// assert_eq!(r1, (255, 10));
    /// let r2 = Rational::from_str_radix("+ff0/a0", 16).unwrap();
    /// assert_eq!(r2, (0xff0, 0xa0));
    /// assert_eq!(*r2.numer(), 51);
    /// assert_eq!(*r2.denom(), 2);
    /// ```
    ///
    /// [`Rational`]: struct.Rational.html
    #[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 ([`&str`][str]) or byte slice
    /// ([`&[u8]`][slice]) into a [`Rational`] number.
    ///
    /// [`Assign<Src> for Rational`][`Assign`] and
    /// [`From<Src> for Rational`][`From`] are implemented with the
    /// unwrapped returned [incomplete-computation value][icv] as
    /// `Src`.
    ///
    /// 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;
    ///
    /// let valid1 = Rational::parse("-12/23");
    /// let r1 = Rational::from(valid1.unwrap());
    /// assert_eq!(r1, (-12, 23));
    /// let valid2 = Rational::parse("+ 12 / 23");
    /// let r2 = Rational::from(valid2.unwrap());
    /// assert_eq!(r2, (12, 23));
    ///
    /// let invalid = Rational::parse("12/");
    /// assert!(invalid.is_err());
    /// ```
    ///
    /// [`Assign`]: trait.Assign.html
    /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
    /// [`Rational`]: struct.Rational.html
    /// [icv]: index.html#incomplete-computation-values
    /// [slice]: https://doc.rust-lang.org/nightly/std/primitive.slice.html
    /// [str]: https://doc.rust-lang.org/nightly/std/primitive.str.html
    #[inline]
    pub fn parse<S: AsRef<[u8]>>(
        src: S,
    ) -> Result<ParseIncomplete, ParseRationalError> {
        parse(src.as_ref(), 10)
    }

    /// Parses a string slice ([`&str`][str]) or byte slice
    /// ([`&[u8]`][slice]) into a [`Rational`] number.
    ///
    /// [`Assign<Src> for Rational`][`Assign`] and
    /// [`From<Src> for Rational`][`From`] are implemented with the
    /// unwrapped returned [incomplete-computation value][icv] as
    /// `Src`.
    ///
    /// 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.
    ///
    /// # Panics
    ///
    /// Panics if `radix` is less than 2 or greater than 36.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    ///
    /// let valid1 = Rational::parse_radix("12/23", 4);
    /// let r1 = Rational::from(valid1.unwrap());
    /// assert_eq!(r1, (2 + 4 * 1, 3 + 4 * 2));
    /// let valid2 = Rational::parse_radix("12 / yz", 36);
    /// let r2 = Rational::from(valid2.unwrap());
    /// assert_eq!(r2, (2 + 36 * 1, 35 + 36 * 34));
    ///
    /// let invalid = Rational::parse_radix("12/", 10);
    /// assert!(invalid.is_err());
    /// ```
    ///
    /// [`Assign`]: trait.Assign.html
    /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
    /// [`Rational`]: struct.Rational.html
    /// [icv]: index.html#incomplete-computation-values
    /// [slice]: https://doc.rust-lang.org/nightly/std/primitive.slice.html
    /// [str]: https://doc.rust-lang.org/nightly/std/primitive.str.html
    #[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.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// use rug::rational::SmallRational;
    /// use std::f32;
    /// let min = Rational::from_f32(f32::MIN).unwrap();
    /// let minus_small = min - &*SmallRational::from((7, 2));
    /// // minus_small is truncated to f32::MIN
    /// assert_eq!(minus_small.to_f32(), f32::MIN);
    /// let times_three_two = minus_small * &*SmallRational::from((3, 2));
    /// // times_three_two is too small
    /// assert_eq!(times_three_two.to_f32(), f32::NEG_INFINITY);
    /// ```
    ///
    /// [`f32`]: https://doc.rust-lang.org/nightly/std/primitive.f32.html
    #[inline]
    pub fn to_f32(&self) -> f32 {
        misc::trunc_f64_to_f32(self.to_f64())
    }

    /// Converts to an [`f64`], rounding towards zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// use rug::rational::SmallRational;
    /// use std::f64;
    ///
    /// // 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 + &*SmallRational::from((7, 2));
    /// // plus_small is truncated to f64::MAX
    /// assert_eq!(plus_small.to_f64(), f64::MAX);
    /// let times_three_two = plus_small * &*SmallRational::from((3, 2));
    /// // times_three_two is too large
    /// assert_eq!(times_three_two.to_f64(), f64::INFINITY);
    /// ```
    ///
    /// [`f64`]: https://doc.rust-lang.org/nightly/std/primitive.f64.html
    #[inline]
    pub fn to_f64(&self) -> f64 {
        unsafe { gmp::mpq_get_d(self.inner()) }
    }

    /// 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");
    /// ```
    #[inline]
    pub fn to_string_radix(&self, radix: i32) -> String {
        let mut s = String::new();
        append_to_string(&mut s, self, radix, false);
        s
    }

    /// Assigns from an [`f32`] if it is [finite][`f32::is_finite`],
    /// losing no precision.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// use std::f32;
    /// let mut r = Rational::new();
    /// let ret = r.assign_f32(12.75);
    /// assert!(ret.is_ok());
    /// assert_eq!(r, (1275, 100));
    /// let ret = r.assign_f32(f32::NAN);
    /// assert!(ret.is_err());
    /// assert_eq!(r, (1275, 100));
    /// ```
    ///
    /// [`f32::is_finite`]: https://doc.rust-lang.org/nightly/std/primitive.f32.html#method.is_finite
    /// [`f32`]: https://doc.rust-lang.org/nightly/std/primitive.f32.html
    #[inline]
    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;
    /// let mut r = Rational::new();
    /// let ret = r.assign_f64(12.75);
    /// assert!(ret.is_ok());
    /// assert_eq!(r, (1275, 100));
    /// let ret = r.assign_f64(1.0 / 0.0);
    /// assert!(ret.is_err());
    /// assert_eq!(r, (1275, 100));
    /// ```
    ///
    /// [`f64::is_finite`]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_finite
    /// [`f64`]: https://doc.rust-lang.org/nightly/std/primitive.f64.html
    #[inline]
    pub fn assign_f64(&mut self, val: f64) -> Result<(), ()> {
        if val.is_finite() {
            unsafe {
                gmp::mpq_set_d(self.inner_mut(), 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.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    ///
    /// // -3 / 5 is in canonical form
    /// let r = unsafe { Rational::from_canonical(-3, 5) };
    /// assert_eq!(r, (-3, 5));
    /// ```
    ///
    /// [`Rational`]: struct.Rational.html
    pub unsafe fn from_canonical<Num, Den>(num: Num, den: Den) -> Self
    where
        Integer: From<Num> + From<Den>,
    {
        let mut dst: Rational = mem::uninitialized();
        {
            let (dnum, dden) = dst.as_mut_numer_denom_no_canonicalization();
            ptr::write(dnum, Integer::from(num));
            ptr::write(dden, Integer::from(den));
        }
        dst
    }

    /// 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.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    ///
    /// let mut r = Rational::new();
    /// // -3 / 5 is in canonical form
    /// unsafe {
    ///     r.assign_canonical(-3, 5);
    /// }
    /// assert_eq!(r, (-3, 5));
    /// ```
    ///
    /// [`Rational`]: struct.Rational.html
    pub unsafe fn assign_canonical<Num, Den>(&mut self, num: Num, den: Den)
    where
        Integer: Assign<Num> + Assign<Den>,
    {
        let (dst_num, dst_den) = self.as_mut_numer_denom_no_canonicalization();
        dst_num.assign(num);
        dst_den.assign(den);
    }

    /// Creates a [`Rational`] number from an initialized
    /// [GMP rational number][`mpq_t`].
    ///
    /// # Safety
    ///
    /// * The value must be initialized.
    /// * The [`gmp_mpfr_sys::gmp::mpq_t`][`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
    /// extern crate gmp_mpfr_sys;
    /// extern crate rug;
    /// use gmp_mpfr_sys::gmp;
    /// use rug::Rational;
    /// use std::mem;
    /// fn main() {
    ///     let r = unsafe {
    ///         let mut q = mem::uninitialized();
    ///         gmp::mpq_init(&mut q);
    ///         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, (-145, 10));
    ///     // since r is a Rational now, deallocation is automatic
    /// }
    /// ```
    ///
    /// [`Rational`]: struct.Rational.html
    /// [`mpq_t`]: https://docs.rs/gmp-mpfr-sys/~1.1/gmp_mpfr_sys/gmp/struct.mpq_t.html
    /// [gmp mpq]: https://tspiteri.gitlab.io/gmp-mpfr-sys/gmp/Rational-Number-Functions.html#index-Rational-number-functions
    #[inline]
    pub 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
    /// extern crate gmp_mpfr_sys;
    /// extern crate rug;
    /// use gmp_mpfr_sys::gmp;
    /// use rug::Rational;
    /// fn main() {
    ///     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);
    ///     }
    /// }
    /// ```
    ///
    /// [`Rational`]: struct.Rational.html
    /// [`mpq_t`]: https://docs.rs/gmp-mpfr-sys/~1.1/gmp_mpfr_sys/gmp/struct.mpq_t.html
    #[inline]
    pub fn into_raw(self) -> mpq_t {
        let ret = self.inner;
        mem::forget(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
    /// extern crate gmp_mpfr_sys;
    /// extern crate rug;
    /// use gmp_mpfr_sys::gmp;
    /// use rug::Rational;
    /// fn main() {
    ///     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, (-145, 10));
    /// }
    /// ```
    ///
    /// [`mpq_t`]: https://docs.rs/gmp-mpfr-sys/~1.1/gmp_mpfr_sys/gmp/struct.mpq_t.html
    #[inline]
    pub 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
    /// extern crate gmp_mpfr_sys;
    /// extern crate rug;
    /// use gmp_mpfr_sys::gmp;
    /// use rug::Rational;
    /// fn main() {
    ///     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, (-10, 145));
    /// }
    /// ```
    ///
    /// [`mpq_t`]: https://docs.rs/gmp-mpfr-sys/~1.1/gmp_mpfr_sys/gmp/struct.mpq_t.html
    #[inline]
    pub fn as_raw_mut(&mut self) -> *mut mpq_t {
        unsafe { self.inner_mut() }
    }

    /// 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)
    /// ```
    ///
    /// [`Integer`]: struct.Integer.html
    #[inline]
    pub fn numer(&self) -> &Integer {
        unsafe { &*cast_ptr!(gmp::mpq_numref_const(self.inner()), Integer) }
    }

    /// 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);
    /// ```
    ///
    /// [`Integer`]: struct.Integer.html
    #[inline]
    pub fn denom(&self) -> &Integer {
        unsafe { &*cast_ptr!(gmp::mpq_denref_const(self.inner()), Integer) }
    }

    /// 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),
    {
        unsafe {
            let numer_ptr =
                cast_ptr_mut!(gmp::mpq_numref(self.inner_mut()), Integer);
            let denom_ptr =
                cast_ptr_mut!(gmp::mpq_denref(self.inner_mut()), Integer);
            func(&mut *numer_ptr, &mut *denom_ptr);
            assert_ne!(
                self.denom().cmp0(),
                Ordering::Equal,
                "division by zero"
            );
            gmp::mpq_canonicalize(self.inner_mut());
        }
    }

    /// 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.
    ///
    /// # Examples
    ///
    /// ```rust
    /// 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, (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);
    /// ```
    ///
    /// [`Rational`]: struct.Rational.html
    #[inline]
    pub unsafe fn as_mut_numer_denom_no_canonicalization(
        &mut self,
    ) -> (&mut Integer, &mut Integer) {
        (
            &mut *cast_ptr_mut!(gmp::mpq_numref(self.inner_mut()), Integer),
            &mut *cast_ptr_mut!(gmp::mpq_denref(self.inner_mut()), Integer),
        )
    }

    /// 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);
    /// ```
    ///
    /// [`Integer`]: struct.Integer.html
    #[inline]
    pub fn into_numer_denom(self) -> (Integer, Integer) {
        let raw = self.into_raw();
        unsafe {
            let num = ptr::read(gmp::mpq_numref_const(&raw));
            let den = ptr::read(gmp::mpq_denref_const(&raw));
            (Integer::from_raw(num), Integer::from_raw(den))
        }
    }

    /// Borrows a negated copy of the [`Rational`] number.
    ///
    /// The returned object implements
    /// [`Deref<Target = Rational>`][`Deref`].
    ///
    /// This method performs a shallow copy and negates it, and
    /// negation does not change the allocated data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let r = Rational::from((7, 11));
    /// let neg_r = r.as_neg();
    /// assert_eq!(*neg_r, (-7, 11));
    /// // methods taking &self can be used on the returned object
    /// let reneg_r = neg_r.as_neg();
    /// assert_eq!(*reneg_r, (7, 11));
    /// assert_eq!(*reneg_r, r);
    /// ```
    ///
    /// [`Deref`]: https://doc.rust-lang.org/nightly/std/ops/trait.Deref.html
    /// [`Rational`]: struct.Rational.html
    #[inline]
    pub fn as_neg(&self) -> BorrowRational {
        let mut ret = BorrowRational {
            inner: self.inner,
            phantom: PhantomData,
        };
        let size = self.numer().inner().size.checked_neg().expect("overflow");
        unsafe {
            (*gmp::mpq_numref(&mut ret.inner)).size = size;
        }
        ret
    }

    /// Borrows an absolute copy of the [`Rational`] number.
    ///
    /// The returned object implements
    /// [`Deref<Target = Rational>`][`Deref`].
    ///
    /// This method performs a shallow copy and possibly negates it,
    /// and negation does not change the allocated data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let r = Rational::from((-7, 11));
    /// let abs_r = r.as_abs();
    /// assert_eq!(*abs_r, (7, 11));
    /// // methods taking &self can be used on the returned object
    /// let reabs_r = abs_r.as_abs();
    /// assert_eq!(*reabs_r, (7, 11));
    /// assert_eq!(*reabs_r, *abs_r);
    /// ```
    ///
    /// [`Deref`]: https://doc.rust-lang.org/nightly/std/ops/trait.Deref.html
    /// [`Rational`]: struct.Rational.html
    #[inline]
    pub fn as_abs(&self) -> BorrowRational {
        let mut ret = BorrowRational {
            inner: self.inner,
            phantom: PhantomData,
        };
        let size = self.numer().inner().size.checked_abs().expect("overflow");
        unsafe {
            (*gmp::mpq_numref(&mut ret.inner)).size = size;
        }
        ret
    }

    /// Borrows a reciprocal copy of the [`Rational`] number.
    ///
    /// The returned object implements
    /// [`Deref<Target = Rational>`][`Deref`].
    ///
    /// 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;
    /// let r = Rational::from((-7, 11));
    /// let recip_r = r.as_recip();
    /// assert_eq!(*recip_r, (-11, 7));
    /// // methods taking &self can be used on the returned object
    /// let rerecip_r = recip_r.as_recip();
    /// assert_eq!(*rerecip_r, (-7, 11));
    /// assert_eq!(*rerecip_r, r);
    /// ```
    ///
    /// [`Deref`]: https://doc.rust-lang.org/nightly/std/ops/trait.Deref.html
    /// [`Rational`]: struct.Rational.html
    pub fn as_recip(&self) -> BorrowRational {
        assert_ne!(self.cmp0(), Ordering::Equal, "division by zero");
        let mut inner: mpq_t = unsafe { mem::uninitialized() };
        unsafe {
            let mut dst_num = ptr::read(self.denom().inner());
            let mut dst_den = ptr::read(self.numer().inner());
            if dst_den.size < 0 {
                dst_den.size = dst_den.size.wrapping_neg();
                dst_num.size = dst_num.size.checked_neg().expect("overflow");
            }
            ptr::write(gmp::mpq_numref(&mut inner), dst_num);
            ptr::write(gmp::mpq_denref(&mut inner), dst_den);
        }
        BorrowRational {
            inner,
            phantom: PhantomData,
        }
    }

    /// Returns the same result as [`self.cmp(&0.into())`][`cmp`], but
    /// is faster.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// use std::cmp::Ordering;
    /// 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);
    /// ```
    ///
    /// [`cmp`]: https://doc.rust-lang.org/nightly/std/cmp/trait.Ord.html#tymethod.cmp
    #[inline]
    pub fn cmp0(&self) -> Ordering {
        self.numer().cmp0()
    }

    /// Compares the absolute values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// use std::cmp::Ordering;
    /// 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())
    }

    math_op1! {
        gmp::mpq_abs;
        /// Computes the absolute value.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// let r = Rational::from((-100, 17));
        /// let abs = r.abs();
        /// assert_eq!(abs, (100, 17));
        /// ```
        fn abs();
        /// Computes the absolute value.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// let mut r = Rational::from((-100, 17));
        /// r.abs_mut();
        /// assert_eq!(r, (100, 17));
        /// ```
        fn abs_mut;
        /// Computes the absolute value.
        ///
        /// [`Assign<Src> for Rational`][`Assign`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// let r = Rational::from((-100, 17));
        /// let r_ref = r.abs_ref();
        /// let abs = Rational::from(r_ref);
        /// assert_eq!(abs, (100, 17));
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn abs_ref -> AbsIncomplete;
    }
    rat_op_int! {
        xgmp::mpq_signum;
        /// Computes the signum.
        ///
        /// * 0 if the value is zero
        /// * 1 if the value is positive
        /// * −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);
        /// ```
        fn signum();
        /// Computes the signum.
        ///
        /// * 0 if the value is zero
        /// * 1 if the value is positive
        /// * −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);
        /// ```
        fn signum_mut;
        /// Computes the signum.
        ///
        /// * 0 if the value is zero
        /// * 1 if the value is positive
        /// * −1 if the value is negative
        ///
        /// [`Assign<Src> for Integer`][`Assign`],
        /// [`Assign<Src> for Rational`][`Assign`],
        /// [`From<Src> for Integer`][`From`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # 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);
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn signum_ref -> SignumIncomplete;
    }

    /// Clamps the value within the specified bounds.
    ///
    /// # Panics
    ///
    /// Panics if the maximum value is less than the minimum value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let min = (-3, 2);
    /// let max = (3, 2);
    /// let too_small = Rational::from((-5, 2));
    /// let clamped1 = too_small.clamp(&min, &max);
    /// assert_eq!(clamped1, (-3, 2));
    /// let in_range = Rational::from((1, 2));
    /// let clamped2 = in_range.clamp(&min, &max);
    /// assert_eq!(clamped2, (1, 2));
    /// ```
    #[inline]
    pub fn clamp<'a, 'b, Min, Max>(mut self, min: &'a Min, max: &'b Max) -> Self
    where
        Self: PartialOrd<Min>
            + PartialOrd<Max>
            + Assign<&'a Min>
            + Assign<&'b 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;
    /// let min = (-3, 2);
    /// let max = (3, 2);
    /// let mut too_small = Rational::from((-5, 2));
    /// too_small.clamp_mut(&min, &max);
    /// assert_eq!(too_small, (-3, 2));
    /// let mut in_range = Rational::from((1, 2));
    /// in_range.clamp_mut(&min, &max);
    /// assert_eq!(in_range, (1, 2));
    /// ```
    pub fn clamp_mut<'a, 'b, Min, Max>(&mut self, min: &'a Min, max: &'b Max)
    where
        Self: PartialOrd<Min>
            + PartialOrd<Max>
            + Assign<&'a Min>
            + Assign<&'b 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.
    ///
    /// [`Assign<Src> for Rational`][`Assign`] and
    /// [`From<Src> for Rational`][`From`] are implemented with the
    /// returned [incomplete-computation value][icv] as `Src`.
    ///
    /// # Panics
    ///
    /// Panics if the maximum value is less than the minimum value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Rational;
    /// let min = (-3, 2);
    /// let max = (3, 2);
    /// let too_small = Rational::from((-5, 2));
    /// let r1 = too_small.clamp_ref(&min, &max);
    /// let clamped1 = Rational::from(r1);
    /// assert_eq!(clamped1, (-3, 2));
    /// let in_range = Rational::from((1, 2));
    /// let r2 = in_range.clamp_ref(&min, &max);
    /// let clamped2 = Rational::from(r2);
    /// assert_eq!(clamped2, (1, 2));
    /// ```
    ///
    /// [`Assign`]: trait.Assign.html
    /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
    /// [icv]: index.html#incomplete-computation-values
    #[inline]
    pub fn clamp_ref<'a, Min, Max>(
        &'a self,
        min: &'a Min,
        max: &'a Max,
    ) -> ClampIncomplete<'a, Min, Max>
    where
        Self: PartialOrd<Min>
            + PartialOrd<Max>
            + Assign<&'a Min>
            + Assign<&'a Max>,
    {
        ClampIncomplete {
            ref_self: self,
            min,
            max,
        }
    }

    math_op1! {
        xgmp::mpq_inv_check;
        /// Computes the reciprocal.
        ///
        /// # Panics
        ///
        /// Panics if the value is zero.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// let r = Rational::from((-100, 17));
        /// let recip = r.recip();
        /// assert_eq!(recip, (-17, 100));
        /// ```
        fn recip();
        /// 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;
        /// let mut r = Rational::from((-100, 17));
        /// r.recip_mut();
        /// assert_eq!(r, (-17, 100));
        /// ```
        fn recip_mut;
        /// Computes the reciprocal.
        ///
        /// [`Assign<Src> for Rational`][`Assign`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// let r = Rational::from((-100, 17));
        /// let r_ref = r.recip_ref();
        /// let recip = Rational::from(r_ref);
        /// assert_eq!(recip, (-17, 100));
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn recip_ref -> RecipIncomplete;
    }
    rat_op_int! {
        xgmp::mpq_trunc;
        /// 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);
        /// ```
        fn trunc();
        /// 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);
        /// ```
        fn trunc_mut;
        /// Rounds the number towards zero.
        ///
        /// [`Assign<Src> for Integer`][`Assign`],
        /// [`Assign<Src> for Rational`][`Assign`],
        /// [`From<Src> for Integer`][`From`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # 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);
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn trunc_ref -> TruncIncomplete;
    }

    math_op1! {
        xgmp::mpq_trunc_fract;
        /// Computes the fractional part of the number.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// // -100/17 = -5 - 15/17
        /// let r = Rational::from((-100, 17));
        /// let rem = r.rem_trunc();
        /// assert_eq!(rem, (-15, 17));
        /// ```
        fn rem_trunc();
        /// Computes the fractional part of the number.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// // -100/17 = -5 - 15/17
        /// let mut r = Rational::from((-100, 17));
        /// r.rem_trunc_mut();
        /// assert_eq!(r, (-15, 17));
        /// ```
        fn rem_trunc_mut;
        /// Computes the fractional part of the number.
        ///
        /// [`Assign<Src> for Rational`][`Assign`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// // -100/17 = -5 - 15/17
        /// let r = Rational::from((-100, 17));
        /// let r_ref = r.rem_trunc_ref();
        /// let rem = Rational::from(r_ref);
        /// assert_eq!(rem, (-15, 17));
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn rem_trunc_ref -> RemTruncIncomplete;
    }
    rat_op_rat_int! {
        xgmp::mpq_trunc_fract_whole;
        /// Computes the fractional and truncated parts of the number.
        ///
        /// The initial value of `trunc` is ignored.
        ///
        /// # Examples
        ///
        /// ```rust
        /// 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, (-15, 17));
        /// assert_eq!(trunc, -5);
        /// ```
        fn fract_trunc(trunc);
        /// Computes the fractional and truncated parts of the number.
        ///
        /// The initial value of `trunc` is ignored.
        ///
        /// # Examples
        ///
        /// ```rust
        /// 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, (-15, 17));
        /// assert_eq!(whole, -5);
        /// ```
        fn fract_trunc_mut;
        /// Computes the fractional and truncated parts of the number.
        ///
        /// [`Assign<Src> for (Rational, Integer)`][`Assign`],
        /// [`Assign<Src> for (&mut Rational, &mut Integer)`][`Assign`]
        /// and [`From<Src> for (Rational, Integer)`][`From`] are
        /// implemented with the returned
        /// [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// 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, (-15, 17));
        /// assert_eq!(trunc, -5);
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn fract_trunc_ref -> FractTruncIncomplete;
    }
    rat_op_int! {
        xgmp::mpq_ceil;
        /// 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);
        /// ```
        fn ceil();
        /// 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);
        /// ```
        fn ceil_mut;
        /// Rounds the number upwards (towards plus infinity).
        ///
        /// [`Assign<Src> for Integer`][`Assign`],
        /// [`Assign<Src> for Rational`][`Assign`],
        /// [`From<Src> for Integer`][`From`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # 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);
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn ceil_ref -> CeilIncomplete;
    }
    math_op1! {
        xgmp::mpq_ceil_fract;
        /// Computes the non-positive remainder after rounding up.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// // 100/17 = 6 - 2/17
        /// let r = Rational::from((100, 17));
        /// let rem = r.rem_ceil();
        /// assert_eq!(rem, (-2, 17));
        /// ```
        fn rem_ceil();
        /// Computes the non-positive remainder after rounding up.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// // 100/17 = 6 - 2/17
        /// let mut r = Rational::from((100, 17));
        /// r.rem_ceil_mut();
        /// assert_eq!(r, (-2, 17));
        /// ```
        fn rem_ceil_mut;
        /// Computes the non-positive remainder after rounding up.
        ///
        /// [`Assign<Src> for Rational`][`Assign`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// // 100/17 = 6 - 2/17
        /// let r = Rational::from((100, 17));
        /// let r_ref = r.rem_ceil_ref();
        /// let rem = Rational::from(r_ref);
        /// assert_eq!(rem, (-2, 17));
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn rem_ceil_ref -> RemCeilIncomplete;
    }
    rat_op_rat_int! {
        xgmp::mpq_ceil_fract_whole;
        /// 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::{Integer, Rational};
        /// // 100/17 = 6 - 2/17
        /// let r = Rational::from((100, 17));
        /// let (fract, ceil) = r.fract_ceil(Integer::new());
        /// assert_eq!(fract, (-2, 17));
        /// assert_eq!(ceil, 6);
        /// ```
        fn fract_ceil(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::{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, (-2, 17));
        /// assert_eq!(ceil, 6);
        /// ```
        fn fract_ceil_mut;
        /// Computes the fractional and ceil parts of the number.
        ///
        /// The fractional part cannot be greater than zero.
        ///
        /// [`Assign<Src> for (Rational, Integer)`][`Assign`],
        /// [`Assign<Src> for (&mut Rational, &mut Integer)`][`Assign`]
        /// and [`From<Src> for (Rational, Integer)`][`From`] are
        /// implemented with the returned
        /// [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// 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, (-2, 17));
        /// assert_eq!(ceil, 6);
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn fract_ceil_ref -> FractCeilIncomplete;
    }
    rat_op_int! {
        xgmp::mpq_floor;
        /// 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);
        /// ```
        fn floor();
        /// 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);
        /// ```
        fn floor_mut;
        /// Rounds the number downwards (towards minus infinity).
        ///
        /// [`Assign<Src> for Integer`][`Assign`],
        /// [`Assign<Src> for Rational`][`Assign`],
        /// [`From<Src> for Integer`][`From`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # 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);
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn floor_ref -> FloorIncomplete;
    }
    math_op1! {
        xgmp::mpq_floor_fract;
        /// Computes the non-negative remainder after rounding down.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// // -100/17 = -6 + 2/17
        /// let r = Rational::from((-100, 17));
        /// let rem = r.rem_floor();
        /// assert_eq!(rem, (2, 17));
        /// ```
        fn rem_floor();
        /// Computes the non-negative remainder after rounding down.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// // -100/17 = -6 + 2/17
        /// let mut r = Rational::from((-100, 17));
        /// r.rem_floor_mut();
        /// assert_eq!(r, (2, 17));
        /// ```
        fn rem_floor_mut;
        /// Computes the non-negative remainder after rounding down.
        ///
        /// [`Assign<Src> for Rational`][`Assign`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// // -100/17 = -6 + 2/17
        /// let r = Rational::from((-100, 17));
        /// let r_ref = r.rem_floor_ref();
        /// let rem = Rational::from(r_ref);
        /// assert_eq!(rem, (2, 17));
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn rem_floor_ref -> RemFloorIncomplete;
    }
    rat_op_rat_int! {
        xgmp::mpq_floor_fract_whole;
        /// 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::{Integer, Rational};
        /// // -100/17 = -6 + 2/17
        /// let r = Rational::from((-100, 17));
        /// let (fract, floor) = r.fract_floor(Integer::new());
        /// assert_eq!(fract, (2, 17));
        /// assert_eq!(floor, -6);
        /// ```
        fn fract_floor(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::{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, (2, 17));
        /// assert_eq!(floor, -6);
        /// ```
        fn fract_floor_mut;
        /// Computes the fractional and floor parts of the number.
        ///
        /// The fractional part cannot be negative.
        ///
        /// [`Assign<Src> for (Rational, Integer)`][`Assign`],
        /// [`Assign<Src> for (&mut Rational, &mut Integer)`][`Assign`]
        /// and [`From<Src> for (Rational, Integer)`][`From`] are
        /// implemented with the returned
        /// [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// 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, (2, 17));
        /// assert_eq!(floor, -6);
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn fract_floor_ref -> FractFloorIncomplete;
    }
    rat_op_int! {
        xgmp::mpq_round;
        /// 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);
        /// ```
        fn round();
        /// 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);
        /// ```
        fn round_mut;
        /// Rounds the number to the nearest integer.
        ///
        /// When the number lies exactly between two integers, it is
        /// rounded away from zero.
        ///
        /// [`Assign<Src> for Integer`][`Assign`],
        /// [`Assign<Src> for Rational`][`Assign`],
        /// [`From<Src> for Integer`][`From`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # 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);
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn round_ref -> RoundIncomplete;
    }
    math_op1! {
        xgmp::mpq_round_fract;
        /// Computes the remainder after rounding to the nearest
        /// integer.
        ///
        /// # Examples
        ///
        /// ```rust
        /// 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, (1, 2));
        /// // 3.7 = 4 - 0.3 = 4 - 3/10
        /// let r2 = Rational::from((37, 10));
        /// let rem2 = r2.rem_round();
        /// assert_eq!(rem2, (-3, 10));
        /// ```
        fn rem_round();
        /// Computes the remainder after rounding to the nearest
        /// integer.
        ///
        /// # Examples
        ///
        /// ```rust
        /// 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, (1, 2));
        /// // 3.7 = 4 - 0.3 = 4 - 3/10
        /// let mut r2 = Rational::from((37, 10));
        /// r2.rem_round_mut();
        /// assert_eq!(r2, (-3, 10));
        /// ```
        fn rem_round_mut;
        /// Computes the remainder after rounding to the nearest
        /// integer.
        ///
        /// [`Assign<Src> for Rational`][`Assign`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// // -3.5 = -4 + 0.5 = -4 + 1/2
        /// let r1 = Rational::from((-35, 10));
        /// let r_ref1 = r1.rem_round_ref();
        /// let rem1 = Rational::from(r_ref1);
        /// assert_eq!(rem1, (1, 2));
        /// // 3.7 = 4 - 0.3 = 4 - 3/10
        /// let r2 = Rational::from((37, 10));
        /// let r_ref2 = r2.rem_round_ref();
        /// let rem2 = Rational::from(r_ref2);
        /// assert_eq!(rem2, (-3, 10));
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn rem_round_ref -> RemRoundIncomplete;
    }
    rat_op_rat_int! {
        xgmp::mpq_round_fract_whole;
        /// 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.
        ///
        /// # Examples
        ///
        /// ```rust
        /// 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, (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, (-3, 10));
        /// assert_eq!(round2, 4);
        /// ```
        fn fract_round(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.
        ///
        /// # Examples
        ///
        /// ```rust
        /// 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, (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, (-3, 10));
        /// assert_eq!(round2, 4);
        /// ```
        fn fract_round_mut;
        /// 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.
        ///
        /// [`Assign<Src> for (Rational, Integer)`][`Assign`],
        /// [`Assign<Src> for (&mut Rational, &mut Integer)`][`Assign`]
        /// and [`From<Src> for (Rational, Integer)`][`From`] are
        /// implemented with the returned
        /// [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// 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, (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, (-3, 10));
        /// assert_eq!(round2, 4);
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn fract_round_ref -> FractRoundIncomplete;
    }
    math_op1! {
        xgmp::mpq_square;
        /// Computes the square.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// let r = Rational::from((-13, 2));
        /// let square = r.square();
        /// assert_eq!(square, (169, 4));
        /// ```
        fn square();
        /// Computes the square.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// let mut r = Rational::from((-13, 2));
        /// r.square_mut();
        /// assert_eq!(r, (169, 4));
        /// ```
        fn square_mut;
        /// Computes the square.
        ///
        /// [`Assign<Src> for Rational`][`Assign`] and
        /// [`From<Src> for Rational`][`From`] are implemented with
        /// the returned [incomplete-computation value][icv] as `Src`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use rug::Rational;
        /// let r = Rational::from((-13, 2));
        /// assert_eq!(Rational::from(r.square_ref()), (169, 4));
        /// ```
        ///
        /// [`Assign`]: trait.Assign.html
        /// [`From`]: https://doc.rust-lang.org/nightly/std/convert/trait.From.html
        /// [icv]: index.html#incomplete-computation-values
        fn square_ref -> SquareIncomplete;
    }
}

ref_math_op1! { Rational; gmp::mpq_abs; struct AbsIncomplete {} }
ref_rat_op_int! { xgmp::mpq_signum; struct SignumIncomplete {} }

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

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

ref_math_op1! { Rational; xgmp::mpq_inv_check; struct RecipIncomplete {} }
ref_rat_op_int! { xgmp::mpq_trunc; struct TruncIncomplete {} }
ref_math_op1! { Rational; xgmp::mpq_trunc_fract; struct RemTruncIncomplete {} }
ref_rat_op_rat_int! {
    xgmp::mpq_trunc_fract_whole; struct FractTruncIncomplete {}
}
ref_rat_op_int! { xgmp::mpq_ceil; struct CeilIncomplete {} }
ref_math_op1! { Rational; xgmp::mpq_ceil_fract; struct RemCeilIncomplete {} }
ref_rat_op_rat_int! {
    xgmp::mpq_ceil_fract_whole; struct FractCeilIncomplete {}
}
ref_rat_op_int! { xgmp::mpq_floor; struct FloorIncomplete {} }
ref_math_op1! { Rational; xgmp::mpq_floor_fract; struct RemFloorIncomplete {} }
ref_rat_op_rat_int! {
    xgmp::mpq_floor_fract_whole; struct FractFloorIncomplete {}
}
ref_rat_op_int! { xgmp::mpq_round; struct RoundIncomplete {} }
ref_math_op1! { Rational; xgmp::mpq_round_fract; struct RemRoundIncomplete {} }
ref_rat_op_rat_int! {
    xgmp::mpq_round_fract_whole; struct FractRoundIncomplete {}
}
ref_math_op1! { Rational; xgmp::mpq_square; struct SquareIncomplete {} }

#[derive(Debug)]
pub struct BorrowRational<'a> {
    inner: mpq_t,
    phantom: PhantomData<&'a Rational>,
}

impl<'a> Deref for BorrowRational<'a> {
    type Target = Rational;
    #[inline]
    fn deref(&self) -> &Rational {
        let ptr = cast_ptr!(&self.inner, Rational);
        unsafe { &*ptr }
    }
}

pub(crate) fn append_to_string(
    s: &mut String,
    r: &Rational,
    radix: i32,
    to_upper: bool,
) {
    let (num, den) = (r.numer(), r.denom());
    let is_whole = *den == 1;
    let cap_for_den_nul = if is_whole {
        1
    } else {
        big_integer::req_chars(den, radix, 2)
    };
    let cap = big_integer::req_chars(num, radix, cap_for_den_nul);
    s.reserve(cap);
    big_integer::append_to_string(s, num, radix, to_upper);
    if !is_whole {
        s.push('/');
        big_integer::append_to_string(s, den, radix, to_upper);
    }
}

#[derive(Debug)]
pub struct ParseIncomplete {
    c_string: CString,
    radix: i32,
}

impl Assign<ParseIncomplete> for Rational {
    #[inline]
    fn assign(&mut self, src: ParseIncomplete) {
        unsafe {
            let err = gmp::mpq_set_str(
                self.inner_mut(),
                src.c_string.as_ptr(),
                cast(src.radix),
            );
            assert_eq!(err, 0);
            gmp::mpq_canonicalize(self.inner_mut());
        }
    }
}

impl From<ParseIncomplete> for Rational {
    #[inline]
    fn from(src: ParseIncomplete) -> Self {
        let mut dst = Rational::new();
        dst.assign(src);
        dst
    }
}

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

    assert!(radix >= 2 && radix <= 36, "radix out of range");
    let bradix: u8 = cast(radix);
    let small_bound = b'a' - 10 + bradix;
    let capital_bound = b'A' - 10 + bradix;
    let digit_bound = b'0' + bradix;

    let mut v = Vec::with_capacity(bytes.len() + 1);
    let mut has_sign = false;
    let mut has_digits = false;
    let mut denom = false;
    let mut division_by_zero = false;
    for &b in bytes {
        if b == b'/' {
            if denom {
                return Err(Error {
                    kind: Kind::TooManySlashes,
                });
            }
            if !has_digits {
                return Err(Error {
                    kind: Kind::NumerNoDigits,
                });
            }
            v.push(b'/');
            has_digits = false;
            denom = true;
            division_by_zero = true;
            continue;
        }
        let valid_digit = match b {
            b'+' if !denom && !has_sign && !has_digits => {
                has_sign = true;
                continue;
            }
            b'-' if !denom && !has_sign && !has_digits => {
                v.push(b'-');
                has_sign = true;
                continue;
            }
            b'_' if has_digits => continue,
            b' ' | b'\t' | b'\n' | 0x0b | 0x0c | 0x0d => continue,

            _ if b >= b'a' => b < small_bound,
            _ if b >= b'A' => b < capital_bound,
            b'0'...b'9' => b < digit_bound,
            _ => false,
        };
        if !valid_digit {
            return Err(Error {
                kind: Kind::InvalidDigit,
            });
        }
        v.push(b);
        has_digits = true;
        division_by_zero = division_by_zero && b == b'0';
    }
    if !has_digits {
        return Err(Error {
            kind: if denom {
                Kind::DenomNoDigits
            } else {
                Kind::NoDigits
            },
        });
    }
    if division_by_zero {
        return Err(Error {
            kind: Kind::DenomZero,
        });
    }
    // we've only added b'-' and digits, so we know there are no nuls
    let c_string = unsafe { CString::from_vec_unchecked(v) };
    Ok(ParseIncomplete { c_string, radix })
}

#[derive(Debug)]
/**
An error which can be returned when parsing a [`Rational`] number.

See the [`Rational::parse_radix`] method for details on what strings
are accepted.

# Examples

```rust
use rug::Rational;
use rug::rational::ParseRationalError;
// 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);
```

[`Rational::parse_radix`]: ../struct.Rational.html#method.parse_radix
[`Rational`]: ../struct.Rational.html
*/
pub struct ParseRationalError {
    kind: ParseErrorKind,
}

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

impl Error for ParseRationalError {
    fn description(&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 Inner for Rational {
    type Output = mpq_t;
    #[inline]
    fn inner(&self) -> &mpq_t {
        &self.inner
    }
}

impl InnerMut for Rational {
    #[inline]
    unsafe fn inner_mut(&mut self) -> &mut mpq_t {
        &mut self.inner
    }
}