malachite-nz 0.9.2

The bignum types Natural and Integer, with efficient algorithms partially derived from GMP and FLINT.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
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
// Copyright © 2026 Mikhail Hogrefe
//
// Uses code adopted from the GNU MPFR Library.
//
//      Copyright © 1999-2022 Free Software Foundation, Inc.
//
//      Contributed by the AriC and Caramba projects, INRIA.
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.

use crate::natural::InnerNatural::{Large, Small};
use crate::natural::arithmetic::add::limbs_slice_add_limb_in_place;
use crate::natural::arithmetic::float_extras::{MPFR_EVEN_INEX, round_helper_even};
use crate::natural::arithmetic::is_power_of_2::limbs_is_power_of_2;
use crate::natural::arithmetic::shl::limbs_slice_shl_in_place;
use crate::natural::arithmetic::shr::limbs_shr_to_out;
use crate::natural::arithmetic::sub::{
    limbs_sub_limb_in_place, limbs_sub_limb_to_out, limbs_sub_same_length_in_place_left,
    limbs_sub_same_length_in_place_right, limbs_sub_same_length_to_out,
    limbs_sub_same_length_with_borrow_in_in_place_left,
    limbs_sub_same_length_with_borrow_in_to_out, sub_with_borrow,
};
use crate::natural::{
    LIMB_HIGH_BIT, Natural, bit_to_limb_count_ceiling, bit_to_limb_count_floor, limb_to_bit_count,
};
use crate::platform::Limb;
use core::cmp::{
    Ordering::{self, *},
    max,
};
use core::mem::swap;
use malachite_base::num::arithmetic::traits::{
    IsPowerOf2, ModPowerOf2, ModPowerOf2Sub, NegAssign, NegModPowerOf2, OverflowingAddAssign,
    OverflowingNegAssign, PowerOf2, SaturatingAddAssign, SaturatingSubAssign, Sign,
    WrappingAddAssign, WrappingNegAssign, WrappingSubAssign,
};
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::traits::Zero;
use malachite_base::num::conversion::traits::{ExactFrom, SaturatingFrom, WrappingFrom};
use malachite_base::num::logic::traits::LeadingZeros;
use malachite_base::rounding_modes::RoundingMode::{self, *};
use malachite_base::slices::{slice_set_zero, slice_test_zero};

const WIDTH_M1: u64 = Limb::WIDTH - 1;
const IWIDTH_M1: isize = WIDTH_M1 as isize;
const WIDTH_M1_MASK: Limb = Limb::MAX >> 1;
const WIDTH_M2_MASK: Limb = Limb::MAX >> 2;
const HALF_LIMB_HIGH_BIT: Limb = LIMB_HIGH_BIT >> 1;
const IWIDTH: i32 = Limb::WIDTH as i32;
const NEG_ONE: Limb = Limb::MAX;
const NEG_TWO: Limb = Limb::MAX - 1;
const WIDTH_P1: u64 = Limb::WIDTH + 1;
const TWICE_WIDTH: u64 = Limb::WIDTH * 2;
const THRICE_WIDTH: u64 = Limb::WIDTH * 3;
const TWICE_WIDTH_P1: u64 = Limb::WIDTH * 2 + 1;

pub fn sub_float_significands_in_place(
    mut x: &mut Natural,
    x_exp: &mut i32,
    x_prec: u64,
    mut y: &mut Natural,
    y_exp: i32,
    y_prec: u64,
    out_prec: u64,
    rm: RoundingMode,
) -> (Ordering, bool, bool) {
    if x_prec == y_prec && out_prec == x_prec {
        sub_float_significands_in_place_same_prec(x, x_exp, y, y_exp, out_prec, rm)
    } else {
        match (&mut x, &mut y) {
            (Natural(Small(small_x)), Natural(Small(small_y))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*small_x],
                        *x_exp,
                        x_prec,
                        &[*small_y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *small_x = out[0];
                        *x_exp = diff_exp;
                    }
                    (o, false, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*small_x],
                        *x_exp,
                        x_prec,
                        &[*small_y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *x = Natural(Large(out));
                        *x_exp = diff_exp;
                    }
                    (o, false, neg)
                }
            }
            (Natural(Small(small_x)), Natural(Large(ys))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*small_x],
                        *x_exp,
                        x_prec,
                        ys,
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *small_x = out[0];
                        *x_exp = diff_exp;
                    }
                    (o, false, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*small_x],
                        *x_exp,
                        x_prec,
                        ys,
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *x = Natural(Large(out));
                        *x_exp = diff_exp;
                    }
                    (o, false, neg)
                }
            }
            (Natural(Large(xs)), Natural(Small(small_y))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        xs,
                        *x_exp,
                        x_prec,
                        &[*small_y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *x = Natural(Small(out[0]));
                        *x_exp = diff_exp;
                    }
                    (o, false, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        xs,
                        *x_exp,
                        x_prec,
                        &[*small_y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *xs = out;
                        *x_exp = diff_exp;
                    }
                    (o, false, neg)
                }
            }
            (Natural(Large(xs)), Natural(Large(ys))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out, xs, *x_exp, x_prec, ys, y_exp, y_prec, out_prec, rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *x = Natural(Small(out[0]));
                        *x_exp = diff_exp;
                    }
                    (o, false, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out, xs, *x_exp, x_prec, ys, y_exp, y_prec, out_prec, rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *xs = out;
                        *x_exp = diff_exp;
                    }
                    (o, false, neg)
                }
            }
        }
    }
}

pub fn sub_float_significands_in_place_ref(
    mut x: &mut Natural,
    x_exp: &mut i32,
    x_prec: u64,
    y: &Natural,
    y_exp: i32,
    y_prec: u64,
    out_prec: u64,
    rm: RoundingMode,
) -> (Ordering, bool) {
    if x_prec == y_prec && out_prec == x_prec {
        sub_float_significands_in_place_same_prec_ref(x, x_exp, y, y_exp, out_prec, rm)
    } else {
        match (&mut x, y) {
            (Natural(Small(small_x)), Natural(Small(small_y))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*small_x],
                        *x_exp,
                        x_prec,
                        &[*small_y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *small_x = out[0];
                        *x_exp = diff_exp;
                    }
                    (o, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*small_x],
                        *x_exp,
                        x_prec,
                        &[*small_y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *x = Natural(Large(out));
                        *x_exp = diff_exp;
                    }
                    (o, neg)
                }
            }
            (Natural(Small(small_x)), Natural(Large(ys))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*small_x],
                        *x_exp,
                        x_prec,
                        ys,
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *small_x = out[0];
                        *x_exp = diff_exp;
                    }
                    (o, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*small_x],
                        *x_exp,
                        x_prec,
                        ys,
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *x = Natural(Large(out));
                        *x_exp = diff_exp;
                    }
                    (o, neg)
                }
            }
            (Natural(Large(xs)), Natural(Small(small_y))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        xs,
                        *x_exp,
                        x_prec,
                        &[*small_y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *x = Natural(Small(out[0]));
                        *x_exp = diff_exp;
                    }
                    (o, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        xs,
                        *x_exp,
                        x_prec,
                        &[*small_y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *xs = out;
                        *x_exp = diff_exp;
                    }
                    (o, neg)
                }
            }
            (Natural(Large(xs)), Natural(Large(ys))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out, xs, *x_exp, x_prec, ys, y_exp, y_prec, out_prec, rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *x = Natural(Small(out[0]));
                        *x_exp = diff_exp;
                    }
                    (o, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (diff_exp, o, neg) = sub_float_significands_general(
                        &mut out, xs, *x_exp, x_prec, ys, y_exp, y_prec, out_prec, rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    if *out.last().unwrap() == 0 {
                        *x = Natural::ZERO;
                    } else {
                        *xs = out;
                        *x_exp = diff_exp;
                    }
                    (o, neg)
                }
            }
        }
    }
}

pub fn sub_float_significands_ref_ref<'a>(
    x: &'a Natural,
    x_exp: i32,
    x_prec: u64,
    y: &'a Natural,
    y_exp: i32,
    y_prec: u64,
    out_prec: u64,
    rm: RoundingMode,
) -> (Natural, i32, Ordering, bool) {
    if x_prec == y_prec && out_prec == x_prec {
        sub_float_significands_same_prec_ref_ref(x, x_exp, y, y_exp, out_prec, rm)
    } else {
        match (x, y) {
            (Natural(Small(x)), Natural(Small(y))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (out_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*x],
                        x_exp,
                        x_prec,
                        &[*y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    (Natural(Small(out[0])), out_exp, o, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (out_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*x],
                        x_exp,
                        x_prec,
                        &[*y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    (
                        if *out.last().unwrap() == 0 {
                            Natural::ZERO
                        } else {
                            Natural(Large(out))
                        },
                        out_exp,
                        o,
                        neg,
                    )
                }
            }
            (Natural(Small(x)), Natural(Large(ys))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (out_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*x],
                        x_exp,
                        x_prec,
                        ys,
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    (Natural(Small(out[0])), out_exp, o, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (out_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        &[*x],
                        x_exp,
                        x_prec,
                        ys,
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    (
                        if *out.last().unwrap() == 0 {
                            Natural::ZERO
                        } else {
                            Natural(Large(out))
                        },
                        out_exp,
                        o,
                        neg,
                    )
                }
            }
            (Natural(Large(xs)), Natural(Small(y))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (out_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        xs,
                        x_exp,
                        x_prec,
                        &[*y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    (Natural(Small(out[0])), out_exp, o, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (out_exp, o, neg) = sub_float_significands_general(
                        &mut out,
                        xs,
                        x_exp,
                        x_prec,
                        &[*y],
                        y_exp,
                        y_prec,
                        out_prec,
                        rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    (
                        if *out.last().unwrap() == 0 {
                            Natural::ZERO
                        } else {
                            Natural(Large(out))
                        },
                        out_exp,
                        o,
                        neg,
                    )
                }
            }
            (Natural(Large(xs)), Natural(Large(ys))) => {
                if out_prec <= Limb::WIDTH {
                    let mut out = [0];
                    let (out_exp, o, neg) = sub_float_significands_general(
                        &mut out, xs, x_exp, x_prec, ys, y_exp, y_prec, out_prec, rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    (Natural(Small(out[0])), out_exp, o, neg)
                } else {
                    let mut out = vec![0; bit_to_limb_count_ceiling(out_prec)];
                    let (out_exp, o, neg) = sub_float_significands_general(
                        &mut out, xs, x_exp, x_prec, ys, y_exp, y_prec, out_prec, rm,
                    );
                    assert!(rm != Exact || o == Equal, "Inexact float subtraction");
                    (
                        if *out.last().unwrap() == 0 {
                            Natural::ZERO
                        } else {
                            Natural(Large(out))
                        },
                        out_exp,
                        o,
                        neg,
                    )
                }
            }
        }
    }
}

// This is mpfr_sub1sp from sub1sp.c, MPFR 4.2.0.
fn sub_float_significands_in_place_same_prec(
    x: &mut Natural,
    x_exp: &mut i32,
    y: &mut Natural,
    y_exp: i32,
    prec: u64,
    rm: RoundingMode,
) -> (Ordering, bool, bool) {
    match (&mut *x, &mut *y) {
        (Natural(Small(x)), Natural(Small(y))) => {
            let (diff, diff_exp, o, neg) = if prec == Limb::WIDTH {
                sub_float_significands_same_prec_w(*x, *x_exp, *y, y_exp, rm)
            } else {
                sub_float_significands_same_prec_lt_w(*x, *x_exp, *y, y_exp, prec, rm)
            };
            *x = diff;
            *x_exp = diff_exp;
            (o, false, neg)
        }
        (Natural(Large(xs)), Natural(Large(ys))) => match (xs.as_mut_slice(), ys.as_mut_slice()) {
            ([x_0, x_1], [y_0, y_1]) => {
                let (diff_0, diff_1, diff_exp, o, neg) = if prec == TWICE_WIDTH {
                    sub_float_significands_same_prec_2w(*x_0, *x_1, *x_exp, *y_0, *y_1, y_exp, rm)
                } else {
                    sub_float_significands_same_prec_gt_w_lt_2w(
                        *x_0, *x_1, *x_exp, *y_0, *y_1, y_exp, prec, rm,
                    )
                };
                if diff_1 == 0 {
                    *x = Natural::ZERO;
                } else {
                    *x_0 = diff_0;
                    *x_1 = diff_1;
                }
                *x_exp = diff_exp;
                (o, false, neg)
            }
            ([x_0, x_1, x_2], [y_0, y_1, y_2]) if prec != THRICE_WIDTH => {
                let (diff_0, diff_1, diff_2, diff_exp, o, neg) =
                    sub_float_significands_same_prec_gt_2w_lt_3w(
                        *x_0, *x_1, *x_2, *x_exp, *y_0, *y_1, *y_2, y_exp, prec, rm,
                    );
                if diff_2 == 0 {
                    *x = Natural::ZERO;
                } else {
                    *x_0 = diff_0;
                    *x_1 = diff_1;
                    *x_2 = diff_2;
                }
                *x_exp = diff_exp;
                (o, false, neg)
            }
            (xs, ys) => {
                let (diff_exp, o, neg) =
                    sub_float_significands_same_prec_ge_3w_val_val(xs, *x_exp, ys, y_exp, prec, rm);
                if *xs.last().unwrap() == 0 {
                    *x = Natural::ZERO;
                } else {
                    *x_exp = diff_exp;
                }
                (o, neg, neg)
            }
        },
        _ => unreachable!(),
    }
}

// This is mpfr_sub1sp from sub1sp.c, MPFR 4.2.0.
fn sub_float_significands_in_place_same_prec_ref(
    x: &mut Natural,
    x_exp: &mut i32,
    y: &Natural,
    y_exp: i32,
    prec: u64,
    rm: RoundingMode,
) -> (Ordering, bool) {
    match (&mut *x, y) {
        (Natural(Small(x)), Natural(Small(y))) => {
            let (diff, diff_exp, o, neg) = if prec == Limb::WIDTH {
                sub_float_significands_same_prec_w(*x, *x_exp, *y, y_exp, rm)
            } else {
                sub_float_significands_same_prec_lt_w(*x, *x_exp, *y, y_exp, prec, rm)
            };
            *x = diff;
            *x_exp = diff_exp;
            (o, neg)
        }
        (Natural(Large(xs)), Natural(Large(ys))) => match (xs.as_mut_slice(), ys.as_slice()) {
            ([x_0, x_1], &[y_0, y_1]) => {
                let (diff_0, diff_1, diff_exp, o, neg) = if prec == TWICE_WIDTH {
                    sub_float_significands_same_prec_2w(*x_0, *x_1, *x_exp, y_0, y_1, y_exp, rm)
                } else {
                    sub_float_significands_same_prec_gt_w_lt_2w(
                        *x_0, *x_1, *x_exp, y_0, y_1, y_exp, prec, rm,
                    )
                };
                if diff_1 == 0 {
                    *x = Natural::ZERO;
                } else {
                    *x_0 = diff_0;
                    *x_1 = diff_1;
                }
                *x_exp = diff_exp;
                (o, neg)
            }
            ([x_0, x_1, x_2], &[y_0, y_1, y_2]) if prec != THRICE_WIDTH => {
                let (diff_0, diff_1, diff_2, diff_exp, o, neg) =
                    sub_float_significands_same_prec_gt_2w_lt_3w(
                        *x_0, *x_1, *x_2, *x_exp, y_0, y_1, y_2, y_exp, prec, rm,
                    );
                if diff_2 == 0 {
                    *x = Natural::ZERO;
                } else {
                    *x_0 = diff_0;
                    *x_1 = diff_1;
                    *x_2 = diff_2;
                }
                *x_exp = diff_exp;
                (o, neg)
            }
            (xs, ys) => {
                let (diff_exp, o, neg) =
                    sub_float_significands_same_prec_ge_3w_val_ref(xs, *x_exp, ys, y_exp, prec, rm);
                if *xs.last().unwrap() == 0 {
                    *x = Natural::ZERO;
                } else {
                    *x_exp = diff_exp;
                }
                (o, neg)
            }
        },
        _ => unreachable!(),
    }
}

// This is mpfr_sub1sp from sub1sp.c, MPFR 4.2.0.
fn sub_float_significands_same_prec_ref_ref(
    x: &Natural,
    x_exp: i32,
    y: &Natural,
    y_exp: i32,
    prec: u64,
    rm: RoundingMode,
) -> (Natural, i32, Ordering, bool) {
    match (x, y) {
        (Natural(Small(x)), Natural(Small(y))) => {
            let (diff, diff_exp, o, neg) = if prec == Limb::WIDTH {
                sub_float_significands_same_prec_w(*x, x_exp, *y, y_exp, rm)
            } else {
                sub_float_significands_same_prec_lt_w(*x, x_exp, *y, y_exp, prec, rm)
            };
            (Natural(Small(diff)), diff_exp, o, neg)
        }
        (Natural(Large(xs)), Natural(Large(ys))) => match (xs.as_slice(), ys.as_slice()) {
            (&[x_0, x_1], &[y_0, y_1]) => {
                let (diff_0, diff_1, diff_exp, o, neg) = if prec == TWICE_WIDTH {
                    sub_float_significands_same_prec_2w(x_0, x_1, x_exp, y_0, y_1, y_exp, rm)
                } else {
                    sub_float_significands_same_prec_gt_w_lt_2w(
                        x_0, x_1, x_exp, y_0, y_1, y_exp, prec, rm,
                    )
                };
                (
                    if diff_1 == 0 {
                        Natural::ZERO
                    } else {
                        Natural(Large(vec![diff_0, diff_1]))
                    },
                    diff_exp,
                    o,
                    neg,
                )
            }
            (&[x_0, x_1, x_2], &[y_0, y_1, y_2]) if prec != THRICE_WIDTH => {
                let (diff_0, diff_1, diff_2, diff_exp, o, neg) =
                    sub_float_significands_same_prec_gt_2w_lt_3w(
                        x_0, x_1, x_2, x_exp, y_0, y_1, y_2, y_exp, prec, rm,
                    );
                (
                    if diff_2 == 0 {
                        Natural::ZERO
                    } else {
                        Natural(Large(vec![diff_0, diff_1, diff_2]))
                    },
                    diff_exp,
                    o,
                    neg,
                )
            }
            (xs, ys) => {
                let mut out = vec![0; xs.len()];
                let (diff_exp, o, neg) = sub_float_significands_same_prec_ge_3w_ref_ref(
                    &mut out, xs, x_exp, ys, y_exp, prec, rm,
                );
                (
                    if slice_test_zero(&out) {
                        Natural::ZERO
                    } else {
                        Natural(Large(out))
                    },
                    diff_exp,
                    o,
                    neg,
                )
            }
        },
        _ => unreachable!(),
    }
}

// This is mpfr_sub1sp1 from sub1sp.c, MPFR 4.2.0.
fn sub_float_significands_same_prec_lt_w(
    mut x: Limb,
    mut x_exp: i32,
    mut y: Limb,
    mut y_exp: i32,
    prec: u64,
    mut rm: RoundingMode,
) -> (Limb, i32, Ordering, bool) {
    {
        let (mut diff, sticky_bit, round_bit, shift_bit, neg) = if x_exp == y_exp {
            let (a0, neg) = match x.cmp(&y) {
                Equal => return (0, 0, Equal, false),
                Less => (y - x, true),
                Greater => (x - y, false),
            };
            let leading_zeros = a0.leading_zeros();
            x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
            (a0 << leading_zeros, 0, 0, 0, neg)
        } else {
            let neg = x_exp < y_exp;
            if neg {
                // swap x and y
                swap(&mut x_exp, &mut y_exp);
                swap(&mut x, &mut y);
            }
            let exp_diff = u64::exact_from(x_exp - y_exp);
            let shift = Limb::WIDTH - prec;
            let shift_bit = Limb::power_of_2(shift);
            let mask = shift_bit - 1;
            if exp_diff < Limb::WIDTH {
                // neglected part of -y
                let mut sticky_bit = (y << (Limb::WIDTH - exp_diff)).wrapping_neg();
                let mut a0 = x - Limb::from(sticky_bit != 0) - (y >> exp_diff);
                // a0 cannot be zero here since:
                // - if exp_diff >= 2, then a0 >= 2^(w-1) - (2^(w-2)-1) with w = Limb::WIDTH, thus
                //   a0 - 1 >= 2 ^ (w - 2),
                // - if exp_diff = 1, then since prec < Limb::WIDTH we have sticky_bit = 0.
                //
                assert_ne!(a0, 0);
                let leading_zeros = LeadingZeros::leading_zeros(a0);
                if leading_zeros != 0 {
                    a0 = (a0 << leading_zeros) | (sticky_bit >> (Limb::WIDTH - leading_zeros));
                }
                sticky_bit <<= leading_zeros;
                x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
                // shift > 0 since prec < Limb::WIDTH
                assert_ne!(shift, 0);
                let round_bit = a0 & (shift_bit >> 1);
                (
                    a0 & !mask,
                    sticky_bit | (a0 & mask) ^ round_bit,
                    round_bit,
                    shift_bit,
                    neg,
                )
            } else if x > LIMB_HIGH_BIT {
                // We compute x - ulp(x), and the remainder ulp(x) - y satisfies: 1/2 ulp(x) <
                // ulp(x) - y < ulp(x), thus round_bit = sticky_bit = 1.
                (x - shift_bit, 1, 1, shift_bit, neg)
            } else {
                // - Warning: since we have an exponent decrease, when prec = Limb::WIDTH - 1 and d
                //   = Limb::WIDTH, the round bit corresponds to the upper bit of -y. In that case
                //   round_bit = 0 and sticky_bit = 1, except when y0 = LIMB_HIGH_BIT where
                //   round_bit = 1 and sticky_bit = 0.
                // - sticky_bit = 1 below is incorrect when prec = Limb::WIDTH - 1, exp_diff =
                //   Limb::WIDTH and y0 = LIMB_HIGH_BIT, but in that case the even rule would round
                //   up too.
                // - Warning: if exp_diff = Limb::WIDTH and y0 = 1000...000, then x0 - y0 =
                //   |0111...111|1000...000|, which after the shift becomes |111...111|000...000|
                //   thus if prec = Limb::WIDTH - 1 we have round_bit = 1 but sticky_bit = 0.
                //   However, in this case the round even rule will round up, which is what we get
                //   with sticky_bit = 1: the final result will be correct, while sb is incorrect.
                x_exp.saturating_sub_assign(1);
                (
                    !mask,
                    1,
                    Limb::from(shift > 1 || exp_diff > Limb::WIDTH || y == LIMB_HIGH_BIT),
                    shift_bit,
                    neg,
                )
            }
        };
        if round_bit == 0 && sticky_bit == 0 {
            (diff, x_exp, Equal, neg)
        } else {
            if neg {
                rm.neg_assign();
            }
            match rm {
                Exact => panic!("Inexact float subtraction"),
                Nearest => {
                    if round_bit == 0 || (sticky_bit == 0 && (diff & shift_bit) == 0) {
                        (diff, x_exp, Less, neg)
                    } else if diff.overflowing_add_assign(shift_bit) {
                        (LIMB_HIGH_BIT, x_exp.saturating_add(1), Greater, neg)
                    } else {
                        (diff, x_exp, Greater, neg)
                    }
                }
                Floor | Down => (diff, x_exp, Less, neg),
                Ceiling | Up => {
                    if diff.overflowing_add_assign(shift_bit) {
                        (LIMB_HIGH_BIT, x_exp.saturating_add(1), Greater, neg)
                    } else {
                        (diff, x_exp, Greater, neg)
                    }
                }
            }
        }
    }
}

// This is mpfr_sub1sp1n from sub1sp.c, MPFR 4.2.0.
fn sub_float_significands_same_prec_w(
    mut x: Limb,
    mut x_exp: i32,
    mut y: Limb,
    mut y_exp: i32,
    mut rm: RoundingMode,
) -> (Limb, i32, Ordering, bool) {
    let (mut diff, sticky_bit, round_bit, neg) = if x_exp == y_exp {
        let (a0, neg) = match x.cmp(&y) {
            Equal => return (0, 0, Equal, false),
            Less => (y - x, true),
            Greater => (x - y, false),
        };
        let leading_zeros = LeadingZeros::leading_zeros(a0);
        x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
        (a0 << leading_zeros, 0, 0, neg)
    } else {
        let neg = x_exp < y_exp;
        if neg {
            // swap x and y
            swap(&mut x_exp, &mut y_exp);
            swap(&mut x, &mut y);
        }
        let exp_diff = u64::exact_from(x_exp - y_exp);
        if exp_diff < Limb::WIDTH {
            let mut sticky_bit = (y << (Limb::WIDTH - exp_diff)).wrapping_neg();
            let mut a0 = x.wrapping_sub(y >> exp_diff);
            if sticky_bit != 0 {
                a0.wrapping_sub_assign(1);
            }
            // a0 can only be zero when exp_diff = 1, x0 = B / 2, and y0 = B-1, where B = 2 ^
            // Limb::WIDTH, thus x0 - y0 / 2 = 1/2
            if a0 == 0 {
                x_exp.saturating_sub_assign(IWIDTH);
                (LIMB_HIGH_BIT, 0, 0, neg)
            } else {
                let leading_zeros = LeadingZeros::leading_zeros(a0);
                if leading_zeros != 0 {
                    a0 = (a0 << leading_zeros) | (sticky_bit >> (Limb::WIDTH - leading_zeros));
                }
                sticky_bit <<= leading_zeros;
                x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
                let round_bit = sticky_bit & LIMB_HIGH_BIT;
                (a0, sticky_bit & !LIMB_HIGH_BIT, round_bit, neg)
            }
        } else {
            // We compute x - ulp(x)
            if x > LIMB_HIGH_BIT {
                // If exp_diff = Limb::WIDTH, round_bit = 0 and sticky_bit = 1, unless c0 =
                // LIMB_HIGH_BIT in which case round_bit = 1 and sticky_bit = 0. If exp_diff >
                // Limb::WIDTH, round_bit = sticky_bit = 1.
                let b = exp_diff > Limb::WIDTH;
                (
                    x - 1,
                    Limb::from(b || y != LIMB_HIGH_BIT),
                    Limb::from(b || y == LIMB_HIGH_BIT),
                    neg,
                )
            } else {
                // Warning: in this case a0 is shifted by one!
                //
                // If exp_diff = Limb::WIDTH
                // - a) If y0 = LIMB_HIGH_BIT, a0 = 111...111, round_bit = sticky_bit = 0
                // - b) Otherwise, a0 = 111...110, round_bit = -y0 >= 01000...000, sticky_bit =
                //   (-y0) << 2
                //
                // If exp_diff = Limb::WIDTH + 1: a0 = 111...111
                // - c) If y0 = LIMB_HIGH_BIT, round_bit = 1 and sticky_bit = 0
                // - d) Otherwise round_bit = 0 and sticky_bit = 1
                //
                // If exp_diff > Limb::WIDTH + 1:
                // - e) a0 = 111...111, round_bit = sticky_bit = 1
                x_exp.saturating_sub_assign(1);
                if exp_diff == Limb::WIDTH && y > LIMB_HIGH_BIT {
                    // case (b)
                    (
                        NEG_TWO,
                        y.wrapping_neg() << 2,
                        Limb::from(y.wrapping_neg() >= (LIMB_HIGH_BIT >> 1)),
                        neg,
                    )
                } else {
                    // cases (a), (c), (d) and (e)
                    // - round_bit = 1 in case (e) and case (c)
                    // - sticky_bit = 1 in case (d) and (e)
                    let b1 = exp_diff > WIDTH_P1;
                    let b2 = exp_diff == WIDTH_P1;
                    (
                        NEG_ONE,
                        Limb::from(b1 || (b2 && y > LIMB_HIGH_BIT)),
                        Limb::from(b1 || (b2 && y == LIMB_HIGH_BIT)),
                        neg,
                    )
                }
            }
        }
    };
    if round_bit == 0 && sticky_bit == 0 {
        (diff, x_exp, Equal, neg)
    } else {
        if neg {
            rm.neg_assign();
        }
        match rm {
            Exact => panic!("Inexact float subtraction"),
            Nearest => {
                if round_bit == 0 || (sticky_bit == 0 && (diff & 1) == 0) {
                    (diff, x_exp, Less, neg)
                } else if diff.overflowing_add_assign(1) {
                    (LIMB_HIGH_BIT, x_exp.saturating_add(1), Greater, neg)
                } else {
                    (diff, x_exp, Greater, neg)
                }
            }
            Floor | Down => (diff, x_exp, Less, neg),
            Ceiling | Up => {
                if diff.overflowing_add_assign(1) {
                    (LIMB_HIGH_BIT, x_exp.saturating_add(1), Greater, neg)
                } else {
                    (diff, x_exp, Greater, neg)
                }
            }
        }
    }
}

// This is mpfr_sub1sp2 from sub1sp.c, MPFR 4.2.0.
fn sub_float_significands_same_prec_gt_w_lt_2w(
    mut x_0: Limb,
    mut x_1: Limb,
    mut x_exp: i32,
    mut y_0: Limb,
    mut y_1: Limb,
    mut y_exp: i32,
    prec: u64,
    mut rm: RoundingMode,
) -> (Limb, Limb, i32, Ordering, bool) {
    let (mut diff_0, mut diff_1, sticky_bit, round_bit, shift_bit, neg) = if x_exp == y_exp {
        // subtraction is exact in this case
        //
        // first compute a0: if the compiler is smart enough, it will use the generated borrow to
        // get for free the term (x_0 < y_0)
        let (mut a0, overflow) = x_0.overflowing_sub(y_0);
        let mut a1 = x_1.wrapping_sub(y_1);
        if overflow {
            a1.wrapping_sub_assign(1);
        }
        let neg = if a1 == 0 && a0 == 0 {
            return (0, 0, 0, Equal, false);
        } else if a1 >= x_1 {
            // out = x - y mod 2 ^ (2 * Limb::WIDTH)
            let overflow = a0.overflowing_neg_assign();
            a1.wrapping_neg_assign();
            if overflow {
                a1.wrapping_sub_assign(1);
            }
            true
        } else {
            false
        };
        if a1 == 0 {
            a1 = a0;
            a0 = 0;
            x_exp.saturating_sub_assign(IWIDTH);
        }
        // now a1 != 0
        let leading_zeros = LeadingZeros::leading_zeros(a1);
        if leading_zeros != 0 {
            x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
            (
                a0 << leading_zeros,
                (a1 << leading_zeros) | (a0 >> (Limb::WIDTH - leading_zeros)),
                0,
                0,
                0,
                neg,
            )
        } else {
            (a0, a1, 0, 0, 0, neg)
        }
    } else {
        let neg = x_exp < y_exp;
        if neg {
            swap(&mut x_exp, &mut y_exp);
            swap(&mut x_0, &mut y_0);
            swap(&mut x_1, &mut y_1);
        }
        let exp_diff = u64::exact_from(x_exp - y_exp);
        let shift = TWICE_WIDTH - prec;
        let shift_bit = Limb::power_of_2(shift);
        let mask = shift_bit - 1;
        if exp_diff < Limb::WIDTH {
            let comp_diff = Limb::WIDTH - exp_diff;
            let t = (y_1 << comp_diff) | (y_0 >> exp_diff);
            let (mut sticky_bit, overflow_1) = (y_0 << comp_diff).overflowing_neg();
            let (mut a0, overflow_2) = x_0.overflowing_sub(t);
            if overflow_1 {
                a0.wrapping_sub_assign(1);
            }
            let mut a1 = x_1.wrapping_sub(y_1 >> exp_diff);
            if overflow_2 || (x_0 == t && overflow_1) {
                a1.wrapping_sub_assign(1);
            }
            if a1 == 0 {
                // This implies exp_diff = 1, which in turn implies sticky_bit = 0
                assert_eq!(sticky_bit, 0);
                a1 = a0;
                a0 = 0;
                // Since sticky_bit = 0 already, no need to set it to 0
                x_exp.saturating_sub_assign(IWIDTH);
            }
            // now a1 != 0
            assert_ne!(a1, 0);
            let leading_zeros = LeadingZeros::leading_zeros(a1);
            let diff_1 = if leading_zeros != 0 {
                let comp_zeros = Limb::WIDTH - leading_zeros;
                let diff_1 = (a1 << leading_zeros) | (a0 >> comp_zeros);
                a0 = (a0 << leading_zeros) | (sticky_bit >> comp_zeros);
                sticky_bit <<= leading_zeros;
                x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
                diff_1
            } else {
                a1
            };
            // shift > 0 since prec < 2 * Limb::WIDTH
            assert_ne!(shift, 0);
            let round_bit = a0 & (shift_bit >> 1);
            (
                a0 & !mask,
                diff_1,
                sticky_bit | ((a0 & mask) ^ round_bit),
                round_bit,
                shift_bit,
                neg,
            )
        } else if exp_diff < TWICE_WIDTH {
            // Warning: the most significant bit of sticky_bit might become the least significant
            // bit of a0 below
            let mut sticky_bit = if exp_diff == Limb::WIDTH {
                y_0
            } else {
                let mut sticky_bit = y_1 << (TWICE_WIDTH - exp_diff);
                if y_0 != 0 {
                    sticky_bit |= 1;
                }
                sticky_bit
            };
            let mut t = y_1 >> (exp_diff - Limb::WIDTH);
            if sticky_bit != 0 {
                t.wrapping_add_assign(1);
            }
            // Warning: t might overflow to 0 if exp_diff == Limb::WIDTH and sticky_bit != 0
            let (mut a0, overflow) = x_0.overflowing_sub(t);
            let mut a1 = x_1;
            if overflow {
                a1.wrapping_sub_assign(1);
            }
            if t == 0 && sticky_bit != 0 {
                a1.wrapping_sub_assign(1);
            }
            sticky_bit.wrapping_neg_assign();
            // since x_1 has its most significant bit set, we can have an exponent decrease of at
            // most one
            let diff_1 = if a1 < LIMB_HIGH_BIT {
                let diff_1 = (a1 << 1) | (a0 >> WIDTH_M1);
                a0 = (a0 << 1) | (sticky_bit >> WIDTH_M1);
                sticky_bit <<= 1;
                x_exp.saturating_sub_assign(1);
                diff_1
            } else {
                a1
            };
            let round_bit = a0 & (shift_bit >> 1);
            (
                a0 & !mask,
                diff_1,
                sticky_bit | ((a0 & mask) ^ round_bit),
                round_bit,
                shift_bit,
                neg,
            )
        } else {
            // We compute x - ulp(x), and the remainder ulp(x) - y satisfies: 1/2 ulp(x) < ulp(x) -
            // y < ulp(x), thus round_bit = sticky_bit = 1, unless we had an exponent decrease.
            let t = shift_bit;
            let (a0, overflow) = x_0.overflowing_sub(t);
            let mut a1 = x_1;
            if overflow {
                a1.wrapping_sub_assign(1);
            }
            if a1 < LIMB_HIGH_BIT {
                // Necessarily we had x = 1000...000
                //
                // Warning: since we have an exponent decrease, when prec = Limb::WIDTH * 2 - 1 and
                // exp_diff = Limb::WIDTH * 2, the round bit corresponds to the upper bit of -y. In
                // that case round_bit = 0 and sticky_bit = 1, except when y = 1000...000 where
                // round_bit = 1 and sticky_bit = 0.
                //
                // sticky_bit = 1 below is incorrect when prec = Limb::WIDTH * 2 - 1, exp_diff =
                // Limb::WIDTH * 2, and y = 1000...000, but in that case the even rule would round
                // up too.
                x_exp.saturating_sub_assign(1);
                (
                    !mask,
                    Limb::MAX,
                    1,
                    Limb::from(
                        shift > 1 || exp_diff > TWICE_WIDTH || (y_1 == LIMB_HIGH_BIT && y_0 == 0),
                    ),
                    shift_bit,
                    neg,
                )
            } else {
                (a0, a1, 1, 1, shift_bit, neg)
            }
        }
    };
    if round_bit == 0 && sticky_bit == 0 {
        (diff_0, diff_1, x_exp, Equal, neg)
    } else {
        if neg {
            rm.neg_assign();
        }
        match rm {
            Exact => panic!("Inexact float subtraction"),
            Nearest => {
                if round_bit == 0 || (sticky_bit == 0 && (diff_0 & shift_bit) == 0) {
                    (diff_0, diff_1, x_exp, Less, neg)
                } else if diff_0.overflowing_add_assign(shift_bit)
                    && diff_1.overflowing_add_assign(1)
                {
                    (diff_0, LIMB_HIGH_BIT, x_exp.saturating_add(1), Greater, neg)
                } else {
                    (diff_0, diff_1, x_exp, Greater, neg)
                }
            }
            Floor | Down => (diff_0, diff_1, x_exp, Less, neg),
            Ceiling | Up => {
                if diff_0.overflowing_add_assign(shift_bit) && diff_1.overflowing_add_assign(1) {
                    (diff_0, LIMB_HIGH_BIT, x_exp.saturating_add(1), Greater, neg)
                } else {
                    (diff_0, diff_1, x_exp, Greater, neg)
                }
            }
        }
    }
}

// This is mpfr_sub1sp2n from add1sp.c, MPFR 4.2.0.
fn sub_float_significands_same_prec_2w(
    mut x_0: Limb,
    mut x_1: Limb,
    mut x_exp: i32,
    mut y_0: Limb,
    mut y_1: Limb,
    mut y_exp: i32,
    mut rm: RoundingMode,
) -> (Limb, Limb, i32, Ordering, bool) {
    let (mut diff_0, mut diff_1, sticky_bit, round_bit, neg) = if x_exp == y_exp {
        let (mut a0, overflow) = x_0.overflowing_sub(y_0);
        let mut a1 = x_1.wrapping_sub(y_1);
        if overflow {
            a1.wrapping_sub_assign(1);
        }
        let neg = if a1 == 0 && a0 == 0 {
            return (0, 0, 0, Equal, false);
        } else if a1 >= x_1 {
            // since B/2 <= x_1, y_1 < B with B = 2 ^ Limb::WIDTH, if no borrow we have 0 <= x_1 -
            // y_1 - x < B / 2, where x = (x_0 < y_0) is 0 or 1, thus a1 < B / 2 <= x_1
            //
            // negate [a1,a0]
            let overflow = a0.overflowing_neg_assign();
            a1.wrapping_neg_assign();
            if overflow {
                a1.wrapping_sub_assign(1);
            }
            true
        } else {
            false
        };
        // now [a1,a0] is the absolute value of x - y, maybe not normalized
        if a1 == 0 {
            a1 = a0;
            a0 = 0;
            x_exp.saturating_sub_assign(IWIDTH);
        }
        let leading_zeros = LeadingZeros::leading_zeros(a1);
        if leading_zeros != 0 {
            // shift [a1, a0] left by leading_zeros bits and store in result
            x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
            (
                a0 << leading_zeros,
                (a1 << leading_zeros) | (a0 >> (Limb::WIDTH - leading_zeros)),
                0,
                0,
                neg,
            )
        } else {
            (a0, a1, 0, 0, neg)
        }
    } else {
        let neg = x_exp < y_exp;
        if neg {
            swap(&mut x_exp, &mut y_exp);
            swap(&mut x_0, &mut y_0);
            swap(&mut x_1, &mut y_1);
        }
        let exp_diff = u64::exact_from(x_exp - y_exp);
        if exp_diff < Limb::WIDTH {
            let comp_diff = Limb::WIDTH - exp_diff;
            let t = (y_1 << comp_diff) | (y_0 >> exp_diff);
            // t is the part that should be subtracted to x_0:
            // ```
            // |      a1       |      a0       |
            // |     x_1       |     x_0       |
            // |    y_1 >> d   |      t        |     sticky_bit     |
            // ```
            let (mut sticky_bit, overflow_1) = (y_0 << comp_diff).overflowing_neg();
            let (mut a0, overflow_2) = x_0.overflowing_sub(t);
            if overflow_1 {
                a0.wrapping_sub_assign(1);
            }
            let mut a1 = x_1.wrapping_sub(y_1 >> exp_diff);
            if overflow_2 || (x_0 == t && overflow_1) {
                a1.wrapping_sub_assign(1);
            }
            // Now the result is formed of [a1,a0,sticky_bit], which might not be normalized
            if a1 == 0 {
                // this implies d = 1
                assert_eq!(exp_diff, 1);
                a1 = a0;
                a0 = sticky_bit;
                sticky_bit = 0;
                x_exp.saturating_sub_assign(IWIDTH);
            }
            if a1 == 0 {
                assert_eq!(a0, LIMB_HIGH_BIT);
                x_exp.saturating_sub_assign(IWIDTH);
                (sticky_bit, a0, 0, 0, neg)
            } else {
                let leading_zeros = LeadingZeros::leading_zeros(a1);
                if leading_zeros != 0 {
                    let comp_zeros = Limb::WIDTH - leading_zeros;
                    // shift [a1, a0, sticky_bit] left by leading_zeros bits and adjust exponent
                    a1 = (a1 << leading_zeros) | (a0 >> comp_zeros);
                    a0 = (a0 << leading_zeros) | (sticky_bit >> comp_zeros);
                    sticky_bit <<= leading_zeros;
                    x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
                }
                (
                    a0,
                    a1,
                    sticky_bit & !LIMB_HIGH_BIT,
                    sticky_bit & LIMB_HIGH_BIT,
                    neg,
                )
            }
        } else if exp_diff < TWICE_WIDTH {
            // Compute t, the part to be subtracted to x_0, and sticky_bit, the neglected part of y:
            //
            // ```
            // |      a1       |      a0       |
            // |     diff_1    |     diff_0    |
            //                 |      t        |     sticky_bit     |
            // ```
            //
            // Warning: we should not ignore the low bits from y_0 in case exp_diff > Limb::WIDTH
            let comp_diff_1 = exp_diff - Limb::WIDTH;
            let comp_diff_2 = TWICE_WIDTH - exp_diff;
            let mut sticky_bit = if comp_diff_1 == 0 {
                y_0
            } else {
                let mut sticky_bit = (y_1 << comp_diff_2) | (y_0 >> comp_diff_1);
                if y_0 << comp_diff_2 != 0 {
                    sticky_bit |= 1;
                }
                sticky_bit
            };
            let mut t = y_1 >> comp_diff_1;
            if sticky_bit != 0 {
                t.wrapping_add_assign(1);
            }
            // Warning: t might overflow to 0 if exp_diff = Limb::WIDTH, sticky_bit != 0, and y_1 =
            // 111...111.
            let (mut a0, overflow) = x_0.overflowing_sub(t);
            let mut a1 = x_1;
            if overflow {
                a1.wrapping_sub_assign(1);
            }
            if t == 0 && sticky_bit != 0 {
                a1.wrapping_sub_assign(1);
            }
            sticky_bit.wrapping_neg_assign();
            // Now the result is [a1, a0, sticky_bit]. Since x_1 has its most significant bit set,
            // we can have an exponent decrease of at most one
            if a1 < LIMB_HIGH_BIT {
                // shift [a1, a0] left by 1 bit
                a1 = (a1 << 1) | (a0 >> WIDTH_M1);
                assert!(a1 >= LIMB_HIGH_BIT);
                a0 = (a0 << 1) | (sticky_bit >> WIDTH_M1);
                sticky_bit <<= 1;
                x_exp.saturating_sub_assign(1);
            }
            (
                a0,
                a1,
                sticky_bit & !LIMB_HIGH_BIT,
                sticky_bit & LIMB_HIGH_BIT,
                neg,
            )
        } else {
            // ```
            // |      a1       |      a0       |
            // |      x_1      |      x_0      |
            //                                 |   y_1   |   y_0   |
            // ```
            let tst = y_1 == LIMB_HIGH_BIT && y_0 == 0;
            // if exp_diff = Limb::WIDTH * 2 and tst = 1, y = 1 / 2 * ulp(x)
            if x_1 > LIMB_HIGH_BIT || x_0 > 0 {
                let g = exp_diff > TWICE_WIDTH;
                let mut diff_1 = x_1;
                if x_0 == 0 {
                    diff_1.wrapping_sub_assign(1);
                }
                // no borrow in x - ulp(x)
                (
                    x_0.wrapping_sub(1),
                    diff_1,
                    Limb::from(g || !tst),
                    Limb::from(g || tst),
                    neg,
                )
            } else {
                // x = 1000...000, thus subtracting y yields an exponent shift
                x_exp.saturating_sub_assign(1);
                if exp_diff == TWICE_WIDTH && !tst {
                    // y > 1 / 2 * ulp(x)
                    let mut t = y_1.wrapping_neg();
                    if y_0 != 0 {
                        t.wrapping_sub_assign(1);
                    }
                    // The rounding bit is the 2nd most-significant bit of t (where the most
                    // significant bit of t is necessarily 0), and the sticky bit is formed by the
                    // remaining bits of t, and those from -y_0.
                    (
                        NEG_TWO,
                        Limb::MAX,
                        (t << 2) | y_0,
                        Limb::from(t >= HALF_LIMB_HIGH_BIT),
                        neg,
                    )
                } else {
                    // y <= 1 / 2 * ulp(x)
                    let g = exp_diff > TWICE_WIDTH_P1;
                    (
                        NEG_ONE,
                        NEG_ONE,
                        Limb::from(g || (exp_diff == TWICE_WIDTH_P1 && !tst)),
                        Limb::from(g || (exp_diff == TWICE_WIDTH_P1 && tst)),
                        neg,
                    )
                }
            }
        }
    };
    if round_bit == 0 && sticky_bit == 0 {
        (diff_0, diff_1, x_exp, Equal, neg)
    } else {
        if neg {
            rm.neg_assign();
        }
        match rm {
            Exact => panic!("Inexact float subtraction"),
            Nearest => {
                if round_bit == 0 || (sticky_bit == 0 && (diff_0 & 1) == 0) {
                    (diff_0, diff_1, x_exp, Less, neg)
                } else if diff_0.overflowing_add_assign(1) && diff_1.overflowing_add_assign(1) {
                    (diff_0, LIMB_HIGH_BIT, x_exp.saturating_add(1), Greater, neg)
                } else {
                    (diff_0, diff_1, x_exp, Greater, neg)
                }
            }
            Floor | Down => (diff_0, diff_1, x_exp, Less, neg),
            Ceiling | Up => {
                if diff_0.overflowing_add_assign(1) && diff_1.overflowing_add_assign(1) {
                    (diff_0, LIMB_HIGH_BIT, x_exp.saturating_add(1), Greater, neg)
                } else {
                    (diff_0, diff_1, x_exp, Greater, neg)
                }
            }
        }
    }
}

// This is mpfr_sub1sp3 from add1sp.c, MPFR 4.2.0.
fn sub_float_significands_same_prec_gt_2w_lt_3w(
    mut x_0: Limb,
    mut x_1: Limb,
    mut x_2: Limb,
    mut x_exp: i32,
    mut y_0: Limb,
    mut y_1: Limb,
    mut y_2: Limb,
    mut y_exp: i32,
    prec: u64,
    mut rm: RoundingMode,
) -> (Limb, Limb, Limb, i32, Ordering, bool) {
    let (mut diff_0, mut diff_1, mut diff_2, sticky_bit, round_bit, shift_bit, neg) = if x_exp
        == y_exp
    {
        let (mut a0, overflow_1) = x_0.overflowing_sub(y_0);
        let (mut a1, overflow_2) = x_1.overflowing_sub(y_1);
        if overflow_1 {
            a1.wrapping_sub_assign(1);
        }
        // A borrow is generated for diff when either x_1 < y_1 or x_1 = y_1 and x_0 < y_0.
        let mut a2 = x_2.wrapping_sub(y_2);
        if overflow_2 || x_1 == y_1 && overflow_1 {
            a2.wrapping_sub_assign(1);
        }
        let neg = if a2 == 0 && a1 == 0 && a0 == 0 {
            return (0, 0, 0, 0, Equal, false);
        } else if a2 >= x_2 {
            // a = x - y mod 2 ^ (3 * Limb::WIDTH)
            let overflow_1 = a0.overflowing_neg_assign();
            a1.wrapping_neg_assign();
            if overflow_1 {
                a1.wrapping_sub_assign(1);
            }
            a2.wrapping_neg_assign();
            if overflow_1 || a1 != 0 {
                a2.wrapping_sub_assign(1);
            }
            true
        } else {
            false
        };
        if a2 == 0 {
            a2 = a1;
            a1 = a0;
            a0 = 0;
            x_exp.saturating_sub_assign(IWIDTH);
            if a2 == 0 {
                a2 = a1;
                a1 = 0;
                x_exp.saturating_sub_assign(IWIDTH);
            }
        }
        assert_ne!(a2, 0);
        let leading_zeros = LeadingZeros::leading_zeros(a2);
        if leading_zeros != 0 {
            x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
            let comp_zeros = Limb::WIDTH - leading_zeros;
            (
                a0 << leading_zeros,
                (a1 << leading_zeros) | (a0 >> comp_zeros),
                (a2 << leading_zeros) | (a1 >> comp_zeros),
                0,
                0,
                0,
                neg,
            )
        } else {
            (a0, a1, a2, 0, 0, 0, neg)
        }
    } else {
        let neg = x_exp < y_exp;
        if neg {
            swap(&mut x_exp, &mut y_exp);
            swap(&mut x_0, &mut y_0);
            swap(&mut x_1, &mut y_1);
            swap(&mut x_2, &mut y_2);
        }
        let exp_diff = u64::exact_from(x_exp - y_exp);
        let shift = THRICE_WIDTH - prec;
        let shift_bit = Limb::power_of_2(shift);
        let mask = shift_bit - 1;
        if exp_diff < Limb::WIDTH {
            // Warning: we must have the most significant bit of sticky_bit correct since it might
            // become the round bit below
            let comp_diff = Limb::WIDTH - exp_diff;
            let mut sticky_bit = y_0 << comp_diff;
            let (mut a0, overflow) = x_0.overflowing_sub((y_1 << comp_diff) | (y_0 >> exp_diff));
            let mut a1 = x_1.wrapping_sub((y_2 << comp_diff) | (y_1 >> exp_diff));
            if overflow {
                a1.wrapping_sub_assign(1);
            }
            let carry = a1 > x_1 || (a1 == x_1 && overflow);
            let mut a2 = x_2.wrapping_sub(y_2 >> exp_diff);
            if carry {
                a2.wrapping_sub_assign(1);
            }
            // if sticky_bit is non-zero, subtract 1 from a2, a1, a0 since we want a non-negative
            // neglected part
            if sticky_bit != 0 {
                if a1 == 0 && a0 == 0 {
                    a2.wrapping_sub_assign(1);
                }
                if a0 == 0 {
                    a1.wrapping_sub_assign(1);
                }
                a0.wrapping_sub_assign(1);
                // a = a2, a1, a0 cannot become zero here, since:
                // - if exp_diff >= 2, then a2 >= 2 ^ (w - 1) - (2 ^ (w - 2) - 1) with w =
                //   Limb::WIDTH, thus a2 - 1 >= 2 ^ (w - 2),
                // - if exp_diff = 1, then since prec < 3 * Limb::WIDTH we have sticky_bit = 0.
                assert!(a2 > 0 || a1 > 0 || a0 > 0);
                // 2 ^ Limb::WIDTH - sticky_bit
                sticky_bit.wrapping_neg_assign();
            }
            if a2 == 0 {
                // this implies exp_diff = 1, which in turn implies sticky_bit = 0
                assert_eq!(sticky_bit, 0);
                a2 = a1;
                a1 = a0;
                a0 = 0;
                // since sticky_bit = 0 already, no need to set it to 0
                x_exp.saturating_sub_assign(IWIDTH);
                if a2 == 0 {
                    a2 = a1;
                    a1 = 0;
                    x_exp.saturating_sub_assign(IWIDTH);
                }
            }
            assert_ne!(a2, 0);
            let leading_zeros = LeadingZeros::leading_zeros(a2);
            let (diff_1, diff_2) = if leading_zeros != 0 {
                let comp_zeros = Limb::WIDTH - leading_zeros;
                let diff_1 = (a1 << leading_zeros) | (a0 >> comp_zeros);
                a0 = (a0 << leading_zeros) | (sticky_bit >> comp_zeros);
                sticky_bit <<= leading_zeros;
                x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
                (diff_1, (a2 << leading_zeros) | (a1 >> comp_zeros))
            } else {
                (a1, a2)
            };
            // shift > 0 since prec < 2 * Limb::WIDTH
            assert_ne!(shift, 0);
            let round_bit = a0 & (shift_bit >> 1);
            (
                a0 & !mask,
                diff_1,
                diff_2,
                sticky_bit | (a0 & mask) ^ round_bit,
                round_bit,
                shift_bit,
                neg,
            )
        } else if exp_diff < TWICE_WIDTH {
            // Warning: we must have the most significant bit of sticky_bit correct since it might
            // become the round bit below
            let comp_diff = exp_diff - Limb::WIDTH;
            let (mut sticky_bit, y0shifted) = if exp_diff == Limb::WIDTH {
                (y_0, y_1)
            } else {
                let comp_diff_2 = TWICE_WIDTH - exp_diff;
                let mut sticky_bit = y_1 << comp_diff_2;
                if y_0 != 0 {
                    sticky_bit |= 1;
                }
                (sticky_bit, (y_2 << comp_diff_2) | (y_1 >> comp_diff))
            };
            let (mut a0, overflow) = x_0.overflowing_sub(y0shifted);
            let mut a1 = x_1.wrapping_sub(y_2 >> comp_diff);
            if overflow {
                a1.wrapping_sub_assign(1);
            }
            let mut a2 = x_2;
            if a1 > x_1 || (a1 == x_1 && overflow) {
                a2.wrapping_sub_assign(1);
            }
            // if sticky_bit is non-zero, subtract 1 from a2, a1, a0 since we want a non-negative
            // neglected part
            if sticky_bit != 0 {
                if a1 == 0 && a0 == 0 {
                    a2.wrapping_sub_assign(1);
                }
                if a0 == 0 {
                    a1.wrapping_sub_assign(1);
                }
                a0.wrapping_sub_assign(1);
                // a = a2, a1, a0 cannot become zero here, since:
                // - if exp_diff >= 2, then a2 >= 2 ^ (w - 1) - (2 ^ (w - 2) - 1) with w =
                //   Limb::WIDTH, thus a2 - 1 >= 2 ^ (w - 2),
                // - if exp_diff = 1, then since p < 3 * Limb::WIDTH we have sticky_bit = 0.
                assert!(a2 > 0 || a1 > 0 || a0 > 0);
                // 2 ^ Limb::WIDTH - sticky_bit
                sticky_bit.wrapping_neg_assign();
            }
            // since x_2 has its most significant bit set, we can have an exponent decrease of at
            // most one
            let (diff_1, diff_2) = if a2 < LIMB_HIGH_BIT {
                let diff_1 = (a1 << 1) | (a0 >> WIDTH_M1);
                a0 = (a0 << 1) | (sticky_bit >> WIDTH_M1);
                sticky_bit <<= 1;
                x_exp.saturating_sub_assign(1);
                (diff_1, (a2 << 1) | (a1 >> WIDTH_M1))
            } else {
                (a1, a2)
            };
            let round_bit = a0 & (shift_bit >> 1);
            (
                a0 & !mask,
                diff_1,
                diff_2,
                sticky_bit | (a0 & mask) ^ round_bit,
                round_bit,
                shift_bit,
                neg,
            )
        } else if exp_diff < THRICE_WIDTH {
            // warning: we must have the most significant bit of sticky_bit correct since it might
            // become the round bit below
            let mut sticky_bit;
            if exp_diff == TWICE_WIDTH {
                sticky_bit = y_1;
                if y_0 != 0 {
                    sticky_bit |= 1;
                }
            } else {
                sticky_bit = y_2 << (THRICE_WIDTH - exp_diff);
                if y_1 != 0 || y_0 != 0 {
                    sticky_bit |= 1;
                }
            };
            let overflow = sticky_bit.overflowing_neg_assign();
            let mut a0 = x_0.wrapping_sub(y_2 >> (exp_diff - TWICE_WIDTH));
            if overflow {
                a0.wrapping_sub_assign(1);
            }
            let mut a1 = x_1;
            if a0 > x_0 || (a0 == x_0 && overflow) {
                a1.wrapping_sub_assign(1);
            }
            let mut a2 = x_2;
            if a1 > x_1 {
                a2.wrapping_sub_assign(1);
            }
            let (diff_1, diff_2) = if a2 < LIMB_HIGH_BIT {
                let diff_1 = (a1 << 1) | (a0 >> WIDTH_M1);
                a0 = (a0 << 1) | (sticky_bit >> WIDTH_M1);
                sticky_bit <<= 1;
                x_exp.saturating_sub_assign(1);
                (diff_1, (a2 << 1) | (a1 >> WIDTH_M1))
            } else {
                (a1, a2)
            };
            let round_bit = a0 & (shift_bit >> 1);
            (
                a0 & !mask,
                diff_1,
                diff_2,
                sticky_bit | (a0 & mask) ^ round_bit,
                round_bit,
                shift_bit,
                neg,
            )
        } else {
            // We compute x - ulp(x), and the remainder ulp(x) - y satisfies: 1/2 ulp(x) < ulp(x) -
            // y < ulp(x), thus round_bit = sticky_bit = 1.
            let (a0, overflow) = x_0.overflowing_sub(shift_bit);
            let mut a1 = x_1;
            if overflow {
                a1.wrapping_sub_assign(1);
            }
            let mut a2 = x_2;
            if a1 > x_1 {
                a2.wrapping_sub_assign(1);
            }
            if a2 < LIMB_HIGH_BIT {
                // - necessarily we had b = 1000...000
                // - Warning: since we have an exponent decrease, when prec = Limb::WIDTH * 3 - 1
                //   and exp_diff = Limb::WIDTH * 3, the round bit corresponds to the upper bit of
                //   -y. In that case round_bit = 0 and sticky_bit = 1, except when y = 1000...000
                //   where round_bit = 1 and sticky_bit = 0.
                // - sticky_bit = 1 below is incorrect when prec = Limb::WIDTH * 2 - 1, exp_diff =
                //   Limb::WIDTH * 2 and y = 1000...000, but in that case the even rule wound round
                //   up too.
                x_exp.saturating_sub_assign(1);
                (
                    !mask,
                    Limb::MAX,
                    Limb::MAX,
                    1,
                    Limb::from(
                        shift > 1
                            || exp_diff > THRICE_WIDTH
                            || (y_2 == LIMB_HIGH_BIT && y_1 == 0 && y_0 == 0),
                    ),
                    shift_bit,
                    neg,
                )
            } else {
                (a0, a1, a2, 1, 1, shift_bit, neg)
            }
        }
    };
    if round_bit == 0 && sticky_bit == 0 {
        (diff_0, diff_1, diff_2, x_exp, Equal, neg)
    } else {
        if neg {
            rm.neg_assign();
        }
        match rm {
            Exact => panic!("Inexact float subtraction"),
            Nearest => {
                if round_bit == 0 || (sticky_bit == 0 && (diff_0 & shift_bit) == 0) {
                    (diff_0, diff_1, diff_2, x_exp, Less, neg)
                } else {
                    if diff_0.overflowing_add_assign(shift_bit) {
                        diff_1.wrapping_add_assign(1);
                    }
                    if diff_1 == 0 && diff_0 == 0 {
                        diff_2.wrapping_add_assign(1);
                    }
                    if diff_2 == 0 {
                        (
                            diff_0,
                            diff_1,
                            LIMB_HIGH_BIT,
                            x_exp.saturating_add(1),
                            Greater,
                            neg,
                        )
                    } else {
                        (diff_0, diff_1, diff_2, x_exp, Greater, neg)
                    }
                }
            }
            Floor | Down => (diff_0, diff_1, diff_2, x_exp, Less, neg),
            Ceiling | Up => {
                if diff_0.overflowing_add_assign(shift_bit) {
                    diff_1.wrapping_add_assign(1);
                }
                if diff_1 == 0 && diff_0 == 0 {
                    diff_2.wrapping_add_assign(1);
                }
                if diff_2 == 0 {
                    (
                        diff_0,
                        diff_1,
                        LIMB_HIGH_BIT,
                        x_exp.saturating_add(1),
                        Greater,
                        neg,
                    )
                } else {
                    (diff_0, diff_1, diff_2, x_exp, Greater, neg)
                }
            }
        }
    }
}

// Equivalent to shifting xs left by 1, then calling limbs_sub_same_length_to_out.
fn limbs_sub_shl1_same_length_to_out(out: &mut [Limb], xs: &[Limb], ys: &[Limb]) {
    let len = xs.len();
    assert_eq!(len, ys.len());
    assert!(out.len() >= len);
    let mut borrow = false;
    let mut remaining_xs_bits = 0;
    for (out, (&x, &y)) in out.iter_mut().zip(xs.iter().zip(ys.iter())) {
        let shifted_x = (x << 1) | remaining_xs_bits;
        remaining_xs_bits = x >> WIDTH_M1;
        (*out, borrow) = sub_with_borrow(shifted_x, y, borrow);
    }
}

// Equivalent to shifting ys right by `bits`, anding the least-significant limb with `ys0_and`, and
// then calling limbs_sub_same_length_to_out.
fn limbs_sub_shr_same_length_to_out_and_ys0(
    out: &mut [Limb],
    xs: &[Limb],
    ys: &[Limb],
    bits: u64,
    ys0_and: Limb,
) {
    let len = xs.len();
    assert_eq!(len, ys.len());
    assert!(bits < Limb::WIDTH);
    assert!(out.len() >= len);
    let mut borrow = false;
    let comp_bits = Limb::WIDTH - bits;
    for i in 0..len {
        let mut shifted_y = (ys[i] >> bits) | (ys.get(i + 1).unwrap_or(&0) << comp_bits);
        if i == 0 {
            shifted_y &= ys0_and;
        }
        (out[i], borrow) = sub_with_borrow(xs[i], shifted_y, borrow);
    }
}

// Equivalent to shifting ys right by `bits`, anding the least-significant limb with `ys0_and`, and
// then calling limbs_sub_same_length_to_out. Also allows ys to be shorter than xs, and pretends
// that the missing ys limbs are zeros.
fn limbs_sub_shr_greater_to_out_and_ys0(
    out: &mut [Limb],
    xs: &[Limb],
    ys: &[Limb],
    bits: u64,
    ys0_and: Limb,
) {
    let xs_len = xs.len();
    let ys_len = ys.len();
    assert_ne!(ys_len, 0);
    assert!(xs_len >= ys_len);
    assert!(bits < Limb::WIDTH);
    assert!(out.len() >= xs_len);
    let comp_bits = Limb::WIDTH - bits;
    let mut borrow = false;
    for i in 0..xs_len {
        let mut shifted_y = if let Some(y) = ys.get(i) {
            (y >> bits) | (ys.get(i + 1).unwrap_or(&0) << comp_bits)
        } else {
            0
        };
        if i == 0 {
            shifted_y &= ys0_and;
        }
        (out[i], borrow) = sub_with_borrow(xs[i], shifted_y, borrow);
    }
}

// Equivalent to replacing ys[0] with something else, then calling limbs_sub_same_length_to_out.
// Also allows ys to be shorter than xs, and pretends that the missing ys limbs are zeros.
fn limbs_sub_greater_to_out_different_ys0(out: &mut [Limb], xs: &[Limb], ys: &[Limb], ys0: Limb) {
    let xs_len = xs.len();
    let ys_len = ys.len();
    assert_ne!(ys_len, 0);
    assert!(xs_len >= ys_len);
    assert!(out.len() >= xs_len);
    // Peel off the least-significant limb (the one that uses ys0); the rest is a plain subtraction,
    // handled by the unrolled kernel.
    let borrow_0;
    (out[0], borrow_0) = sub_with_borrow(xs[0], ys0, false);
    let borrow = limbs_sub_same_length_with_borrow_in_to_out(
        &mut out[1..ys_len],
        &xs[1..ys_len],
        &ys[1..],
        borrow_0,
    );
    if borrow {
        limbs_sub_limb_to_out(&mut out[ys_len..], &xs[ys_len..], 1);
    } else {
        out[ys_len..xs_len].copy_from_slice(&xs[ys_len..]);
    }
}

fn cmp_size_helper(
    xs: &[Limb],
    x_exp: i32,
    ys: &[Limb],
    y_exp: i32,
    prec: u64,
) -> (usize, usize, bool) {
    let n = bit_to_limb_count_ceiling(prec);
    let nm1 = n - 1;
    let mut k = nm1;
    let neg = match x_exp.cmp(&y_exp) {
        Equal => {
            // Check mantissa since exponents are equal
            let mut x_y_equal = false;
            while xs[k] == ys[k] {
                if k == 0 {
                    x_y_equal = true;
                    break;
                }
                k -= 1;
            }
            // If !x_y_equal, k is the largest integer < n such that xs[k] != ys[k]
            if x_y_equal {
                return (0, 0, false);
            }
            xs[k] < ys[k]
        }
        Less => true,
        Greater => false,
    };
    (n, k, neg)
}

fn sub_float_significands_same_prec_ge_3w_ref_ref<'a>(
    out: &mut [Limb],
    mut xs: &'a [Limb],
    mut x_exp: i32,
    mut ys: &'a [Limb],
    mut y_exp: i32,
    prec: u64,
    mut rm: RoundingMode,
) -> (i32, Ordering, bool) {
    let (n, mut k, neg) = cmp_size_helper(xs, x_exp, ys, y_exp, prec);
    if n == 0 {
        // x == y. Return exact number 0. Setting the most-significant limb to 0 is a sufficient
        // signal to the caller that the entire output is 0, since in every other case the precision
        // of the output is the same as the precision of the inputs, and the most-significant limb
        // is therefore nonzero.
        *out.last_mut().unwrap() = 0;
        return (0, Equal, false);
    }
    let nm1 = n - 1;
    if neg {
        swap(&mut x_exp, &mut y_exp);
        swap(&mut xs, &mut ys);
    }
    let exp_diff = u64::exact_from(x_exp - y_exp);
    let mut round_bit;
    let mut sticky_bit;
    // round_bit_2 is the next bit after the round bit, and sticky_bit_2 the corresponding sticky
    // bit.
    let mut round_bit_2;
    let mut sticky_bit_2;
    let shift = prec.neg_mod_power_of_2(Limb::LOG_WIDTH);
    let shift_bit = Limb::power_of_2(shift);
    let mut goto_exact_normalize = false;
    let mut goto_sub_d1_no_lose = false;
    let mut goto_sub_d1_lose = false;
    let mut limb = 0;
    loop {
        // loop for ExactNormalize, SubD1NoLose, and SubD1Lose
        if !goto_sub_d1_no_lose && !goto_sub_d1_lose && (exp_diff == 0 || goto_exact_normalize) {
            // ```
            // <-- x -->
            // <-- y --> : exact sub
            // ```
            if !goto_exact_normalize {
                limbs_sub_same_length_to_out(out, xs, ys);
            }
            // label ExactNormalize:
            limb = out[nm1];
            if limb != 0 {
                // First limb is not zero.
                let leading_zeros = LeadingZeros::leading_zeros(limb);
                // Warning: leading_zeros can be 0 when we come from the case SubD1Lose with
                // ExactNormalize
                if leading_zeros != 0 {
                    limbs_slice_shl_in_place(out, leading_zeros);
                    x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
                }
                // Last limb should be OK
                assert_eq!(out[0] & (shift_bit - 1), 0);
            } else {
                // - First limb is zero: this can only occur for n >= 2
                // - Find the first limb not equal to zero. It necessarily exists since |x| > |y|.
                //   We know that xs[k] > ys[k] and all upper limbs are equal.
                while out[k] == 0 {
                    k -= 1;
                }
                limb = out[k];
                // out[k] is the non-zero limb of largest index, thus we have to consider the k + 1
                // least-significant limbs
                assert_ne!(limb, 0);
                let leading_zeros = LeadingZeros::leading_zeros(limb);
                k += 1;
                let len = n - k; // Number of most significant zero limbs
                assert_ne!(k, 0);
                if leading_zeros != 0 {
                    limbs_slice_shl_in_place(&mut out[..k], leading_zeros);
                }
                out.copy_within(0..k, len);
                slice_set_zero(&mut out[..len]);
                x_exp = i32::saturating_from(
                    i128::from(x_exp)
                        - (i128::from(leading_zeros)
                            + (i128::wrapping_from(len) << Limb::LOG_WIDTH)),
                );
                // out[len] should have its low bits zero: it is x[0] - y[0].
                assert_eq!(out[len] & Limb::wrapping_from(shift), 0);
            }
            // No rounding is necessary since the result is exact
            assert!(out[nm1].get_highest_bit());
            return (x_exp, Equal, neg);
        } else if exp_diff == 1 || goto_sub_d1_no_lose || goto_sub_d1_lose {
            // ```
            // | <-- x -->
            // |  <-- y -->
            // ```
            if !goto_sub_d1_no_lose && !goto_sub_d1_lose {
                // If we lose at least one bit, compute 2 * x - y (exact), else compute x - y / 2
                limb = xs[k] - (ys[k] >> 1);
            }
            // Let W = 2 ^ Limb::WIDTH: we have |x| - |y| >= limb * W ^ k - (2 * W ^ k - 1) / 2 >=
            // limb
            // * W ^ k - W ^ k + 1 / 2. Thus, if limb > W / 2, |x| - |y| >= 1 / 2 * W ^ n. Moreover,
            //   if
            // trunc(|y|) represents the first prec - 1 bits of |y|, minus the last significant bit
            // called y0 below (in fact y0 is that bit shifted by `shift` bits), then we have
            // |x|-trunc(|y|) >= 1 / 2 * W ^ n + 1, thus the two limbs_sub calls below necessarily
            // yield out > 1 / 2 * W ^ n.
            if !goto_sub_d1_lose && (limb > LIMB_HIGH_BIT || goto_sub_d1_no_lose) {
                // - case limb > W / 2
                // - The exponent cannot decrease: compute x - y / 2.
                // - Shift y in the allocated temporary block
                //
                // label SubD1NoLose:
                let y0 = ys[0] & shift_bit;
                let mask = shift_bit - 1;
                // Zero last bit of y if set
                limbs_sub_shr_same_length_to_out_and_ys0(out, xs, ys, 1, !mask);
                assert!(out[nm1].get_highest_bit());
                if y0 == 0 {
                    // Result is exact: no need of rounding!
                    return (x_exp, Equal, neg);
                }
                // - y0 is non-zero, thus we have to subtract 1 / 2 * ulp(out).
                // - However, we know (see analysis above) that this cannot make the exponent
                //   decrease.
                // - Check last bits
                assert_eq!(out[0] & mask, 0);
                // - No normalization is needed
                // - Rounding is necessary since y0 is non-zero
                // - We have to subtract 1 at the round bit position, and 0 for the lower bits
                round_bit = 1;
                round_bit_2 = 0;
                sticky_bit_2 = 0;
            } else if limb < LIMB_HIGH_BIT || goto_sub_d1_lose {
                // - |x| - |y| <= (W / 2 - 1) * W ^ k + W ^ k - 1 = 1 / 2 * W ^ n - 1
                // - The exponent decreases by one.
                // - Compute 2 * x - y (Exact)
                //
                // label SubD1Lose:
                goto_sub_d1_lose = false;
                limbs_sub_shl1_same_length_to_out(out, xs, ys);
                x_exp.saturating_sub_assign(1);
                assert_eq!(k, nm1);
                goto_exact_normalize = true;
                continue;
            } else {
                // - Case: limb = 100000000000
                // - Check while b[l] == y'[l] (Y' is Y shifted by 1)
                // - If x[l] < y'[l] => We lose at least one bit
                // - If x[l] > y'[l] => We don't lose any bit
                // - If l == -1 => We don't lose any bit AND the result is 100000000000 0000000000
                //   00000000000
                let mut l = n;
                let mut yl_shifted;
                loop {
                    // The first loop will compare x[n - 2] and y'[n - 2]
                    yl_shifted = ys[l - 1] << WIDTH_M1;
                    l -= 1;
                    if l == 0 {
                        break;
                    }
                    yl_shifted += ys[l - 1] >> 1;
                    if xs[l - 1] != yl_shifted {
                        break;
                    }
                }
                if l == 0 {
                    if yl_shifted != 0 {
                        // Since yl_shifted is what should be subtracted from out[-1], if non-zero
                        // then necessarily the precision is a multiple of Limb::WIDTH, and we lose
                        // one bit, thus the (exact) result is a power of 2 minus 1.
                        for o in out.iter_mut() {
                            *o = Limb::MAX;
                        }
                        x_exp.saturating_sub_assign(1);
                    } else {
                        // yl_shifted = 0: result is a power of 2.
                        let (out_last, out_init) = out.split_last_mut().unwrap();
                        slice_set_zero(out_init);
                        *out_last = LIMB_HIGH_BIT;
                    }
                    // No Normalize is needed, no Rounding is needed
                    return (x_exp, Equal, neg);
                } else if xs[l - 1] > yl_shifted {
                    // - cl_shifted is the shifted value c'[l]
                    // - |x| - |y| >= 1 / 2 * W ^ n
                    //
                    // goto SubD1NoLose;
                    goto_sub_d1_no_lose = true;
                } else {
                    // We cannot have xs[l] = yl_shifted since the only way we can exit the while
                    // loop above is when xs[l] != yl_shifted or l < 0, and the case l < 0 was
                    // already treated above.
                    assert!(xs[l - 1] < yl_shifted);
                    // |x| - |y| <= 1 / 2 * W ^ n - 1 and is exact
                    goto_sub_d1_lose = true;
                }
                continue;
            }
        } else if exp_diff >= prec {
            // The difference of exponents is larger than the precision of all operands, thus the
            // result is either x or x - 1 ulp, with a possible exact result when x = prec, x = 2 ^
            // e and y = 1 / 2 * ulp(x)
            //
            // - We can't set OUT before since we use ys for rounding...
            // - Perform rounding: check if out = b or out = x - ulp(x)
            if exp_diff == prec {
                // since y is normalized, we need to subtract 1 / 2 * ulp(x)
                round_bit = 1;
                // round_bit_2 is the bit of weight 1 / 4 * ulp(x) in y. We assume a limb has at
                // least 2 bits. If the precision is 1, we read in the unused bits, which should be
                // zero, and this is what we want.
                round_bit_2 = ys[nm1] & HALF_LIMB_HIGH_BIT;
                // We also need sticky_bit_2
                sticky_bit_2 = ys[nm1] & WIDTH_M2_MASK;
                let mut k = nm1;
                while sticky_bit_2 == 0 && k > 0 {
                    k -= 1;
                    sticky_bit_2 = ys[k];
                }
            } else {
                round_bit = 0;
                if exp_diff == prec + 1 {
                    round_bit_2 = 1;
                    sticky_bit_2 = ys[nm1] & WIDTH_M1_MASK;
                    let mut k = nm1;
                    while sticky_bit_2 == 0 && k > 0 {
                        k -= 1;
                        sticky_bit_2 = ys[k];
                    }
                } else {
                    round_bit_2 = 0;
                    sticky_bit_2 = 1; // since C is non-zero
                }
            }
            // Copy mantissa X in OUT
            out.copy_from_slice(xs);
        } else {
            // case 2 <= exp_diff < prec
            //
            // Compute round_bit = Cp and sticky_bit = C'p + 1
            //
            // Compute round_bit and round_bit_2 from Y The round bit is bit prec - exp_diff in Y,
            // assuming the most significant bit of Y is bit 0
            let x = prec - exp_diff;
            let mut kx = nm1 - bit_to_limb_count_floor(x);
            let mut sx_bit = Limb::power_of_2(WIDTH_M1 - (x & Limb::WIDTH_MASK));
            // the round bit is in ys[kx], at position sx
            assert!(prec >= exp_diff);
            round_bit = ys[kx] & sx_bit;
            // Now compute rxx: since exp_diff >= 2 it always exists in Y
            sx_bit = if sx_bit == 1 {
                // rxx is in the next limb
                kx = kx.checked_sub(1).unwrap();
                LIMB_HIGH_BIT
            } else {
                // round_bit and round_bit_2 are in the same limb
                sx_bit >> 1
            };
            round_bit_2 = ys[kx] & sx_bit;
            // Now look at the remaining low bits of Y to determine sticky_bit_2
            sticky_bit_2 = ys[kx] & (sx_bit - 1);
            while sticky_bit_2 == 0 && kx > 0 {
                kx -= 1;
                sticky_bit_2 = ys[kx];
            }
            // Clean shifted Y'
            let mask = shift_bit - 1;
            let dm = exp_diff & Limb::WIDTH_MASK;
            let m = bit_to_limb_count_floor(exp_diff);
            if dm == 0 {
                assert_ne!(m, 0);
                // - dm = 0 and m > 0: Just copy
                // - Subtract the mantissa y from x in out
                limbs_sub_greater_to_out_different_ys0(out, xs, &ys[m..], ys[m] & !mask);
            } else if m == 0 {
                // dm >=2 and m == 0: just shift
                assert!(dm >= 2);
                // Subtract the mantissa y from x in out
                limbs_sub_shr_same_length_to_out_and_ys0(out, xs, ys, dm, !mask);
            } else {
                // - dm > 0 and m > 0: shift and zero
                // - Subtract the mantissa y from x in out
                limbs_sub_shr_greater_to_out_and_ys0(out, xs, &ys[m..], dm, !mask);
            }
            // Normalize: we lose at most one bit
            if !out[nm1].get_highest_bit() {
                // - High bit is not set and we have to fix it.
                // - OUT >= 010000xxx001
                limbs_slice_shl_in_place(out, 1);
                // OUT >= 100000xxx010
                if round_bit != 0 {
                    // - Check if Y = -1
                    // - Since Y == -1, we have to subtract one more
                    limbs_sub_limb_in_place(out, shift_bit);
                    assert!(out[nm1].get_highest_bit());
                }
                // - OUT >= 10000xxx001
                // - Final exponent -1 since we have shifted the mantissa
                x_exp.saturating_sub_assign(1);
                round_bit = round_bit_2;
                round_bit_2 = sticky_bit_2;
                // We don't have anymore a valid Yp + 1, but since Oyr >= 100000xxx001, the final
                // sub can't unnormalize.
            }
            assert_eq!(out[0] & mask, 0);
        }
        // only loop when emulating gotos
        break;
    }
    let mut out_power_of_2;
    loop {
        // At this point out contains x - high(y), normalized, and we have to subtract round_bit *
        // 1/2 ulp(out), round_bit_2 * 1/4 ulp(out), and sticky_bit_2 * 1/8 ulp(out), interpreting
        // round_bit/round_bit_2/sticky_bit_2 as 1 if non-zero.
        sticky_bit = round_bit_2 | sticky_bit_2;
        if round_bit == 0 && sticky_bit == 0 {
            return (x_exp, Equal, neg);
        }
        out_power_of_2 = limbs_is_power_of_2(out);
        if out_power_of_2 && round_bit != 0 {
            limbs_sub_limb_in_place(out, shift_bit);
            out[nm1] |= LIMB_HIGH_BIT;
            x_exp.saturating_sub_assign(1);
            round_bit = round_bit_2;
            round_bit_2 = sticky_bit_2;
            sticky_bit_2 = 0;
        } else {
            break;
        }
    }
    // Now if out is a power of two, necessary round_bit = 0, which means the exact result is always
    // in (pred(out), out), and the bounds cannot be attained
    if neg {
        rm.neg_assign();
    }
    match rm {
        Exact => panic!("Inexact float subtraction"),
        Nearest => {
            if out_power_of_2 {
                assert_eq!(round_bit, 0);
                // Since we are at the end of the binade, we have in fact round_bit = round_bit_2
                // and sticky_bit = sticky_bit_2
                round_bit = round_bit_2;
                sticky_bit = sticky_bit_2;
            }
            if (prec == 1 || out[0] & shift_bit == 0 || round_bit == 0)
                && (sticky_bit == 0 || round_bit == 0)
            {
                (x_exp, Greater, neg)
            } else {
                limbs_sub_limb_in_place(out, shift_bit);
                if out_power_of_2 {
                    // deal with cancellation
                    out[nm1] |= LIMB_HIGH_BIT;
                    x_exp.saturating_sub_assign(1);
                }
                (x_exp, Less, neg)
            }
        }
        Floor | Down => {
            limbs_sub_limb_in_place(out, shift_bit);
            if out_power_of_2 {
                // deal with cancellation
                out[nm1] |= LIMB_HIGH_BIT;
                x_exp.saturating_sub_assign(1);
            }
            (x_exp, Less, neg)
        }
        Ceiling | Up => (x_exp, Greater, neg),
    }
}

// Equivalent to shifting xs left by 1, then calling limbs_sub_same_length_to_out.
fn limbs_sub_shl1_same_length_in_place_left(xs: &mut [Limb], ys: &[Limb]) {
    let len = xs.len();
    assert_eq!(len, ys.len());
    let mut borrow = false;
    let mut remaining_xs_bits = 0;
    for (x, &y) in xs.iter_mut().zip(ys.iter()) {
        let shifted_x = (*x << 1) | remaining_xs_bits;
        remaining_xs_bits = *x >> WIDTH_M1;
        (*x, borrow) = sub_with_borrow(shifted_x, y, borrow);
    }
}

// Equivalent to shifting ys right by `bits`, anding the least-significant limb with `ys0_and`, and
// then calling limbs_sub_same_length_in_place_left.
fn limbs_sub_shr_same_length_in_place_left_and_ys0(
    xs: &mut [Limb],
    ys: &[Limb],
    bits: u64,
    ys0_and: Limb,
) {
    let len = xs.len();
    assert_eq!(len, ys.len());
    assert!(bits < Limb::WIDTH);
    let mut borrow = false;
    let comp_bits = Limb::WIDTH - bits;
    for i in 0..len {
        let mut shifted_y = (ys[i] >> bits) | (ys.get(i + 1).unwrap_or(&0) << comp_bits);
        if i == 0 {
            shifted_y &= ys0_and;
        }
        (xs[i], borrow) = sub_with_borrow(xs[i], shifted_y, borrow);
    }
}

// Equivalent to shifting ys right by `bits`, anding the least-significant limb with `ys0_and`, and
// then calling limbs_sub_same_length_in_place_left. Also allows ys to be shorter than xs, and
// pretends that the missing ys limbs are zeros.
fn limbs_sub_shr_greater_in_place_left_and_ys0(
    xs: &mut [Limb],
    ys: &[Limb],
    bits: u64,
    ys0_and: Limb,
) {
    let xs_len = xs.len();
    let ys_len = ys.len();
    assert_ne!(ys_len, 0);
    assert!(xs_len >= ys_len);
    assert!(bits < Limb::WIDTH);
    let comp_bits = Limb::WIDTH - bits;
    let mut borrow = false;
    for (i, x) in xs.iter_mut().enumerate() {
        let mut shifted_y = if let Some(y) = ys.get(i) {
            (y >> bits) | (ys.get(i + 1).unwrap_or(&0) << comp_bits)
        } else {
            0
        };
        if i == 0 {
            shifted_y &= ys0_and;
        }
        (*x, borrow) = sub_with_borrow(*x, shifted_y, borrow);
    }
}

// Equivalent to replacing ys[0] with something else, then calling
// limbs_sub_same_length_in_place_left. Also allows ys to be shorter than xs, and pretends that the
// missing ys limbs are zeros.
fn limbs_sub_greater_in_place_left_different_ys0(xs: &mut [Limb], ys: &[Limb], ys0: Limb) {
    let xs_len = xs.len();
    let ys_len = ys.len();
    assert_ne!(ys_len, 0);
    assert!(xs_len >= ys_len);
    // Peel off the least-significant limb (the one that uses ys0); the rest is a plain subtraction,
    // handled by the unrolled kernel.
    let borrow_0;
    (xs[0], borrow_0) = sub_with_borrow(xs[0], ys0, false);
    let borrow =
        limbs_sub_same_length_with_borrow_in_in_place_left(&mut xs[1..ys_len], &ys[1..], borrow_0);
    if borrow {
        limbs_sub_limb_in_place(&mut xs[ys_len..], 1);
    }
}

fn sub_float_significands_same_prec_ge_3w_val_val<'a>(
    mut xs: &'a mut [Limb],
    mut x_exp: i32,
    mut ys: &'a mut [Limb],
    mut y_exp: i32,
    prec: u64,
    mut rm: RoundingMode,
) -> (i32, Ordering, bool) {
    let (n, _, neg) = cmp_size_helper(xs, x_exp, ys, y_exp, prec);
    if n == 0 {
        // x == y. Return exact number 0. Setting the most-significant limb to 0 is a sufficient
        // signal to the caller that the entire output is 0, since in every other case the precision
        // of the output is the same as the precision of the inputs, and the most-significant limb
        // is therefore nonzero.
        *xs.last_mut().unwrap() = 0;
        return (0, Equal, false);
    }
    if neg {
        rm.neg_assign();
        swap(&mut x_exp, &mut y_exp);
        swap(&mut xs, &mut ys);
    }
    let (exp, o) =
        sub_float_significands_same_prec_ge_3w_val_ref_helper(xs, x_exp, ys, y_exp, prec, rm);
    (exp, o, neg)
}

fn sub_float_significands_same_prec_ge_3w_val_ref(
    xs: &mut [Limb],
    x_exp: i32,
    ys: &[Limb],
    y_exp: i32,
    prec: u64,
    rm: RoundingMode,
) -> (i32, Ordering, bool) {
    let (n, _, neg) = cmp_size_helper(xs, x_exp, ys, y_exp, prec);
    if n == 0 {
        // x == y. Return exact number 0. Setting the most-significant limb to 0 is a sufficient
        // signal to the caller that the entire output is 0, since in every other case the precision
        // of the output is the same as the precision of the inputs, and the most-significant limb
        // is therefore nonzero.
        *xs.last_mut().unwrap() = 0;
        return (0, Equal, false);
    }
    if neg {
        let (exp, o) =
            sub_float_significands_same_prec_ge_3w_ref_val_helper(ys, y_exp, xs, x_exp, prec, -rm);
        (exp, o, true)
    } else {
        let (exp, o) =
            sub_float_significands_same_prec_ge_3w_val_ref_helper(xs, x_exp, ys, y_exp, prec, rm);
        (exp, o, false)
    }
}

fn sub_float_significands_same_prec_ge_3w_val_ref_helper(
    xs: &mut [Limb],
    mut x_exp: i32,
    ys: &[Limb],
    y_exp: i32,
    prec: u64,
    rm: RoundingMode,
) -> (i32, Ordering) {
    let n = bit_to_limb_count_ceiling(prec);
    let nm1 = n - 1;
    let mut k = nm1;
    let exp_diff = u64::exact_from(x_exp - y_exp);
    let mut round_bit;
    let mut sticky_bit;
    // round_bit_2 is the next bit after the round bit, and sticky_bit_2 the corresponding sticky
    // bit.
    let mut round_bit_2;
    let mut sticky_bit_2;
    let shift = prec.neg_mod_power_of_2(Limb::LOG_WIDTH);
    let shift_bit = Limb::power_of_2(shift);
    let mut goto_exact_normalize = false;
    let mut goto_sub_d1_no_lose = false;
    let mut goto_sub_d1_lose = false;
    let mut limb = 0;
    loop {
        // loop for ExactNormalize, SubD1NoLose, and SubD1Lose
        if !goto_sub_d1_no_lose && !goto_sub_d1_lose && (exp_diff == 0 || goto_exact_normalize) {
            // ```
            // <-- x -->
            // <-- y --> : exact sub
            // ```
            if !goto_exact_normalize {
                limbs_sub_same_length_in_place_left(xs, ys);
            }
            // label ExactNormalize:
            limb = xs[nm1];
            if limb != 0 {
                // First limb is not zero.
                let leading_zeros = LeadingZeros::leading_zeros(limb);
                // Warning: leading_zeros can be 0 when we come from the case SubD1Lose with
                // ExactNormalize
                if leading_zeros != 0 {
                    limbs_slice_shl_in_place(xs, leading_zeros);
                    x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
                }
                // Last limb should be OK
                assert_eq!(xs[0] & (shift_bit - 1), 0);
            } else {
                // - First limb is zero: this can only occur for n >= 2
                // - Find the first limb not equal to zero. It necessarily exists since |x| > |y|.
                //   We know that xs[k] > ys[k] and all upper limbs are equal.
                while xs[k] == 0 {
                    k -= 1;
                }
                limb = xs[k];
                // out[k] is the non-zero limb of largest index, thus we have to consider the k + 1
                // least-significant limbs
                assert_ne!(limb, 0);
                let leading_zeros = LeadingZeros::leading_zeros(limb);
                k += 1;
                let len = n - k; // Number of most significant zero limbs
                assert_ne!(k, 0);
                if leading_zeros != 0 {
                    limbs_slice_shl_in_place(&mut xs[..k], leading_zeros);
                }
                xs.copy_within(0..k, len);
                slice_set_zero(&mut xs[..len]);
                x_exp = i32::saturating_from(
                    i128::from(x_exp)
                        - (i128::from(leading_zeros)
                            + (i128::wrapping_from(len) << Limb::LOG_WIDTH)),
                );
                // out[len] should have its low bits zero: it is x[0] - y[0].
                assert_eq!(xs[len] & Limb::wrapping_from(shift), 0);
            }
            // No rounding is necessary since the result is exact
            assert!(xs[nm1].get_highest_bit());
            return (x_exp, Equal);
        } else if exp_diff == 1 || goto_sub_d1_no_lose || goto_sub_d1_lose {
            // ```
            // | <-- x -->
            // |  <-- y -->
            // ```
            if !goto_sub_d1_no_lose && !goto_sub_d1_lose {
                // If we lose at least one bit, compute 2 * x - y (exact), else compute x - y / 2
                limb = xs[k] - (ys[k] >> 1);
            }
            // Let W = 2 ^ Limb::WIDTH: we have |x| - |y| >= limb * W ^ k - (2 * W ^ k - 1) / 2 >=
            // limb
            // * W ^ k - W ^ k + 1 / 2. Thus, if limb > W / 2, |x| - |y| >= 1 / 2 * W ^ n. Moreover,
            //   if
            // trunc(|y|) represents the first prec - 1 bits of |y|, minus the last significant bit
            // called y0 below (in fact y0 is that bit shifted by `shift` bits), then we have
            // |x|-trunc(|y|) >= 1 / 2 * W ^ n + 1, thus the two limbs_sub calls below necessarily
            // yield out > 1 / 2 * W ^ n.
            if !goto_sub_d1_lose && (limb > LIMB_HIGH_BIT || goto_sub_d1_no_lose) {
                // - case limb > W / 2
                // - The exponent cannot decrease: compute x - y / 2.
                // - Shift y in the allocated temporary block
                //
                // label SubD1NoLose:
                let y0 = ys[0] & shift_bit;
                let mask = shift_bit - 1;
                // Zero last bit of y if set
                limbs_sub_shr_same_length_in_place_left_and_ys0(xs, ys, 1, !mask);
                assert!(xs[nm1].get_highest_bit());
                if y0 == 0 {
                    // Result is exact: no need of rounding!
                    return (x_exp, Equal);
                }
                // - y0 is non-zero, thus we have to subtract 1 / 2 * ulp(out).
                // - However, we know (see analysis above) that this cannot make the exponent
                //   decrease.
                // - Check last bits
                assert_eq!(xs[0] & mask, 0);
                // - No normalization is needed
                // - Rounding is necessary since y0 is non-zero
                // - We have to subtract 1 at the round bit position, and 0 for the lower bits
                round_bit = 1;
                round_bit_2 = 0;
                sticky_bit_2 = 0;
            } else if limb < LIMB_HIGH_BIT || goto_sub_d1_lose {
                // - |x| - |y| <= (W / 2 - 1) * W ^ k + W ^ k - 1 = 1 / 2 * W ^ n - 1
                // - The exponent decreases by one.
                // - Compute 2 * x - y (Exact)
                //
                // label SubD1Lose:
                goto_sub_d1_lose = false;
                limbs_sub_shl1_same_length_in_place_left(xs, ys);
                x_exp.saturating_sub_assign(1);
                assert_eq!(k, nm1);
                goto_exact_normalize = true;
                continue;
            } else {
                // - Case: limb = 100000000000
                // - Check while b[l] == y'[l] (Y' is Y shifted by 1)
                // - If x[l] < y'[l] => We lose at least one bit
                // - If x[l] > y'[l] => We don't lose any bit
                // - If l == -1 => We don't lose any bit AND the result is 100000000000 0000000000
                //   00000000000
                let mut l = n;
                let mut yl_shifted;
                loop {
                    // The first loop will compare x[n - 2] and y'[n - 2]
                    yl_shifted = ys[l - 1] << WIDTH_M1;
                    l -= 1;
                    if l == 0 {
                        break;
                    }
                    yl_shifted += ys[l - 1] >> 1;
                    if xs[l - 1] != yl_shifted {
                        break;
                    }
                }
                if l == 0 {
                    if yl_shifted != 0 {
                        // Since yl_shifted is what should be subtracted from out[-1], if non-zero
                        // then necessarily the precision is a multiple of Limb::WIDTH, and we lose
                        // one bit, thus the (exact) result is a power of 2 minus 1.
                        for x in xs.iter_mut() {
                            *x = Limb::MAX;
                        }
                        x_exp.saturating_sub_assign(1);
                    } else {
                        // yl_shifted = 0: result is a power of 2.
                        let (xs_last, xs_init) = xs.split_last_mut().unwrap();
                        slice_set_zero(xs_init);
                        *xs_last = LIMB_HIGH_BIT;
                    }
                    // No Normalize is needed, no Rounding is needed
                    return (x_exp, Equal);
                } else if xs[l - 1] > yl_shifted {
                    // - cl_shifted is the shifted value c'[l]
                    // - |x| - |y| >= 1 / 2 * W ^ n
                    //
                    // goto SubD1NoLose;
                    goto_sub_d1_no_lose = true;
                } else {
                    // We cannot have xs[l] = yl_shifted since the only way we can exit the while
                    // loop above is when xs[l] != yl_shifted or l < 0, and the case l < 0 was
                    // already treated above.
                    assert!(xs[l - 1] < yl_shifted);
                    // |x| - |y| <= 1 / 2 * W ^ n - 1 and is exact
                    goto_sub_d1_lose = true;
                }
                continue;
            }
        } else if exp_diff >= prec {
            // The difference of exponents is larger than the precision of all operands, thus the
            // result is either x or x - 1 ulp, with a possible exact result when x = prec, x = 2 ^
            // e and y = 1 / 2 * ulp(x)
            //
            // - We can't set OUT before since we use ys for rounding...
            // - Perform rounding: check if out = b or out = x - ulp(x)
            if exp_diff == prec {
                // since y is normalized, we need to subtract 1 / 2 * ulp(x)
                round_bit = 1;
                // round_bit_2 is the bit of weight 1 / 4 * ulp(x) in y. We assume a limb has at
                // least 2 bits. If the precision is 1, we read in the unused bits, which should be
                // zero, and this is what we want.
                round_bit_2 = ys[nm1] & HALF_LIMB_HIGH_BIT;
                // We also need sticky_bit_2
                sticky_bit_2 = ys[nm1] & WIDTH_M2_MASK;
                let mut k = nm1;
                while sticky_bit_2 == 0 && k > 0 {
                    k -= 1;
                    sticky_bit_2 = ys[k];
                }
            } else {
                round_bit = 0;
                if exp_diff == prec + 1 {
                    round_bit_2 = 1;
                    sticky_bit_2 = ys[nm1] & WIDTH_M1_MASK;
                    let mut k = nm1;
                    while sticky_bit_2 == 0 && k > 0 {
                        k -= 1;
                        sticky_bit_2 = ys[k];
                    }
                } else {
                    round_bit_2 = 0;
                    sticky_bit_2 = 1; // since C is non-zero
                }
            }
        } else {
            // case 2 <= exp_diff < prec
            //
            // Compute round_bit = Cp and sticky_bit = C'p + 1
            //
            // Compute round_bit and round_bit_2 from Y The round bit is bit prec - exp_diff in Y,
            // assuming the most significant bit of Y is bit 0
            let x = prec - exp_diff;
            let mut kx = nm1 - bit_to_limb_count_floor(x);
            let mut sx_bit = Limb::power_of_2(WIDTH_M1 - (x & Limb::WIDTH_MASK));
            // the round bit is in ys[kx], at position sx
            assert!(prec >= exp_diff);
            round_bit = ys[kx] & sx_bit;
            // Now compute rxx: since exp_diff >= 2 it always exists in Y
            sx_bit = if sx_bit == 1 {
                // rxx is in the next limb
                kx = kx.checked_sub(1).unwrap();
                LIMB_HIGH_BIT
            } else {
                // round_bit and round_bit_2 are in the same limb
                sx_bit >> 1
            };
            round_bit_2 = ys[kx] & sx_bit;
            // Now look at the remaining low bits of Y to determine sticky_bit_2
            sticky_bit_2 = ys[kx] & (sx_bit - 1);
            while sticky_bit_2 == 0 && kx > 0 {
                kx -= 1;
                sticky_bit_2 = ys[kx];
            }
            // Clean shifted Y'
            let mask = shift_bit - 1;
            let dm = exp_diff & Limb::WIDTH_MASK;
            let m = bit_to_limb_count_floor(exp_diff);
            if dm == 0 {
                assert_ne!(m, 0);
                // - dm = 0 and m > 0: Just copy
                // - Subtract the mantissa y from x in out
                limbs_sub_greater_in_place_left_different_ys0(xs, &ys[m..], ys[m] & !mask);
            } else if m == 0 {
                // dm >=2 and m == 0: just shift
                assert!(dm >= 2);
                // Subtract the mantissa y from x in out
                limbs_sub_shr_same_length_in_place_left_and_ys0(xs, ys, dm, !mask);
            } else {
                // - dm > 0 and m > 0: shift and zero
                // - Subtract the mantissa y from x in out
                limbs_sub_shr_greater_in_place_left_and_ys0(xs, &ys[m..], dm, !mask);
            }
            // Normalize: we lose at most one bit
            if !xs[nm1].get_highest_bit() {
                // - High bit is not set and we have to fix it.
                // - OUT >= 010000xxx001
                limbs_slice_shl_in_place(xs, 1);
                // OUT >= 100000xxx010
                if round_bit != 0 {
                    // - Check if Y = -1
                    // - Since Y == -1, we have to subtract one more
                    limbs_sub_limb_in_place(xs, shift_bit);
                    assert!(xs[nm1].get_highest_bit());
                }
                // - OUT >= 10000xxx001
                // - Final exponent -1 since we have shifted the mantissa
                x_exp.saturating_sub_assign(1);
                round_bit = round_bit_2;
                round_bit_2 = sticky_bit_2;
                // We don't have anymore a valid Yp + 1, but since Oyr >= 100000xxx001, the final
                // sub can't unnormalize.
            }
            assert_eq!(xs[0] & mask, 0);
        }
        // only loop when emulating gotos
        break;
    }
    let mut out_power_of_2;
    loop {
        // At this point out contains x - high(y), normalized, and we have to subtract round_bit *
        // 1/2 ulp(out), round_bit_2 * 1/4 ulp(out), and sticky_bit_2 * 1/8 ulp(out), interpreting
        // round_bit/round_bit_2/sticky_bit_2 as 1 if non-zero.
        sticky_bit = round_bit_2 | sticky_bit_2;
        if round_bit == 0 && sticky_bit == 0 {
            return (x_exp, Equal);
        }
        out_power_of_2 = limbs_is_power_of_2(xs);
        if out_power_of_2 && round_bit != 0 {
            limbs_sub_limb_in_place(xs, shift_bit);
            xs[nm1] |= LIMB_HIGH_BIT;
            x_exp.saturating_sub_assign(1);
            round_bit = round_bit_2;
            round_bit_2 = sticky_bit_2;
            sticky_bit_2 = 0;
        } else {
            break;
        }
    }
    // Now if out is a power of two, necessary round_bit = 0, which means the exact result is always
    // in (pred(xs), xs), and the bounds cannot be attained
    match rm {
        Exact => panic!("Inexact float subtraction"),
        Nearest => {
            if out_power_of_2 {
                assert_eq!(round_bit, 0);
                // Since we are at the end of the binade, we have in fact round_bit = round_bit_2
                // and sticky_bit = sticky_bit_2
                round_bit = round_bit_2;
                sticky_bit = sticky_bit_2;
            }
            if (prec == 1 || xs[0] & shift_bit == 0 || round_bit == 0)
                && (sticky_bit == 0 || round_bit == 0)
            {
                (x_exp, Greater)
            } else {
                limbs_sub_limb_in_place(xs, shift_bit);
                if out_power_of_2 {
                    // deal with cancellation
                    xs[nm1] |= LIMB_HIGH_BIT;
                    x_exp.saturating_sub_assign(1);
                }
                (x_exp, Less)
            }
        }
        Floor | Down => {
            limbs_sub_limb_in_place(xs, shift_bit);
            if out_power_of_2 {
                // deal with cancellation
                xs[nm1] |= LIMB_HIGH_BIT;
                x_exp.saturating_sub_assign(1);
            }
            (x_exp, Less)
        }
        Ceiling | Up => (x_exp, Greater),
    }
}

// Equivalent to shifting xs left by 1, then calling limbs_sub_same_length_in_place_right.
fn limbs_sub_shl1_same_length_in_place_right(xs: &[Limb], ys: &mut [Limb]) {
    let len = xs.len();
    assert_eq!(len, ys.len());
    let mut borrow = false;
    let mut remaining_xs_bits = 0;
    for (&x, y) in xs.iter().zip(ys.iter_mut()) {
        let shifted_x = (x << 1) | remaining_xs_bits;
        remaining_xs_bits = x >> WIDTH_M1;
        (*y, borrow) = sub_with_borrow(shifted_x, *y, borrow);
    }
}

// Equivalent to shifting ys right by `bits`, anding the least-significant limb with `ys0_and`, and
// then calling limbs_sub_same_length_in_place_right.
fn limbs_sub_shr_same_length_in_place_right_and_ys0(
    xs: &[Limb],
    ys: &mut [Limb],
    bits: u64,
    ys0_and: Limb,
) {
    let len = xs.len();
    assert_eq!(len, ys.len());
    assert!(bits < Limb::WIDTH);
    let mut borrow = false;
    let comp_bits = Limb::WIDTH - bits;
    for i in 0..len {
        let mut shifted_y = (ys[i] >> bits) | (ys.get(i + 1).unwrap_or(&0) << comp_bits);
        if i == 0 {
            shifted_y &= ys0_and;
        }
        (ys[i], borrow) = sub_with_borrow(xs[i], shifted_y, borrow);
    }
}

fn limbs_sub_shr_greater_in_place_right_and_ys0(
    xs: &[Limb],
    ys: &mut [Limb],
    bits: u64,
    ys0_and: Limb,
    m: usize,
) {
    let n = xs.len();
    assert_ne!(n, 0);
    assert!(bits < Limb::WIDTH);
    let comp_bits = Limb::WIDTH - bits;
    let mut borrow = false;
    for i in 0..n {
        let mut shifted_y = if let Some(y) = ys.get(i + m) {
            (y >> bits) | (ys.get(i + m + 1).unwrap_or(&0) << comp_bits)
        } else {
            0
        };
        if i == 0 {
            shifted_y &= ys0_and;
        }
        (ys[i], borrow) = sub_with_borrow(xs[i], shifted_y, borrow);
    }
}

fn limbs_sub_greater_in_place_right_different_ys0(
    xs: &[Limb],
    ys: &mut [Limb],
    ys0: Limb,
    m: usize,
) {
    if xs.is_empty() {
        return;
    }
    // The reads (at i + m) and writes (at i) may overlap, so the unrolled kernel can't be used;
    // each read happens before the write at the same index, so ascending order is correct.
    let mut borrow;
    (ys[0], borrow) = sub_with_borrow(xs[0], ys0, false);
    for i in 1..xs.len() {
        let y = ys.get(i + m).copied().unwrap_or(0);
        (ys[i], borrow) = sub_with_borrow(xs[i], y, borrow);
    }
}

fn sub_float_significands_same_prec_ge_3w_ref_val_helper(
    xs: &[Limb],
    mut x_exp: i32,
    ys: &mut [Limb],
    y_exp: i32,
    prec: u64,
    rm: RoundingMode,
) -> (i32, Ordering) {
    let n = bit_to_limb_count_ceiling(prec);
    let nm1 = n - 1;
    let mut k = nm1;
    let exp_diff = u64::exact_from(x_exp - y_exp);
    let mut round_bit;
    let mut sticky_bit;
    // round_bit_2 is the next bit after the round bit, and sticky_bit_2 the corresponding sticky
    // bit.
    let mut round_bit_2;
    let mut sticky_bit_2;
    let shift = prec.neg_mod_power_of_2(Limb::LOG_WIDTH);
    let shift_bit = Limb::power_of_2(shift);
    let mut goto_exact_normalize = false;
    let mut goto_sub_d1_no_lose = false;
    let mut goto_sub_d1_lose = false;
    let mut limb = 0;
    loop {
        // loop for ExactNormalize, SubD1NoLose, and SubD1Lose
        if !goto_sub_d1_no_lose && !goto_sub_d1_lose && (exp_diff == 0 || goto_exact_normalize) {
            // ```
            // <-- x -->
            // <-- y --> : exact sub
            // ```
            if !goto_exact_normalize {
                limbs_sub_same_length_in_place_right(xs, ys);
            }
            // label ExactNormalize:
            limb = ys[nm1];
            if limb != 0 {
                // First limb is not zero.
                let leading_zeros = LeadingZeros::leading_zeros(limb);
                // Warning: leading_zeros can be 0 when we come from the case SubD1Lose with
                // ExactNormalize
                if leading_zeros != 0 {
                    limbs_slice_shl_in_place(ys, leading_zeros);
                    x_exp.saturating_sub_assign(i32::wrapping_from(leading_zeros));
                }
                // Last limb should be OK
                assert_eq!(ys[0] & (shift_bit - 1), 0);
            } else {
                // - First limb is zero: this can only occur for n >= 2
                // - Find the first limb not equal to zero. It necessarily exists since |x| > |y|.
                //   We know that xs[k] > ys[k] and all upper limbs are equal.
                while ys[k] == 0 {
                    k -= 1;
                }
                limb = ys[k];
                // out[k] is the non-zero limb of largest index, thus we have to consider the k + 1
                // least-significant limbs
                assert_ne!(limb, 0);
                let leading_zeros = LeadingZeros::leading_zeros(limb);
                k += 1;
                let len = n - k; // Number of most significant zero limbs
                assert_ne!(k, 0);
                if leading_zeros != 0 {
                    limbs_slice_shl_in_place(&mut ys[..k], leading_zeros);
                }
                ys.copy_within(0..k, len);
                slice_set_zero(&mut ys[..len]);
                x_exp = i32::saturating_from(
                    i128::from(x_exp)
                        - (i128::from(leading_zeros)
                            + (i128::wrapping_from(len) << Limb::LOG_WIDTH)),
                );
                // out[len] should have its low bits zero: it is x[0] - y[0].
                assert_eq!(ys[len] & Limb::wrapping_from(shift), 0);
            }
            // No rounding is necessary since the result is exact
            assert!(ys[nm1].get_highest_bit());
            return (x_exp, Equal);
        } else if exp_diff == 1 || goto_sub_d1_no_lose || goto_sub_d1_lose {
            // ```
            // | <-- x -->
            // |  <-- y -->
            // ```
            if !goto_sub_d1_no_lose && !goto_sub_d1_lose {
                // If we lose at least one bit, compute 2 * x - y (exact), else compute x - y / 2
                limb = xs[k] - (ys[k] >> 1);
            }
            // Let W = 2 ^ Limb::WIDTH: we have |x| - |y| >= limb * W ^ k - (2 * W ^ k - 1) / 2 >=
            // limb
            // * W ^ k - W ^ k + 1 / 2. Thus, if limb > W / 2, |x| - |y| >= 1 / 2 * W ^ n. Moreover,
            //   if
            // trunc(|y|) represents the first prec - 1 bits of |y|, minus the last significant bit
            // called y0 below (in fact y0 is that bit shifted by `shift` bits), then we have
            // |x|-trunc(|y|) >= 1 / 2 * W ^ n + 1, thus the two limbs_sub calls below necessarily
            // yield out > 1 / 2 * W ^ n.
            if !goto_sub_d1_lose && (limb > LIMB_HIGH_BIT || goto_sub_d1_no_lose) {
                // - case limb > W / 2
                // - The exponent cannot decrease: compute x - y / 2.
                // - Shift y in the allocated temporary block
                //
                // label SubD1NoLose:
                let y0 = ys[0] & shift_bit;
                let mask = shift_bit - 1;
                // Zero last bit of y if set
                limbs_sub_shr_same_length_in_place_right_and_ys0(xs, ys, 1, !mask);
                assert!(ys[nm1].get_highest_bit());
                if y0 == 0 {
                    // Result is exact: no need of rounding!
                    return (x_exp, Equal);
                }
                // - y0 is non-zero, thus we have to subtract 1 / 2 * ulp(out).
                // - However, we know (see analysis above) that this cannot make the exponent
                //   decrease.
                // - Check last bits
                assert_eq!(ys[0] & mask, 0);
                // - No normalization is needed
                // - Rounding is necessary since y0 is non-zero
                // - We have to subtract 1 at the round bit position, and 0 for the lower bits
                round_bit = 1;
                round_bit_2 = 0;
                sticky_bit_2 = 0;
            } else if limb < LIMB_HIGH_BIT || goto_sub_d1_lose {
                // - |x| - |y| <= (W / 2 - 1) * W ^ k + W ^ k - 1 = 1 / 2 * W ^ n - 1
                // - The exponent decreases by one.
                // - Compute 2 * x - y (Exact)
                //
                // label SubD1Lose:
                goto_sub_d1_lose = false;
                limbs_sub_shl1_same_length_in_place_right(xs, ys);
                x_exp.saturating_sub_assign(1);
                assert_eq!(k, nm1);
                goto_exact_normalize = true;
                continue;
            } else {
                // - Case: limb = 100000000000
                // - Check while b[l] == y'[l] (Y' is Y shifted by 1)
                // - If x[l] < y'[l] => We lose at least one bit
                // - If x[l] > y'[l] => We don't lose any bit
                // - If l == -1 => We don't lose any bit AND the result is 100000000000 0000000000
                //   00000000000
                let mut l = n;
                let mut yl_shifted;
                loop {
                    // The first loop will compare x[n - 2] and y'[n - 2]
                    yl_shifted = ys[l - 1] << WIDTH_M1;
                    l -= 1;
                    if l == 0 {
                        break;
                    }
                    yl_shifted += ys[l - 1] >> 1;
                    if xs[l - 1] != yl_shifted {
                        break;
                    }
                }
                if l == 0 {
                    if yl_shifted != 0 {
                        // Since yl_shifted is what should be subtracted from out[-1], if non-zero
                        // then necessarily the precision is a multiple of Limb::WIDTH, and we lose
                        // one bit, thus the (exact) result is a power of 2 minus 1.
                        for o in ys.iter_mut() {
                            *o = Limb::MAX;
                        }
                        x_exp.saturating_sub_assign(1);
                    } else {
                        // yl_shifted = 0: result is a power of 2.
                        let (ys_last, ys_init) = ys.split_last_mut().unwrap();
                        slice_set_zero(ys_init);
                        *ys_last = LIMB_HIGH_BIT;
                    }
                    // No Normalize is needed, no Rounding is needed
                    return (x_exp, Equal);
                } else if xs[l - 1] > yl_shifted {
                    // - cl_shifted is the shifted value c'[l]
                    // - |x| - |y| >= 1 / 2 * W ^ n
                    //
                    // goto SubD1NoLose;
                    goto_sub_d1_no_lose = true;
                } else {
                    // We cannot have xs[l] = yl_shifted since the only way we can exit the while
                    // loop above is when xs[l] != yl_shifted or l < 0, and the case l < 0 was
                    // already treated above.
                    assert!(xs[l - 1] < yl_shifted);
                    // |x| - |y| <= 1 / 2 * W ^ n - 1 and is exact
                    goto_sub_d1_lose = true;
                }
                continue;
            }
        } else if exp_diff >= prec {
            // The difference of exponents is larger than the precision of all operands, thus the
            // result is either x or x - 1 ulp, with a possible exact result when x = prec, x = 2 ^
            // e and y = 1 / 2 * ulp(x)
            //
            // - We can't set OUT before since we use ys for rounding...
            // - Perform rounding: check if out = b or out = x - ulp(x)
            if exp_diff == prec {
                // since y is normalized, we need to subtract 1 / 2 * ulp(x)
                round_bit = 1;
                // round_bit_2 is the bit of weight 1 / 4 * ulp(x) in y. We assume a limb has at
                // least 2 bits. If the precision is 1, we read in the unused bits, which should be
                // zero, and this is what we want.
                round_bit_2 = ys[nm1] & HALF_LIMB_HIGH_BIT;
                // We also need sticky_bit_2
                sticky_bit_2 = ys[nm1] & WIDTH_M2_MASK;
                let mut k = nm1;
                while sticky_bit_2 == 0 && k > 0 {
                    k -= 1;
                    sticky_bit_2 = ys[k];
                }
            } else {
                round_bit = 0;
                if exp_diff == prec + 1 {
                    round_bit_2 = 1;
                    sticky_bit_2 = ys[nm1] & WIDTH_M1_MASK;
                    let mut k = nm1;
                    while sticky_bit_2 == 0 && k > 0 {
                        k -= 1;
                        sticky_bit_2 = ys[k];
                    }
                } else {
                    round_bit_2 = 0;
                    sticky_bit_2 = 1; // since C is non-zero
                }
            }
            // Copy mantissa X to Y
            ys.copy_from_slice(xs);
        } else {
            // case 2 <= exp_diff < prec
            //
            // Compute round_bit = Cp and sticky_bit = C'p + 1
            //
            // Compute round_bit and round_bit_2 from Y The round bit is bit prec - exp_diff in Y,
            // assuming the most significant bit of Y is bit 0
            let x = prec - exp_diff;
            let mut kx = nm1 - bit_to_limb_count_floor(x);
            let mut sx_bit = Limb::power_of_2(WIDTH_M1 - (x & Limb::WIDTH_MASK));
            // the round bit is in ys[kx], at position sx
            assert!(prec >= exp_diff);
            round_bit = ys[kx] & sx_bit;
            // Now compute rxx: since exp_diff >= 2 it always exists in Y
            sx_bit = if sx_bit == 1 {
                // rxx is in the next limb
                kx = kx.checked_sub(1).unwrap();
                LIMB_HIGH_BIT
            } else {
                // round_bit and round_bit_2 are in the same limb
                sx_bit >> 1
            };
            round_bit_2 = ys[kx] & sx_bit;
            // Now look at the remaining low bits of Y to determine sticky_bit_2
            sticky_bit_2 = ys[kx] & (sx_bit - 1);
            while sticky_bit_2 == 0 && kx > 0 {
                kx -= 1;
                sticky_bit_2 = ys[kx];
            }
            // Clean shifted Y'
            let mask = shift_bit - 1;
            let dm = exp_diff & Limb::WIDTH_MASK;
            let m = bit_to_limb_count_floor(exp_diff);
            if dm == 0 {
                assert_ne!(m, 0);
                // - dm = 0 and m > 0: Just copy
                // - Subtract the mantissa y from x in out
                limbs_sub_greater_in_place_right_different_ys0(xs, ys, ys[m] & !mask, m);
            } else if m == 0 {
                // dm >=2 and m == 0: just shift
                assert!(dm >= 2);
                // Subtract the mantissa y from x in out
                limbs_sub_shr_same_length_in_place_right_and_ys0(xs, ys, dm, !mask);
            } else {
                // - dm > 0 and m > 0: shift and zero
                // - Subtract the mantissa y from x in out
                limbs_sub_shr_greater_in_place_right_and_ys0(xs, ys, dm, !mask, m);
            }
            // Normalize: we lose at most one bit
            if !ys[nm1].get_highest_bit() {
                // - High bit is not set and we have to fix it.
                // - OUT >= 010000xxx001
                limbs_slice_shl_in_place(ys, 1);
                // OUT >= 100000xxx010
                if round_bit != 0 {
                    // - Check if Y = -1
                    // - Since Y == -1, we have to subtract one more
                    limbs_sub_limb_in_place(ys, shift_bit);
                    assert!(ys[nm1].get_highest_bit());
                }
                // - OUT >= 10000xxx001
                // - Final exponent -1 since we have shifted the mantissa
                x_exp.saturating_sub_assign(1);
                round_bit = round_bit_2;
                round_bit_2 = sticky_bit_2;
                // We don't have anymore a valid Yp + 1, but since Oyr >= 100000xxx001, the final
                // sub can't unnormalize.
            }
            assert_eq!(ys[0] & mask, 0);
        }
        // only loop when emulating gotos
        break;
    }
    let mut ys_power_of_2;
    loop {
        // At this point out contains x - high(y), normalized, and we have to subtract round_bit *
        // 1/2 ulp(out), round_bit_2 * 1/4 ulp(out), and sticky_bit_2 * 1/8 ulp(out), interpreting
        // round_bit/round_bit_2/sticky_bit_2 as 1 if non-zero.
        sticky_bit = round_bit_2 | sticky_bit_2;
        if round_bit == 0 && sticky_bit == 0 {
            return (x_exp, Equal);
        }
        ys_power_of_2 = limbs_is_power_of_2(ys);
        if ys_power_of_2 && round_bit != 0 {
            limbs_sub_limb_in_place(ys, shift_bit);
            ys[nm1] |= LIMB_HIGH_BIT;
            x_exp.saturating_sub_assign(1);
            round_bit = round_bit_2;
            round_bit_2 = sticky_bit_2;
            sticky_bit_2 = 0;
        } else {
            break;
        }
    }
    // Now if out is a power of two, necessary round_bit = 0, which means the exact result is always
    // in (pred(ys), ys), and the bounds cannot be attained
    match rm {
        Exact => panic!("Inexact float subtraction"),
        Nearest => {
            if ys_power_of_2 {
                assert_eq!(round_bit, 0);
                // Since we are at the end of the binade, we have in fact round_bit = round_bit_2
                // and sticky_bit = sticky_bit_2
                round_bit = round_bit_2;
                sticky_bit = sticky_bit_2;
            }
            if (prec == 1 || ys[0] & shift_bit == 0 || round_bit == 0)
                && (sticky_bit == 0 || round_bit == 0)
            {
                (x_exp, Greater)
            } else {
                limbs_sub_limb_in_place(ys, shift_bit);
                if ys_power_of_2 {
                    // deal with cancellation
                    ys[nm1] |= LIMB_HIGH_BIT;
                    x_exp.saturating_sub_assign(1);
                }
                (x_exp, Less)
            }
        }
        Floor | Down => {
            limbs_sub_limb_in_place(ys, shift_bit);
            if ys_power_of_2 {
                // deal with cancellation
                ys[nm1] |= LIMB_HIGH_BIT;
                x_exp.saturating_sub_assign(1);
            }
            (x_exp, Less)
        }
        Ceiling | Up => (x_exp, Greater),
    }
}

// This is mpfr_cmp2 from cmp2.c, MPFR 4.2.0, returning `cancel` along with `sign`.
pub fn exponent_shift_compare<'a>(
    mut xs: &'a [Limb],
    mut x_exp: i64,
    mut x_prec: u64,
    mut ys: &'a [Limb],
    mut y_exp: i64,
    mut y_prec: u64,
) -> (Ordering, u64) {
    // x == y should not happen, since cmp2 is called only from agm (with different variables) and
    // from sub1 (if b=c, then sub1sp would be called instead). So, no need for a particular
    // optimization here.
    //
    // the cases b=0 or c=0 are also treated apart in agm and sub (which calls sub1)
    let sdiff_exp = x_exp - y_exp;
    let mut sign;
    let mut diff_exp;
    // index of the most significant limb of x and y
    let mut xi = bit_to_limb_count_floor(x_prec - 1);
    let mut yi = bit_to_limb_count_floor(y_prec - 1);
    let mut xi_done = false;
    let mut yi_done = false;
    let mut res = 0;
    if sdiff_exp >= 0 {
        sign = Greater; // assumes |x| > |y|; will be changed if not.
        diff_exp = u64::wrapping_from(sdiff_exp);
        let mut cancel = 0;
        // If diff_exp != 0, i.e. diff_exp > 0, then |x| > |y|. Otherwise...
        if diff_exp == 0 {
            // Skip the identical most significant limbs, adding Limb::WIDTH to the number of
            // canceled bits at each iteration.
            while !xi_done && !yi_done && xs[xi] == ys[yi] {
                if xi == 0 {
                    xi_done = true;
                } else {
                    xi -= 1;
                }
                if yi == 0 {
                    yi_done = true;
                } else {
                    yi -= 1;
                }
                res += Limb::WIDTH;
            }
            if xi_done {
                // |x| = |y|
                if yi_done {
                    return (Equal, cancel);
                }
                // x has been read entirely, but not y. Thus |x| <= |y|. Swap xs and ys, and take
                // the opposite sign for the symmetric case below (simulating a swap). Note:
                // "yi_done = true;" is necessary to enter the following "if" (probably less
                // confusing than a "goto").
                swap(&mut xs, &mut ys);
                swap(&mut xi, &mut yi);
                swap(&mut x_exp, &mut y_exp);
                swap(&mut x_prec, &mut y_prec);
                xi_done = yi_done;
                yi_done = true;
                sign = Less;
            }
            if yi_done {
                // y discards exactly the upper part of x
                assert!(!xi_done);
                // Skip null limbs of x (= non-represented null limbs of y), adding Limb::WIDTH to
                // the number of canceled bits at each iteration.
                while xs[xi] == 0 {
                    // |x| = |y|
                    if xi == 0 {
                        xi_done = true;
                    } else {
                        xi -= 1;
                    }
                    if xi_done {
                        return (Equal, cancel);
                    }
                    res += Limb::WIDTH;
                }
                let z = LeadingZeros::leading_zeros(xs[xi]);
                // xs[xn] != 0
                cancel = res + z;
                return (sign, cancel);
            }
            assert!(!xi_done);
            assert!(!yi_done);
            assert!(xs[xi] != ys[yi]);
            // |x| != |y|. If |x| < |y|: swap xs and ys, and take the opposite sign.
            if xs[xi] < ys[yi] {
                swap(&mut xs, &mut ys);
                swap(&mut xi, &mut yi);
                swap(&mut xi_done, &mut yi_done);
                swap(&mut x_exp, &mut y_exp);
                swap(&mut x_prec, &mut y_prec);
                sign = Less;
            }
        }
    } else {
        // We necessarily have |x| < |y|.
        sign = Less;
        diff_exp = u64::exact_from(-sdiff_exp);
        swap(&mut xs, &mut ys);
        swap(&mut xi, &mut yi);
        swap(&mut x_exp, &mut y_exp);
        swap(&mut x_prec, &mut y_prec);
    }
    // Now we have removed the identical upper limbs of x and y (when diff_exp = 0), and after the
    // possible swap, we have |x| > |y|. The value diff_exp = EXP(x) - EXP(y) can be regarded as the
    // number of leading zeros of y, when aligned with x.
    //
    // When a limb of y is read from memory, the part that is not taken into account for the
    // operation with a limb xs[xn] of x will be put in lasty, shifted to the leftmost part (for
    // alignment with x):
    // ```
    // [-------- xs[xn] --------][------- xs[xn-1] -------]
    // [-- old_lasty --][-------- ys[yn] --------]
    //                           [-- new_lastc --]
    // ```
    // Note: if diff_exp == 0, then lasty will always remain 0.
    let mut lasty = 0;
    // Compute the next limb difference, which cannot be 0 (dif >= 1).
    let mut yy;
    if diff_exp < Limb::WIDTH {
        yy = ys[yi] >> diff_exp;
        if diff_exp != 0 {
            lasty = ys[yi] << (Limb::WIDTH - diff_exp);
        }
        if yi == 0 {
            yi_done = true;
        } else {
            yi -= 1;
        }
    } else {
        yy = 0;
        // remove Limb::WIDTH leading zeros
        diff_exp -= Limb::WIDTH;
    }
    // no borrow out in subtraction below
    assert!(xs[xi] >= yy);
    let mut dif = xs[xi] - yy;
    if xi == 0 {
        xi_done = true;
    } else {
        xi -= 1;
    }
    assert!(dif >= 1);
    let mut high_dif = false;
    // The current difference, here and later, is expressed under the form [high_dif][dif], where
    // high_dif is 0 or 1, and dif is a limb. Here, since we have computed a difference of limbs
    // (with x >= y), high_dif = 0.
    //
    // One needs to accumulate canceled bits for the remaining case where x and y are close to each
    // other due to a long borrow propagation:
    // ```
    //   x = [common part]1000...000[low(x)]
    //   y = [common part]0111...111[low(y)]
    // ```
    // After eliminating the common part above, we have computed a difference of the most
    // significant parts, which has been stored in [high_dif][dif] with high_dif = 0. We will loop
    // as long as the currently computed difference [high_dif][dif] = 1 (it is >= 1 by
    // construction). The computation of the difference will be:
    // ```
    //    1xxx...xxx
    //   - yyy...yyy
    // ```
    // where the leading 1 before xxx...xxx corresponds to [high_dif][dif] at the beginning of the
    // loop. We will exit the loop also when y has entirely been taken into account as cancellation
    // is no longer possible in this case (it is no longer possible to cancel the leading 1). Note:
    // We can enter the loop only with diff_exp = 0 (with a non-empty common part, partly or
    // entirely removed) or with diff_exp = 1 (with an empty common part). Indeed, if diff_exp > 1,
    // then no limbs have been skipped, so that xs[xn] had its MSB equal to 1 and the most two
    // significant bits of yy are 0, which implies that dif > 1.
    while (!yi_done || lasty != 0) && !high_dif && dif == 1 {
        // Since we consider the next limb, we assume a cancellation of Limb::WIDTH (the new
        // exponent of the difference now being the one of the MSB of the next limb). But if the
        // leading 1 remains 1 in the difference (i.e. high_dif = 1 at the end of the loop), then we
        // will need to decrease res.
        res += Limb::WIDTH;
        // - See comment before the loop
        // - Next limb of x or non-represented 0
        assert!(diff_exp <= 1);
        let xx = if xi_done {
            0
        } else {
            let r = xs[xi];
            if xi == 0 {
                xi_done = true;
            } else {
                xi -= 1;
            }
            r
        };
        if yi_done {
            yy = lasty;
            lasty = 0;
        } else if diff_exp == 0 {
            yy = ys[yi];
            if yi == 0 {
                yi_done = true;
            } else {
                yi -= 1;
            }
        } else {
            assert_eq!(diff_exp, 1);
            assert!(lasty == 0 || lasty == LIMB_HIGH_BIT);
            yy = lasty + (ys[yi] >> 1);
            lasty = ys[yi] << (Limb::WIDTH - 1);
            if yi == 0 {
                yi_done = true;
            } else {
                yi -= 1;
            }
        }
        dif = xx.wrapping_sub(yy);
        high_dif = xx >= yy;
    }
    // Now, y has entirely been taken into account or [high_dif][dif] > 1. In any case,
    // [high_dif][dif] >= 1 by construction. First, we determine the currently number of canceled
    // bits, corresponding to the exponent of the current difference. The trailing bits of y, if
    // any, can still decrease the exponent of the difference when [high_dif][dif] is a power of
    // two, but since [high_dif][dif] > 1 in this case, by not more than 1.
    if high_dif {
        // high_dif == 1 See comment at the beginning of the above loop.
        res = res.checked_sub(1).unwrap();
        // Terminate if [high_dif][dif] is not a power of two.
        if dif != 0 {
            return (sign, res);
        }
    } else {
        // high_dif == 0
        assert!(dif >= 1); // [high_dif][dif] >= 1
        res += LeadingZeros::leading_zeros(dif);
        // Terminate if [high_dif][dif] is not a power of two.
        if !dif.is_power_of_2() {
            return (sign, res);
        }
    }
    // Now, the result will be res + (low(x) < low(y)).
    //
    // If y has entirely been taken into account, it can no longer modify the current result.
    if yi_done && lasty == 0 {
        return (sign, res);
    }
    if !xi_done {
        for &x in xs[..=xi].iter().rev() {
            if diff_exp >= Limb::WIDTH {
                diff_exp -= Limb::WIDTH;
                assert_eq!(yy, 0);
            } else if yi_done {
                yy = lasty;
                lasty = 0;
            } else if diff_exp == 0 {
                yy = ys[yi];
                if yi == 0 {
                    yi_done = true;
                } else {
                    yi -= 1;
                }
            } else {
                assert!((1..Limb::WIDTH).contains(&diff_exp));
                yy = lasty + (ys[yi] >> diff_exp);
                lasty = ys[yi] << (Limb::WIDTH - diff_exp);
                if yi == 0 {
                    yi_done = true;
                } else {
                    yi -= 1;
                }
            }
            if x != yy {
                return (sign, if x < yy { res + 1 } else { res });
            }
        }
    }
    // x has entirely been read. Determine whether the trailing part of y is non-zero.
    if lasty != 0 || !slice_test_zero(&ys[..=yi]) {
        res += 1;
    }
    (sign, res)
}

fn sub_float_significands_general<'a>(
    out: &mut [Limb],
    mut xs: &'a [Limb],
    mut x_exp: i32,
    mut x_prec: u64,
    mut ys: &'a [Limb],
    mut y_exp: i32,
    mut y_prec: u64,
    out_prec: u64,
    mut rm: RoundingMode,
) -> (i32, Ordering, bool) {
    let mut xs_len = xs.len();
    let mut ys_len = ys.len();
    let out_len = out.len();
    let mut add_exp = false;
    let (sign, cancel) =
        exponent_shift_compare(xs, i64::from(x_exp), x_prec, ys, i64::from(y_exp), y_prec);
    if sign == Equal {
        // x == y. Return exact number 0. Setting the most-significant limb to 0 is a sufficient
        // signal to the caller that the entire output is 0, since in every other case the precision
        // of the output is the same as the precision of the inputs, and the most-significant limb
        // is therefore nonzero.
        *out.last_mut().unwrap() = 0;
        return (0, Equal, false);
    }
    // sign != 0, so that cancel has a valid value.
    //
    // If subtraction: sign(out) = sign * sign(x) If addition: sign(out) = sign of the larger
    // argument in absolute value.
    //
    // Both cases can be simplified in:
    // ```
    // if (sign>0)
    //    if addition: sign(out) = sign * sign(x) = sign(x)
    //    if subtraction, x is greater, so sign(out) = sign(x)
    // else
    //    if subtraction, sign(out) = -sign(x)
    //    if addition, sign(out) = sign(y) (since y is greater)
    //      But if it is an addition, sign(x) and sign(y) are opposed!
    //      So sign(out) = -sign(x)
    // ```
    let neg = sign == Less;
    if neg {
        // swap x and y so that |x| > |y|
        swap(&mut xs, &mut ys);
        swap(&mut xs_len, &mut ys_len);
        swap(&mut x_exp, &mut y_exp);
        swap(&mut x_prec, &mut y_prec);
        rm.neg_assign();
    }
    let exp_diff = u64::exact_from(x_exp - y_exp);
    // Check if y is too small.
    let mut inexact = 0;
    if max(out_prec, x_prec) + 2 <= exp_diff {
        // Remember, we can't have an exact result!
        // ```
        //   A.AAAAAAAAAAAAAAAAA
        // = B.BBBBBBBBBBBBBBB
        //  -                     C.CCCCCCCCCCCCC
        // A = S*ABS(B) +/- ulp(a)
        // ```
        assert_ne!(rm, Exact, "Inexact float subtraction");
        let mut exp_a = x_exp;
        let increment_exp;
        (inexact, increment_exp) = round_helper_even(out, out_prec, xs, x_prec, rm);
        if increment_exp {
            exp_a += 1;
        }
        if inexact == 0 && rm != Down && rm != Floor {
            // out = x, but the exact value of x - y is a bit below. Then, except for directed
            // rounding similar to toward zero and before overflow checking: a is the correctly
            // rounded value and since |x| - |y| < |out|, the ternary value is given by the sign of
            // out.
            inexact = 1;
        } else if inexact != 0 && inexact != MPFR_EVEN_INEX {
            // ```
            //   O.OOOOOOOOOOOOOO
            // = X.XXXXXXXXXXXXXXX
            //  -                   Y.YYYYYYYYYYYYY
            // ```
            //
            // It isn't exact, so PREC(x) > PREC(out) and the last PREC(x)-PREC(out) bits of x are
            // not all zeros. Subtracting y from x will not have an effect on the rounding except in
            // case of a midpoint in the round-to-nearest mode, when the even rounding was done away
            // from zero instead of toward zero.
            //
            // In case of even rounding:
            // ```
            //   1.BBBBBBBBBBBBBx10
            // -                     1.CCCCCCCCCCCC
            // = 1.BBBBBBBBBBBBBx01  Rounded to PREC(x)
            // = 1.BBBBBBBBBBBBBx    Nearest / Rounded to PREC(out)
            // ```
            //
            // Set gives:
            // ```
            //   1.BBBBBBBBBBBBB0   if inexact == EVEN_INEX  (x == 0)
            //   1.BBBBBBBBBBBBB1+1 if inexact == -EVEN_INEX (x == 1)
            // ````
            // which means we get a wrong rounded result if x == 1, i.e. inexact == MPFR_EVEN_INEX
            // (for positive numbers).
            //
            // Nothing to do.
        } else {
            // We need to take the value preceding |out|. We can't use mpfr_nexttozero due to a
            // possible out-of-range exponent. But this will allow us to have more specific code.
            limbs_sub_limb_in_place(out, Limb::power_of_2(limb_to_bit_count(out_len) - out_prec));
            let last_out = out.last_mut().unwrap();
            if !last_out.get_highest_bit() {
                exp_a.saturating_sub_assign(1);
                // The following is valid whether out_len = 1 or out_len > 1.
                *last_out |= LIMB_HIGH_BIT;
            }
            inexact = -1;
        }
        return (exp_a, inexact.sign(), neg);
    }
    // Reserve a space to store x aligned with the result, i.e. shifted by (-cancel) % Limb::WIDTH
    // to the right
    let shift_x = cancel.neg_mod_power_of_2(Limb::LOG_WIDTH);
    let cancel1 = bit_to_limb_count_floor(cancel + shift_x);
    let mut shifted_x;
    // the `high cancel1` limbs from x should not be taken into account
    let xs = if shift_x == 0 {
        // no need of an extra space
        xs
    } else {
        shifted_x = vec![0; xs_len + 1];
        let (shifted_head, shifted_tail) = shifted_x.split_first_mut().unwrap();
        *shifted_head = limbs_shr_to_out(shifted_tail, xs, shift_x);
        xs_len += 1;
        &shifted_x
    };
    // Reserve a space to store y aligned with the result, i.e. shifted by (diff_exp - cancel) %
    // Limb::WIDTH to the right
    let shift_y = exp_diff
        .mod_power_of_2(Limb::LOG_WIDTH)
        .mod_power_of_2_sub(cancel.mod_power_of_2(Limb::LOG_WIDTH), Limb::LOG_WIDTH);
    assert!(shift_y < Limb::WIDTH);
    let mut shifted_y;
    let ys = if shift_y == 0 {
        ys
    } else {
        shifted_y = vec![0; ys_len + 1];
        let (shifted_head, shifted_tail) = shifted_y.split_first_mut().unwrap();
        *shifted_head = limbs_shr_to_out(shifted_tail, ys, shift_y);
        ys_len += 1;
        &shifted_y
    };
    // here we have shift_y = (diff_exp - cancel) % Limb::WIDTH, 0 <= shift_y < Limb::WIDTH, thus we
    // want cancel2 = ceil((cancel - diff_exp) / Limb::WIDTH)
    let cancel2 = if cancel >= exp_diff {
        // Note that cancel is signed and will be converted to mpfr_uexp_t (type of diff_exp) in the
        // expression below, so that this will work even if cancel is very large and diff_exp = 0.
        (i128::from(cancel) - i128::from(exp_diff) + i128::wrapping_from(IWIDTH_M1))
            >> Limb::LOG_WIDTH
    } else {
        -((i128::from(exp_diff) - i128::from(cancel)) >> Limb::LOG_WIDTH)
    };
    // The high cancel2 limbs from x should not be taken into account
    //
    // ```
    //                 ap[an-1]        ap[0]
    //             <----------------+-----------|---->
    //             <----------PREC(a)----------><-sh->
    // cancel1
    // limbs        bp[bn-cancel1-1]
    // <--...-----><----------------+-----------+----------->
    //  cancel2
    //  limbs       cp[cn-cancel2-1]                                    cancel2 >= 0
    //    <--...--><----------------+----------------+---------------->
    //                (-cancel2)                                        cancel2 < 0
    //                   limbs      <----------------+---------------->
    // ```
    //
    // First part: put in out[0..out_len - 1] the value of high(x) - high(y), where high(x) consists
    // of the high out_len + cancel1 limbs of x, and high(y) consists of the high out_len + cancel2
    // limbs of y.
    //
    // Copy high(x) into out
    if out_len + cancel1 <= xs_len {
        // ```
        // out: <----------------+-----------|---->
        // xs:  <----------------------------------------->
        // ```
        let xs_hi = &xs[xs_len - out_len - cancel1..];
        out.copy_from_slice(&xs_hi[..out_len]);
    } else {
        // ```
        // out: <----------------+-----------|---->
        // xs:  <------------------------->
        // ```
        if cancel1 < xs_len {
            let (out_lo, out_hi) = out.split_at_mut(out_len + cancel1 - xs_len);
            slice_set_zero(out_lo);
            out_hi.copy_from_slice(&xs[..xs_len - cancel1]);
        }
    }
    // subtract high(y)
    if i128::wrapping_from(out_len) + cancel2 > 0 {
        if cancel2 >= 0 {
            let cancel2 = usize::exact_from(cancel2);
            if out_len + cancel2 <= ys_len {
                // ```
                // out: <----------------------------->
                // ys:  <----------------------------------------->
                // ```
                let ys_hi = &ys[ys_len - out_len - cancel2..];
                limbs_sub_same_length_in_place_left(out, &ys_hi[..out_len]);
            } else {
                // ```
                // out: <---------------------------->
                // ys:  <------------------------->
                // ```
                if ys_len > cancel2 {
                    limbs_sub_same_length_in_place_left(
                        &mut out[out_len + cancel2 - ys_len..],
                        &ys[..ys_len - cancel2],
                    );
                }
            }
        } else {
            // cancel2 < 0
            let neg_cancel2 = usize::exact_from(-cancel2);
            let (out_lo, out_hi) = out.split_at_mut(out_len - neg_cancel2);
            let borrow = if out_len - neg_cancel2 <= ys_len {
                // ```
                // a: <----------------------------->
                // c: <----------------------------->
                // ```
                limbs_sub_same_length_in_place_left(out_lo, &ys[ys_len - (out_len - neg_cancel2)..])
            } else {
                // ```
                // a: <---------------------------->
                // c: <---------------->
                // ```
                let len = out_lo.len();
                limbs_sub_same_length_in_place_left(&mut out_lo[len - ys_len..], ys)
            };
            limbs_sub_limb_in_place(out_hi, Limb::from(borrow));
        }
    }
    // Now perform rounding
    let shift = limb_to_bit_count(out_len) - out_prec;
    let shift_bit = Limb::power_of_2(shift);
    let shift_mask = shift_bit - 1;
    // Last unused bits from out
    let out_head = out.first_mut().unwrap();
    let carry = *out_head & shift_mask;
    *out_head -= carry;
    let mut cmp_low = 0;
    let mut goto_truncate = false;
    let mut goto_end_of_sub = false;
    if rm == Nearest {
        if shift != 0 {
            let half_shift_bit = shift_bit >> 1;
            // Can decide except when carry = 2 ^ (sh - 1) [middle] or carry = 0 [truncate, but
            // cannot decide inexact flag]
            if carry > half_shift_bit {
                if limbs_slice_add_limb_in_place(out, shift_bit) {
                    // result is a power of 2: 11111111111111 + 1 = 1000000000000000
                    out[out_len - 1] = LIMB_HIGH_BIT;
                    add_exp = true;
                }
                // result larger than exact value
                inexact = 1;
                goto_truncate = true;
            } else if carry != 0 && carry < half_shift_bit {
                inexact = -1; // result if smaller than exact value
                goto_truncate = true;
            } else {
                // now carry = 2 ^ (sh - 1), in which case cmp_low = 2, or carry = 0, in which case
                // cmp_low = 0
                cmp_low = if carry == 0 { 0 } else { 2 };
            }
        }
    } else if carry != 0 {
        if rm == Floor || rm == Down || rm == Exact {
            inexact = -1;
        } else {
            if limbs_slice_add_limb_in_place(out, shift_bit) {
                // result is a power of 2: 11111111111111 + 1 = 1000000000000000
                out[out_len - 1] = LIMB_HIGH_BIT;
                add_exp = true;
            }
            // result larger than exact value
            inexact = 1;
        }
        goto_truncate = true;
    }
    if !goto_truncate {
        // We have to consider the low (xs_len - (out_len + cancel1)) limbs from x, and the (ys_len
        // - (out_len + cancel2)) limbs from y.
        xs_len.saturating_sub_assign(out_len + cancel1);
        let ys_len0 = ys_len;
        ys_len = usize::saturating_from(
            i128::wrapping_from(ys_len) - (i128::wrapping_from(out_len) + cancel2),
        );
        // For rounding to nearest, we couldn't conclude up to here in the following cases:
        // - shift = 0, then cmp_low = 0: we can either truncate, subtract one ulp or add one ulp:
        //   -1 ulp < low(x) - low(y) < 1 ulp
        // - shift > 0 but the low `shift` bits from high(x) - high(y) equal 2 ^ (shift - 1): -0.5
        //   ulp <= -1 / 2 ^ shift < low(x) - low(y) - 0.5 < 1 / 2 ^ shift <= 0.5 ulp we can't
        //   decide the rounding, in that case cmp_low = 2: either we truncate and flag = -1, or we
        //   add one ulp and flag = 1
        // - The low shift > 0 bits from high(x)-high(y) equal 0: we know we have to truncate but we
        //   can't decide the ternary value, here cmp_low = 0: -0.5 ulp <= -1 / 2 ^ shift < low(x)
        //   -low(y) < 1 / 2 ^ shift <= 0.5 ulp we always truncate and inexact can be any of -1, 0,
        //   1
        // - Note: here ys_len might exceed ys_len0, in which case we consider a zero limb
        let mut k: i32 = 0;
        while xs_len != 0 || ys_len != 0 {
            // - If cmp_low < 0, we know low(x) - low(y) < 0
            // - If cmp_low > 0, we know low(x) - low(y) > 0 (more precisely if cmp_low = 2, low(x)
            //   - low(y) = 0.5 ulp so far)
            // - If cmp_low = 0, so far low(x) - low(y) = 0
            // - get next limbs
            let mut xx = if xs_len != 0 {
                xs_len -= 1;
                xs[xs_len]
            } else {
                0
            };
            let mut yy = if ys_len != 0 && {
                let c = ys_len <= ys_len0;
                ys_len -= 1;
                c
            } {
                ys[ys_len]
            } else {
                0
            };
            // cmp_low compares low(x) and low(y)
            if cmp_low == 0 {
                // case 1 or 3
                cmp_low = match xx.cmp(&yy) {
                    Greater => 1,
                    Less => -2 + k,
                    Equal => 0,
                };
            }
            // Case 1 for k=0 splits into 7 subcases:
            // - 1a: xx > yy + half
            // - 1b: xx = yy + half
            // - 1c: 0 < xx - yy < half
            // - 1d: xx = yy
            // - 1e: -half < xx - yy < 0
            // - 1f: xx - yy = -half
            // - 1g: xx - yy < -half
            //
            // Case 2 splits into 3 subcases:
            // - 2a: xx > yy
            // - 2b: xx = yy
            // - 2c: xx < yy
            //
            // Case 3 splits into 3 subcases:
            // - 3a: xx > yy
            // - 3b: xx = yy
            // - 3c: xx < yy
            //
            // The case rounding to nearest with sh=0 is special since one couldn't subtract above
            // 1/2 ulp in the trailing limb of the result
            if rm == Nearest && shift == 0 && k == 0 {
                // case 1 for k = 0
                // - add one ulp if xx > yy + half
                // - truncate if yy - half < xx < yy + half
                // - sub one ulp if xx < yy - half
                if cmp_low < 0 {
                    // - xx < yy: -1 ulp < low(b) - low(c) < 0,
                    // - cases 1e, 1f and 1g
                    if yy >= LIMB_HIGH_BIT {
                        yy -= LIMB_HIGH_BIT;
                    } else {
                        // since xx < yy < half, xx + half < 2 * half
                        xx += LIMB_HIGH_BIT;
                    }
                    // Now we have xx < yy + half: we have to subtract one ulp if xx < yy, and
                    // truncate if xx > yy
                } else {
                    // xx >= yy, cases 1a to 1d
                    if yy < LIMB_HIGH_BIT {
                        yy += LIMB_HIGH_BIT;
                    } else {
                        // since xx >= yy >= half, xx - half >= 0
                        xx -= LIMB_HIGH_BIT;
                    }
                    // Now we have xx > yy - half: we have to add one ulp if xx > yy, and truncate
                    // if xx < yy
                    if cmp_low > 0 {
                        cmp_low = 2;
                    }
                }
            }
            match cmp_low.sign() {
                Less => {
                    // low(x) - low(y) < 0: either truncate or subtract one ulp
                    match rm {
                        Floor | Down => {
                            limbs_sub_limb_in_place(out, shift_bit);
                            inexact = -1;
                            goto_end_of_sub = true;
                        }
                        Ceiling | Up | Exact => {
                            inexact = 1;
                            goto_truncate = true;
                        }
                        Nearest => {
                            // - If cmp_low < 0 and xx > yy, then -0.5 ulp < low(x) - low(y) < 0,
                            //   whatever the value of shift.
                            // - If shift > 0, then cmp_low < 0 implies that the initial neglected
                            //   shift bits were 0 (otherwise cmp_low = 2 initially), thus the
                            //   weight of the new bits is less than 0.5 ulp too.
                            // - If k > 0 (and shift = 0) this means that either the first neglected
                            //   limbs xx and yy were equal (thus cmp_low was 0 for k = 0), or we
                            //   had xx - yy = -0.5 ulp or 0.5 ulp.
                            // - The last case is not possible here since we would have cmp_low > 0
                            //   which is sticky.
                            // - In the first case (where we have cmp_low = -1), we truncate,
                            //   whereas in the 2nd case we have cmp_low = -2 and we subtract one
                            //   ulp.
                            if xx > yy || shift > 0 || cmp_low == -1 {
                                // - -0.5 ulp < low(b)-low(c) < 0,
                                // - xx > yy corresponds to cases 1e and 1f1
                                // - shift > 0 corresponds to cases 3c and 3b3
                                // - cmp_low = -1 corresponds to case 1d3 (also 3b3)
                                inexact = 1;
                                goto_truncate = true;
                            } else if xx < yy {
                                // Here shift = 0 and low(x) - low(y) < -0.5 ulp, this corresponds
                                // to cases 1g and 1f3
                                //
                                limbs_sub_limb_in_place(out, shift_bit);
                                inexact = -1;
                                goto_end_of_sub = true;
                            }
                            // The only case where we can't conclude is shift = 0 and xx = yy, i.e.,
                            // we have low(x)
                            // - low(y) = -0.5 ulp (up to now), thus we don't know if we must
                            //   truncate or
                            // subtract one ulp. Note: for shift = 0 we can't have low(x) - low(y) =
                            // -0.5 ulp up to now, since low(x) - low(y) > 1 / 2 ^ shift
                        }
                    }
                }
                Greater => {
                    // 0 < low(x) - low(y): either truncate or add one ulp
                    match rm {
                        Floor | Down | Exact => {
                            inexact = -1;
                            goto_truncate = true;
                        }
                        Ceiling | Up => {
                            if limbs_slice_add_limb_in_place(out, shift_bit) {
                                // result is a power of 2: 11111111111111 + 1 = 1000000000000000
                                out[out_len - 1] = LIMB_HIGH_BIT;
                                add_exp = true;
                            }
                            // result larger than exact value
                            inexact = 1;
                            goto_truncate = true;
                        }
                        Nearest => {
                            match xx.cmp(&yy) {
                                Greater => {
                                    // If sh = 0, then xx > yy means that low(x) - low(y) > 0.5 ulp,
                                    // and similarly when cmp_low = 2.
                                    if cmp_low == 2 {
                                        // cases 1a, 1b1, 2a and 2b1
                                        //
                                        // shift > 0 and cmp_low > 0: this implies that the `shift`
                                        // initial neglected bits were 0, and the remaining low(x) -
                                        // low(y) > 0, but its weight is less than 0.5 ulp
                                        if limbs_slice_add_limb_in_place(out, shift_bit) {
                                            // result is a power of 2: 11111111111111 + 1 =
                                            // 1000000000000000
                                            out[out_len - 1] = LIMB_HIGH_BIT;
                                            add_exp = true;
                                        }
                                        // result larger than exact value
                                        inexact = 1;
                                    } else {
                                        // 0 < low(x) - low(y) < 0.5 ulp, this corresponds to cases
                                        // 3a, 1d1 and 3b1
                                        inexact = -1;
                                    }
                                    goto_truncate = true;
                                }
                                Less => {
                                    // 0 < low(x) - low(y) < 0.5 ulp, cases 1c, 1b3, 2b3 and 2c
                                    inexact = -1;
                                    goto_truncate = true;
                                }
                                Equal => {
                                    // The only case where we can't conclude is xx = yy, i.e.,
                                    // low(x) - low(y) = 0.5 ulp (up to now), thus we don't know if
                                    // we must truncate or add one ulp.
                                }
                            }
                        }
                    }
                }
                _ => {}
            }
            // After k = 0, we cannot conclude in the following cases, we split them according to
            // the values of xx and yy for k = 1:
            // ```
            // 1b. shift = 0 and cmp_low = 1 and xx-yy = half [around 0.5 ulp]
            //     1b1. xx > yy: add one ulp, inex = 1
            //     1b2: xx = yy: cannot conclude
            //     1b3: xx < yy: truncate, inex = -1
            // 1d. shift = 0 and cmp_low = 0 and xx-yy = 0 [around 0]
            //     1d1: xx > yy: truncate, inex = -1
            //     1d2: xx = yy: cannot conclude
            //     1d3: xx < yy: truncate, inex = +1
            // 1f. shift = 0 and cmp_low = -1 and xx-yy = -half [around -0.5 ulp]
            //     1f1: xx > yy: truncate, inex = +1
            //     1f2: xx = yy: cannot conclude
            //     1f3: xx < yy: sub one ulp, inex = -1
            // 2b. shift > 0 and cmp_low = 2 and xx=yy [around 0.5 ulp]
            //     2b1. xx > yy: add one ulp, inex = 1
            //     2b2: xx = yy: cannot conclude
            //     2b3: xx < yy: truncate, inex = -1
            // 3b. shift > 0 and cmp_low = 0 [around 0]
            //     3b1. xx > yy: truncate, inex = -1
            //     3b2: xx = yy: cannot conclude
            //     3b3: xx < yy: truncate, inex = +1
            // ```
            if goto_truncate || goto_end_of_sub {
                break;
            }
            k = 1;
        }
        if !goto_truncate && !goto_end_of_sub {
            inexact = if rm == Nearest && cmp_low != 0 {
                // Even rounding rule
                if (out[0] >> shift) & 1 != 0 {
                    if cmp_low < 0 {
                        limbs_sub_limb_in_place(out, shift_bit);
                        goto_end_of_sub = true;
                        -1
                    } else {
                        if limbs_slice_add_limb_in_place(out, shift_bit) {
                            // result is a power of 2: 11111111111111 + 1 = 1000000000000000
                            out[out_len - 1] = LIMB_HIGH_BIT;
                            add_exp = true;
                        }
                        // result larger than exact value
                        1
                    }
                } else if cmp_low > 0 {
                    -1
                } else {
                    1
                }
            } else {
                0
            };
        }
    }
    let last_out = &mut out[out_len - 1];
    if !goto_end_of_sub && *last_out >> WIDTH_M1 == 0 {
        // case 1 - varepsilon
        *last_out = LIMB_HIGH_BIT;
        add_exp = true;
    }
    // We have to set MPFR_EXP(out) to MPFR_EXP(x) - cancel + diff_exp, taking care of
    // underflows/overflows in that computation, and of the allowed exponent range
    let exp_a = if cancel != 0 {
        x_exp = i32::saturating_from(i128::from(x_exp) - i128::from(cancel));
        if add_exp {
            x_exp.saturating_add_assign(1);
        }
        x_exp
    } else {
        // cancel = 0: MPFR_EXP(out) <- MPFR_EXP(x) + diff_exp
        //
        // In case cancel = 0, diff_exp can still be 1, in case x is just below a power of two, y is
        // very small, prec(out) < prec(x), and rnd = away or nearest
        if add_exp {
            x_exp.saturating_add_assign(1);
        }
        x_exp
    };
    // check that result is msb-normalized
    assert!(last_out.get_highest_bit());
    (exp_a, inexact.sign(), neg)
}