1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
// Copyright © 2016–2024 Trevor Spiteri

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

use crate::ext::xmpz;
use crate::integer::arith::MulIncomplete;
use crate::integer::{BorrowInteger, MiniInteger, Order};
use crate::misc;
use crate::misc::{StringLike, VecLike};
use crate::ops::{DivRounding, NegAssign, SubFrom};
#[cfg(feature = "rand")]
use crate::rand::MutRandState;
#[cfg(feature = "rational")]
use crate::rational::BorrowRational;
use crate::{Assign, Complete};
use az::{Az, Cast, CheckedCast, UnwrappedAs, UnwrappedCast, WrappingCast};
use core::cmp::Ordering;
use core::ffi::{c_char, c_uint, c_ulong};
use core::fmt::{Display, Formatter, Result as FmtResult};
use core::mem;
use core::mem::{ManuallyDrop, MaybeUninit};
use core::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign};
#[cfg(feature = "rational")]
use core::ptr::NonNull;
use core::slice;
use gmp_mpfr_sys::gmp;
#[cfg(feature = "rational")]
use gmp_mpfr_sys::gmp::mpq_t;
use gmp_mpfr_sys::gmp::{bitcnt_t, limb_t, mpz_t};
#[cfg(feature = "std")]
use std::error::Error;

/**
An arbitrary-precision integer.

Standard arithmetic operations, bitwise operations and comparisons are
supported. In standard arithmetic operations such as addition, you can mix
`Integer` and primitive integer types; the result will be an `Integer`.

Internally the integer is not stored using a two’s-complement representation,
however, for bitwise operations and shifts, the functionality is the same as if
the representation was using two’s complement.

# Examples

```rust
use rug::{Assign, Integer};
// Create an integer initialized as zero.
let mut int = Integer::new();
assert_eq!(int, 0);
assert_eq!(int.to_u32(), Some(0));
int.assign(-14);
assert_eq!(int, -14);
assert_eq!(int.to_u32(), None);
assert_eq!(int.to_i32(), Some(-14));
```

Arithmetic operations with mixed arbitrary and primitive types are allowed. Note
that in the following example, there is only one allocation. The `Integer`
instance is moved into the shift operation so that the result can be stored in
the same instance, then that result is similarly consumed by the addition
operation.

```rust
use rug::Integer;
let mut a = Integer::from(0xc);
a = (a << 80) + 0xffee;
assert_eq!(a.to_string_radix(16), "c0000000000000000ffee");
//                                 ↑   ↑   ↑   ↑   ↑   ↑
//                                80  64  48  32  16   0
```

Bitwise operations on `Integer` values behave as if the value uses a
two’s-complement representation.

```rust
use rug::Integer;

let mut i = Integer::from(1);
i = i << 1000;
// i is now 1000000... (1000 zeros)
assert_eq!(i.significant_bits(), 1001);
assert_eq!(i.find_one(0), Some(1000));
i -= 1;
// i is now 111111... (1000 ones)
assert_eq!(i.count_ones(), Some(1000));

let a = Integer::from(0xf00d);
// -1 is all ones in two’s complement
let all_ones_xor_a = Integer::from(-1 ^ &a);
// a is unchanged as we borrowed it
let complement_a = !a;
// now a has been moved, so this would cause an error:
// assert!(a > 0);
assert_eq!(all_ones_xor_a, complement_a);
assert_eq!(complement_a, -0xf00e);
assert_eq!(format!("{:x}", complement_a), "-f00e");
```

To initialize a large `Integer` that does not fit in a primitive type, you can
parse a string.

```rust
use rug::Integer;
let s1 = "123456789012345678901234567890";
let i1 = s1.parse::<Integer>().unwrap();
assert_eq!(i1.significant_bits(), 97);
let s2 = "ffff0000ffff0000ffff0000ffff0000ffff0000";
let i2 = Integer::from_str_radix(s2, 16).unwrap();
assert_eq!(i2.significant_bits(), 160);
assert_eq!(i2.count_ones(), Some(80));
```

Operations on two borrowed `Integer` values result in an [incomplete-computation
value][icv] that has to be assigned to a new `Integer` value.

```rust
use rug::Integer;
let a = Integer::from(10);
let b = Integer::from(3);
let a_b_ref = &a + &b;
let a_b = Integer::from(a_b_ref);
assert_eq!(a_b, 13);
```

As a special case, when an [incomplete-computation value][icv] is obtained from
multiplying two `Integer` references, it can be added to or subtracted from
another `Integer` (or reference). This can be useful for multiply-accumulate
operations.

```rust
use rug::Integer;
let mut acc = Integer::from(100);
let m1 = Integer::from(3);
let m2 = Integer::from(7);
// 100 + 3 × 7 = 121
acc += &m1 * &m2;
assert_eq!(acc, 121);
let other = Integer::from(2000);
// Do not consume any values here:
// 2000 - 3 × 7 = 1979
let sub = Integer::from(&other - &m1 * &m2);
assert_eq!(sub, 1979);
```

The `Integer` 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 an
    `Integer`.

```rust
use rug::Integer;

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

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

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

[icv]: crate#incomplete-computation-values
*/
#[repr(transparent)]
pub struct Integer {
    inner: mpz_t,
}

impl Integer {
    #[inline]
    pub(crate) const fn inner(&self) -> &mpz_t {
        &self.inner
    }
    #[inline]
    pub(crate) unsafe fn inner_mut(&mut self) -> &mut mpz_t {
        &mut self.inner
    }
    #[inline]
    pub(crate) const fn inner_data(&self) -> &[limb_t] {
        let limbs = self.inner.size.unsigned_abs();
        let limbs_usize = limbs as usize;
        if limbs != limbs_usize as c_uint {
            panic!("overflow");
        }
        unsafe { slice::from_raw_parts(self.inner.d.as_ptr(), limbs_usize) }
    }
}

static_assert_same_layout!(Integer, mpz_t);
static_assert_same_layout!(BorrowInteger<'_>, mpz_t);

static_assert_same_size!(Integer, Option<Integer>);

impl Integer {
    /// Zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// assert_eq!(Integer::ZERO, 0);
    /// ```
    pub const ZERO: Integer = Integer::new();

    /// One.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// assert_eq!(*Integer::ONE, 1);
    /// ```
    pub const ONE: &'static Integer = {
        const MINI: MiniInteger = MiniInteger::const_from_bool(true);
        const BORROW: BorrowInteger = MINI.borrow();
        BorrowInteger::const_deref(&BORROW)
    };

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

    /// Constructs a new arbitrary-precision [`Integer`] with value 0.
    ///
    /// The created [`Integer`] will have no allocated memory yet.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::new();
    /// assert_eq!(i, 0);
    /// ```
    #[inline]
    pub const fn new() -> Self {
        Integer {
            inner: xmpz::owned_init(),
        }
    }

    /// Constructs a new arbitrary-precision [`Integer`] with at least the
    /// specified capacity.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::with_capacity(137);
    /// assert!(i.capacity() >= 137);
    /// ```
    #[inline]
    pub fn with_capacity(bits: usize) -> Self {
        unsafe {
            let mut dst = MaybeUninit::uninit();
            xmpz::init2(dst.as_mut_ptr(), bits);
            dst.assume_init()
        }
    }

    /// Returns the capacity in bits that can be stored without reallocating.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::with_capacity(137);
    /// assert!(i.capacity() >= 137);
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        self.inner
            .alloc
            .unwrapped_as::<usize>()
            .checked_mul(gmp::LIMB_BITS.az::<usize>())
            .expect("overflow")
    }

    /// Reserves capacity for at least `additional` more bits in the
    /// [`Integer`].
    ///
    /// If the integer already has enough excess capacity, this function does
    /// nothing.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // 0x2000_0000 needs 30 bits.
    /// let mut i = Integer::from(0x2000_0000);
    /// assert_eq!(i.significant_bits(), 30);
    /// i.reserve(290);
    /// let capacity = i.capacity();
    /// assert!(capacity >= 320);
    /// i.reserve(0);
    /// assert_eq!(i.capacity(), capacity);
    /// i.reserve(291);
    /// assert!(i.capacity() >= 321);
    /// ```
    pub fn reserve(&mut self, additional: usize) {
        let used_bits = xmpz::significant_bits(self);
        let req_bits = used_bits.checked_add(additional).expect("overflow");
        let alloc_bits = (self.inner.alloc.az::<usize>())
            .checked_mul(gmp::LIMB_BITS.az::<usize>())
            .expect("overflow");
        if alloc_bits < req_bits {
            unsafe {
                gmp::mpz_realloc2(self.as_raw_mut(), req_bits.unwrapped_cast());
            }
        }
    }

    /// Shrinks the capacity of the [`Integer`] as much as possible.
    ///
    /// The capacity can still be larger than the number of significant bits.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // let i be 100 bits wide
    /// let mut i = Integer::from_str_radix("fffff12345678901234567890", 16)
    ///     .unwrap();
    /// assert_eq!(i.significant_bits(), 100);
    /// assert!(i.capacity() >= 100);
    /// i >>= 80;
    /// i.shrink_to_fit();
    /// assert!(i.capacity() >= 20);
    /// ```
    pub fn shrink_to_fit(&mut self) {
        self.shrink_to(0);
    }

    /// Shrinks the capacity of the [`Integer`] with a lower bound in bits.
    ///
    /// The capacity will remain at least as large as both the current number of
    /// siginificant bits and the supplied value.
    ///
    /// If the current capacity is less than the lower limit, this method has no
    /// effect.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // let i be 100 bits wide
    /// let mut i = Integer::from_str_radix("fffff12345678901234567890", 16)
    ///     .unwrap();
    /// assert_eq!(i.significant_bits(), 100);
    /// assert!(i.capacity() >= 100);
    /// i >>= 80;
    /// i.shrink_to(50);
    /// assert!(i.capacity() >= 50);
    /// i.shrink_to(0);
    /// assert!(i.capacity() >= 20);
    /// ```
    pub fn shrink_to(&mut self, min_capacity: usize) {
        let min_limbs = DivRounding::div_ceil(min_capacity, gmp::LIMB_BITS.az::<usize>());
        if min_limbs >= self.inner.alloc.unwrapped_as::<usize>() {
            return;
        }
        let used_limbs = self.inner.size.checked_abs().expect("overflow");
        if min_limbs > used_limbs.unwrapped_as::<usize>() {
            // we already know that self.inner.alloc > min_limbs
            // and that min_limbs > 0
            unsafe {
                gmp::_mpz_realloc(self.as_raw_mut(), min_limbs.unwrapped_cast());
            }
        } else if self.inner.alloc > used_limbs {
            if used_limbs == 0 {
                *self = Integer::ZERO;
            } else {
                unsafe {
                    gmp::_mpz_realloc(self.as_raw_mut(), used_limbs.unwrapped_cast());
                }
            }
        }
    }

    /// Creates an [`Integer`] from an initialized [GMP integer][mpz_t].
    ///
    /// # Safety
    ///
    ///   * The function must *not* be used to create a constant [`Integer`],
    ///     though it can be used to create a static [`Integer`]. This is
    ///     because constant values are *copied* on use, leading to undefined
    ///     behavior when they are dropped.
    ///   * The value must be initialized as a valid [`mpz_t`].
    ///   * The [`mpz_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.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use core::mem::MaybeUninit;
    /// use gmp_mpfr_sys::gmp;
    /// use rug::Integer;
    /// let i = unsafe {
    ///     let mut z = MaybeUninit::uninit();
    ///     gmp::mpz_init_set_ui(z.as_mut_ptr(), 15);
    ///     let z = z.assume_init();
    ///     // z is initialized and unique
    ///     Integer::from_raw(z)
    /// };
    /// assert_eq!(i, 15);
    /// // since i is an Integer now, deallocation is automatic
    /// ```
    ///
    /// This can be used to create a static [`Integer`] using
    /// [`MPZ_ROINIT_N`][gmp::MPZ_ROINIT_N] to initialize the raw value. See the
    /// [GMP documentation][gmp roinit] for details.
    ///
    /// ```rust
    /// use gmp_mpfr_sys::gmp;
    /// use gmp_mpfr_sys::gmp::{limb_t, mpz_t};
    /// use rug::Integer;
    /// const LIMBS: [limb_t; 2] = [123, 456];
    /// const MPZ: mpz_t =
    ///     unsafe { gmp::MPZ_ROINIT_N(LIMBS.as_ptr().cast_mut(), -2) };
    /// // Must *not* be const, otherwise it would lead to undefined
    /// // behavior on use, as it would create a copy that is dropped.
    /// static I: Integer = unsafe { Integer::from_raw(MPZ) };
    /// let check = -((Integer::from(LIMBS[1]) << gmp::NUMB_BITS) + LIMBS[0]);
    /// assert_eq!(I, check);
    /// ```
    ///
    /// [gmp roinit]: gmp_mpfr_sys::C::GMP::Integer_Functions#index-MPZ_005fROINIT_005fN
    #[inline]
    pub const unsafe fn from_raw(raw: mpz_t) -> Self {
        Integer { inner: raw }
    }

    /// Converts an [`Integer`] into a [GMP integer][mpz_t].
    ///
    /// The returned object should be freed to avoid memory leaks.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gmp_mpfr_sys::gmp;
    /// use rug::Integer;
    /// let i = Integer::from(15);
    /// let mut z = i.into_raw();
    /// unsafe {
    ///     let u = gmp::mpz_get_ui(&z);
    ///     assert_eq!(u, 15);
    ///     // free object to prevent memory leak
    ///     gmp::mpz_clear(&mut z);
    /// }
    /// ```
    #[inline]
    pub const fn into_raw(self) -> mpz_t {
        let ret = self.inner;
        let _ = ManuallyDrop::new(self);
        ret
    }

    /// Returns a pointer to the inner [GMP integer][mpz_t].
    ///
    /// The returned pointer will be valid for as long as `self` is valid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gmp_mpfr_sys::gmp;
    /// use rug::Integer;
    /// let i = Integer::from(15);
    /// let z_ptr = i.as_raw();
    /// unsafe {
    ///     let u = gmp::mpz_get_ui(z_ptr);
    ///     assert_eq!(u, 15);
    /// }
    /// // i is still valid
    /// assert_eq!(i, 15);
    /// ```
    #[inline]
    pub const fn as_raw(&self) -> *const mpz_t {
        &self.inner
    }

    /// Returns an unsafe mutable pointer to the inner [GMP integer][mpz_t].
    ///
    /// The returned pointer will be valid for as long as `self` is valid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gmp_mpfr_sys::gmp;
    /// use rug::Integer;
    /// let mut i = Integer::from(15);
    /// let z_ptr = i.as_raw_mut();
    /// unsafe {
    ///     gmp::mpz_add_ui(z_ptr, z_ptr, 20);
    /// }
    /// assert_eq!(i, 35);
    /// ```
    #[inline]
    pub fn as_raw_mut(&mut self) -> *mut mpz_t {
        &mut self.inner
    }

    /// Creates an [`Integer`] from a [slice] of digits of type `T`, where `T`
    /// can be any [unsigned integer primitive type][UnsignedPrimitive].
    ///
    /// The resulting value cannot be negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::integer::Order;
    /// use rug::Integer;
    /// let digits = [0x5678u16, 0x1234u16];
    /// let i = Integer::from_digits(&digits, Order::Lsf);
    /// assert_eq!(i, 0x1234_5678);
    /// ```
    ///
    /// [slice]: prim@slice
    pub fn from_digits<T: UnsignedPrimitive>(digits: &[T], order: Order) -> Self {
        let capacity = digits.len().checked_mul(T::PRIVATE.bits).expect("overflow");
        let mut i = Integer::with_capacity(capacity);
        i.assign_digits(digits, order);
        i
    }

    /// Assigns from a [slice] of digits of type `T`, where `T` can be any
    /// [unsigned integer primitive type][UnsignedPrimitive].
    ///
    /// The resulting value cannot be negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::integer::Order;
    /// use rug::Integer;
    /// let digits = [0x5678u16, 0x1234u16];
    /// let mut i = Integer::new();
    /// i.assign_digits(&digits, Order::Lsf);
    /// assert_eq!(i, 0x1234_5678);
    /// ```
    ///
    /// [slice]: prim@slice
    pub fn assign_digits<T: UnsignedPrimitive>(&mut self, digits: &[T], order: Order) {
        // Safety: it is valid to read digits.len() digits from digits.as_mut_ptr().
        unsafe {
            self.assign_digits_unaligned(digits.as_ptr(), digits.len(), order);
        }
    }

    /// Assigns from digits of type `T` in a memory area, where `T` can be any
    /// [unsigned integer primitive type][UnsignedPrimitive].
    ///
    /// The memory area is addressed using a pointer and a length. The `len`
    /// parameter is the number of digits, *not* the number of bytes.
    ///
    /// There are no data alignment restrictions on `src`, any address is
    /// allowed.
    ///
    /// The resulting value cannot be negative.
    ///
    /// # Safety
    ///
    /// To avoid undefined behavior, `src` must be [valid] for reading `len`
    /// digits, that is `len` × `size_of::<T>()` bytes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::integer::Order;
    /// use rug::Integer;
    /// // hex bytes: [ fe dc ba 98 87 87 87 87 76 54 32 10 ]
    /// let digits = [
    ///     0xfedc_ba98u32.to_be(),
    ///     0x8787_8787u32.to_be(),
    ///     0x7654_3210u32.to_be(),
    /// ];
    /// let ptr = digits.as_ptr();
    /// let mut i = Integer::new();
    /// unsafe {
    ///     let unaligned = (ptr.cast::<u8>()).offset(2).cast::<u32>();
    ///     i.assign_digits_unaligned(unaligned, 2, Order::MsfBe);
    /// }
    /// assert_eq!(i, 0xba98_8787_8787_7654u64);
    /// ```
    ///
    /// [valid]: core::ptr#safety
    pub unsafe fn assign_digits_unaligned<T: UnsignedPrimitive>(
        &mut self,
        src: *const T,
        len: usize,
        order: Order,
    ) {
        let bytes = mem::size_of::<T>();
        let nails = 8 * bytes - T::PRIVATE.bits;
        let raw = self.as_raw_mut();
        let (order, endian) = (order.order(), order.endian());
        let src = src.cast();
        unsafe {
            gmp::mpz_import(raw, len, order, bytes, endian, nails, src);
        }
    }

    /// Returns the number of digits of type `T` required to represent the
    /// absolute value.
    ///
    /// `T` can be any [unsigned integer primitive type][UnsignedPrimitive].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    ///
    /// let i: Integer = Integer::from(1) << 256;
    /// assert_eq!(i.significant_digits::<bool>(), 257);
    /// assert_eq!(i.significant_digits::<u8>(), 33);
    /// assert_eq!(i.significant_digits::<u16>(), 17);
    /// assert_eq!(i.significant_digits::<u32>(), 9);
    /// assert_eq!(i.significant_digits::<u64>(), 5);
    /// ```
    #[inline]
    pub fn significant_digits<T: UnsignedPrimitive>(&self) -> usize {
        DivRounding::div_ceil(xmpz::significant_bits(self), T::PRIVATE.bits)
    }

    /// Converts the absolute value to a [`Vec`] of digits of type `T`, where
    /// `T` can be any [unsigned integer primitive type][UnsignedPrimitive].
    ///
    /// The [`Integer`] type also has the [`as_limbs`][Integer::as_limbs]
    /// method, which can be used to borrow the digits without copying them.
    /// This does come with some more constraints compared to `to_digits`:
    ///
    ///  1. The digit width is not optional and depends on the implementation:
    ///     [`limb_t`] is typically [`u64`] on 64-bit systems and [`u32`] on
    ///     32-bit systems.
    ///  2. The order is not optional and is least significant digit first, with
    ///     each digit in the target’s endianness, equivalent to
    ///     <code>[Order]::[Lsf][Order::Lsf]</code>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::integer::Order;
    /// use rug::Integer;
    /// let i = Integer::from(0x1234_5678_9abc_def0u64);
    /// let digits = i.to_digits::<u32>(Order::MsfBe);
    /// assert_eq!(digits, [0x1234_5678u32.to_be(), 0x9abc_def0u32.to_be()]);
    ///
    /// let zero = Integer::new();
    /// let digits_zero = zero.to_digits::<u32>(Order::MsfBe);
    /// assert!(digits_zero.is_empty());
    /// ```
    #[cfg(feature = "std")]
    pub fn to_digits<T: UnsignedPrimitive>(&self, order: Order) -> Vec<T> {
        let digit_count = self.significant_digits::<T>();
        let mut v = Vec::<T>::with_capacity(digit_count);
        unsafe {
            let digits_ptr = v.as_mut_ptr();
            let mut count = MaybeUninit::uninit();
            gmp::mpz_export(
                digits_ptr.cast(),
                count.as_mut_ptr(),
                order.order(),
                T::PRIVATE.bytes,
                order.endian(),
                T::PRIVATE.nails,
                self.as_raw(),
            );
            assert_eq!(count.assume_init(), digit_count);
            v.set_len(digit_count);
        }
        v
    }

    /// Writes the absolute value into a [slice] of digits of type `T`, where
    /// `T` can be any [unsigned integer primitive type][UnsignedPrimitive].
    ///
    /// The slice must be large enough to hold the digits; the minimum size can
    /// be obtained using the [`significant_digits`] method.
    ///
    /// # Panics
    ///
    /// Panics if the slice does not have sufficient capacity.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::integer::Order;
    /// use rug::Integer;
    /// let i = Integer::from(0x1234_5678_9abc_def0u64);
    /// let mut digits = [0xffff_ffffu32; 4];
    /// i.write_digits(&mut digits, Order::MsfBe);
    /// let word0 = 0x9abc_def0u32;
    /// let word1 = 0x1234_5678u32;
    /// assert_eq!(digits, [0, 0, word1.to_be(), word0.to_be()]);
    /// ```
    ///
    /// [`significant_digits`]: `Integer::significant_digits`
    /// [slice]: prim@slice
    pub fn write_digits<T: UnsignedPrimitive>(&self, digits: &mut [T], order: Order) {
        // Safety: it is valid to write digits.len() digits into digits.as_mut_ptr().
        unsafe {
            self.write_digits_unaligned(digits.as_mut_ptr(), digits.len(), order);
        }
    }

    /// Writes the absolute value into a memory area of digits of type `T`,
    /// where `T` can be any [unsigned integer primitive
    /// type][UnsignedPrimitive].
    ///
    /// The memory area is addressed using a pointer and a length. The `len`
    /// parameter is the number of digits, *not* the number of bytes.
    ///
    /// The length must be large enough to hold the digits; the minimum length
    /// can be obtained using the [`significant_digits`] method.
    ///
    /// There are no data alignment restrictions on `dst`, any address is
    /// allowed.
    ///
    /// The memory locations can be uninitialized before this method is called;
    /// this method sets all `len` elements, padding with zeros if the length is
    /// larger than required.
    ///
    /// # Safety
    ///
    /// To avoid undefined behavior, `dst` must be [valid] for writing `len`
    /// digits, that is `len` × `size_of::<T>()` bytes.
    ///
    /// # Panics
    ///
    /// Panics if the length is less than the number of digits.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::integer::Order;
    /// use rug::Integer;
    /// let i = Integer::from(0xfedc_ba98_7654_3210u64);
    /// let mut digits = [0xffff_ffffu32; 4];
    /// let ptr = digits.as_mut_ptr();
    /// unsafe {
    ///     let unaligned = (ptr.cast::<u8>()).offset(2).cast::<u32>();
    ///     i.write_digits_unaligned(unaligned, 3, Order::MsfBe);
    /// }
    /// assert_eq!(
    ///     digits,
    ///     [
    ///         0xffff_0000u32.to_be(),
    ///         0x0000_fedcu32.to_be(),
    ///         0xba98_7654u32.to_be(),
    ///         0x3210_ffffu32.to_be(),
    ///     ]
    /// );
    /// ```
    ///
    /// The following example shows how to write into uninitialized memory. In
    /// practice, the following code could be replaced by a call to the safe
    /// method [`to_digits`].
    ///
    /// ```rust
    /// use rug::integer::Order;
    /// use rug::Integer;
    /// let i = Integer::from(0x1234_5678_9abc_def0u64);
    /// let len = i.significant_digits::<u32>();
    /// assert_eq!(len, 2);
    ///
    /// // The following code is equivalent to:
    /// //     let digits = i.to_digits::<u32>(Order::MsfBe);
    /// let mut digits = Vec::<u32>::with_capacity(len);
    /// let ptr = digits.as_mut_ptr();
    /// unsafe {
    ///     i.write_digits_unaligned(ptr, len, Order::MsfBe);
    ///     digits.set_len(len);
    /// }
    ///
    /// assert_eq!(digits, [0x1234_5678u32.to_be(), 0x9abc_def0u32.to_be()]);
    /// ```
    ///
    /// [`significant_digits`]: `Integer::significant_digits`
    /// [`to_digits`]: `Integer::to_digits`
    /// [valid]: `core::ptr`#safety
    pub unsafe fn write_digits_unaligned<T: UnsignedPrimitive>(
        &self,
        dst: *mut T,
        len: usize,
        order: Order,
    ) {
        let digit_count = self.significant_digits::<T>();
        let zero_count = len.checked_sub(digit_count).expect("not enough capacity");
        let zero_bytes = zero_count * T::PRIVATE.bytes;
        let (zeros, digits) = if order.order() < 0 {
            let offset = digit_count.unwrapped_cast();
            (unsafe { dst.offset(offset) }, dst)
        } else {
            let offset = zero_count.unwrapped_cast();
            (dst, unsafe { dst.offset(offset) })
        };
        unsafe {
            // use *mut u8 to allow for unaligned pointers
            (zeros.cast::<u8>()).write_bytes(0, zero_bytes);
        }
        let mut count = MaybeUninit::uninit();
        let digits = digits.cast();
        let count_ptr = count.as_mut_ptr();
        let (order, endian) = (order.order(), order.endian());
        let raw = self.as_raw();
        unsafe {
            gmp::mpz_export(
                digits,
                count_ptr,
                order,
                T::PRIVATE.bytes,
                endian,
                T::PRIVATE.nails,
                raw,
            );
        }
        assert_eq!(unsafe { count.assume_init() }, digit_count);
    }

    /// Extracts a [slice] of [limbs][limb_t] used to store the value.
    ///
    /// The [slice] contains the absolute value of `self`, with the least
    /// significant limb first.
    ///
    /// The [`Integer`] type also implements
    /// <code>[AsRef]\<[\[][slice][limb_t][][\]][slice]></code>, which is
    /// equivalent to this method.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// assert!(Integer::new().as_limbs().is_empty());
    /// assert_eq!(Integer::from(13).as_limbs(), &[13]);
    /// assert_eq!(Integer::from(-23).as_limbs(), &[23]);
    /// ```
    ///
    /// `int.as_limbs()` is like a borrowing non-copy version of
    /// <code>int.[to\_digits][Integer::to_digits]::\<[limb\_t]>([Order]::[Lsf][Order::Lsf])</code>.
    ///
    /// ```rust
    /// use gmp_mpfr_sys::gmp::limb_t;
    /// use rug::integer::Order;
    /// use rug::Integer;
    /// let int = Integer::from(0x1234_5678_9abc_def0u64);
    /// // no copying for int_slice, which is borrowing int
    /// let int_slice = int.as_limbs();
    /// // digits is a copy and does not borrow int
    /// let digits = int.to_digits::<limb_t>(Order::Lsf);
    /// // no copying for digits_slice, which is borrowing digits
    /// let digits_slice = &digits[..];
    /// assert_eq!(int_slice, digits_slice);
    /// ```
    ///
    /// [slice]: prim@slice
    pub const fn as_limbs(&self) -> &[limb_t] {
        self.inner_data()
    }

    /// Creates an [`Integer`] from an [`f32`] if it is
    /// [finite][f32::is_finite], rounding towards zero.
    ///
    /// This conversion can also be performed using
    /// <code>value.[checked\_as]::\<[Integer]>()</code>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from_f32(-5.6).unwrap();
    /// assert_eq!(i, -5);
    /// let neg_inf = Integer::from_f32(f32::NEG_INFINITY);
    /// assert!(neg_inf.is_none());
    /// ```
    ///
    /// [checked\_as]: az::CheckedAs::checked_as
    #[inline]
    pub fn from_f32(value: f32) -> Option<Self> {
        value.checked_cast()
    }

    /// Creates an [`Integer`] from an [`f64`] if it is
    /// [finite][f64::is_finite], rounding towards zero.
    ///
    /// This conversion can also be performed using
    /// <code>value.[checked\_as]::\<[Integer]>()</code>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from_f64(1e20).unwrap();
    /// assert_eq!(i, "100000000000000000000".parse::<Integer>().unwrap());
    /// let inf = Integer::from_f64(f64::INFINITY);
    /// assert!(inf.is_none());
    /// ```
    ///
    /// [checked\_as]: az::CheckedAs::checked_as
    #[inline]
    pub fn from_f64(value: f64) -> Option<Self> {
        value.checked_cast()
    }

    /// Parses an [`Integer`] using the given radix.
    ///
    /// # Panics
    ///
    /// Panics if `radix` is less than 2 or greater than 36.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from_str_radix("-ff", 16).unwrap();
    /// assert_eq!(i, -0xff);
    /// ```
    #[inline]
    pub fn from_str_radix(src: &str, radix: i32) -> Result<Self, ParseIntegerError> {
        Ok(Integer::from(Integer::parse_radix(src, radix)?))
    }

    /// Parses a decimal string slice (<code>\&[str]</code>) or byte slice
    /// (<code>[\&\[][slice][u8][][\]][slice]</code>) into an [`Integer`].
    ///
    /// The following are implemented with the unwrapped returned
    /// [incomplete-computation value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// The string can start with an optional minus or plus sign. ASCII
    /// whitespace is ignored everywhere in the string. Underscores anywhere
    /// except before the first digit are ignored as well.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    ///
    /// assert_eq!(Integer::parse("1223").unwrap().complete(), 1223);
    /// assert_eq!(Integer::parse("123 456 789").unwrap().complete(), 123_456_789);
    ///
    /// let invalid = Integer::parse("789a");
    /// assert!(invalid.is_err());
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    /// [slice]: prim@slice
    #[inline]
    pub fn parse<S: AsRef<[u8]>>(src: S) -> Result<ParseIncomplete, ParseIntegerError> {
        parse(src.as_ref(), 10)
    }

    /// Parses a string slice (<code>\&[str]</code>) or byte slice
    /// (<code>[\&\[][slice][u8][][\]][slice]</code>) into an
    /// [`Integer`].
    ///
    /// The following are implemented with the unwrapped returned
    /// [incomplete-computation value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// The string can start with an optional minus or plus sign. ASCII
    /// whitespace is ignored everywhere in the string. Underscores anywhere
    /// except before the first digit are ignored as well.
    ///
    /// See also [`assign_bytes_radix_unchecked`], which is an unsafe low-level
    /// method that can be used if parsing is already done by an external
    /// function.
    ///
    /// # Panics
    ///
    /// Panics if `radix` is less than 2 or greater than 36.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    ///
    /// let valid1 = Integer::parse_radix("1223", 4);
    /// assert_eq!(valid1.unwrap().complete(), 3 + 4 * (2 + 4 * (2 + 4 * 1)));
    /// let valid2 = Integer::parse_radix("1234 abcd", 16);
    /// assert_eq!(valid2.unwrap().complete(), 0x1234_abcd);
    ///
    /// let invalid = Integer::parse_radix("123", 3);
    /// assert!(invalid.is_err());
    /// ```
    ///
    /// [`assign_bytes_radix_unchecked`]: Self::assign_bytes_radix_unchecked
    /// [icv]: crate#incomplete-computation-values
    /// [slice]: prim@slice
    #[inline]
    pub fn parse_radix<S: AsRef<[u8]>>(
        src: S,
        radix: i32,
    ) -> Result<ParseIncomplete, ParseIntegerError> {
        parse(src.as_ref(), radix)
    }

    /// Assigns from bytes in the given radix.
    ///
    /// The radix must be between 2 and 256 inclusive.
    ///
    /// Each byte must be a value from 0 to `radix - 1`, not an ASCII character.
    /// The bytes must be ordered most-significant byte first.
    ///
    /// If `is_negative` is [`true`], the returned value is negative (unless it is 0).
    ///
    /// # Safety
    ///
    /// The caller must ensure that
    ///
    ///   * 2&nbsp;≤&nbsp;`radix`&nbsp;≤&nbsp;256
    ///   * all bytes are in the range 0&nbsp;≤&nbsp;<i>x</i>&nbsp;<&nbsp;`radix`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let bytes = &[0, 3, 9, 2];
    /// let radix = 10;
    /// let neg = true;
    /// let mut i = Integer::new();
    /// // SAFETY: radix and bytes are in the required ranges
    /// unsafe {
    ///     i.assign_bytes_radix_unchecked(bytes, radix, neg);
    /// }
    /// assert_eq!(i, -392);
    /// ```
    pub unsafe fn assign_bytes_radix_unchecked(
        &mut self,
        bytes: &[u8],
        radix: i32,
        is_negative: bool,
    ) {
        if bytes.is_empty() {
            xmpz::set_0(self);
            return;
        }
        xmpz::realloc_for_mpn_set_str(self, bytes.len(), radix);
        unsafe {
            let size = gmp::mpn_set_str(self.inner.d.as_ptr(), bytes.as_ptr(), bytes.len(), radix);
            self.inner.size = (if is_negative { -size } else { size }).unwrapped_cast();
        }
    }

    /// Converts to an [`i8`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[i8]::[try\_from]\(\&integer)</code>
    ///   * <code>[i8]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[i8]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[i8]>()</code>
    ///   * <code>integer.[checked\_as]::\<[i8]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(-100);
    /// assert_eq!(fits.to_i8(), Some(-100));
    /// let small = Integer::from(-200);
    /// assert_eq!(small.to_i8(), None);
    /// let large = Integer::from(200);
    /// assert_eq!(large.to_i8(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_i8(&self) -> Option<i8> {
        self.checked_cast()
    }

    /// Converts to an [`i16`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[i16]::[try\_from]\(\&integer)</code>
    ///   * <code>[i16]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[i16]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[i16]>()</code>
    ///   * <code>integer.[checked\_as]::\<[i16]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(-30_000);
    /// assert_eq!(fits.to_i16(), Some(-30_000));
    /// let small = Integer::from(-40_000);
    /// assert_eq!(small.to_i16(), None);
    /// let large = Integer::from(40_000);
    /// assert_eq!(large.to_i16(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_i16(&self) -> Option<i16> {
        self.checked_cast()
    }

    /// Converts to an [`i32`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[i32]::[try\_from]\(\&integer)</code>
    ///   * <code>[i32]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[i32]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[i32]>()</code>
    ///   * <code>integer.[checked\_as]::\<[i32]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(-50);
    /// assert_eq!(fits.to_i32(), Some(-50));
    /// let small = Integer::from(-123456789012345_i64);
    /// assert_eq!(small.to_i32(), None);
    /// let large = Integer::from(123456789012345_i64);
    /// assert_eq!(large.to_i32(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_i32(&self) -> Option<i32> {
        self.checked_cast()
    }

    /// Converts to an [`i64`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[i64]::[try\_from]\(\&integer)</code>
    ///   * <code>[i64]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[i64]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[i64]>()</code>
    ///   * <code>integer.[checked\_as]::\<[i64]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(-50);
    /// assert_eq!(fits.to_i64(), Some(-50));
    /// let small = Integer::from_str_radix("-fedcba9876543210", 16).unwrap();
    /// assert_eq!(small.to_i64(), None);
    /// let large = Integer::from_str_radix("fedcba9876543210", 16).unwrap();
    /// assert_eq!(large.to_i64(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_i64(&self) -> Option<i64> {
        self.checked_cast()
    }

    /// Converts to an [`i128`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[i128]::[try\_from]\(\&integer)</code>
    ///   * <code>[i128]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[i128]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[i128]>()</code>
    ///   * <code>integer.[checked\_as]::\<[i128]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(-50);
    /// assert_eq!(fits.to_i128(), Some(-50));
    /// let small: Integer = Integer::from(-1) << 130;
    /// assert_eq!(small.to_i128(), None);
    /// let large: Integer = Integer::from(1) << 130;
    /// assert_eq!(large.to_i128(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_i128(&self) -> Option<i128> {
        self.checked_cast()
    }

    /// Converts to an [`isize`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[isize]::[try\_from]\(\&integer)</code>
    ///   * <code>[isize]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[isize]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[isize]>()</code>
    ///   * <code>integer.[checked\_as]::\<[isize]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(0x1000);
    /// assert_eq!(fits.to_isize(), Some(0x1000));
    /// let large: Integer = Integer::from(0x1000) << 128;
    /// assert_eq!(large.to_isize(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_isize(&self) -> Option<isize> {
        self.checked_cast()
    }

    /// Converts to an [`u8`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[u8]::[try\_from]\(\&integer)</code>
    ///   * <code>[u8]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[u8]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[u8]>()</code>
    ///   * <code>integer.[checked\_as]::\<[u8]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(200);
    /// assert_eq!(fits.to_u8(), Some(200));
    /// let neg = Integer::from(-1);
    /// assert_eq!(neg.to_u8(), None);
    /// let large = Integer::from(300);
    /// assert_eq!(large.to_u8(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_u8(&self) -> Option<u8> {
        self.checked_cast()
    }

    /// Converts to an [`u16`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[u16]::[try\_from]\(\&integer)</code>
    ///   * <code>[u16]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[u16]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[u16]>()</code>
    ///   * <code>integer.[checked\_as]::\<[u16]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(60_000);
    /// assert_eq!(fits.to_u16(), Some(60_000));
    /// let neg = Integer::from(-1);
    /// assert_eq!(neg.to_u16(), None);
    /// let large = Integer::from(70_000);
    /// assert_eq!(large.to_u16(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_u16(&self) -> Option<u16> {
        self.checked_cast()
    }

    /// Converts to an [`u32`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[u32]::[try\_from]\(\&integer)</code>
    ///   * <code>[u32]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[u32]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[u32]>()</code>
    ///   * <code>integer.[checked\_as]::\<[u32]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(1234567890);
    /// assert_eq!(fits.to_u32(), Some(1234567890));
    /// let neg = Integer::from(-1);
    /// assert_eq!(neg.to_u32(), None);
    /// let large = Integer::from(123456789012345_u64);
    /// assert_eq!(large.to_u32(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_u32(&self) -> Option<u32> {
        self.checked_cast()
    }

    /// Converts to an [`u64`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[u64]::[try\_from]\(\&integer)</code>
    ///   * <code>[u64]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[u64]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[u64]>()</code>
    ///   * <code>integer.[checked\_as]::\<[u64]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(123456789012345_u64);
    /// assert_eq!(fits.to_u64(), Some(123456789012345));
    /// let neg = Integer::from(-1);
    /// assert_eq!(neg.to_u64(), None);
    /// let large = "1234567890123456789012345".parse::<Integer>().unwrap();
    /// assert_eq!(large.to_u64(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_u64(&self) -> Option<u64> {
        self.checked_cast()
    }

    /// Converts to an [`u128`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[u128]::[try\_from]\(\&integer)</code>
    ///   * <code>[u128]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[u128]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[u128]>()</code>
    ///   * <code>integer.[checked\_as]::\<[u128]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(12345678901234567890_u128);
    /// assert_eq!(fits.to_u128(), Some(12345678901234567890));
    /// let neg = Integer::from(-1);
    /// assert_eq!(neg.to_u128(), None);
    /// let large = "1234567890123456789012345678901234567890"
    ///     .parse::<Integer>()
    ///     .unwrap();
    /// assert_eq!(large.to_u128(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_u128(&self) -> Option<u128> {
        self.checked_cast()
    }

    /// Converts to an [`usize`] if the value fits.
    ///
    /// This conversion can also be performed using
    ///   * <code>[usize]::[try\_from]\(\&integer)</code>
    ///   * <code>[usize]::[try\_from]\(integer)</code>
    ///   * <code>(\&integer).[checked\_as]::\<[usize]>()</code>
    ///   * <code>integer.[borrow]\().[checked\_as]::\<[usize]>()</code>
    ///   * <code>integer.[checked\_as]::\<[usize]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let fits = Integer::from(0x1000);
    /// assert_eq!(fits.to_usize(), Some(0x1000));
    /// let neg = Integer::from(-1);
    /// assert_eq!(neg.to_usize(), None);
    /// let large: Integer = Integer::from(0x1000) << 128;
    /// assert_eq!(large.to_usize(), None);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [checked\_as]: az::CheckedAs::checked_as
    /// [try\_from]: core::convert::TryFrom::try_from
    #[inline]
    pub fn to_usize(&self) -> Option<usize> {
        self.checked_cast()
    }

    /// Converts to an [`i8`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[i8]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[i8]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[i8]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let large = Integer::from(0x1234);
    /// assert_eq!(large.to_i8_wrapping(), 0x34);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_i8_wrapping(&self) -> i8 {
        self.wrapping_cast()
    }

    /// Converts to an [`i16`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[i16]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[i16]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[i16]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let large = Integer::from(0x1234_5678);
    /// assert_eq!(large.to_i16_wrapping(), 0x5678);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_i16_wrapping(&self) -> i16 {
        self.wrapping_cast()
    }

    /// Converts to an [`i32`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[i32]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[i32]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[i32]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let large = Integer::from(0x1234_5678_9abc_def0_u64);
    /// assert_eq!(large.to_i32_wrapping(), 0x9abc_def0_u32 as i32);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_i32_wrapping(&self) -> i32 {
        self.wrapping_cast()
    }

    /// Converts to an [`i64`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[i64]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[i64]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[i64]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let large = Integer::from_str_radix("f123456789abcdef0", 16).unwrap();
    /// assert_eq!(large.to_i64_wrapping(), 0x1234_5678_9abc_def0);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_i64_wrapping(&self) -> i64 {
        self.wrapping_cast()
    }

    /// Converts to an [`i128`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[i128]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[i128]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[i128]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let s = "f123456789abcdef0123456789abcdef0";
    /// let large = Integer::from_str_radix(s, 16).unwrap();
    /// assert_eq!(
    ///     large.to_i128_wrapping(),
    ///     0x1234_5678_9abc_def0_1234_5678_9abc_def0
    /// );
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_i128_wrapping(&self) -> i128 {
        self.wrapping_cast()
    }

    /// Converts to an [`isize`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[isize]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[isize]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[isize]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let large: Integer = (Integer::from(0x1000) << 128) | 0x1234;
    /// assert_eq!(large.to_isize_wrapping(), 0x1234);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_isize_wrapping(&self) -> isize {
        self.wrapping_cast()
    }

    /// Converts to a [`u8`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[u8]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[u8]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[u8]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let neg = Integer::from(-1);
    /// assert_eq!(neg.to_u8_wrapping(), 0xff);
    /// let large = Integer::from(0x1234);
    /// assert_eq!(large.to_u8_wrapping(), 0x34);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_u8_wrapping(&self) -> u8 {
        self.wrapping_cast()
    }

    /// Converts to a [`u16`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[u16]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[u16]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[u16]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let neg = Integer::from(-1);
    /// assert_eq!(neg.to_u16_wrapping(), 0xffff);
    /// let large = Integer::from(0x1234_5678);
    /// assert_eq!(large.to_u16_wrapping(), 0x5678);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_u16_wrapping(&self) -> u16 {
        self.wrapping_cast()
    }

    /// Converts to a [`u32`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[u32]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[u32]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[u32]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let neg = Integer::from(-1);
    /// assert_eq!(neg.to_u32_wrapping(), 0xffff_ffff);
    /// let large = Integer::from(0x1234_5678_9abc_def0_u64);
    /// assert_eq!(large.to_u32_wrapping(), 0x9abc_def0);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_u32_wrapping(&self) -> u32 {
        self.wrapping_cast()
    }

    /// Converts to a [`u64`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[u64]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[u64]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[u64]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let neg = Integer::from(-1);
    /// assert_eq!(neg.to_u64_wrapping(), 0xffff_ffff_ffff_ffff);
    /// let large = Integer::from_str_radix("f123456789abcdef0", 16).unwrap();
    /// assert_eq!(large.to_u64_wrapping(), 0x1234_5678_9abc_def0);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_u64_wrapping(&self) -> u64 {
        self.wrapping_cast()
    }

    /// Converts to a [`u128`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[u128]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[u128]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[u128]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let neg = Integer::from(-1);
    /// assert_eq!(
    ///     neg.to_u128_wrapping(),
    ///     0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff
    /// );
    /// let s = "f123456789abcdef0123456789abcdef0";
    /// let large = Integer::from_str_radix(s, 16).unwrap();
    /// assert_eq!(
    ///     large.to_u128_wrapping(),
    ///     0x1234_5678_9abc_def0_1234_5678_9abc_def0
    /// );
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_u128_wrapping(&self) -> u128 {
        self.wrapping_cast()
    }

    /// Converts to a [`usize`], wrapping if the value does not fit.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[wrapping\_as]::\<[usize]>()</code>
    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[usize]>()</code>
    ///   * <code>integer.[wrapping\_as]::\<[usize]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let large: Integer = (Integer::from(0x1000) << 128) | 0x1234;
    /// assert_eq!(large.to_usize_wrapping(), 0x1234);
    /// ```
    ///
    /// [borrow]: core::borrow::Borrow::borrow
    /// [wrapping\_as]: az::WrappingAs::wrapping_as
    #[inline]
    pub fn to_usize_wrapping(&self) -> usize {
        self.wrapping_cast()
    }

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

    /// Converts to an [`f64`], rounding towards zero.
    ///
    /// This conversion can also be performed using
    ///   * <code>(\&integer).[az]::\<[f64]>()</code>
    ///   * <code>integer.[borrow]\().[az]::\<[f64]>()</code>
    ///   * <code>integer.[az]::\<[f64]>()</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    ///
    /// // An `f64` has 53 bits of precision.
    /// let exact = 0x1f_ffff_ffff_ffff_u64;
    /// let i = Integer::from(exact);
    /// assert_eq!(i.to_f64(), exact as f64);
    ///
    /// // large has 56 ones
    /// let large = 0xff_ffff_ffff_ffff_u64;
    /// // trunc has 53 ones followed by 3 zeros
    /// let trunc = 0xff_ffff_ffff_fff8_u64;
    /// let j = Integer::from(large);
    /// assert_eq!(j.to_f64() as u64, trunc);
    ///
    /// let max = Integer::from_f64(f64::MAX).unwrap();
    /// let max_plus_one = max + 1u32;
    /// // max_plus_one is truncated to f64::MAX
    /// assert_eq!(max_plus_one.to_f64(), f64::MAX);
    /// let times_two = max_plus_one * 2u32;
    /// // times_two is too large
    /// assert_eq!(times_two.to_f64(), f64::INFINITY);
    /// ```
    ///
    /// [az]: az::Az::az
    /// [borrow]: core::borrow::Borrow::borrow
    #[inline]
    pub fn to_f64(&self) -> f64 {
        self.cast()
    }

    /// Converts to an [`f32`] and an exponent, rounding towards zero.
    ///
    /// The returned [`f32`] is in the range
    /// 0.5&nbsp;≤&nbsp;<i>x</i>&nbsp;<&nbsp;1. If the value is zero, `(0.0, 0)`
    /// is returned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let zero = Integer::new();
    /// let (d0, exp0) = zero.to_f32_exp();
    /// assert_eq!((d0, exp0), (0.0, 0));
    /// let fifteen = Integer::from(15);
    /// let (d15, exp15) = fifteen.to_f32_exp();
    /// assert_eq!((d15, exp15), (15.0 / 16.0, 4));
    /// ```
    #[inline]
    pub fn to_f32_exp(&self) -> (f32, u32) {
        let (f, exp) = self.to_f64_exp();
        let trunc_f = misc::trunc_f64_to_f32(f);
        (trunc_f, exp)
    }

    /// Converts to an [`f64`] and an exponent, rounding towards zero.
    ///
    /// The returned [`f64`] is in the range
    /// 0.5&nbsp;≤&nbsp;<i>x</i>&nbsp;<&nbsp;1. If the value is zero, `(0.0, 0)`
    /// is returned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let zero = Integer::new();
    /// let (d0, exp0) = zero.to_f64_exp();
    /// assert_eq!((d0, exp0), (0.0, 0));
    /// let fifteen = Integer::from(15);
    /// let (d15, exp15) = fifteen.to_f64_exp();
    /// assert_eq!((d15, exp15), (15.0 / 16.0, 4));
    /// ```
    #[inline]
    pub fn to_f64_exp(&self) -> (f64, u32) {
        let (f, exp) = xmpz::get_f64_2exp(self);
        (f, exp.unwrapped_cast())
    }

    /// Returns a string representation of the number for the specified `radix`.
    ///
    /// # Panics
    ///
    /// Panics if `radix` is less than 2 or greater than 36.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let mut i = Integer::new();
    /// assert_eq!(i.to_string_radix(10), "0");
    /// i.assign(-10);
    /// assert_eq!(i.to_string_radix(16), "-a");
    /// i.assign(0x1234cdef);
    /// assert_eq!(i.to_string_radix(4), "102031030313233");
    /// i.assign(Integer::parse_radix("123456789aAbBcCdDeEfF", 16).unwrap());
    /// assert_eq!(i.to_string_radix(16), "123456789aabbccddeeff");
    /// ```
    #[cfg(feature = "std")]
    #[inline]
    pub fn to_string_radix(&self, radix: i32) -> String {
        let mut s = StringLike::new_string();
        append_to_string(&mut s, self, radix, false);
        s.unwrap_string()
    }

    /// Assigns from an [`f32`] if it is [finite][f32::is_finite], rounding
    /// towards zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::new();
    /// let ret = i.assign_f64(-12.7);
    /// assert!(ret.is_ok());
    /// assert_eq!(i, -12);
    /// let ret = i.assign_f32(f32::NAN);
    /// assert!(ret.is_err());
    /// assert_eq!(i, -12);
    /// ```
    #[inline]
    #[allow(clippy::result_unit_err)]
    pub fn assign_f32(&mut self, val: f32) -> Result<(), ()> {
        self.assign_f64(val.into())
    }

    /// Assigns from an [`f64`] if it is [finite][f64::is_finite],
    /// rounding towards zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::new();
    /// let ret = i.assign_f64(12.7);
    /// assert!(ret.is_ok());
    /// assert_eq!(i, 12);
    /// let ret = i.assign_f64(1.0 / 0.0);
    /// assert!(ret.is_err());
    /// assert_eq!(i, 12);
    /// ```
    #[inline]
    #[allow(clippy::result_unit_err)]
    pub fn assign_f64(&mut self, val: f64) -> Result<(), ()> {
        xmpz::set_f64(self, val)
    }

    /// Borrows a negated copy of the [`Integer`].
    ///
    /// The returned object implements <code>[Deref]\<[Target][Deref::Target] = [Integer]></code>.
    ///
    /// This method performs a shallow copy and negates it, and negation does
    /// not change the allocated data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(42);
    /// let neg_i = i.as_neg();
    /// assert_eq!(*neg_i, -42);
    /// // methods taking &self can be used on the returned object
    /// let reneg_i = neg_i.as_neg();
    /// assert_eq!(*reneg_i, 42);
    /// assert_eq!(*reneg_i, i);
    /// ```
    ///
    /// [Deref::Target]: core::ops::Deref::Target
    /// [Deref]: core::ops::Deref
    pub const fn as_neg(&self) -> BorrowInteger<'_> {
        let mut raw = self.inner;
        raw.size = match raw.size.checked_neg() {
            Some(s) => s,
            None => panic!("overflow"),
        };
        // Safety: the lifetime of the return type is equal to the lifetime of self.
        unsafe { BorrowInteger::from_raw(raw) }
    }

    /// Borrows an absolute copy of the [`Integer`].
    ///
    /// The returned object implements <code>[Deref]\<[Target][Deref::Target] = [Integer]></code>.
    ///
    /// This method performs a shallow copy and possibly negates it, and
    /// negation does not change the allocated data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(-42);
    /// let abs_i = i.as_abs();
    /// assert_eq!(*abs_i, 42);
    /// // methods taking &self can be used on the returned object
    /// let reabs_i = abs_i.as_abs();
    /// assert_eq!(*reabs_i, 42);
    /// assert_eq!(*reabs_i, *abs_i);
    /// ```
    ///
    /// [Deref::Target]: core::ops::Deref::Target
    /// [Deref]: core::ops::Deref
    pub const fn as_abs(&self) -> BorrowInteger<'_> {
        let mut raw = self.inner;
        raw.size = match raw.size.checked_abs() {
            Some(s) => s,
            None => panic!("overflow"),
        };
        // Safety: the lifetime of the return type is equal to the lifetime of self.
        unsafe { BorrowInteger::from_raw(raw) }
    }

    #[cfg(feature = "rational")]
    /// Borrows a copy of the [`Integer`] as a [`Rational`][Rational] number.
    ///
    /// The returned object implements
    /// <code>[Deref]\<[Target][Deref::Target] = [Rational]></code>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(4);
    /// let r = i.as_rational();
    /// assert_eq!(*r, 4);
    /// // methods taking &self can be used on the returned object
    /// let recip_r = r.as_recip();
    /// assert_eq!(*recip_r, 0.25);
    /// ```
    ///
    /// [Deref::Target]: core::ops::Deref::Target
    /// [Deref]: core::ops::Deref
    /// [Rational]: crate::Rational
    pub const fn as_rational(&self) -> BorrowRational<'_> {
        const ONE: limb_t = 1;
        // use NonNull::new_unchecked because NonNull::from is not usable in const
        let raw_rational = mpq_t {
            num: self.inner,
            den: mpz_t {
                alloc: 1,
                size: 1,
                d: unsafe { NonNull::new_unchecked((&ONE as *const limb_t).cast_mut()) },
            },
        };
        // Safety: the lifetime of the return type is equal to the lifetime of self.
        // Safety: the number is in canonical form as the denominator is 1.
        unsafe { BorrowRational::from_raw(raw_rational) }
    }

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

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

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

    /// Returns [`true`] if the number is even.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// assert!(!(Integer::from(13).is_even()));
    /// assert!(Integer::from(-14).is_even());
    /// ```
    #[inline]
    pub const fn is_even(&self) -> bool {
        xmpz::even_p(self)
    }

    /// Returns [`true`] if the number is odd.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// assert!(Integer::from(13).is_odd());
    /// assert!(!Integer::from(-14).is_odd());
    /// ```
    #[inline]
    pub const fn is_odd(&self) -> bool {
        xmpz::odd_p(self)
    }

    /// Returns [`true`] if the number is divisible by `divisor`. Unlike other
    /// division functions, `divisor` can be zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(230);
    /// assert!(i.is_divisible(&Integer::from(10)));
    /// assert!(!i.is_divisible(&Integer::from(100)));
    /// assert!(!i.is_divisible(&Integer::new()));
    /// ```
    #[inline]
    pub fn is_divisible(&self, divisor: &Self) -> bool {
        xmpz::divisible_p(self, divisor)
    }

    /// Returns [`true`] if the number is divisible by `divisor`. Unlike other
    /// division functions, `divisor` can be zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(230);
    /// assert!(i.is_divisible_u(23));
    /// assert!(!i.is_divisible_u(100));
    /// assert!(!i.is_divisible_u(0));
    /// ```
    #[inline]
    pub fn is_divisible_u(&self, divisor: u32) -> bool {
        xmpz::divisible_ui_p(self, divisor.into())
    }

    /// Returns [`true`] if the number is divisible by 2<sup><i>b</i></sup>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(15 << 17);
    /// assert!(i.is_divisible_2pow(16));
    /// assert!(i.is_divisible_2pow(17));
    /// assert!(!i.is_divisible_2pow(18));
    /// ```
    #[inline]
    pub fn is_divisible_2pow(&self, b: u32) -> bool {
        xmpz::divisible_2exp_p(self, b.into())
    }

    /// Returns [`true`] if the number is congruent to <i>c</i> mod
    /// <i>divisor</i>, that is, if there exists a <i>q</i> such that `self` =
    /// <i>c</i> + <i>q</i> × <i>divisor</i>. Unlike other division functions,
    /// `divisor` can be zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let n = Integer::from(105);
    /// let divisor = Integer::from(10);
    /// assert!(n.is_congruent(&Integer::from(5), &divisor));
    /// assert!(n.is_congruent(&Integer::from(25), &divisor));
    /// assert!(!n.is_congruent(&Integer::from(7), &divisor));
    /// // n is congruent to itself if divisor is 0
    /// assert!(n.is_congruent(&n, &Integer::from(0)));
    /// ```
    #[inline]
    pub fn is_congruent(&self, c: &Self, divisor: &Self) -> bool {
        xmpz::congruent_p(self, c, divisor)
    }

    /// Returns [`true`] if the number is congruent to <i>c</i> mod
    /// <i>divisor</i>, that is, if there exists a <i>q</i> such that `self` =
    /// <i>c</i> + <i>q</i> × <i>divisor</i>. Unlike other division functions,
    /// `divisor` can be zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let n = Integer::from(105);
    /// assert!(n.is_congruent_u(3335, 10));
    /// assert!(!n.is_congruent_u(107, 10));
    /// // n is congruent to itself if divisor is 0
    /// assert!(n.is_congruent_u(105, 0));
    /// ```
    #[inline]
    pub fn is_congruent_u(&self, c: u32, divisor: u32) -> bool {
        xmpz::congruent_ui_p(self, c.into(), divisor.into())
    }

    /// Returns [`true`] if the number is congruent to <i>c</i> mod
    /// 2<sup><i>b</i></sup>, that is, if there exists a <i>q</i> such that
    /// `self` = <i>c</i> + <i>q</i> × 2<sup><i>b</i></sup>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let n = Integer::from(13 << 17 | 21);
    /// assert!(n.is_congruent_2pow(&Integer::from(7 << 17 | 21), 17));
    /// assert!(!n.is_congruent_2pow(&Integer::from(13 << 17 | 22), 17));
    /// ```
    #[inline]
    pub fn is_congruent_2pow(&self, c: &Self, b: u32) -> bool {
        xmpz::congruent_2exp_p(self, c, b.into())
    }

    /// Returns [`true`] if the number is a perfect power.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // 0 is 0 to the power of anything
    /// assert!(Integer::from(0).is_perfect_power());
    /// // 25 is 5 to the power of 2
    /// assert!(Integer::from(25).is_perfect_power());
    /// // -243 is -3 to the power of 5
    /// assert!(Integer::from(243).is_perfect_power());
    ///
    /// assert!(!Integer::from(24).is_perfect_power());
    /// assert!(!Integer::from(-100).is_perfect_power());
    /// ```
    #[inline]
    pub fn is_perfect_power(&self) -> bool {
        xmpz::perfect_power_p(self)
    }

    /// Returns [`true`] if the number is a perfect square.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// assert!(Integer::from(0).is_perfect_square());
    /// assert!(Integer::from(1).is_perfect_square());
    /// assert!(Integer::from(4).is_perfect_square());
    /// assert!(Integer::from(9).is_perfect_square());
    ///
    /// assert!(!Integer::from(15).is_perfect_square());
    /// assert!(!Integer::from(-9).is_perfect_square());
    /// ```
    #[inline]
    pub fn is_perfect_square(&self) -> bool {
        xmpz::perfect_square_p(self)
    }

    /// Returns [`true`] if the number is a power of two.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// assert!(Integer::from(1).is_power_of_two());
    /// assert!(Integer::from(4).is_power_of_two());
    /// assert!(Integer::from(1 << 30).is_power_of_two());
    ///
    /// assert!(!Integer::from(7).is_power_of_two());
    /// assert!(!Integer::from(0).is_power_of_two());
    /// assert!(!Integer::from(-1).is_power_of_two());
    /// ```
    #[inline]
    pub fn is_power_of_two(&self) -> bool {
        xmpz::power_of_two_p(self)
    }

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

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

    /// Returns the number of bits required to represent the absolute value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    ///
    /// assert_eq!(Integer::from(0).significant_bits(), 0);  //    “”
    /// assert_eq!(Integer::from(1).significant_bits(), 1);  //   “1”
    /// assert_eq!(Integer::from(4).significant_bits(), 3);  // “100”
    /// assert_eq!(Integer::from(7).significant_bits(), 3);  // “111”
    /// assert_eq!(Integer::from(-1).significant_bits(), 1); //   “1”
    /// assert_eq!(Integer::from(-4).significant_bits(), 3); // “100”
    /// assert_eq!(Integer::from(-7).significant_bits(), 3); // “111”
    /// ```
    #[inline]
    pub fn significant_bits(&self) -> u32 {
        xmpz::significant_bits(self).unwrapped_cast()
    }

    /// Returns the number of bits required to represent the value using a
    /// two’s-complement representation.
    ///
    /// For non-negative numbers, this method returns one more than
    /// the [`significant_bits`] method, since an extra zero is needed
    /// before the most significant bit.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    ///
    /// assert_eq!(Integer::from(-5).signed_bits(), 4); // “1011”
    /// assert_eq!(Integer::from(-4).signed_bits(), 3); //  “100”
    /// assert_eq!(Integer::from(-3).signed_bits(), 3); //  “101”
    /// assert_eq!(Integer::from(-2).signed_bits(), 2); //   “10”
    /// assert_eq!(Integer::from(-1).signed_bits(), 1); //    “1”
    /// assert_eq!(Integer::from(0).signed_bits(), 1);  //    “0”
    /// assert_eq!(Integer::from(1).signed_bits(), 2);  //   “01”
    /// assert_eq!(Integer::from(2).signed_bits(), 3);  //  “010”
    /// assert_eq!(Integer::from(3).signed_bits(), 3);  //  “011”
    /// assert_eq!(Integer::from(4).signed_bits(), 4);  // “0100”
    /// ```
    ///
    /// [`significant_bits`]: Integer::significant_bits
    #[inline]
    pub fn signed_bits(&self) -> u32 {
        xmpz::signed_bits(self).unwrapped_cast()
    }

    /// Returns the number of one bits if the value ≥ 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// assert_eq!(Integer::from(0).count_ones(), Some(0));
    /// assert_eq!(Integer::from(15).count_ones(), Some(4));
    /// assert_eq!(Integer::from(-1).count_ones(), None);
    /// ```
    #[inline]
    pub fn count_ones(&self) -> Option<u32> {
        xmpz::popcount(self).map(UnwrappedCast::unwrapped_cast)
    }

    /// Returns the number of zero bits if the value < 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// assert_eq!(Integer::from(0).count_zeros(), None);
    /// assert_eq!(Integer::from(1).count_zeros(), None);
    /// assert_eq!(Integer::from(-1).count_zeros(), Some(0));
    /// assert_eq!(Integer::from(-2).count_zeros(), Some(1));
    /// assert_eq!(Integer::from(-7).count_zeros(), Some(2));
    /// assert_eq!(Integer::from(-8).count_zeros(), Some(3));
    /// ```
    #[inline]
    pub fn count_zeros(&self) -> Option<u32> {
        xmpz::zerocount(self).map(UnwrappedCast::unwrapped_cast)
    }

    /// Returns the location of the first zero, starting at `start`. If the bit
    /// at location `start` is zero, returns `start`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // -2 is ...11111110
    /// assert_eq!(Integer::from(-2).find_zero(0), Some(0));
    /// assert_eq!(Integer::from(-2).find_zero(1), None);
    /// // 15 is ...00001111
    /// assert_eq!(Integer::from(15).find_zero(0), Some(4));
    /// assert_eq!(Integer::from(15).find_zero(20), Some(20));
    /// ```
    #[inline]
    #[doc(alias = "trailing_ones")]
    pub fn find_zero(&self, start: u32) -> Option<u32> {
        xmpz::scan0(self, start.into()).map(UnwrappedCast::unwrapped_cast)
    }

    /// Returns the location of the first one, starting at `start`. If the bit
    /// at location `start` is one, returns `start`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // 1 is ...00000001
    /// assert_eq!(Integer::from(1).find_one(0), Some(0));
    /// assert_eq!(Integer::from(1).find_one(1), None);
    /// // -16 is ...11110000
    /// assert_eq!(Integer::from(-16).find_one(0), Some(4));
    /// assert_eq!(Integer::from(-16).find_one(20), Some(20));
    /// ```
    #[inline]
    #[doc(alias = "trailing_zeros")]
    pub fn find_one(&self, start: u32) -> Option<u32> {
        xmpz::scan1(self, start.into()).map(UnwrappedCast::unwrapped_cast)
    }

    /// Sets the bit at location `index` to 1 if `val` is [`true`] or 0 if `val`
    /// is [`false`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let mut i = Integer::from(-1);
    /// assert_eq!(*i.set_bit(0, false), -2);
    /// i.assign(0xff);
    /// assert_eq!(*i.set_bit(11, true), 0x8ff);
    /// ```
    #[inline]
    pub fn set_bit(&mut self, index: u32, val: bool) -> &mut Self {
        if val {
            xmpz::setbit(self, index.into());
        } else {
            xmpz::clrbit(self, index.into());
        }
        self
    }

    /// Returns [`true`] if the bit at location `index` is 1 or [`false`] if the
    /// bit is 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(0b100101);
    /// assert!(i.get_bit(0));
    /// assert!(!i.get_bit(1));
    /// assert!(i.get_bit(5));
    /// let neg = Integer::from(-1);
    /// assert!(neg.get_bit(1000));
    /// ```
    #[inline]
    pub fn get_bit(&self, index: u32) -> bool {
        xmpz::tstbit(self, index.into())
    }

    /// Toggles the bit at location `index`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(0b100101);
    /// i.toggle_bit(5);
    /// assert_eq!(i, 0b101);
    /// ```
    #[inline]
    pub fn toggle_bit(&mut self, index: u32) -> &mut Self {
        xmpz::combit(self, index.into());
        self
    }

    /// Retuns the Hamming distance if the two numbers have the same sign.
    ///
    /// The Hamming distance is the number of different bits.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(-1);
    /// assert_eq!(Integer::from(0).hamming_dist(&i), None);
    /// assert_eq!(Integer::from(-1).hamming_dist(&i), Some(0));
    /// // -1 is ...11111111 and -13 is ...11110011
    /// assert_eq!(Integer::from(-13).hamming_dist(&i), Some(2));
    /// ```
    #[inline]
    pub fn hamming_dist(&self, other: &Self) -> Option<u32> {
        xmpz::hamdist(self, other).map(UnwrappedCast::unwrapped_cast)
    }

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

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

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

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

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

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

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

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

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

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

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

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

    /// Keeps the <i>n</i> least significant bits only, producing a result that
    /// is greater or equal to 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(-1);
    /// let keep_8 = i.keep_bits(8);
    /// assert_eq!(keep_8, 0xff);
    /// ```
    #[inline]
    #[must_use]
    pub fn keep_bits(mut self, n: u32) -> Self {
        self.keep_bits_mut(n);
        self
    }

    /// Keeps the <i>n</i> least significant bits only, producing a result that
    /// is greater or equal to 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(-1);
    /// i.keep_bits_mut(8);
    /// assert_eq!(i, 0xff);
    /// ```
    #[inline]
    pub fn keep_bits_mut(&mut self, n: u32) {
        xmpz::fdiv_r_2exp(self, (), n.into());
    }

    /// Keeps the <i>n</i> least significant bits only, producing a result that
    /// is greater or equal to 0.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(-1);
    /// let r = i.keep_bits_ref(8);
    /// let eight_bits = Integer::from(r);
    /// assert_eq!(eight_bits, 0xff);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn keep_bits_ref(&self, n: u32) -> KeepBitsIncomplete {
        let n = n.into();
        KeepBitsIncomplete { ref_self: self, n }
    }

    /// Keeps the <i>n</i> least significant bits only, producing a negative
    /// result if the <i>n</i>th least significant bit is one.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(-1);
    /// let i_keep_8 = i.keep_signed_bits(8);
    /// assert_eq!(i_keep_8, -1);
    /// let j = Integer::from(15 << 8 | 15);
    /// let j_keep_8 = j.keep_signed_bits(8);
    /// assert_eq!(j_keep_8, 15);
    /// ```
    #[inline]
    #[must_use]
    pub fn keep_signed_bits(mut self, n: u32) -> Self {
        self.keep_signed_bits_mut(n);
        self
    }

    /// Keeps the <i>n</i> least significant bits only, producing a negative
    /// result if the <i>n</i>th least significant bit is one.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(-1);
    /// i.keep_signed_bits_mut(8);
    /// assert_eq!(i, -1);
    /// let mut j = Integer::from(15 << 8 | 15);
    /// j.keep_signed_bits_mut(8);
    /// assert_eq!(j, 15);
    /// ```
    #[inline]
    pub fn keep_signed_bits_mut(&mut self, n: u32) {
        xmpz::keep_signed_bits(self, (), n.into());
    }

    /// Keeps the <i>n</i> least significant bits only, producing a negative
    /// result if the <i>n</i>th least significant bit is one.
    ///
    /// The following are implemented with the returned
    /// [incomplete-computation value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(-1);
    /// let r = i.keep_signed_bits_ref(8);
    /// let eight_bits = Integer::from(r);
    /// assert_eq!(eight_bits, -1);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn keep_signed_bits_ref(&self, n: u32) -> KeepSignedBitsIncomplete<'_> {
        let n = n.into();
        KeepSignedBitsIncomplete { ref_self: self, n }
    }

    /// Finds the next power of two, or 1 if the number ≤ 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(-3).next_power_of_two();
    /// assert_eq!(i, 1);
    /// let i = Integer::from(4).next_power_of_two();
    /// assert_eq!(i, 4);
    /// let i = Integer::from(7).next_power_of_two();
    /// assert_eq!(i, 8);
    /// ```
    #[inline]
    #[must_use]
    pub fn next_power_of_two(mut self) -> Self {
        self.next_power_of_two_mut();
        self
    }

    /// Finds the next power of two, or 1 if the number ≤ 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(53);
    /// i.next_power_of_two_mut();
    /// assert_eq!(i, 64);
    /// ```
    #[inline]
    pub fn next_power_of_two_mut(&mut self) {
        xmpz::next_pow_of_two(self, ());
    }

    /// Finds the next power of two, or 1 if the number ≤ 0.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(53);
    /// let r = i.next_power_of_two_ref();
    /// let next = Integer::from(r);
    /// assert_eq!(next, 64);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn next_power_of_two_ref(&self) -> NextPowerOfTwoIncomplete<'_> {
        NextPowerOfTwoIncomplete { ref_self: self }
    }

    /// Finds the modulus, or the remainder of Euclidean division.
    ///
    /// The result is always zero or positive.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let dividend = Integer::from(-1003);
    /// let divisor = Integer::from(-10);
    /// let modulus = dividend.modulo(&divisor);
    /// assert_eq!(modulus, 7);
    /// ```
    #[inline]
    #[must_use]
    #[doc(alias = "rem_euclid")]
    pub fn modulo(mut self, divisor: &Self) -> Self {
        self.modulo_mut(divisor);
        self
    }

    /// Finds the modulus, or the remainder of Euclidean division.
    ///
    /// The result is always zero or positive.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut m = Integer::from(-1003);
    /// let divisor = Integer::from(-10);
    /// m.modulo_mut(&divisor);
    /// assert_eq!(m, 7);
    /// ```
    #[inline]
    pub fn modulo_mut(&mut self, divisor: &Self) {
        xmpz::modulo(self, (), divisor);
    }

    /// Finds the modulus, or the remainder of Euclidean division `dividend` /
    /// `self`.
    ///
    /// The result is always zero or positive.
    ///
    /// # Panics
    ///
    /// Panics if `self` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let dividend = Integer::from(-1003);
    /// let mut m = Integer::from(-10);
    /// m.modulo_from(&dividend);
    /// assert_eq!(m, 7);
    /// ```
    #[inline]
    pub fn modulo_from(&mut self, dividend: &Self) {
        xmpz::modulo(self, dividend, ());
    }

    /// Finds the modulus, or the remainder of Euclidean division.
    ///
    /// The result is always zero or positive.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let dividend = Integer::from(-1003);
    /// let divisor = Integer::from(-10);
    /// let r = dividend.modulo_ref(&divisor);
    /// let modulus = Integer::from(r);
    /// assert_eq!(modulus, 7);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    pub fn modulo_ref<'a>(&'a self, divisor: &'a Self) -> ModuloIncomplete<'_> {
        ModuloIncomplete {
            ref_self: self,
            divisor,
        }
    }

    /// Performs a division producing both the quotient and remainder.
    ///
    /// The remainder has the same sign as the dividend.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let dividend = Integer::from(23);
    /// let divisor = Integer::from(-10);
    /// let (quotient, rem) = dividend.div_rem(divisor);
    /// assert_eq!(quotient, -2);
    /// assert_eq!(rem, 3);
    /// ```
    #[inline]
    pub fn div_rem(mut self, mut divisor: Self) -> (Self, Self) {
        self.div_rem_mut(&mut divisor);
        (self, divisor)
    }

    /// Performs a division producing both the quotient and remainder.
    ///
    /// The remainder has the same sign as the dividend.
    ///
    /// The quotient is stored in `self` and the remainder is stored in
    /// `divisor`.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut dividend_quotient = Integer::from(-23);
    /// let mut divisor_rem = Integer::from(10);
    /// dividend_quotient.div_rem_mut(&mut divisor_rem);
    /// assert_eq!(dividend_quotient, -2);
    /// assert_eq!(divisor_rem, -3);
    /// ```
    #[inline]
    pub fn div_rem_mut(&mut self, divisor: &mut Self) {
        xmpz::tdiv_qr(self, divisor, (), ());
    }

    /// Performs a division producing both the quotient and remainder.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
    ///
    /// The remainder has the same sign as the dividend.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// let dividend = Integer::from(-23);
    /// let divisor = Integer::from(-10);
    /// let (quotient, rem) = dividend.div_rem_ref(&divisor).complete();
    /// assert_eq!(quotient, 2);
    /// assert_eq!(rem, -3);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn div_rem_ref<'a>(&'a self, divisor: &'a Self) -> DivRemIncomplete<'_> {
        DivRemIncomplete {
            ref_self: self,
            divisor,
        }
    }

    /// Performs a division producing both the quotient and remainder, with the
    /// quotient rounded up.
    ///
    /// The sign of the remainder is the opposite of the divisor’s sign.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let dividend = Integer::from(23);
    /// let divisor = Integer::from(-10);
    /// let (quotient, rem) = dividend.div_rem_ceil(divisor);
    /// assert_eq!(quotient, -2);
    /// assert_eq!(rem, 3);
    /// ```
    #[inline]
    pub fn div_rem_ceil(mut self, mut divisor: Self) -> (Self, Self) {
        self.div_rem_ceil_mut(&mut divisor);
        (self, divisor)
    }

    /// Performs a division producing both the quotient and remainder, with the
    /// quotient rounded up.
    ///
    /// The sign of the remainder is the opposite of the divisor’s sign.
    ///
    /// The quotient is stored in `self` and the remainder is stored in
    /// `divisor`.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut dividend_quotient = Integer::from(-23);
    /// let mut divisor_rem = Integer::from(10);
    /// dividend_quotient.div_rem_ceil_mut(&mut divisor_rem);
    /// assert_eq!(dividend_quotient, -2);
    /// assert_eq!(divisor_rem, -3);
    /// ```
    #[inline]
    pub fn div_rem_ceil_mut(&mut self, divisor: &mut Self) {
        xmpz::cdiv_qr(self, divisor, (), ());
    }

    /// Performs a division producing both the quotient and remainder, with the
    /// quotient rounded up.
    ///
    /// The sign of the remainder is the opposite of the divisor’s sign.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// let dividend = Integer::from(-23);
    /// let divisor = Integer::from(-10);
    /// let (quotient, rem) = dividend.div_rem_ceil_ref(&divisor).complete();
    /// assert_eq!(quotient, 3);
    /// assert_eq!(rem, 7);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn div_rem_ceil_ref<'a>(&'a self, divisor: &'a Self) -> DivRemCeilIncomplete<'_> {
        DivRemCeilIncomplete {
            ref_self: self,
            divisor,
        }
    }

    /// Performs a division producing both the quotient and remainder, with the
    /// quotient rounded down.
    ///
    /// The remainder has the same sign as the divisor.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let dividend = Integer::from(23);
    /// let divisor = Integer::from(-10);
    /// let (quotient, rem) = dividend.div_rem_floor(divisor);
    /// assert_eq!(quotient, -3);
    /// assert_eq!(rem, -7);
    /// ```
    #[inline]
    pub fn div_rem_floor(mut self, mut divisor: Self) -> (Self, Self) {
        self.div_rem_floor_mut(&mut divisor);
        (self, divisor)
    }

    /// Performs a division producing both the quotient and remainder, with the
    /// quotient rounded down.
    ///
    /// The remainder has the same sign as the divisor.
    ///
    /// The quotient is stored in `self` and the remainder is stored in
    /// `divisor`.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut dividend_quotient = Integer::from(-23);
    /// let mut divisor_rem = Integer::from(10);
    /// dividend_quotient.div_rem_floor_mut(&mut divisor_rem);
    /// assert_eq!(dividend_quotient, -3);
    /// assert_eq!(divisor_rem, 7);
    /// ```
    #[inline]
    pub fn div_rem_floor_mut(&mut self, divisor: &mut Self) {
        xmpz::fdiv_qr(self, divisor, (), ());
    }

    /// Performs a division producing both the quotient and remainder, with the
    /// quotient rounded down.
    ///
    /// The remainder has the same sign as the divisor.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// let dividend = Integer::from(-23);
    /// let divisor = Integer::from(-10);
    /// let (quotient, rem) = dividend.div_rem_floor_ref(&divisor).complete();
    /// assert_eq!(quotient, 2);
    /// assert_eq!(rem, -3);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn div_rem_floor_ref<'a>(&'a self, divisor: &'a Self) -> DivRemFloorIncomplete<'_> {
        DivRemFloorIncomplete {
            ref_self: self,
            divisor,
        }
    }

    /// Performs a division producing both the quotient and remainder, with the
    /// quotient rounded to the nearest integer.
    ///
    /// When the quotient before rounding lies exactly between two integers, it
    /// is rounded away from zero.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // 23 / -10 → -2 rem 3
    /// let (q, rem) = Integer::from(23).div_rem_round((-10).into());
    /// assert!(q == -2 && rem == 3);
    /// // 25 / 10 → 3 rem -5
    /// let (q, rem) = Integer::from(25).div_rem_round(10.into());
    /// assert!(q == 3 && rem == -5);
    /// // -27 / 10 → -3 rem 3
    /// let (q, rem) = Integer::from(-27).div_rem_round(10.into());
    /// assert!(q == -3 && rem == 3);
    /// ```
    #[inline]
    pub fn div_rem_round(mut self, mut divisor: Self) -> (Self, Self) {
        self.div_rem_round_mut(&mut divisor);
        (self, divisor)
    }

    /// Performs a division producing both the quotient and remainder, with the
    /// quotient rounded to the nearest integer.
    ///
    /// When the quotient before rounding lies exactly between two integers, it
    /// is rounded away from zero.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // -25 / -10 → 3 rem 5
    /// let mut dividend_quotient = Integer::from(-25);
    /// let mut divisor_rem = Integer::from(-10);
    /// dividend_quotient.div_rem_round_mut(&mut divisor_rem);
    /// assert_eq!(dividend_quotient, 3);
    /// assert_eq!(divisor_rem, 5);
    /// ```
    #[inline]
    pub fn div_rem_round_mut(&mut self, divisor: &mut Self) {
        xmpz::rdiv_qr(self, divisor, (), ());
    }

    /// Performs a division producing both the quotient and remainder, with the
    /// quotient rounded to the nearest integer.
    ///
    /// When the quotient before rounding lies exactly between two integers, it
    /// is rounded away from zero.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// // -28 / -10 → 3 rem 2
    /// let dividend = Integer::from(-28);
    /// let divisor = Integer::from(-10);
    /// let (quotient, rem) = dividend.div_rem_round_ref(&divisor).complete();
    /// assert_eq!(quotient, 3);
    /// assert_eq!(rem, 2);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn div_rem_round_ref<'a>(&'a self, divisor: &'a Self) -> DivRemRoundIncomplete<'_> {
        DivRemRoundIncomplete {
            ref_self: self,
            divisor,
        }
    }

    /// Performs Euclidean division producing both the quotient and remainder,
    /// with a positive remainder.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let dividend = Integer::from(23);
    /// let divisor = Integer::from(-10);
    /// let (quotient, rem) = dividend.div_rem_euc(divisor);
    /// assert_eq!(quotient, -2);
    /// assert_eq!(rem, 3);
    /// ```
    #[inline]
    pub fn div_rem_euc(mut self, mut divisor: Self) -> (Self, Self) {
        self.div_rem_euc_mut(&mut divisor);
        (self, divisor)
    }

    /// Performs Euclidean division producing both the quotient and remainder,
    /// with a positive remainder.
    ///
    /// The quotient is stored in `self` and the remainder is stored in
    /// `divisor`.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut dividend_quotient = Integer::from(-23);
    /// let mut divisor_rem = Integer::from(10);
    /// dividend_quotient.div_rem_euc_mut(&mut divisor_rem);
    /// assert_eq!(dividend_quotient, -3);
    /// assert_eq!(divisor_rem, 7);
    /// ```
    #[inline]
    pub fn div_rem_euc_mut(&mut self, divisor: &mut Self) {
        xmpz::ediv_qr(self, divisor, (), ());
    }

    /// Performs Euclidan division producing both the quotient and remainder,
    /// with a positive remainder.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// let dividend = Integer::from(-23);
    /// let divisor = Integer::from(-10);
    /// let (quotient, rem) = dividend.div_rem_euc_ref(&divisor).complete();
    /// assert_eq!(quotient, 3);
    /// assert_eq!(rem, 7);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn div_rem_euc_ref<'a>(&'a self, divisor: &'a Self) -> DivRemEucIncomplete<'_> {
        DivRemEucIncomplete {
            ref_self: self,
            divisor,
        }
    }

    /// Returns the modulo, or the remainder of Euclidean division by a [`u32`].
    ///
    /// The result is always zero or positive.
    ///
    /// # Panics
    ///
    /// Panics if `modulo` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let pos = Integer::from(23);
    /// assert_eq!(pos.mod_u(1), 0);
    /// assert_eq!(pos.mod_u(10), 3);
    /// assert_eq!(pos.mod_u(100), 23);
    /// let neg = Integer::from(-23);
    /// assert_eq!(neg.mod_u(1), 0);
    /// assert_eq!(neg.mod_u(10), 7);
    /// assert_eq!(neg.mod_u(100), 77);
    /// ```
    #[inline]
    pub fn mod_u(&self, modulo: u32) -> u32 {
        xmpz::fdiv_ui(self, modulo.into()).wrapping_cast()
    }

    /// Performs an exact division.
    ///
    /// This is much faster than normal division, but produces correct results
    /// only when the division is exact.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(12345 * 54321);
    /// let quotient = i.div_exact(&Integer::from(12345));
    /// assert_eq!(quotient, 54321);
    /// ```
    #[inline]
    #[must_use]
    pub fn div_exact(mut self, divisor: &Self) -> Self {
        self.div_exact_mut(divisor);
        self
    }

    /// Performs an exact division.
    ///
    /// This is much faster than normal division, but produces correct results
    /// only when the division is exact.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(12345 * 54321);
    /// i.div_exact_mut(&Integer::from(12345));
    /// assert_eq!(i, 54321);
    /// ```
    #[inline]
    pub fn div_exact_mut(&mut self, divisor: &Self) {
        xmpz::divexact(self, (), divisor);
    }

    /// Performs an exact division `dividend` / `self`.
    ///
    /// This is much faster than normal division, but produces correct results
    /// only when the division is exact.
    ///
    /// # Panics
    ///
    /// Panics if `self` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(12345);
    /// i.div_exact_from(&Integer::from(12345 * 54321));
    /// assert_eq!(i, 54321);
    /// ```
    pub fn div_exact_from(&mut self, dividend: &Integer) {
        xmpz::divexact(self, dividend, ());
    }

    /// Performs an exact division.
    ///
    /// This is much faster than normal division, but produces correct results
    /// only when the division is exact.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(12345 * 54321);
    /// let divisor = Integer::from(12345);
    /// let r = i.div_exact_ref(&divisor);
    /// let quotient = Integer::from(r);
    /// assert_eq!(quotient, 54321);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn div_exact_ref<'a>(&'a self, divisor: &'a Self) -> DivExactIncomplete<'_> {
        DivExactIncomplete {
            ref_self: self,
            divisor,
        }
    }

    /// Performs an exact division.
    ///
    /// This is much faster than normal division, but produces correct results
    /// only when the division is exact.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(12345 * 54321);
    /// let q = i.div_exact_u(12345);
    /// assert_eq!(q, 54321);
    /// ```
    #[inline]
    #[must_use]
    pub fn div_exact_u(mut self, divisor: u32) -> Self {
        self.div_exact_u_mut(divisor);
        self
    }

    /// Performs an exact division.
    ///
    /// This is much faster than normal division, but produces correct results
    /// only when the division is exact.
    ///
    /// # Panics
    ///
    /// Panics if `divisor` is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(12345 * 54321);
    /// i.div_exact_u_mut(12345);
    /// assert_eq!(i, 54321);
    /// ```
    #[inline]
    pub fn div_exact_u_mut(&mut self, divisor: u32) {
        xmpz::divexact_u32(self, (), divisor);
    }

    /// Performs an exact division.
    ///
    /// This is much faster than normal division, but produces correct results
    /// only when the division is exact.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(12345 * 54321);
    /// let r = i.div_exact_u_ref(12345);
    /// assert_eq!(Integer::from(r), 54321);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn div_exact_u_ref(&self, divisor: u32) -> DivExactUIncomplete<'_> {
        DivExactUIncomplete {
            ref_self: self,
            divisor,
        }
    }

    /// Finds the inverse modulo `modulo` and returns [`Ok(inverse)`][Ok] if it
    /// exists, or [`Err(unchanged)`][Err] if the inverse does not exist.
    ///
    /// The inverse exists if the modulo is not zero, and `self` and the modulo
    /// are co-prime, that is their GCD is 1.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let n = Integer::from(2);
    /// // Modulo 4, 2 has no inverse: there is no i such that 2 × i = 1.
    /// let inv_mod_4 = match n.invert(&Integer::from(4)) {
    ///     Ok(_) => unreachable!(),
    ///     Err(unchanged) => unchanged,
    /// };
    /// // no inverse exists, so value is unchanged
    /// assert_eq!(inv_mod_4, 2);
    /// let n = inv_mod_4;
    /// // Modulo 5, the inverse of 2 is 3, as 2 × 3 = 1.
    /// let inv_mod_5 = match n.invert(&Integer::from(5)) {
    ///     Ok(inverse) => inverse,
    ///     Err(_) => unreachable!(),
    /// };
    /// assert_eq!(inv_mod_5, 3);
    /// ```
    #[inline]
    pub fn invert(mut self, modulo: &Self) -> Result<Self, Self> {
        match self.invert_mut(modulo) {
            Ok(()) => Ok(self),
            Err(()) => Err(self),
        }
    }

    /// Finds the inverse modulo `modulo` if an inverse exists.
    ///
    /// The inverse exists if the modulo is not zero, and `self` and the modulo
    /// are co-prime, that is their GCD is 1.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut n = Integer::from(2);
    /// // Modulo 4, 2 has no inverse: there is no i such that 2 × i = 1.
    /// match n.invert_mut(&Integer::from(4)) {
    ///     Ok(()) => unreachable!(),
    ///     Err(()) => assert_eq!(n, 2),
    /// }
    /// // Modulo 5, the inverse of 2 is 3, as 2 × 3 = 1.
    /// match n.invert_mut(&Integer::from(5)) {
    ///     Ok(()) => assert_eq!(n, 3),
    ///     Err(()) => unreachable!(),
    /// }
    /// ```
    #[inline]
    #[allow(clippy::result_unit_err)]
    pub fn invert_mut(&mut self, modulo: &Self) -> Result<(), ()> {
        match self.invert_ref(modulo) {
            Some(InvertIncomplete { sinverse, .. }) => {
                xmpz::finish_invert(self, &sinverse, modulo);
                Ok(())
            }
            None => Err(()),
        }
    }

    /// Finds the inverse modulo `modulo` if an inverse exists.
    ///
    /// The inverse exists if the modulo is not zero, and `self` and the modulo
    /// are co-prime, that is their GCD is 1.
    ///
    /// The following are implemented with the unwrapped returned
    /// [incomplete-computation value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let two = Integer::from(2);
    /// let four = Integer::from(4);
    /// let five = Integer::from(5);
    ///
    /// // Modulo 4, 2 has no inverse, there is no i such that 2 × i = 1.
    /// // For this conversion, if no inverse exists, the Integer
    /// // created is left unchanged as 0.
    /// assert!(two.invert_ref(&four).is_none());
    ///
    /// // Modulo 5, the inverse of 2 is 3, as 2 × 3 = 1.
    /// let r = two.invert_ref(&five).unwrap();
    /// let inverse = Integer::from(r);
    /// assert_eq!(inverse, 3);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    pub fn invert_ref<'a>(&'a self, modulo: &'a Self) -> Option<InvertIncomplete<'a>> {
        xmpz::start_invert(self, modulo).map(|sinverse| InvertIncomplete { sinverse, modulo })
    }

    /// Raises a number to the power of `exponent` modulo `modulo` and returns
    /// [`Ok(power)`][Ok] if an answer exists, or [`Err(unchanged)`][Err] if it
    /// does not.
    ///
    /// If the exponent is negative, then the number must have an inverse for an
    /// answer to exist.
    ///
    /// When the exponent is positive and the modulo is not zero, an answer
    /// always exists.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // 7 ^ 5 = 16807
    /// let n = Integer::from(7);
    /// let e = Integer::from(5);
    /// let m = Integer::from(1000);
    /// let power = match n.pow_mod(&e, &m) {
    ///     Ok(power) => power,
    ///     Err(_) => unreachable!(),
    /// };
    /// assert_eq!(power, 807);
    /// ```
    ///
    /// When the exponent is negative, an answer exists if an inverse exists.
    ///
    /// ```rust
    /// use rug::Integer;
    /// // 7 × 143 modulo 1000 = 1, so 7 has an inverse 143.
    /// // 7 ^ -5 modulo 1000 = 143 ^ 5 modulo 1000 = 943.
    /// let n = Integer::from(7);
    /// let e = Integer::from(-5);
    /// let m = Integer::from(1000);
    /// let power = match n.pow_mod(&e, &m) {
    ///     Ok(power) => power,
    ///     Err(_) => unreachable!(),
    /// };
    /// assert_eq!(power, 943);
    /// ```
    #[inline]
    pub fn pow_mod(mut self, exponent: &Self, modulo: &Self) -> Result<Self, Self> {
        match self.pow_mod_mut(exponent, modulo) {
            Ok(()) => Ok(self),
            Err(()) => Err(self),
        }
    }

    /// Raises a number to the power of `exponent` modulo `modulo` if an answer
    /// exists.
    ///
    /// If the exponent is negative, then the number must have an inverse for an
    /// answer to exist.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// // Modulo 1000, 2 has no inverse: there is no i such that 2 × i = 1.
    /// let mut n = Integer::from(2);
    /// let e = Integer::from(-5);
    /// let m = Integer::from(1000);
    /// match n.pow_mod_mut(&e, &m) {
    ///     Ok(()) => unreachable!(),
    ///     Err(()) => assert_eq!(n, 2),
    /// }
    /// // 7 × 143 modulo 1000 = 1, so 7 has an inverse 143.
    /// // 7 ^ -5 modulo 1000 = 143 ^ 5 modulo 1000 = 943.
    /// n.assign(7);
    /// match n.pow_mod_mut(&e, &m) {
    ///     Ok(()) => assert_eq!(n, 943),
    ///     Err(()) => unreachable!(),
    /// }
    /// ```
    #[inline]
    #[allow(clippy::result_unit_err)]
    pub fn pow_mod_mut(&mut self, exponent: &Self, modulo: &Self) -> Result<(), ()> {
        let Some(PowModIncomplete { sinverse, .. }) = self.pow_mod_ref(exponent, modulo) else {
            return Err(());
        };
        if let Some(sinverse) = &sinverse {
            xmpz::pow_mod(self, sinverse, exponent, modulo);
        } else {
            xmpz::pow_mod(self, (), exponent, modulo);
        }
        Ok(())
    }

    /// Raises a number to the power of `exponent` modulo `modulo` if an answer
    /// exists.
    ///
    /// If the exponent is negative, then the number must have an inverse for an
    /// answer to exist.
    ///
    /// The following are implemented with the unwrapped returned
    /// [incomplete-computation value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let two = Integer::from(2);
    /// let thousand = Integer::from(1000);
    /// let minus_five = Integer::from(-5);
    /// let seven = Integer::from(7);
    ///
    /// // Modulo 1000, 2 has no inverse: there is no i such that 2 × i = 1.
    /// assert!(two.pow_mod_ref(&minus_five, &thousand).is_none());
    ///
    /// // 7 × 143 modulo 1000 = 1, so 7 has an inverse 143.
    /// // 7 ^ -5 modulo 1000 = 143 ^ 5 modulo 1000 = 943.
    /// let r = seven.pow_mod_ref(&minus_five, &thousand).unwrap();
    /// let power = Integer::from(r);
    /// assert_eq!(power, 943);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    pub fn pow_mod_ref<'a>(
        &'a self,
        exponent: &'a Self,
        modulo: &'a Self,
    ) -> Option<PowModIncomplete<'a>> {
        if exponent.is_negative() {
            let InvertIncomplete { sinverse, .. } = self.invert_ref(modulo)?;
            Some(PowModIncomplete {
                ref_self: None,
                sinverse: Some(sinverse),
                exponent,
                modulo,
            })
        } else if !modulo.is_zero() {
            Some(PowModIncomplete {
                ref_self: Some(self),
                sinverse: None,
                exponent,
                modulo,
            })
        } else {
            None
        }
    }

    /// Raises a number to the power of `exponent` modulo `modulo`, with
    /// resilience to side-channel attacks.
    ///
    /// The exponent must be greater than zero, and the modulo must be odd.
    ///
    /// This method is intended for cryptographic purposes where resilience to
    /// side-channel attacks is desired. The function is designed to take the
    /// same time and use the same cache access patterns for same-sized
    /// arguments, assuming that the arguments are placed at the same position
    /// and the machine state is identical when starting.
    ///
    /// # Panics
    ///
    /// Panics if `exponent` ≤ 0 or if `modulo` is even.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # // wrap in fn to suppress valgrind false positive
    /// # fn doctest_secure_pow_mod() {
    /// use rug::Integer;
    /// // 7 ^ 4 mod 13 = 9
    /// let n = Integer::from(7);
    /// let e = Integer::from(4);
    /// let m = Integer::from(13);
    /// let power = n.secure_pow_mod(&e, &m);
    /// assert_eq!(power, 9);
    /// # }
    /// # doctest_secure_pow_mod();
    /// ```
    #[inline]
    #[must_use]
    pub fn secure_pow_mod(mut self, exponent: &Self, modulo: &Self) -> Self {
        self.secure_pow_mod_mut(exponent, modulo);
        self
    }

    /// Raises a number to the power of `exponent` modulo `modulo`, with
    /// resilience to side-channel attacks.
    ///
    /// The exponent must be greater than zero, and the modulo must be odd.
    ///
    /// This method is intended for cryptographic purposes where resilience to
    /// side-channel attacks is desired. The function is designed to take the
    /// same time and use the same cache access patterns for same-sized
    /// arguments, assuming that the arguments are placed at the same position
    /// and the machine state is identical when starting.
    ///
    /// # Panics
    ///
    /// Panics if `exponent` ≤ 0 or if `modulo` is even.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # // wrap in fn to suppress valgrind false positive
    /// # fn doctest_secure_pow_mod_mut() {
    /// use rug::Integer;
    /// // 7 ^ 4 mod 13 = 9
    /// let mut n = Integer::from(7);
    /// let e = Integer::from(4);
    /// let m = Integer::from(13);
    /// n.secure_pow_mod_mut(&e, &m);
    /// assert_eq!(n, 9);
    /// # }
    /// # doctest_secure_pow_mod_mut();
    /// ```
    #[inline]
    pub fn secure_pow_mod_mut(&mut self, exponent: &Self, modulo: &Self) {
        xmpz::powm_sec(self, (), exponent, modulo);
    }

    /// Raises a number to the power of `exponent` modulo `modulo`, with
    /// resilience to side-channel attacks.
    ///
    /// The exponent must be greater than zero, and the modulo must be odd.
    ///
    /// This method is intended for cryptographic purposes where resilience to
    /// side-channel attacks is desired. The function is designed to take the
    /// same time and use the same cache access patterns for same-sized
    /// arguments, assuming that the arguments are placed at the same position
    /// and the machine state is identical when starting.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Panics
    ///
    /// Panics if `exponent` ≤ 0 or if `modulo` is even.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # // wrap in fn to suppress valgrind false positive
    /// # fn doctest_secure_pow_mod_ref() {
    /// use rug::Integer;
    /// // 7 ^ 4 mod 13 = 9
    /// let n = Integer::from(7);
    /// let e = Integer::from(4);
    /// let m = Integer::from(13);
    /// let power = Integer::from(n.secure_pow_mod_ref(&e, &m));
    /// assert_eq!(power, 9);
    /// # }
    /// # doctest_secure_pow_mod_ref();
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn secure_pow_mod_ref<'a>(
        &'a self,
        exponent: &'a Self,
        modulo: &'a Self,
    ) -> SecurePowModIncomplete<'a> {
        SecurePowModIncomplete {
            ref_self: self,
            exponent,
            modulo,
        }
    }

    /// Raises `base` to the power of `exponent`.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// assert_eq!(Integer::u_pow_u(13, 12).complete(), 13_u64.pow(12));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn u_pow_u(base: u32, exponent: u32) -> UPowUIncomplete {
        UPowUIncomplete { base, exponent }
    }

    /// Raises `base` to the power of `exponent`.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let mut ans = Integer::new();
    /// ans.assign(Integer::i_pow_u(-13, 13));
    /// assert_eq!(ans, (-13_i64).pow(13));
    /// ans.assign(Integer::i_pow_u(13, 13));
    /// assert_eq!(ans, (13_i64).pow(13));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn i_pow_u(base: i32, exponent: u32) -> IPowUIncomplete {
        IPowUIncomplete { base, exponent }
    }

    /// Computes the <i>n</i>th root and truncates the result.
    ///
    /// # Panics
    ///
    /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
    /// negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(1004);
    /// let root = i.root(3);
    /// assert_eq!(root, 10);
    /// ```
    #[inline]
    #[must_use]
    pub fn root(mut self, n: u32) -> Self {
        self.root_mut(n);
        self
    }

    /// Computes the <i>n</i>th root and truncates the result.
    ///
    /// # Panics
    ///
    /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
    /// negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(1004);
    /// i.root_mut(3);
    /// assert_eq!(i, 10);
    /// ```
    #[inline]
    pub fn root_mut(&mut self, n: u32) {
        xmpz::root(self, (), n.into());
    }

    /// Computes the <i>n</i>th root and truncates the result.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(1004);
    /// assert_eq!(Integer::from(i.root_ref(3)), 10);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn root_ref(&self, n: u32) -> RootIncomplete<'_> {
        let n = n.into();
        RootIncomplete { ref_self: self, n }
    }

    /// Computes the <i>n</i>th root and returns the truncated root and the
    /// remainder.
    ///
    /// The remainder is the original number minus the truncated root raised to
    /// the power of <i>n</i>.
    ///
    /// The initial value of `remainder` is ignored.
    ///
    /// # Panics
    ///
    /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
    /// negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(1004);
    /// let (root, rem) = i.root_rem(Integer::new(), 3);
    /// assert_eq!(root, 10);
    /// assert_eq!(rem, 4);
    /// ```
    #[inline]
    pub fn root_rem(mut self, mut remainder: Self, n: u32) -> (Self, Self) {
        self.root_rem_mut(&mut remainder, n);
        (self, remainder)
    }

    /// Computes the <i>n</i>th root and returns the truncated root and the
    /// remainder.
    ///
    /// The remainder is the original number minus the truncated root raised to
    /// the power of <i>n</i>.
    ///
    /// The initial value of `remainder` is ignored.
    ///
    /// # Panics
    ///
    /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
    /// negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(1004);
    /// let mut rem = Integer::new();
    /// i.root_rem_mut(&mut rem, 3);
    /// assert_eq!(i, 10);
    /// assert_eq!(rem, 4);
    /// ```
    #[inline]
    pub fn root_rem_mut(&mut self, remainder: &mut Self, n: u32) {
        xmpz::rootrem(self, remainder, (), n.into());
    }

    /// Computes the <i>n</i>th root and returns the truncated root and the
    /// remainder.
    ///
    /// The remainder is the original number minus the truncated root raised to
    /// the power of <i>n</i>.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Complete, Integer};
    /// let i = Integer::from(1004);
    /// let mut root = Integer::new();
    /// let mut rem = Integer::new();
    /// // 1004 = 10^3 + 5
    /// (&mut root, &mut rem).assign(i.root_rem_ref(3));
    /// assert_eq!(root, 10);
    /// assert_eq!(rem, 4);
    /// // 1004 = 3^6 + 275
    /// let (other_root, other_rem) = i.root_rem_ref(6).complete();
    /// assert_eq!(other_root, 3);
    /// assert_eq!(other_rem, 275);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn root_rem_ref(&self, n: u32) -> RootRemIncomplete<'_> {
        let n = n.into();
        RootRemIncomplete { ref_self: self, n }
    }

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

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

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

    /// Computes the square root and truncates the result.
    ///
    /// # Panics
    ///
    /// Panics if the value is negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(104);
    /// let sqrt = i.sqrt();
    /// assert_eq!(sqrt, 10);
    /// ```
    #[inline]
    #[must_use]
    pub fn sqrt(mut self) -> Self {
        self.sqrt_mut();
        self
    }

    /// Computes the square root and truncates the result.
    ///
    /// # Panics
    ///
    /// Panics if the value is negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(104);
    /// i.sqrt_mut();
    /// assert_eq!(i, 10);
    /// ```
    #[inline]
    pub fn sqrt_mut(&mut self) {
        xmpz::sqrt(self, ());
    }

    /// Computes the square root and truncates the result.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(104);
    /// assert_eq!(Integer::from(i.sqrt_ref()), 10);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn sqrt_ref(&self) -> SqrtIncomplete<'_> {
        SqrtIncomplete { ref_self: self }
    }

    /// Computes the square root and the remainder.
    ///
    /// The remainder is the original number minus the truncated root squared.
    ///
    /// The initial value of `remainder` is ignored.
    ///
    /// # Panics
    ///
    /// Panics if the value is negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(104);
    /// let (sqrt, rem) = i.sqrt_rem(Integer::new());
    /// assert_eq!(sqrt, 10);
    /// assert_eq!(rem, 4);
    /// ```
    #[inline]
    pub fn sqrt_rem(mut self, mut remainder: Self) -> (Self, Self) {
        self.sqrt_rem_mut(&mut remainder);
        (self, remainder)
    }

    /// Computes the square root and the remainder.
    ///
    /// The remainder is the original number minus the truncated root squared.
    ///
    /// The initial value of `remainder` is ignored.
    ///
    /// # Panics
    ///
    /// Panics if the value is negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(104);
    /// let mut rem = Integer::new();
    /// i.sqrt_rem_mut(&mut rem);
    /// assert_eq!(i, 10);
    /// assert_eq!(rem, 4);
    /// ```
    #[inline]
    pub fn sqrt_rem_mut(&mut self, remainder: &mut Self) {
        xmpz::sqrtrem(self, remainder, ());
    }

    /// Computes the square root and the remainder.
    ///
    /// The remainder is the original number minus the truncated root squared.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let i = Integer::from(104);
    /// let mut sqrt = Integer::new();
    /// let mut rem = Integer::new();
    /// let r = i.sqrt_rem_ref();
    /// (&mut sqrt, &mut rem).assign(r);
    /// assert_eq!(sqrt, 10);
    /// assert_eq!(rem, 4);
    /// let r = i.sqrt_rem_ref();
    /// let (other_sqrt, other_rem) = <(Integer, Integer)>::from(r);
    /// assert_eq!(other_sqrt, 10);
    /// assert_eq!(other_rem, 4);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn sqrt_rem_ref(&self) -> SqrtRemIncomplete<'_> {
        SqrtRemIncomplete { ref_self: self }
    }

    /// Determines wheter a number is prime.
    ///
    /// This function uses some trial divisions, a Baille-PSW probable prime
    /// test, then `reps`&nbsp;&minus;&nbsp;24 Miller-Rabin probabilistic
    /// primality tests.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::integer::IsPrime;
    /// use rug::Integer;
    /// let no = Integer::from(163 * 4003);
    /// assert_eq!(no.is_probably_prime(30), IsPrime::No);
    /// let yes = Integer::from(817_504_243);
    /// assert_eq!(yes.is_probably_prime(30), IsPrime::Yes);
    /// // 16_412_292_043_871_650_369 is actually a prime.
    /// let probably = Integer::from(16_412_292_043_871_650_369_u64);
    /// assert_eq!(probably.is_probably_prime(30), IsPrime::Probably);
    /// ```
    #[inline]
    pub fn is_probably_prime(&self, reps: u32) -> IsPrime {
        match xmpz::probab_prime_p(self, reps.unwrapped_cast()) {
            0 => IsPrime::No,
            1 => IsPrime::Probably,
            2 => IsPrime::Yes,
            _ => unreachable!(),
        }
    }

    /// Identifies primes using a probabilistic algorithm; the chance of a
    /// composite passing will be extremely small.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(800_000_000);
    /// let prime = i.next_prime();
    /// assert_eq!(prime, 800_000_011);
    /// ```
    #[inline]
    #[must_use]
    pub fn next_prime(mut self) -> Self {
        self.next_prime_mut();
        self
    }

    /// Identifies primes using a probabilistic algorithm; the chance of a
    /// composite passing will be extremely small.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(800_000_000);
    /// i.next_prime_mut();
    /// assert_eq!(i, 800_000_011);
    /// ```
    #[inline]
    pub fn next_prime_mut(&mut self) {
        xmpz::nextprime(self, ());
    }

    /// Identifies primes using a probabilistic algorithm; the chance of a
    /// composite passing will be extremely small.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(800_000_000);
    /// let r = i.next_prime_ref();
    /// let prime = Integer::from(r);
    /// assert_eq!(prime, 800_000_011);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn next_prime_ref(&self) -> NextPrimeIncomplete<'_> {
        NextPrimeIncomplete { ref_self: self }
    }

    /// Identifies previous prime number using a probabilistic algorithm; the
    /// chance of a composite passing will be extremely small.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(800_000_000);
    /// let prime = i.prev_prime();
    /// assert_eq!(prime, 799_999_999);
    /// ```
    #[inline]
    #[must_use]
    pub fn prev_prime(mut self) -> Self {
        self.prev_prime_mut();
        self
    }

    /// Identifies previous prime number using a probabilistic algorithm; the
    /// chance of a composite passing will be extremely small.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(800_000_000);
    /// i.prev_prime_mut();
    /// assert_eq!(i, 799_999_999);
    /// ```
    #[inline]
    pub fn prev_prime_mut(&mut self) {
        xmpz::prevprime(self, ());
    }

    /// Identifies previous prime number using a probabilistic algorithm; the
    /// chance of a composite passing will be extremely small.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(800_000_000);
    /// let r = i.prev_prime_ref();
    /// let prime = Integer::from(r);
    /// assert_eq!(prime, 799_999_999);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn prev_prime_ref(&self) -> PrevPrimeIncomplete<'_> {
        PrevPrimeIncomplete { ref_self: self }
    }

    /// Finds the greatest common divisor.
    ///
    /// The result is always positive except when both inputs are zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let a = Integer::new();
    /// let mut b = Integer::new();
    /// // gcd of 0, 0 is 0
    /// let gcd1 = a.gcd(&b);
    /// assert_eq!(gcd1, 0);
    /// b.assign(10);
    /// // gcd of 0, 10 is 10
    /// let gcd2 = gcd1.gcd(&b);
    /// assert_eq!(gcd2, 10);
    /// b.assign(25);
    /// // gcd of 10, 25 is 5
    /// let gcd3 = gcd2.gcd(&b);
    /// assert_eq!(gcd3, 5);
    /// ```
    #[inline]
    #[must_use]
    pub fn gcd(mut self, other: &Self) -> Self {
        self.gcd_mut(other);
        self
    }

    /// Finds the greatest common divisor.
    ///
    /// The result is always positive except when both inputs are zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let mut a = Integer::new();
    /// let mut b = Integer::new();
    /// // gcd of 0, 0 is 0
    /// a.gcd_mut(&b);
    /// assert_eq!(a, 0);
    /// b.assign(10);
    /// // gcd of 0, 10 is 10
    /// a.gcd_mut(&b);
    /// assert_eq!(a, 10);
    /// b.assign(25);
    /// // gcd of 10, 25 is 5
    /// a.gcd_mut(&b);
    /// assert_eq!(a, 5);
    /// ```
    #[inline]
    pub fn gcd_mut(&mut self, other: &Self) {
        xmpz::gcd(self, (), other);
    }

    /// Finds the greatest common divisor.
    ///
    /// The result is always positive except when both inputs are zero.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let a = Integer::from(100);
    /// let b = Integer::from(125);
    /// let r = a.gcd_ref(&b);
    /// // gcd of 100, 125 is 25
    /// assert_eq!(Integer::from(r), 25);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn gcd_ref<'a>(&'a self, other: &'a Self) -> GcdIncomplete<'_> {
        GcdIncomplete {
            ref_self: self,
            other,
        }
    }

    /// Finds the greatest common divisor.
    ///
    /// The result is always positive except when both inputs are zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::new();
    /// // gcd of 0, 0 is 0
    /// let gcd1 = i.gcd_u(0);
    /// assert_eq!(gcd1, 0);
    /// // gcd of 0, 10 is 10
    /// let gcd2 = gcd1.gcd_u(10);
    /// assert_eq!(gcd2, 10);
    /// // gcd of 10, 25 is 5
    /// let gcd3 = gcd2.gcd_u(25);
    /// assert_eq!(gcd3, 5);
    /// ```
    #[inline]
    #[must_use]
    pub fn gcd_u(mut self, other: u32) -> Self {
        self.gcd_u_mut(other);
        self
    }

    /// Finds the greatest common divisor.
    ///
    /// The result is always positive except when both inputs are zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::new();
    /// // gcd of 0, 0 is 0
    /// i.gcd_u_mut(0);
    /// assert_eq!(i, 0);
    /// // gcd of 0, 10 is 10
    /// i.gcd_u_mut(10);
    /// assert_eq!(i, 10);
    /// // gcd of 10, 25 is 5
    /// i.gcd_u_mut(25);
    /// assert_eq!(i, 5);
    /// ```
    #[inline]
    pub fn gcd_u_mut(&mut self, other: u32) {
        xmpz::gcd_ui(self, (), other.into());
    }

    /// Finds the greatest common divisor.
    ///
    /// The result is always positive except when both inputs are zero.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Option]\<[u32]></code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// The implementation of <code>[From]\<Src> for [Option]\<[u32]></code> is
    /// useful to obtain the result as a [`u32`] if it fits. If
    /// `other`&nbsp;>&nbsp;0 , the result always fits. If the result does not
    /// fit, it is equal to the absolute value of `self`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(100);
    /// let r = i.gcd_u_ref(125);
    /// // gcd of 100, 125 is 25
    /// assert_eq!(Integer::from(r), 25);
    /// let r = i.gcd_u_ref(125);
    /// assert_eq!(Option::<u32>::from(r), Some(25));
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn gcd_u_ref(&self, other: u32) -> GcdUIncomplete<'_> {
        let other = other.into();
        GcdUIncomplete {
            ref_self: self,
            other,
        }
    }

    /// Finds the greatest common divisor (GCD) of the two inputs (`self` and
    /// `other`), and two coefficients to obtain the GCD from the two inputs.
    ///
    /// The GCD is always positive except when both inputs are zero. If the
    /// inputs are <i>a</i> and <i>b</i>, then the GCD is <i>g</i> and the
    /// coefficients are <i>s</i> and <i>t</i> such that
    ///
    /// <i>a</i> × <i>s</i> + <i>b</i> × <i>t</i> = <i>g</i>
    ///
    /// The values <i>s</i> and <i>t</i> are chosen such that normally,
    /// |<i>s</i>|&nbsp;<&nbsp;|<i>b</i>|&nbsp;/&nbsp;(2<i>g</i>) and
    /// |<i>t</i>|&nbsp;<&nbsp;|<i>a</i>|&nbsp;/&nbsp;(2<i>g</i>), and these
    /// relations define <i>s</i> and <i>t</i> uniquely. There are a few
    /// exceptional cases:
    ///
    ///   * If |<i>a</i>|&nbsp;=&nbsp;|<i>b</i>|, then <i>s</i>&nbsp;=&nbsp;0,
    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
    ///   * Otherwise, if <i>b</i>&nbsp;=&nbsp;0 or
    ///     |<i>b</i>|&nbsp;=&nbsp;2<i>g</i>, then
    ///     <i>s</i>&nbsp;=&nbsp;sgn(<i>a</i>), and if <i>a</i>&nbsp;=&nbsp;0 or
    ///     |<i>a</i>|&nbsp;=&nbsp;2<i>g</i>, then
    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
    ///
    /// The initial value of `rop` is ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let a = Integer::from(4);
    /// let b = Integer::from(6);
    /// let (g, s, t) = a.extended_gcd(b, Integer::new());
    /// assert_eq!(g, 2);
    /// assert_eq!(s, -1);
    /// assert_eq!(t, 1);
    /// ```
    #[inline]
    pub fn extended_gcd(mut self, mut other: Self, mut rop: Self) -> (Self, Self, Self) {
        self.extended_gcd_mut(&mut other, &mut rop);
        (self, other, rop)
    }

    /// Finds the greatest common divisor (GCD) of the two inputs (`self` and
    /// `other`), and two coefficients to obtain the GCD from the two inputs.
    ///
    /// The GCD is stored in `self`, and the two coefficients are stored in
    /// `other` and `rop`.
    ///
    /// The GCD is always positive except when both inputs are zero. If the
    /// inputs are <i>a</i> and <i>b</i>, then the GCD is <i>g</i> and the
    /// coefficients are <i>s</i> and <i>t</i> such that
    ///
    /// <i>a</i> × <i>s</i> + <i>b</i> × <i>t</i> = <i>g</i>
    ///
    /// The values <i>s</i> and <i>t</i> are chosen such that normally,
    /// |<i>s</i>|&nbsp;<&nbsp;|<i>b</i>|&nbsp;/&nbsp;(2<i>g</i>) and
    /// |<i>t</i>|&nbsp;<&nbsp;|<i>a</i>|&nbsp;/&nbsp;(2<i>g</i>), and these
    /// relations define <i>s</i> and <i>t</i> uniquely. There are a few
    /// exceptional cases:
    ///
    ///   * If |<i>a</i>|&nbsp;=&nbsp;|<i>b</i>|, then <i>s</i>&nbsp;=&nbsp;0,
    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
    ///   * Otherwise, if <i>b</i>&nbsp;=&nbsp;0 or
    ///     |<i>b</i>|&nbsp;=&nbsp;2<i>g</i>, then
    ///     <i>s</i>&nbsp;=&nbsp;sgn(<i>a</i>), and if <i>a</i>&nbsp;=&nbsp;0 or
    ///     |<i>a</i>|&nbsp;=&nbsp;2<i>g</i>, then
    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
    ///
    /// The initial value of `rop` is ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut a_g = Integer::from(4);
    /// let mut b_s = Integer::from(6);
    /// let mut t = Integer::new();
    /// a_g.extended_gcd_mut(&mut b_s, &mut t);
    /// assert_eq!(a_g, 2);
    /// assert_eq!(b_s, -1);
    /// assert_eq!(t, 1);
    /// ```
    #[inline]
    pub fn extended_gcd_mut(&mut self, other: &mut Self, rop: &mut Self) {
        xmpz::gcdext(self, other, Some(rop), (), ());
    }

    /// Finds the greatest common divisor (GCD) of the two inputs (`self` and
    /// `other`), and two coefficients to obtain the GCD from the two inputs.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer], [Integer][][)][tuple]> for Src</code>
    ///
    /// In the case that only one of the two coefficients is required, the
    /// following are also implemented:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///
    /// The GCD is always positive except when both inputs are zero. If the
    /// inputs are <i>a</i> and <i>b</i>, then the GCD is <i>g</i> and the
    /// coefficients are <i>s</i> and <i>t</i> such that
    ///
    /// <i>a</i> × <i>s</i> + <i>b</i> × <i>t</i> = <i>g</i>
    ///
    /// The values <i>s</i> and <i>t</i> are chosen such that normally,
    /// |<i>s</i>|&nbsp;<&nbsp;|<i>b</i>|&nbsp;/&nbsp;(2<i>g</i>) and
    /// |<i>t</i>|&nbsp;<&nbsp;|<i>a</i>|&nbsp;/&nbsp;(2<i>g</i>), and these
    /// relations define <i>s</i> and <i>t</i> uniquely. There are a few
    /// exceptional cases:
    ///
    ///   * If |<i>a</i>|&nbsp;=&nbsp;|<i>b</i>|, then <i>s</i>&nbsp;=&nbsp;0,
    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
    ///   * Otherwise, if <i>b</i>&nbsp;=&nbsp;0 or
    ///     |<i>b</i>|&nbsp;=&nbsp;2<i>g</i>, then
    ///     <i>s</i>&nbsp;=&nbsp;sgn(<i>a</i>), and if <i>a</i>&nbsp;=&nbsp;0 or
    ///     |<i>a</i>|&nbsp;=&nbsp;2<i>g</i>, then
    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let a = Integer::from(4);
    /// let b = Integer::from(6);
    /// let r = a.extended_gcd_ref(&b);
    /// let mut g = Integer::new();
    /// let mut s = Integer::new();
    /// let mut t = Integer::new();
    /// (&mut g, &mut s, &mut t).assign(r);
    /// assert_eq!(a, 4);
    /// assert_eq!(b, 6);
    /// assert_eq!(g, 2);
    /// assert_eq!(s, -1);
    /// assert_eq!(t, 1);
    /// ```
    ///
    /// In the case that only one of the two coefficients is required, this can
    /// be achieved as follows:
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let a = Integer::from(4);
    /// let b = Integer::from(6);
    ///
    /// // no t required
    /// let (mut g1, mut s1) = (Integer::new(), Integer::new());
    /// (&mut g1, &mut s1).assign(a.extended_gcd_ref(&b));
    /// assert_eq!(g1, 2);
    /// assert_eq!(s1, -1);
    ///
    /// // no s required
    /// let (mut g2, mut t2) = (Integer::new(), Integer::new());
    /// (&mut g2, &mut t2).assign(b.extended_gcd_ref(&a));
    /// assert_eq!(g2, 2);
    /// assert_eq!(t2, 1);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn extended_gcd_ref<'a>(&'a self, other: &'a Self) -> GcdExtIncomplete<'_> {
        GcdExtIncomplete {
            ref_self: self,
            other,
        }
    }

    /// Finds the least common multiple.
    ///
    /// The result is always positive except when one or both inputs are zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let a = Integer::from(10);
    /// let mut b = Integer::from(25);
    /// // lcm of 10, 25 is 50
    /// let lcm1 = a.lcm(&b);
    /// assert_eq!(lcm1, 50);
    /// b.assign(0);
    /// // lcm of 50, 0 is 0
    /// let lcm2 = lcm1.lcm(&b);
    /// assert_eq!(lcm2, 0);
    /// ```
    #[inline]
    #[must_use]
    pub fn lcm(mut self, other: &Self) -> Self {
        self.lcm_mut(other);
        self
    }

    /// Finds the least common multiple.
    ///
    /// The result is always positive except when one or both inputs are zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let mut a = Integer::from(10);
    /// let mut b = Integer::from(25);
    /// // lcm of 10, 25 is 50
    /// a.lcm_mut(&b);
    /// assert_eq!(a, 50);
    /// b.assign(0);
    /// // lcm of 50, 0 is 0
    /// a.lcm_mut(&b);
    /// assert_eq!(a, 0);
    /// ```
    #[inline]
    pub fn lcm_mut(&mut self, other: &Self) {
        xmpz::lcm(self, (), other);
    }

    /// Finds the least common multiple.
    ///
    /// The result is always positive except when one or both inputs are zero.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let a = Integer::from(100);
    /// let b = Integer::from(125);
    /// let r = a.lcm_ref(&b);
    /// // lcm of 100, 125 is 500
    /// assert_eq!(Integer::from(r), 500);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn lcm_ref<'a>(&'a self, other: &'a Self) -> LcmIncomplete<'_> {
        LcmIncomplete {
            ref_self: self,
            other,
        }
    }

    /// Finds the least common multiple.
    ///
    /// The result is always positive except when one or both inputs are zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(10);
    /// // lcm of 10, 25 is 50
    /// let lcm1 = i.lcm_u(25);
    /// assert_eq!(lcm1, 50);
    /// // lcm of 50, 0 is 0
    /// let lcm2 = lcm1.lcm_u(0);
    /// assert_eq!(lcm2, 0);
    /// ```
    #[inline]
    #[must_use]
    pub fn lcm_u(mut self, other: u32) -> Self {
        self.lcm_u_mut(other);
        self
    }

    /// Finds the least common multiple.
    ///
    /// The result is always positive except when one or both inputs are zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(10);
    /// // lcm of 10, 25 is 50
    /// i.lcm_u_mut(25);
    /// assert_eq!(i, 50);
    /// // lcm of 50, 0 is 0
    /// i.lcm_u_mut(0);
    /// assert_eq!(i, 0);
    /// ```
    #[inline]
    pub fn lcm_u_mut(&mut self, other: u32) {
        xmpz::lcm_ui(self, (), other.into());
    }

    /// Finds the least common multiple.
    ///
    /// The result is always positive except when one or both inputs are zero.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let i = Integer::from(100);
    /// let r = i.lcm_u_ref(125);
    /// // lcm of 100, 125 is 500
    /// assert_eq!(Integer::from(r), 500);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn lcm_u_ref(&self, other: u32) -> LcmUIncomplete<'_> {
        let other = other.into();
        LcmUIncomplete {
            ref_self: self,
            other,
        }
    }

    /// Calculates the Jacobi symbol (`self`/<i>n</i>).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let m = Integer::from(10);
    /// let mut n = Integer::from(13);
    /// assert_eq!(m.jacobi(&n), 1);
    /// n.assign(15);
    /// assert_eq!(m.jacobi(&n), 0);
    /// n.assign(17);
    /// assert_eq!(m.jacobi(&n), -1);
    /// ```
    #[inline]
    pub fn jacobi(&self, n: &Self) -> i32 {
        xmpz::jacobi(self, n).cast()
    }

    /// Calculates the Legendre symbol (`self`/<i>p</i>).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let a = Integer::from(5);
    /// let mut p = Integer::from(7);
    /// assert_eq!(a.legendre(&p), -1);
    /// p.assign(11);
    /// assert_eq!(a.legendre(&p), 1);
    /// ```
    #[inline]
    pub fn legendre(&self, p: &Self) -> i32 {
        xmpz::legendre(self, p).cast()
    }

    /// Calculates the Jacobi symbol (`self`/<i>n</i>) with the Kronecker
    /// extension.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let k = Integer::from(3);
    /// let mut n = Integer::from(16);
    /// assert_eq!(k.kronecker(&n), 1);
    /// n.assign(17);
    /// assert_eq!(k.kronecker(&n), -1);
    /// n.assign(18);
    /// assert_eq!(k.kronecker(&n), 0);
    /// ```
    #[inline]
    pub fn kronecker(&self, n: &Self) -> i32 {
        xmpz::kronecker(self, n).cast()
    }

    /// Removes all occurrences of `factor`, and returns the number of
    /// occurrences removed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(Integer::u_pow_u(13, 50));
    /// i *= 1000;
    /// let (remove, count) = i.remove_factor(&Integer::from(13));
    /// assert_eq!(remove, 1000);
    /// assert_eq!(count, 50);
    /// ```
    #[inline]
    pub fn remove_factor(mut self, factor: &Self) -> (Self, u32) {
        let count = self.remove_factor_mut(factor);
        (self, count)
    }

    /// Removes all occurrences of `factor`, and returns the number of
    /// occurrences removed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// let mut i = Integer::from(Integer::u_pow_u(13, 50));
    /// i *= 1000;
    /// let count = i.remove_factor_mut(&Integer::from(13));
    /// assert_eq!(i, 1000);
    /// assert_eq!(count, 50);
    /// ```
    #[inline]
    pub fn remove_factor_mut(&mut self, factor: &Self) -> u32 {
        xmpz::remove(self, (), factor).unwrapped_cast()
    }

    /// Removes all occurrences of `factor`, and counts the number of
    /// occurrences removed.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [u32][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [u32][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [u32][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [u32][][)][tuple]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let mut i = Integer::from(Integer::u_pow_u(13, 50));
    /// i *= 1000;
    /// let factor = Integer::from(13);
    /// let r = i.remove_factor_ref(&factor);
    /// let (mut j, mut count) = (Integer::new(), 0);
    /// (&mut j, &mut count).assign(r);
    /// assert_eq!(count, 50);
    /// assert_eq!(j, 1000);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn remove_factor_ref<'a>(&'a self, factor: &'a Self) -> RemoveFactorIncomplete<'a> {
        RemoveFactorIncomplete {
            ref_self: self,
            factor,
        }
    }

    /// Computes the factorial of <i>n</i>.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// // 10 × 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1
    /// assert_eq!(Integer::factorial(10).complete(), 3628800);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn factorial(n: u32) -> FactorialIncomplete {
        let n = n.into();
        FactorialIncomplete { n }
    }

    /// Computes the double factorial of <i>n</i>.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// // 10 × 8 × 6 × 4 × 2
    /// assert_eq!(Integer::factorial_2(10).complete(), 3840);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn factorial_2(n: u32) -> Factorial2Incomplete {
        let n = n.into();
        Factorial2Incomplete { n }
    }

    /// Computes the <i>m</i>-multi factorial of <i>n</i>.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// // 10 × 7 × 4 × 1
    /// assert_eq!(Integer::factorial_m(10, 3).complete(), 280);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn factorial_m(n: u32, m: u32) -> FactorialMIncomplete {
        let n = n.into();
        let m = m.into();
        FactorialMIncomplete { n, m }
    }

    /// Computes the primorial of <i>n</i>.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// // 7 × 5 × 3 × 2
    /// assert_eq!(Integer::primorial(10).complete(), 210);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn primorial(n: u32) -> PrimorialIncomplete {
        let n = n.into();
        PrimorialIncomplete { n }
    }

    /// Computes the binomial coefficient over <i>k</i>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // 7 choose 2 is 21
    /// let i = Integer::from(7);
    /// let bin = i.binomial(2);
    /// assert_eq!(bin, 21);
    /// ```
    #[inline]
    #[must_use]
    pub fn binomial(mut self, k: u32) -> Self {
        self.binomial_mut(k);
        self
    }

    /// Computes the binomial coefficient over <i>k</i>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // 7 choose 2 is 21
    /// let mut i = Integer::from(7);
    /// i.binomial_mut(2);
    /// assert_eq!(i, 21);
    /// ```
    #[inline]
    pub fn binomial_mut(&mut self, k: u32) {
        xmpz::bin_ui(self, (), k.into());
    }

    /// Computes the binomial coefficient over <i>k</i>.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// // 7 choose 2 is 21
    /// let i = Integer::from(7);
    /// assert_eq!(i.binomial_ref(2).complete(), 21);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn binomial_ref(&self, k: u32) -> BinomialIncomplete<'_> {
        let k = k.into();
        BinomialIncomplete { ref_self: self, k }
    }

    /// Computes the binomial coefficient <i>n</i> over <i>k</i>.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::Integer;
    /// // 7 choose 2 is 21
    /// let b = Integer::binomial_u(7, 2);
    /// let i = Integer::from(b);
    /// assert_eq!(i, 21);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn binomial_u(n: u32, k: u32) -> BinomialUIncomplete {
        let n = n.into();
        let k = k.into();
        BinomialUIncomplete { n, k }
    }

    /// Computes the Fibonacci number.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// This function is meant for an isolated number. If a sequence of
    /// Fibonacci numbers is required, the first two values of the sequence
    /// should be computed with the [`fibonacci_2`][Integer::fibonacci_2]
    /// method, then iterations should be used.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// assert_eq!(Integer::fibonacci(12).complete(), 144);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn fibonacci(n: u32) -> FibonacciIncomplete {
        let n = n.into();
        FibonacciIncomplete { n }
    }

    /// Computes a Fibonacci number, and the previous Fibonacci number.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
    ///
    /// This function is meant to calculate isolated numbers. If a sequence of
    /// Fibonacci numbers is required, the first two values of the sequence
    /// should be computed with this function, then iterations should be used.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let f = Integer::fibonacci_2(12);
    /// let mut pair = <(Integer, Integer)>::from(f);
    /// assert_eq!(pair.0, 144);
    /// assert_eq!(pair.1, 89);
    /// // Fibonacci number F[-1] is 1
    /// pair.assign(Integer::fibonacci_2(0));
    /// assert_eq!(pair.0, 0);
    /// assert_eq!(pair.1, 1);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn fibonacci_2(n: u32) -> Fibonacci2Incomplete {
        let n = n.into();
        Fibonacci2Incomplete { n }
    }

    /// Computes the Lucas number.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// This function is meant for an isolated number. If a sequence of Lucas
    /// numbers is required, the first two values of the sequence should be
    /// computed with the [`lucas_2`][Integer::lucas_2] method, then iterations
    /// should be used.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Complete, Integer};
    /// assert_eq!(Integer::lucas(12).complete(), 322);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn lucas(n: u32) -> LucasIncomplete {
        let n = n.into();
        LucasIncomplete { n }
    }

    /// Computes a Lucas number, and the previous Lucas number.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
    ///
    /// This function is meant to calculate isolated numbers. If a sequence of
    /// Lucas numbers is required, the first two values of the sequence should
    /// be computed with this function, then iterations should be used.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::{Assign, Integer};
    /// let l = Integer::lucas_2(12);
    /// let mut pair = <(Integer, Integer)>::from(l);
    /// assert_eq!(pair.0, 322);
    /// assert_eq!(pair.1, 199);
    /// pair.assign(Integer::lucas_2(0));
    /// assert_eq!(pair.0, 2);
    /// assert_eq!(pair.1, -1);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn lucas_2(n: u32) -> Lucas2Incomplete {
        let n = n.into();
        Lucas2Incomplete { n }
    }

    #[cfg(feature = "rand")]
    /// Generates a random number with a specified maximum number of bits.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rand::RandState;
    /// use rug::{Assign, Integer};
    /// let mut rand = RandState::new();
    /// let mut i = Integer::from(Integer::random_bits(0, &mut rand));
    /// assert_eq!(i, 0);
    /// i.assign(Integer::random_bits(80, &mut rand));
    /// assert!(i.significant_bits() <= 80);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn random_bits(bits: u32, rng: &mut dyn MutRandState) -> RandomBitsIncomplete {
        let bits = bits.into();
        RandomBitsIncomplete { bits, rng }
    }

    #[cfg(feature = "rand")]
    /// Generates a non-negative random number below the given boundary value.
    ///
    /// # Panics
    ///
    /// Panics if the boundary value is less than or equal to zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rand::RandState;
    /// use rug::Integer;
    /// let mut rand = RandState::new();
    /// let i = Integer::from(15);
    /// let below = i.random_below(&mut rand);
    /// println!("0 ≤ {} < 15", below);
    /// assert!(below < 15);
    /// ```
    #[inline]
    #[must_use]
    pub fn random_below(mut self, rng: &mut dyn MutRandState) -> Self {
        self.random_below_mut(rng);
        self
    }

    #[cfg(feature = "rand")]
    /// Generates a non-negative random number below the given boundary value.
    ///
    /// # Panics
    ///
    /// Panics if the boundary value is less than or equal to zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rand::RandState;
    /// use rug::Integer;
    /// let mut rand = RandState::new();
    /// let mut i = Integer::from(15);
    /// i.random_below_mut(&mut rand);
    /// println!("0 ≤ {} < 15", i);
    /// assert!(i < 15);
    /// ```
    #[inline]
    pub fn random_below_mut(&mut self, rng: &mut dyn MutRandState) {
        xmpz::urandomm(self, rng, ());
    }

    #[cfg(feature = "rand")]
    /// Generates a non-negative random number below the given boundary value.
    ///
    /// The following are implemented with the returned [incomplete-computation
    /// value][icv] as `Src`:
    ///   * <code>[Assign]\<Src> for [Integer]</code>
    ///   * <code>[From]\<Src> for [Integer]</code>
    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
    ///
    /// # Panics
    ///
    /// Panics if the boundary value is less than or equal to zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::rand::RandState;
    /// use rug::Integer;
    /// let mut rand = RandState::new();
    /// let bound = Integer::from(15);
    /// let i = Integer::from(bound.random_below_ref(&mut rand));
    /// println!("0 ≤ {} < {}", i, bound);
    /// assert!(i < bound);
    /// ```
    ///
    /// [icv]: crate#incomplete-computation-values
    #[inline]
    pub fn random_below_ref<'a>(
        &'a self,
        rng: &'a mut dyn MutRandState,
    ) -> RandomBelowIncomplete<'a> {
        RandomBelowIncomplete {
            ref_self: self,
            rng,
        }
    }

    /// This method has been renamed to [`extended_gcd`][Integer::extended_gcd].
    #[deprecated(since = "1.18.0", note = "renamed to `extended_gcd`")]
    #[inline]
    pub fn gcd_cofactors(self, other: Self, rop: Self) -> (Self, Self, Self) {
        self.extended_gcd(other, rop)
    }

    /// This method has been renamed to
    /// [`extended_gcd_mut`][Integer::extended_gcd_mut].
    #[deprecated(since = "1.18.0", note = "renamed to `extended_gcd_mut`")]
    #[inline]
    pub fn gcd_cofactors_mut(&mut self, other: &mut Self, rop: &mut Self) {
        self.extended_gcd_mut(other, rop);
    }

    /// This method has been renamed to
    /// [`extended_gcd_ref`][Integer::extended_gcd_ref].
    #[deprecated(since = "1.18.0", note = "renamed to `extended_gcd_ref`")]
    #[inline]
    pub fn gcd_cofactors_ref<'a>(&'a self, other: &'a Self) -> GcdExtIncomplete<'_> {
        self.extended_gcd_ref(other)
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

ref_math_op1! { Integer; xmpz::abs; struct AbsIncomplete {} }
ref_math_op1! { Integer; xmpz::signum; struct SignumIncomplete {} }

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

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

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

ref_math_op1! { Integer; xmpz::fdiv_r_2exp; struct KeepBitsIncomplete { n: bitcnt_t } }
ref_math_op1! { Integer; xmpz::keep_signed_bits; struct KeepSignedBitsIncomplete { n: bitcnt_t } }
ref_math_op1! { Integer; xmpz::next_pow_of_two; struct NextPowerOfTwoIncomplete {} }
ref_math_op2! { Integer; xmpz::modulo; struct ModuloIncomplete { divisor } }
ref_math_op2_2! { Integer; xmpz::tdiv_qr; struct DivRemIncomplete { divisor } }
ref_math_op2_2! { Integer; xmpz::cdiv_qr; struct DivRemCeilIncomplete { divisor } }
ref_math_op2_2! { Integer; xmpz::fdiv_qr; struct DivRemFloorIncomplete { divisor } }
ref_math_op2_2! { Integer; xmpz::rdiv_qr; struct DivRemRoundIncomplete { divisor } }
ref_math_op2_2! { Integer; xmpz::ediv_qr; struct DivRemEucIncomplete { divisor } }
ref_math_op2! { Integer; xmpz::divexact; struct DivExactIncomplete { divisor } }
ref_math_op1! { Integer; xmpz::divexact_u32; struct DivExactUIncomplete { divisor: u32 } }

#[derive(Debug)]
pub struct PowModIncomplete<'a> {
    ref_self: Option<&'a Integer>,
    sinverse: Option<Integer>,
    exponent: &'a Integer,
    modulo: &'a Integer,
}

impl Assign<PowModIncomplete<'_>> for Integer {
    #[inline]
    fn assign(&mut self, src: PowModIncomplete<'_>) {
        match (src.ref_self, src.sinverse) {
            (Some(base), None) => {
                debug_assert!(!src.exponent.is_negative());
                xmpz::pow_mod(self, base, src.exponent, src.modulo);
            }
            (None, Some(sinverse)) => {
                debug_assert!(src.exponent.is_negative());
                xmpz::pow_mod(self, &sinverse, src.exponent, src.modulo);
            }
            _ => unreachable!(),
        }
    }
}

// do not use from_assign! macro to reuse sinverse
impl From<PowModIncomplete<'_>> for Integer {
    #[inline]
    fn from(src: PowModIncomplete<'_>) -> Self {
        match (src.ref_self, src.sinverse) {
            (Some(base), None) => {
                debug_assert!(!src.exponent.is_negative());
                let mut dst = Integer::new();
                xmpz::pow_mod(&mut dst, base, src.exponent, src.modulo);
                dst
            }
            (None, Some(mut sinverse)) => {
                debug_assert!(src.exponent.is_negative());
                xmpz::pow_mod(&mut sinverse, (), src.exponent, src.modulo);
                sinverse
            }
            _ => unreachable!(),
        }
    }
}

pub struct SecurePowModIncomplete<'a> {
    ref_self: &'a Integer,
    exponent: &'a Integer,
    modulo: &'a Integer,
}

impl Assign<SecurePowModIncomplete<'_>> for Integer {
    #[inline]
    fn assign(&mut self, src: SecurePowModIncomplete<'_>) {
        xmpz::powm_sec(self, src.ref_self, src.exponent, src.modulo);
    }
}

from_assign! { SecurePowModIncomplete<'_> => Integer }

ref_math_op0! { Integer; xmpz::u32_pow_u32; struct UPowUIncomplete { base: u32, exponent: u32 } }
ref_math_op0! { Integer; xmpz::i32_pow_u32; struct IPowUIncomplete { base: i32, exponent: u32 } }
ref_math_op1! { Integer; xmpz::root; struct RootIncomplete { n: c_ulong } }
ref_math_op1_2! { Integer; xmpz::rootrem; struct RootRemIncomplete { n: c_ulong } }
ref_math_op1! { Integer; xmpz::sqrt; struct SqrtIncomplete {} }
ref_math_op1_2! { Integer; xmpz::sqrtrem; struct SqrtRemIncomplete {} }
ref_math_op1! { Integer; xmpz::nextprime; struct NextPrimeIncomplete {} }
ref_math_op1! { Integer; xmpz::prevprime; struct PrevPrimeIncomplete {} }
ref_math_op2! { Integer; xmpz::gcd; struct GcdIncomplete { other } }
ref_math_op1! { Integer; xmpz::gcd_ui; struct GcdUIncomplete { other: c_ulong } }

impl From<GcdUIncomplete<'_>> for Option<u32> {
    #[inline]
    fn from(src: GcdUIncomplete) -> Self {
        let gcd = xmpz::gcd_opt_ui(None, src.ref_self, src.other.into());
        if gcd == 0 && !src.ref_self.is_zero() {
            None
        } else {
            gcd.checked_cast()
        }
    }
}

#[derive(Debug)]
pub struct GcdExtIncomplete<'a> {
    ref_self: &'a Integer,
    other: &'a Integer,
}

impl Assign<GcdExtIncomplete<'_>> for (&mut Integer, &mut Integer, &mut Integer) {
    #[inline]
    fn assign(&mut self, src: GcdExtIncomplete<'_>) {
        xmpz::gcdext(self.0, self.1, Some(self.2), src.ref_self, src.other);
    }
}

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

from_assign! { GcdExtIncomplete<'_> => Integer, Integer, Integer }

impl Assign<GcdExtIncomplete<'_>> for (&mut Integer, &mut Integer) {
    #[inline]
    fn assign(&mut self, src: GcdExtIncomplete<'_>) {
        xmpz::gcdext(self.0, self.1, None, src.ref_self, src.other);
    }
}

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

impl From<GcdExtIncomplete<'_>> for (Integer, Integer) {
    #[inline]
    fn from(src: GcdExtIncomplete<'_>) -> Self {
        let mut dst = Self::default();
        Assign::assign(&mut (&mut dst.0, &mut dst.1), src);
        dst
    }
}

ref_math_op2! { Integer; xmpz::lcm; struct LcmIncomplete { other } }
ref_math_op1! { Integer; xmpz::lcm_ui; struct LcmUIncomplete { other: c_ulong } }

#[derive(Debug)]
pub struct InvertIncomplete<'a> {
    sinverse: Integer,
    modulo: &'a Integer,
}

impl Assign<InvertIncomplete<'_>> for Integer {
    #[inline]
    fn assign(&mut self, src: InvertIncomplete<'_>) {
        xmpz::finish_invert(self, &src.sinverse, src.modulo);
    }
}

// do not use from_assign! macro to reuse sinverse
impl From<InvertIncomplete<'_>> for Integer {
    #[inline]
    fn from(mut src: InvertIncomplete<'_>) -> Self {
        xmpz::finish_invert(&mut src.sinverse, (), src.modulo);
        src.sinverse
    }
}

#[derive(Debug)]
pub struct RemoveFactorIncomplete<'a> {
    ref_self: &'a Integer,
    factor: &'a Integer,
}

impl Assign<RemoveFactorIncomplete<'_>> for (&mut Integer, &mut u32) {
    #[inline]
    fn assign(&mut self, src: RemoveFactorIncomplete<'_>) {
        *self.1 = xmpz::remove(self.0, src.ref_self, src.factor).unwrapped_cast();
    }
}

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

from_assign! { RemoveFactorIncomplete<'_> => Integer, u32 }

ref_math_op0! { Integer; xmpz::fac_ui; struct FactorialIncomplete { n: c_ulong } }
ref_math_op0! { Integer; xmpz::twofac_ui; struct Factorial2Incomplete { n: c_ulong } }
ref_math_op0! { Integer; xmpz::mfac_uiui; struct FactorialMIncomplete { n: c_ulong, m: c_ulong } }
ref_math_op0! { Integer; xmpz::primorial_ui; struct PrimorialIncomplete { n: c_ulong } }
ref_math_op1! { Integer; xmpz::bin_ui; struct BinomialIncomplete { k: c_ulong } }
ref_math_op0! { Integer; xmpz::bin_uiui; struct BinomialUIncomplete { n: c_ulong, k: c_ulong } }
ref_math_op0! { Integer; xmpz::fib_ui; struct FibonacciIncomplete { n: c_ulong } }
ref_math_op0_2! { Integer; xmpz::fib2_ui; struct Fibonacci2Incomplete { n: c_ulong } }
ref_math_op0! { Integer; xmpz::lucnum_ui; struct LucasIncomplete { n: c_ulong } }
ref_math_op0_2! { Integer; xmpz::lucnum2_ui; struct Lucas2Incomplete { n: c_ulong } }

#[cfg(feature = "rand")]
pub struct RandomBitsIncomplete<'a> {
    bits: bitcnt_t,
    rng: &'a mut dyn MutRandState,
}

#[cfg(feature = "rand")]
impl Assign<RandomBitsIncomplete<'_>> for Integer {
    #[inline]
    fn assign(&mut self, src: RandomBitsIncomplete) {
        xmpz::urandomb(self, src.rng, src.bits);
    }
}

#[cfg(feature = "rand")]
impl From<RandomBitsIncomplete<'_>> for Integer {
    #[inline]
    fn from(src: RandomBitsIncomplete) -> Self {
        let mut dst = Integer::new();
        dst.assign(src);
        dst
    }
}

#[cfg(feature = "rand")]
pub struct RandomBelowIncomplete<'a> {
    ref_self: &'a Integer,
    rng: &'a mut dyn MutRandState,
}

#[cfg(feature = "rand")]
impl Assign<RandomBelowIncomplete<'_>> for Integer {
    #[inline]
    fn assign(&mut self, src: RandomBelowIncomplete) {
        xmpz::urandomm(self, src.rng, src.ref_self);
    }
}

#[cfg(feature = "rand")]
impl From<RandomBelowIncomplete<'_>> for Integer {
    #[inline]
    fn from(src: RandomBelowIncomplete) -> Self {
        let mut dst = Integer::new();
        dst.assign(src);
        dst
    }
}

pub(crate) fn req_chars(i: &Integer, radix: i32, extra: usize) -> usize {
    assert!((2..=36).contains(&radix), "radix out of range");
    let size = unsafe { gmp::mpz_sizeinbase(i.as_raw(), radix) };
    let size_extra = size.checked_add(extra).expect("overflow");
    if i.is_negative() {
        size_extra.checked_add(1).expect("overflow")
    } else {
        size_extra
    }
}

pub(crate) fn append_to_string(s: &mut StringLike, i: &Integer, radix: i32, to_upper: bool) {
    // add 1 for nul
    let size = req_chars(i, radix, 1);
    s.reserve(size);
    let reserved_ptr = s.as_str().as_ptr();
    let case_radix = if to_upper { -radix } else { radix };
    unsafe {
        let alloced = s.reserved_space();
        gmp::mpz_get_str(
            cast_ptr_mut!(alloced.as_mut_ptr(), c_char),
            case_radix.cast(),
            i.as_raw(),
        );
        let nul_index = alloced
            .iter()
            .position(|&x: &MaybeUninit<u8>| {
                // SAFETY: bytes will be initialized up to and including nul
                x.assume_init() == 0
            })
            .unwrap();
        s.increase_len(nul_index);
    }
    debug_assert_eq!(reserved_ptr, s.as_str().as_ptr());
}

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

impl Assign<ParseIncomplete> for Integer {
    #[inline]
    fn assign(&mut self, src: ParseIncomplete) {
        // SAFETY: radix is in correct range, and all digits are < radix
        unsafe {
            self.assign_bytes_radix_unchecked(src.digits.as_slice(), src.radix, src.is_negative);
        }
    }
}

from_assign! { ParseIncomplete => Integer }

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

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

    let mut digits = VecLike::new();
    digits.reserve(bytes.len());
    let mut has_sign = false;
    let mut is_negative = false;
    let mut has_digits = false;
    for &b in bytes {
        let digit = match b {
            b'+' if !has_sign && !has_digits => {
                has_sign = true;
                continue;
            }
            b'-' if !has_sign && !has_digits => {
                is_negative = true;
                has_sign = true;
                continue;
            }
            b'_' if has_digits => continue,
            b' ' | b'\t' | b'\n' | 0x0b | 0x0c | 0x0d => continue,

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

            // error
            _ => bradix,
        };
        if digit >= bradix {
            return Err(Error {
                kind: Kind::InvalidDigit,
            });
        };
        has_digits = true;
        if digit > 0 || !digits.as_slice().is_empty() {
            digits.push(digit);
        }
    }
    if !has_digits {
        return Err(Error {
            kind: Kind::NoDigits,
        });
    }
    Ok(ParseIncomplete {
        is_negative,
        digits,
        radix,
    })
}

/**
An error which can be returned when parsing an [`Integer`].

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

# Examples

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

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

impl ParseIntegerError {
    fn desc(&self) -> &str {
        use self::ParseErrorKind::*;
        match self.kind {
            InvalidDigit => "invalid digit found in string",
            NoDigits => "string has no digits",
        }
    }
}

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

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

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/**
Whether a number is prime.

See the
<code>[Integer]::[is\_probably\_prime][Integer::is_probably_prime]</code>
method.

# Examples

```rust
use rug::integer::IsPrime;
use rug::Integer;
let no = Integer::from(163 * 4003);
assert_eq!(no.is_probably_prime(30), IsPrime::No);
let yes = Integer::from(817_504_243);
assert_eq!(yes.is_probably_prime(30), IsPrime::Yes);
// 16_412_292_043_871_650_369 is actually a prime.
let probably = Integer::from(16_412_292_043_871_650_369_u64);
assert_eq!(probably.is_probably_prime(30), IsPrime::Probably);
```
*/
pub enum IsPrime {
    /// The number is definitely not prime.
    No,
    /// The number is probably prime.
    Probably,
    /// The number is definitely prime.
    Yes,
}

/// Conversions between [`Integer`] and a [slice] of digits of this
/// type are provided.
///
/// For conversion from digits to [`Integer`], see
/// <code>[Integer]::[from\_digits][Integer::from_digits]</code>
/// and
/// <code>[Integer]::[assign\_digits][Integer::assign_digits]</code>.
/// For conversion from [`Integer`] to digits, see
/// <code>[Integer]::[significant\_digits][Integer::significant_digits]</code>,
/// <code>[Integer]::[to\_digits][Integer::to_digits]</code>, and
/// <code>[Integer]::[write\_digits][Integer::write_digits]</code>.
///
/// This trait is sealed and cannot be implemented for more types; it
/// is implemented for [`bool`] and the unsigned integer types [`u8`],
/// [`u16`], [`u32`], [`u64`], [`u128`] and [`usize`].
///
/// [slice]: prim@slice
pub trait UnsignedPrimitive: SealedUnsignedPrimitive {}

pub struct PrivateUnsignedPrimitive {
    bytes: usize,
    bits: usize,
    nails: usize,
}

/// # Safety
///
/// Bit patterns can be written to the implementing type. Implementations must
/// make sure that all bit patterns are allowed.
pub unsafe trait SealedUnsignedPrimitive: Sized {
    const PRIVATE: PrivateUnsignedPrimitive = PrivateUnsignedPrimitive {
        bytes: mem::size_of::<Self>(),
        bits: mem::size_of::<Self>() * 8,
        nails: 0,
    };
}

// Safety: We set nails to 7 so that only 0 or 1 can be written into bool.
impl UnsignedPrimitive for bool {}
unsafe impl SealedUnsignedPrimitive for bool {
    const PRIVATE: PrivateUnsignedPrimitive = PrivateUnsignedPrimitive {
        bytes: mem::size_of::<Self>(),
        bits: 1,
        nails: mem::size_of::<Self>() * 8 - 1,
    };
}

impl UnsignedPrimitive for u8 {}
unsafe impl SealedUnsignedPrimitive for u8 {}

impl UnsignedPrimitive for u16 {}
unsafe impl SealedUnsignedPrimitive for u16 {}

impl UnsignedPrimitive for u32 {}
unsafe impl SealedUnsignedPrimitive for u32 {}

impl UnsignedPrimitive for u64 {}
unsafe impl SealedUnsignedPrimitive for u64 {}

impl UnsignedPrimitive for u128 {}
unsafe impl SealedUnsignedPrimitive for u128 {}

impl UnsignedPrimitive for usize {}
unsafe impl SealedUnsignedPrimitive for usize {}