cmpa 0.1.6

Multiprecision arithmetic primitives commonly needed for asymmetric cryptography
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023-2026 SUSE LLC
// Author: Nicolai Stange <nstange@suse.de>

//! Accessors for multiprecision integers as stored in buffer slices of a number
//! of supported representations.
//!
//! Multiprecision integers are stored in caller provided buffer slices. For
//! operating on them, these get wrapped in one of the representation-specific
//! types listed below, each of which provides a view of the wrapped slice as a
//! multiprecision integer. The following representations are supported, each
//! with a variant for read-only access and a `Mut` variant for read-write
//! access:
//! - Big-endian byte slices: [`MpBigEndianUIntByteSlice`] and
//!   [`MpMutBigEndianUIntByteSlice`].
//! - Little-endian byte slices: [`MpLittleEndianUIntByteSlice`] and
//!   [`MpMutLittleEndianUIntByteSlice`].
//! - Native-endian [`LimbType`] slices: [`MpNativeEndianUIntLimbsSlice`] and
//!   [`MpMutNativeEndianUIntLimbsSlice`]. The
//!   [length of these in units of bytes](MpUIntCommon::len) is always a
//!   multiple of the [`LimbType`] size, c.f.
//!   [`MpNativeEndianUIntLimbsSlice::nlimbs_for_len()`] for allocating
//!   suitably sized buffers.
//!
//! All of these implement the [`MpUIntCommon`] trait and either of [`MpUInt`]
//! or [`MpMutUInt`], through which the arithmetic primitives access the
//! multiprecision integers in units of [`LimbType`]. The native-endian
//! representation is the most efficient one to operate on, because its
//! [`LimbType`] words can get accessed directly, whereas for the byte slice
//! representations, they need to get assembled from and disassembled into the
//! individual bytes. Nonetheless, all of the implemented multiprecision integer
//! arithmetic primitives support any of the representations, even in mixed
//! combinations for the different operands.
//!
//! For converting between the representations and to or from Rust's native
//! integer types, the following primitives are provided:
//! - [`MpMutUInt::copy_from()`] copies a multiprecision integer from any
//!   representation into another one, zero-extending it as needed.
//!   [`MpMutUInt::copy_from_cond()`] is its constant-time conditional
//!   counterpart.
//! - [`MpMutUInt::set_to_u8()`], [`MpMutUInt::set_to_u16()`],
//!   [`MpMutUInt::set_to_u32()`] and [`MpMutUInt::set_to_u64()`] set a
//!   multiprecision integer to a native integer value.
//! - [`MpUIntCommon::try_into_u8()`], [`MpUIntCommon::try_into_u16()`],
//!   [`MpUIntCommon::try_into_u32()`] and [`MpUIntCommon::try_into_u64()`]
//!   convert a multiprecision integer into a native integer, failing if the
//!   value doesn't fit.

use core::{self, convert, fmt, marker, mem, slice};

use super::limb::{
    LIMB_BITS, LIMB_BYTES, LimbChoice, LimbType, ct_find_first_set_bit_l, ct_find_last_set_bit_l,
    ct_find_last_set_byte_l, ct_is_nonzero_l, ct_is_zero_l, ct_lsb_mask_l,
};
use super::usize_ct_cmp::ct_eq_usize_usize;

mod private;
pub(super) use private::{
    MpMutUIntSlicePriv, MpUIntCommonPriv, MpUIntSliceCommonPriv, MpUIntSlicePriv,
};

/// Determine the number of [`LimbType`] limbs spanned by a multiprecision
/// integer of a given [length in units of bytes](MpUIntCommon::len).
///
/// That is, convert the length to units of [`LimbType`] limbs, rounding up.
/// This applies to any of the supported multiprecision integer representations.
///
/// Runs in constant time, independent of the argument value.
///
/// # Arguments
///
/// * `len` - The multiprecision integer's [length in units of
///   bytes](MpUIntCommon::len).
// Don't use usize::div_ceil(), which is implemented with a conditional:
// ct_lshift_mp() passes a secret shift distance here.
#[allow(clippy::manual_div_ceil)]
pub(super) const fn ct_mp_nlimbs(len: usize) -> usize {
    (len + LIMB_BYTES - 1) / LIMB_BYTES
}

/// Align a multiprecision integer's [length in units of
/// bytes](MpUIntCommon::len) to the [`LimbType`] size.
///
/// That is, round the length up to the next multiple of the [`LimbType`] size
/// in bytes, i.e. to the length of the [`LimbType`] limbs spanned by a
/// multiprecision integer of the given length, c.f. [`ct_mp_nlimbs()`].
///
/// Runs in constant time, independent of the argument value.
///
/// # Arguments
///
/// * `len` - The multiprecision integer's [length in units of
///   bytes](MpUIntCommon::len).
pub(super) const fn ct_mp_limbs_align_len(len: usize) -> usize {
    ct_mp_nlimbs(len) * LIMB_BYTES
}

#[test]
fn test_ct_mp_nlimbs() {
    assert_eq!(ct_mp_nlimbs(0), 0);
    assert_eq!(ct_mp_nlimbs(1), 1);
    assert_eq!(ct_mp_nlimbs(LIMB_BYTES - 1), 1);
    assert_eq!(ct_mp_nlimbs(LIMB_BYTES), 1);
    assert_eq!(ct_mp_nlimbs(LIMB_BYTES + 1), 2);
    assert_eq!(ct_mp_nlimbs(2 * LIMB_BYTES - 1), 2);
}

/// Internal helper to load some fully contained limb from a multiprecision
/// integer big-endian byte buffer.
///
/// The specified limb is returned in the host's native endianess.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. This
/// internal helper is used whenever the specified limb is not such a partially
/// covered high limb.
///
/// Runs in constant time as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   big-endian order.
/// * `src_end` - The position past the end of the limb to be loaded from
///   `limbs`. Must be at least a [`LimbType`]'s size in bytes.
fn _be_mp_load_l_full(limbs: &[u8], src_end: usize) -> LimbType {
    debug_assert!(src_end >= LIMB_BYTES);
    let src_begin = src_end - LIMB_BYTES;
    let src = &limbs[src_begin..src_end];
    let src = <[u8; LIMB_BYTES] as TryFrom<&[u8]>>::try_from(src).unwrap();
    LimbType::from_be_bytes(src)
}

/// Internal helper to load some partially contained limb from a multiprecision
/// integer big-endian byte buffer.
///
/// The specified limb is returned in the host's native endianess.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. This
/// internal helper is used whenever the specified limb is such a partially
/// covered high limb.
///
/// Execution time depends only on the `src_end` argument and is otherwise
/// constant as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   big-endian order.
/// * `src_end` - The position past the end of the limb to be loaded from
///   `limbs`. Must be less than a [`LimbType`]'s size in bytes.
fn _be_mp_load_l_high_partial(limbs: &[u8], src_end: usize) -> LimbType {
    debug_assert!(src_end < LIMB_BYTES);
    let mut src: [u8; LIMB_BYTES] = [0; LIMB_BYTES];
    src[LIMB_BYTES - src_end..LIMB_BYTES].copy_from_slice(&limbs[0..src_end]);
    LimbType::from_be_bytes(src)
}

/// Load some fully contained limb from a multiprecision integer big-endian byte
/// buffer.
///
/// The specified limb is returned in the host's native endianess.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. The
/// generic [`be_mp_load_l()`] implements some extra logic for handling this
/// special case of a partially stored high limb, which can be avoided if it is
/// known that the limb to be accessed is completely covered by the `limbs`
/// buffer. This function here provides such a less generic, but more performant
/// variant.
///
/// Runs in constant time as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   big-endian order.
/// * `i` - The index of the limb to load, counted from least to most
///   significant. The limb must be fully contained in `limbs`, i.e.
///   `limbs` must span at least `i + 1` [`LimbType`]s.
fn be_mp_load_l_full(limbs: &[u8], i: usize) -> LimbType {
    debug_assert!((i + 1) * LIMB_BYTES <= limbs.len());
    let src_end = limbs.len() - i * LIMB_BYTES;
    _be_mp_load_l_full(limbs, src_end)
}

/// Load some limb from a multiprecision integer big-endian byte buffer.
///
/// The specified limb is returned in the host's native endianess.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. If it
/// is known that the limb to be accessed at position `i` is fully covered by
/// the `limbs` buffer, consider using [`be_mp_load_l_full()`] for improved
/// performance instead.
///
/// Execution time depends only on the multiprecision integer's length and the
/// limb index argument `i`, and is otherwise constant as far as branching is
/// concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   big-endian order.
/// * `i` - The index of the limb to load, counted from least to most
///   significant. The limb must be at least partially contained in
///   `limbs`.
fn be_mp_load_l(limbs: &[u8], i: usize) -> LimbType {
    debug_assert!(i * LIMB_BYTES < limbs.len());
    let src_end = limbs.len() - i * LIMB_BYTES;
    if src_end >= LIMB_BYTES {
        _be_mp_load_l_full(limbs, src_end)
    } else {
        _be_mp_load_l_high_partial(limbs, src_end)
    }
}

#[test]
fn test_be_mp_load_l() {
    let limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    assert_eq!(be_mp_load_l(&limbs, 0), 0);
    assert_eq!(be_mp_load_l(&limbs, 1), 0);

    let mut limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    limbs[LIMB_BYTES] = 0x80;
    limbs[LIMB_BYTES - 1] = 1;
    assert_eq!(be_mp_load_l(&limbs, 0), 1 << (LIMB_BITS - 1));
    assert_eq!(be_mp_load_l_full(&limbs, 0), 1 << (LIMB_BITS - 1));
    assert_eq!(be_mp_load_l(&limbs, 1), 1);
    assert_eq!(be_mp_load_l_full(&limbs, 1), 1);

    let limbs: [u8; 1] = [0; 1];
    assert_eq!(be_mp_load_l(&limbs, 0), 0);

    let limbs: [u8; LIMB_BYTES + 1] = [0; LIMB_BYTES + 1];
    assert_eq!(be_mp_load_l(&limbs, 0), 0);
    assert_eq!(be_mp_load_l_full(&limbs, 0), 0);
    assert_eq!(be_mp_load_l(&limbs, 1), 0);

    let limbs: [u8; 2] = [0, 1];
    assert_eq!(be_mp_load_l(&limbs, 0), 1);

    let mut limbs: [u8; LIMB_BYTES + 2] = [0; LIMB_BYTES + 2];
    limbs[1] = 1;
    assert_eq!(be_mp_load_l(&limbs, 0), 0);
    assert_eq!(be_mp_load_l_full(&limbs, 0), 0);
    assert_eq!(be_mp_load_l(&limbs, 1), 1);

    let limbs: [u8; 2] = [1, 0];
    assert_eq!(be_mp_load_l(&limbs, 0), 0x0100);

    let mut limbs: [u8; LIMB_BYTES + 2] = [0; LIMB_BYTES + 2];
    limbs[0] = 1;
    assert_eq!(be_mp_load_l(&limbs, 0), 0);
    assert_eq!(be_mp_load_l_full(&limbs, 0), 0);
    assert_eq!(be_mp_load_l(&limbs, 1), 0x0100);
}

/// Internal helper to update some fully contained limb in a multiprecision
/// integer big-endian byte buffer.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. This
/// internal helper is used whenever the specified limb is not such a partially
/// covered high limb.
///
/// Runs in constant time as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   big-endian order.
/// * `dst_end` - The position past the end of the limb to be updated in
///   `limbs`. Must be at least a [`LimbType`]'s size in bytes.
/// * `value` - The value to store in `limbs` at the specified position.
fn _be_mp_store_l_full(limbs: &mut [u8], dst_end: usize, value: LimbType) {
    debug_assert!(dst_end >= LIMB_BYTES);
    let dst_begin = dst_end - LIMB_BYTES;
    let dst = &mut limbs[dst_begin..dst_end];
    let dst = <&mut [u8; LIMB_BYTES] as TryFrom<&mut [u8]>>::try_from(dst).unwrap();
    *dst = value.to_be_bytes();
}

/// Internal helper to update some partially contained limb in a multiprecision
/// integer big-endian byte buffer.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. This
/// internal helper is used whenever the specified limb is such a partially
/// covered high limb.
///
/// Execution time depends only on the `dst_end` argument and is otherwise
/// constant as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   big-endian order.
/// * `dst_end` - The position past the end of the limb to be updated in
///   `limbs`. Must be less than a [`LimbType`]'s size in bytes.
/// * `value` - The value to store in `limbs` at the specified position. The
///   high bits corresponding to any of the excess limb bytes not covered by
///   `limbs` can have arbitrary values, but are ignored.
fn _be_mp_store_l_high_partial(limbs: &mut [u8], dst_end: usize, value: LimbType) {
    debug_assert!(dst_end < LIMB_BYTES);
    let dst = &mut limbs[0..dst_end];
    let src: [u8; LIMB_BYTES] = value.to_be_bytes();
    dst.copy_from_slice(&src[LIMB_BYTES - dst_end..LIMB_BYTES]);
}

/// Update some fully contained limb in a multiprecision integer big-endian byte
/// buffer.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. The
/// generic [`be_mp_store_l()`] implements some extra logic for handling this
/// special case of a partially stored high limb, which can be avoided if it is
/// known that the limb to be accessed is completely covered by the `limbs`
/// buffer. This function here provides such a less generic, but more performant
/// variant.
///
/// Runs in constant time.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   big-endian order.
/// * `i` - The index of the limb to update, counted from least to most
///   significant. The limb must be fully contained in `limbs`, i.e.
///   `limbs` must span at least `i + 1` [`LimbType`]s.
/// * `value` - The value to store at limb index `i` in `limbs`.
fn be_mp_store_l_full(limbs: &mut [u8], i: usize, value: LimbType) {
    debug_assert!((i + 1) * LIMB_BYTES <= limbs.len());
    let dst_end = limbs.len() - i * LIMB_BYTES;
    _be_mp_store_l_full(limbs, dst_end, value);
}

/// Update some limb in a multiprecision integer big-endian byte buffer.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. If the
/// most significant limb is to be stored, all bytes in `value` corresponding to
/// these excess bytes must be zero accordingly.
///
/// If it is known that the limb to be stored at position `i` is fully covered
/// by the `limbs` buffer, consider using [`be_mp_store_l_full()`] for improved
/// performance instead.
///
/// Execution time depends only on the multiprecision integer's length and the
/// limb index argument `i`, and is otherwise constant as far as branching is
/// concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   big-endian order.
/// * `i` - The index of the limb to update, counted from least to most
///   significant. The limb must be at least partially contained in
///   `limbs`.
/// * `value` - The value to store at limb index `i` in `limbs`.
fn be_mp_store_l(limbs: &mut [u8], i: usize, value: LimbType) {
    debug_assert!(i * LIMB_BYTES < limbs.len());
    let dst_end = limbs.len() - i * LIMB_BYTES;
    if dst_end >= LIMB_BYTES {
        _be_mp_store_l_full(limbs, dst_end, value);
    } else {
        debug_assert_eq!(value >> (8 * dst_end), 0);
        _be_mp_store_l_high_partial(limbs, dst_end, value);
    }
}

#[test]
fn test_be_mp_store_l() {
    let mut limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    be_mp_store_l(&mut limbs, 0, 1 << (LIMB_BITS - 1));
    be_mp_store_l(&mut limbs, 1, 1);
    assert_eq!(be_mp_load_l(&limbs, 0), 1 << (LIMB_BITS - 1));
    assert_eq!(be_mp_load_l(&limbs, 1), 1);

    let mut limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    be_mp_store_l_full(&mut limbs, 0, 1 << (LIMB_BITS - 1));
    be_mp_store_l_full(&mut limbs, 1, 1);
    assert_eq!(be_mp_load_l(&limbs, 0), 1 << (LIMB_BITS - 1));
    assert_eq!(be_mp_load_l(&limbs, 1), 1);

    let mut limbs: [u8; 1] = [0; 1];
    be_mp_store_l(&mut limbs, 0, 1);
    assert_eq!(be_mp_load_l(&limbs, 0), 1);

    let mut limbs: [u8; LIMB_BYTES - 1] = [0; LIMB_BYTES - 1];
    be_mp_store_l(&mut limbs, 0, 1);
    assert_eq!(be_mp_load_l(&limbs, 0), 1);

    let mut limbs: [u8; LIMB_BYTES - 1] = [0; LIMB_BYTES - 1];
    be_mp_store_l(&mut limbs, 0, 1 << (LIMB_BITS - 8 - 1));
    assert_eq!(be_mp_load_l(&limbs, 0), 1 << (LIMB_BITS - 8 - 1));

    let mut limbs: [u8; 2] = [0; 2];
    be_mp_store_l(&mut limbs, 0, 1);
    assert_eq!(be_mp_load_l(&limbs, 0), 1);

    let mut limbs: [u8; 2] = [0; 2];
    be_mp_store_l(&mut limbs, 0, 0x0100);
    assert_eq!(be_mp_load_l(&limbs, 0), 0x0100);

    let mut limbs: [u8; LIMB_BYTES + 2] = [0; LIMB_BYTES + 2];
    be_mp_store_l(&mut limbs, 1, 1);
    assert_eq!(be_mp_load_l(&limbs, 0), 0);
    assert_eq!(be_mp_load_l(&limbs, 1), 1);

    let mut limbs: [u8; LIMB_BYTES + 2] = [0; LIMB_BYTES + 2];
    be_mp_store_l(&mut limbs, 1, 0x0100);
    assert_eq!(be_mp_load_l(&limbs, 0), 0);
    assert_eq!(be_mp_load_l(&limbs, 1), 0x0100);
}

/// Internal helper to clear the high bytes of a multiprecision integer
/// big-endian byte buffer.
///
/// Set all bytes at positions `>= begin` to zero, with positions counted in
/// units of bytes from least to most significant. That is, the multiprecision
/// integer gets truncated to its `begin` least significant bytes. If `begin` is
/// `>= limbs.len()`, nothing is cleared.
///
/// Execution time depends only on the length of `limbs` and the `begin`
/// argument and is otherwise constant as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   big-endian order.
/// * `begin` - The position of the least significant byte to clear, counted
///   in units of bytes from least to most significant.
fn be_mp_clear_bytes_above(limbs: &mut [u8], begin: usize) {
    let limbs_len = limbs.len();
    if limbs_len <= begin {
        return;
    }
    limbs[..limbs_len - begin].fill(0);
}

#[test]
fn test_be_mp_clear_bytes_above() {
    let mut limbs: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    be_mp_store_l(&mut limbs, 0, !0);
    be_mp_store_l(&mut limbs, 1, !0 >> 8);
    be_mp_clear_bytes_above(&mut limbs, LIMB_BYTES + 1);
    assert_eq!(be_mp_load_l(&limbs, 0), !0);
    assert_eq!(be_mp_load_l(&limbs, 1), 0xff);

    let mut limbs: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    be_mp_store_l(&mut limbs, 0, !0);
    be_mp_store_l(&mut limbs, 1, !0 >> 8);
    be_mp_clear_bytes_above(&mut limbs, LIMB_BYTES - 1);
    assert_eq!(be_mp_load_l(&limbs, 0), !0 >> 8);
    assert_eq!(be_mp_load_l(&limbs, 1), 0);

    let mut limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    be_mp_store_l(&mut limbs, 0, !0);
    be_mp_store_l(&mut limbs, 1, !0);
    be_mp_clear_bytes_above(&mut limbs, 2 * LIMB_BYTES);
    assert_eq!(be_mp_load_l(&limbs, 0), !0);
    assert_eq!(be_mp_load_l(&limbs, 1), !0);
}

/// Internal helper to clear the low bytes of a multiprecision integer
/// big-endian byte buffer.
///
/// Set all bytes at positions `< end` to zero, with positions counted in units
/// of bytes from least to most significant. If `end` is `>= limbs.len()`, all
/// of `limbs` is cleared.
///
/// Execution time depends only on the length of `limbs` and the `end`
/// argument and is otherwise constant as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   big-endian order.
/// * `end` - The position past the most significant byte to clear, counted
///   in units of bytes from least to most significant.
fn be_mp_clear_bytes_below(limbs: &mut [u8], end: usize) {
    let limbs_len = limbs.len();
    let end = end.min(limbs_len);
    limbs[limbs_len - end..].fill(0);
}

#[test]
fn test_be_mp_clear_bytes_below() {
    let mut limbs: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    be_mp_store_l(&mut limbs, 0, !0);
    be_mp_store_l(&mut limbs, 1, !0 >> 8);
    be_mp_clear_bytes_below(&mut limbs, LIMB_BYTES + 1);
    assert_eq!(be_mp_load_l(&limbs, 0), 0);
    assert_eq!(be_mp_load_l(&limbs, 1), (!0 >> 8) & !0xff);

    let mut limbs: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    be_mp_store_l(&mut limbs, 0, !0);
    be_mp_store_l(&mut limbs, 1, !0 >> 8);
    be_mp_clear_bytes_below(&mut limbs, LIMB_BYTES - 1);
    assert_eq!(be_mp_load_l(&limbs, 0), 0xff << (8 * (LIMB_BYTES - 1)));
    assert_eq!(be_mp_load_l(&limbs, 1), !0 >> 8);

    let mut limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    be_mp_store_l(&mut limbs, 0, !0);
    be_mp_store_l(&mut limbs, 1, !0);
    be_mp_clear_bytes_below(&mut limbs, 0);
    assert_eq!(be_mp_load_l(&limbs, 0), !0);
    assert_eq!(be_mp_load_l(&limbs, 1), !0);
}

/// Internal helper to load some fully contained limb from a multiprecision
/// integer little-endian byte buffer.
///
/// The specified limb is returned in the host's native endianess.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. This
/// internal helper is used whenever the specified limb is not such a partially
/// covered high limb.
///
/// Runs in constant time as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   little-endian order.
/// * `src_begin` - The position of the limb to be loaded from `limbs`.
///   At least a [`LimbType`]'s size in bytes must remain in `limbs` from
///   there on.
fn _le_mp_load_l_full(limbs: &[u8], src_begin: usize) -> LimbType {
    debug_assert!(src_begin + LIMB_BYTES <= limbs.len());
    let src_end = src_begin + LIMB_BYTES;
    let src = &limbs[src_begin..src_end];
    let src = <[u8; LIMB_BYTES] as TryFrom<&[u8]>>::try_from(src).unwrap();
    LimbType::from_le_bytes(src)
}

/// Internal helper to load some partially contained limb from a multiprecision
/// integer little-endian byte buffer.
///
/// The specified limb is returned in the host's native endianess.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. This
/// internal helper is used whenever the specified limb is such a partially
/// covered high limb.
///
/// Execution time depends only on the length of `limbs` and the `src_begin`
/// argument and is otherwise constant as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   little-endian order.
/// * `src_begin` - The position of the limb to be loaded from `limbs`. Must
///   be `<= limbs.len()`, with less than a [`LimbType`]'s size in bytes
///   remaining in `limbs` from there on.
fn _le_mp_load_l_high_partial(limbs: &[u8], src_begin: usize) -> LimbType {
    debug_assert!(src_begin <= limbs.len() && limbs.len() - src_begin < LIMB_BYTES);
    let mut src: [u8; LIMB_BYTES] = [0; LIMB_BYTES];
    src[..limbs.len() - src_begin].copy_from_slice(&limbs[src_begin..]);
    LimbType::from_le_bytes(src)
}

/// Load some fully contained limb from a multiprecision integer little-endian
/// byte buffer.
///
/// The specified limb is returned in the host's native endianess.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. The
/// generic [`le_mp_load_l()`] implements some extra logic for handling this
/// special case of a partially stored high limb, which can be avoided if it is
/// known that the limb to be accessed is completely covered by the `limbs`
/// buffer. This function here provides such a less generic, but more performant
/// variant.
///
/// Runs in constant time as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   little-endian order.
/// * `i` - The index of the limb to load, counted from least to most
///   significant. The limb must be fully contained in `limbs`, i.e.
///   `limbs` must span at least `i + 1` [`LimbType`]s.
fn le_mp_load_l_full(limbs: &[u8], i: usize) -> LimbType {
    let src_begin = i * LIMB_BYTES;
    debug_assert!(src_begin + LIMB_BYTES <= limbs.len());
    _le_mp_load_l_full(limbs, src_begin)
}

/// Load some limb from a multiprecision integer little-endian byte buffer.
///
/// The specified limb is returned in the host's native endianess.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. If it
/// is known that the limb to be accessed at position `i` is fully covered by
/// the `limbs` buffer, consider using [`le_mp_load_l_full()`] for improved
/// performance instead.
///
/// Execution time depends only on the multiprecision integer's length and the
/// limb index argument `i`, and is otherwise constant as far as branching is
/// concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   little-endian order.
/// * `i` - The index of the limb to load, counted from least to most
///   significant. The limb must be at least partially contained in
///   `limbs`.
fn le_mp_load_l(limbs: &[u8], i: usize) -> LimbType {
    let src_begin = i * LIMB_BYTES;
    debug_assert!(src_begin < limbs.len());
    if src_begin + LIMB_BYTES <= limbs.len() {
        _le_mp_load_l_full(limbs, src_begin)
    } else {
        _le_mp_load_l_high_partial(limbs, src_begin)
    }
}

#[test]
fn test_le_mp_load_l() {
    let limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    assert_eq!(le_mp_load_l(&limbs, 0), 0);
    assert_eq!(le_mp_load_l(&limbs, 1), 0);

    let mut limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    limbs[LIMB_BYTES - 1] = 0x80;
    limbs[LIMB_BYTES] = 1;
    assert_eq!(le_mp_load_l(&limbs, 0), 1 << (LIMB_BITS - 1));
    assert_eq!(le_mp_load_l_full(&limbs, 0), 1 << (LIMB_BITS - 1));
    assert_eq!(le_mp_load_l(&limbs, 1), 1);
    assert_eq!(le_mp_load_l_full(&limbs, 1), 1);

    let limbs: [u8; 1] = [0; 1];
    assert_eq!(le_mp_load_l(&limbs, 0), 0);

    let limbs: [u8; LIMB_BYTES + 1] = [0; LIMB_BYTES + 1];
    assert_eq!(le_mp_load_l(&limbs, 0), 0);
    assert_eq!(le_mp_load_l_full(&limbs, 0), 0);
    assert_eq!(le_mp_load_l(&limbs, 1), 0);

    let limbs: [u8; 2] = [1, 0];
    assert_eq!(le_mp_load_l(&limbs, 0), 1);

    let mut limbs: [u8; LIMB_BYTES + 2] = [0; LIMB_BYTES + 2];
    limbs[LIMB_BYTES] = 1;
    assert_eq!(le_mp_load_l(&limbs, 0), 0);
    assert_eq!(le_mp_load_l_full(&limbs, 0), 0);
    assert_eq!(le_mp_load_l(&limbs, 1), 1);

    let limbs: [u8; 2] = [0, 1];
    assert_eq!(le_mp_load_l(&limbs, 0), 0x0100);

    let mut limbs: [u8; LIMB_BYTES + 2] = [0; LIMB_BYTES + 2];
    limbs[LIMB_BYTES + 1] = 1;
    assert_eq!(le_mp_load_l(&limbs, 0), 0);
    assert_eq!(le_mp_load_l_full(&limbs, 0), 0);
    assert_eq!(le_mp_load_l(&limbs, 1), 0x0100);
}

/// Internal helper to update some fully contained limb in a multiprecision
/// integer little-endian byte buffer.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. This
/// internal helper is used whenever the specified limb is not such a partially
/// covered high limb.
///
/// Runs in constant time as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   little-endian order.
/// * `dst_begin` - The position of the limb to be updated in `limbs`.
///   At least a [`LimbType`]'s size in bytes must remain in `limbs` from
///   there on.
/// * `value` - The value to store in `limbs` at the specified position.
fn _le_mp_store_l_full(limbs: &mut [u8], dst_begin: usize, value: LimbType) {
    debug_assert!(dst_begin + LIMB_BYTES <= limbs.len());
    let dst_end = dst_begin + LIMB_BYTES;
    let dst = &mut limbs[dst_begin..dst_end];
    let dst = <&mut [u8; LIMB_BYTES] as TryFrom<&mut [u8]>>::try_from(dst).unwrap();
    *dst = value.to_le_bytes();
}

/// Internal helper to update some partially contained limb in a multiprecision
/// integer little-endian byte buffer.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. This
/// internal helper is used whenever the specified limb is such a partially
/// covered high limb.
///
/// Execution time depends only on the length of `limbs` and the `dst_begin`
/// argument and is otherwise constant as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   little-endian order.
/// * `dst_begin` - The position of the limb to be updated in `limbs`. Must
///   be `<= limbs.len()`, with less than a [`LimbType`]'s size in bytes
///   remaining in `limbs` from there on.
/// * `value` - The value to store in `limbs` at the specified position. The
///   high bits corresponding to any of the excess limb bytes not covered by
///   `limbs` can have arbitrary values, but are ignored.
fn _le_mp_store_l_high_partial(limbs: &mut [u8], dst_begin: usize, value: LimbType) {
    debug_assert!(dst_begin <= limbs.len() && limbs.len() - dst_begin < LIMB_BYTES);
    let dst_end = limbs.len();
    let dst = &mut limbs[dst_begin..];
    let src: [u8; LIMB_BYTES] = value.to_le_bytes();
    dst.copy_from_slice(&src[0..dst_end - dst_begin]);
}

/// Update some fully contained limb in a multiprecision integer little-endian
/// byte buffer.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. The
/// generic [`le_mp_store_l()`] implements some extra logic for handling this
/// special case of a partially stored high limb, which can be avoided if it is
/// known that the limb to be accessed is completely covered by the `limbs`
/// buffer. This function here provides such a less generic, but more performant
/// variant.
///
/// Runs in constant time.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   little-endian order.
/// * `i` - The index of the limb to update, counted from least to most
///   significant. The limb must be fully contained in `limbs`, i.e.
///   `limbs` must span at least `i + 1` [`LimbType`]s.
/// * `value` - The value to store at limb index `i` in `limbs`.
fn le_mp_store_l_full(limbs: &mut [u8], i: usize, value: LimbType) {
    let dst_begin = i * LIMB_BYTES;
    debug_assert!(dst_begin + LIMB_BYTES <= limbs.len());
    _le_mp_store_l_full(limbs, dst_begin, value);
}

/// Update some limb in a multiprecision integer little-endian byte buffer.
///
/// The byte buffer's length doesn't necessarily align with the size of a
/// [`LimbType`], in which case the most significant limb's might be stored only
/// partially, with its virtual excess high bytes defined to equal zero. If the
/// most significant limb is to be stored, all bytes in `value` corresponding to
/// these excess bytes must be zero accordingly.
///
/// If it is known that the limb to be stored at position `i` is fully covered
/// by the `limbs` buffer, consider using [`le_mp_store_l_full()`] for improved
/// performance instead.
///
/// Execution time depends only on the multiprecision integer's length and the
/// limb index argument `i`, and is otherwise constant as far as branching is
/// concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   little-endian order.
/// * `i` - The index of the limb to update, counted from least to most
///   significant. The limb must be at least partially contained in
///   `limbs`.
/// * `value` - The value to store at limb index `i` in `limbs`.
fn le_mp_store_l(limbs: &mut [u8], i: usize, value: LimbType) {
    let dst_begin = i * LIMB_BYTES;
    debug_assert!(dst_begin < limbs.len());
    if dst_begin + LIMB_BYTES <= limbs.len() {
        _le_mp_store_l_full(limbs, dst_begin, value);
    } else {
        debug_assert_eq!(value >> (8 * (limbs.len() - dst_begin)), 0);
        _le_mp_store_l_high_partial(limbs, dst_begin, value);
    }
}

#[test]
fn test_le_mp_store_l() {
    let mut limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    le_mp_store_l(&mut limbs, 0, 1 << (LIMB_BITS - 1));
    le_mp_store_l(&mut limbs, 1, 1);
    assert_eq!(le_mp_load_l(&limbs, 0), 1 << (LIMB_BITS - 1));
    assert_eq!(le_mp_load_l(&limbs, 1), 1);

    let mut limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    le_mp_store_l_full(&mut limbs, 0, 1 << (LIMB_BITS - 1));
    le_mp_store_l_full(&mut limbs, 1, 1);
    assert_eq!(le_mp_load_l(&limbs, 0), 1 << (LIMB_BITS - 1));
    assert_eq!(le_mp_load_l(&limbs, 1), 1);

    let mut limbs: [u8; 1] = [0; 1];
    le_mp_store_l(&mut limbs, 0, 1);
    assert_eq!(le_mp_load_l(&limbs, 0), 1);

    let mut limbs: [u8; LIMB_BYTES - 1] = [0; LIMB_BYTES - 1];
    le_mp_store_l(&mut limbs, 0, 1);
    assert_eq!(le_mp_load_l(&limbs, 0), 1);

    let mut limbs: [u8; LIMB_BYTES - 1] = [0; LIMB_BYTES - 1];
    le_mp_store_l(&mut limbs, 0, 1 << (LIMB_BITS - 8 - 1));
    assert_eq!(le_mp_load_l(&limbs, 0), 1 << (LIMB_BITS - 8 - 1));

    let mut limbs: [u8; 2] = [0; 2];
    le_mp_store_l(&mut limbs, 0, 1);
    assert_eq!(le_mp_load_l(&limbs, 0), 1);

    let mut limbs: [u8; 2] = [0; 2];
    le_mp_store_l(&mut limbs, 0, 0x0100);
    assert_eq!(le_mp_load_l(&limbs, 0), 0x0100);

    let mut limbs: [u8; LIMB_BYTES + 2] = [0; LIMB_BYTES + 2];
    le_mp_store_l(&mut limbs, 1, 1);
    assert_eq!(le_mp_load_l(&limbs, 0), 0);
    assert_eq!(le_mp_load_l(&limbs, 1), 1);

    let mut limbs: [u8; LIMB_BYTES + 2] = [0; LIMB_BYTES + 2];
    le_mp_store_l(&mut limbs, 1, 0x0100);
    assert_eq!(le_mp_load_l(&limbs, 0), 0);
    assert_eq!(le_mp_load_l(&limbs, 1), 0x0100);
}

/// Internal helper to clear the high bytes of a multiprecision integer
/// little-endian byte buffer.
///
/// Set all bytes at positions `>= begin` to zero, with positions counted in
/// units of bytes from least to most significant. That is, the multiprecision
/// integer gets truncated to its `begin` least significant bytes. If `begin` is
/// `>= limbs.len()`, nothing is cleared.
///
/// Execution time depends only on the length of `limbs` and the `begin`
/// argument and is otherwise constant as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   little-endian order.
/// * `begin` - The position of the least significant byte to clear, counted
///   in units of bytes from least to most significant.
fn le_mp_clear_bytes_above(limbs: &mut [u8], begin: usize) {
    if limbs.len() <= begin {
        return;
    }
    limbs[begin..].fill(0);
}

#[test]
fn test_le_mp_clear_bytes_above() {
    let mut limbs: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    le_mp_store_l(&mut limbs, 0, !0);
    le_mp_store_l(&mut limbs, 1, !0 >> 8);
    le_mp_clear_bytes_above(&mut limbs, LIMB_BYTES + 1);
    assert_eq!(le_mp_load_l(&limbs, 0), !0);
    assert_eq!(le_mp_load_l(&limbs, 1), 0xff);

    let mut limbs: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    le_mp_store_l(&mut limbs, 0, !0);
    le_mp_store_l(&mut limbs, 1, !0 >> 8);
    le_mp_clear_bytes_above(&mut limbs, LIMB_BYTES - 1);
    assert_eq!(le_mp_load_l(&limbs, 0), !0 >> 8);
    assert_eq!(le_mp_load_l(&limbs, 1), 0);

    let mut limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    le_mp_store_l(&mut limbs, 0, !0);
    le_mp_store_l(&mut limbs, 1, !0);
    le_mp_clear_bytes_above(&mut limbs, 2 * LIMB_BYTES);
    assert_eq!(le_mp_load_l(&limbs, 0), !0);
    assert_eq!(le_mp_load_l(&limbs, 1), !0);
}

/// Internal helper to clear the low bytes of a multiprecision integer
/// little-endian byte buffer.
///
/// Set all bytes at positions `< end` to zero, with positions counted in units
/// of bytes from least to most significant. If `end` is `>= limbs.len()`, all
/// of `limbs` is cleared.
///
/// Execution time depends only on the length of `limbs` and the `end`
/// argument and is otherwise constant as far as branching is concerned.
///
/// # Arguments
///
/// * `limbs` - The multiprecision integer's underlying byte buffer in
///   little-endian order.
/// * `end` - The position past the most significant byte to clear, counted
///   in units of bytes from least to most significant.
fn le_mp_clear_bytes_below(limbs: &mut [u8], end: usize) {
    let end = end.min(limbs.len());
    limbs[..end].fill(0);
}

#[test]
fn test_le_mp_clear_bytes_below() {
    let mut limbs: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    le_mp_store_l(&mut limbs, 0, !0);
    le_mp_store_l(&mut limbs, 1, !0 >> 8);
    le_mp_clear_bytes_below(&mut limbs, LIMB_BYTES + 1);
    assert_eq!(le_mp_load_l(&limbs, 0), 0);
    assert_eq!(le_mp_load_l(&limbs, 1), (!0 >> 8) & !0xff);

    let mut limbs: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    le_mp_store_l(&mut limbs, 0, !0);
    le_mp_store_l(&mut limbs, 1, !0 >> 8);
    le_mp_clear_bytes_below(&mut limbs, LIMB_BYTES - 1);
    assert_eq!(le_mp_load_l(&limbs, 0), 0xff << (8 * (LIMB_BYTES - 1)));
    assert_eq!(le_mp_load_l(&limbs, 1), !0 >> 8);

    let mut limbs: [u8; 2 * LIMB_BYTES] = [0; 2 * LIMB_BYTES];
    le_mp_store_l(&mut limbs, 0, !0);
    le_mp_store_l(&mut limbs, 1, !0);
    le_mp_clear_bytes_below(&mut limbs, 0);
    assert_eq!(le_mp_load_l(&limbs, 0), !0);
    assert_eq!(le_mp_load_l(&limbs, 1), !0);
}

/// Error returned by the conversions of multiprecision integers into native
/// integer types.
///
/// Returned by [`MpUIntCommon::try_into_u8()`],
/// [`MpUIntCommon::try_into_u16()`], [`MpUIntCommon::try_into_u32()`] and
/// [`MpUIntCommon::try_into_u64()`] if the multiprecision integer's value
/// exceeds the range of the target native integer type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MpUIntCommonTryIntoNativeError;

macro_rules! _mpu_try_into_native_u {
    ($nt:ty, $name:ident) => {
        #[doc = concat!("Convert the multiprecision integer to a [`", stringify!($nt), "`].")]
        ///
        /// Execution time depends only on the multiprecision integer's [length
        /// in units of bytes](MpUIntCommon::len) and on whether its value fits,
        /// and is otherwise constant as far as branching is concerned.
        ///
        /// # Errors
        ///
        /// Returns [`MpUIntCommonTryIntoNativeError`] if the multiprecision
        /// integer's value exceeds the native type's range.
        fn $name(&self) -> Result<$nt, MpUIntCommonTryIntoNativeError> {
            let native_type_nlimbs = ct_mp_nlimbs(mem::size_of::<$nt>());
            let nbytes_from_last = ((mem::size_of::<$nt>() - 1) % LIMB_BYTES) + 1;
            let nlimbs = self.nlimbs();
            let mut head_is_nonzero = 0;
            for i in native_type_nlimbs..nlimbs {
                head_is_nonzero |= self.load_l(i);
            }
            // The multiprecision integer might be shorter than the native
            // type, with its missing high limbs defined to equal zero.
            let last_val = if native_type_nlimbs <= nlimbs {
                self.load_l(native_type_nlimbs - 1)
            } else {
                0
            };
            let last_mask = ct_lsb_mask_l(8 * nbytes_from_last as u32);
            head_is_nonzero |= last_val & !last_mask;
            if ct_is_nonzero_l(head_is_nonzero) != 0 {
                return Err(MpUIntCommonTryIntoNativeError);
            }
            let mut result: $nt = (last_val & last_mask) as $nt;
            let mut i = native_type_nlimbs - 1;
            while i > 0 {
                i -= 1;
                // This loop only gets executed in case
                // LIMB_BITS < $nt::BITS. Avoid a compiler error for smaller
                // native types due to a too large shift distance.
                result <<= LIMB_BITS.min(<$nt>::BITS - 1);
                if i < nlimbs {
                    result |= self.load_l(i) as $nt;
                }
            }
            Ok(result)
        }
    };
}

/// Common interface to multiprecision integers of any of the supported
/// representations.
///
/// [`MpUIntCommon`] provides read access to a multiprecision integer in units
/// of [`LimbType`], independent of how it's stored in the underlying buffer.
/// Limbs are indexed from least to most significant.
///
/// A multiprecision integer's [length in units of bytes](MpUIntCommon::len)
/// doesn't need to be a multiple of the [`LimbType`] size for the byte slice
/// representations. If it isn't, the underlying buffer holds only the low
/// bytes of the most significant limb, and its missing high bytes read as
/// zero.
///
/// This trait is implemented by both the read-only and the mutable
/// representation-specific types, e.g. [`MpBigEndianUIntByteSlice`] and
/// [`MpMutBigEndianUIntByteSlice`], c.f. the [module level
/// documentation](self). The read-only ones implement [`MpUInt`] in addition,
/// the mutable ones [`MpMutUInt`]. Arithmetic primitives taking an operand
/// they only read from are generic over [`MpUIntCommon`], so that either kind
/// can be passed.
///
/// The trait is sealed, i.e. it cannot be implemented outside of this crate.
pub trait MpUIntCommon: MpUIntCommonPriv + fmt::LowerHex {
    /// The multiprecision integer's length in units of bytes.
    fn len(&self) -> usize {
        self._len()
    }

    /// The number of [`LimbType`] limbs spanned by the multiprecision integer.
    ///
    /// That is, its [length in units of bytes](Self::len) converted to units of
    /// [`LimbType`] limbs, rounding up, c.f.
    /// [`MpNativeEndianUIntLimbsSlice::nlimbs_for_len()`].
    fn nlimbs(&self) -> usize {
        ct_mp_nlimbs(self.len())
    }

    /// Whether the multiprecision integer's [length in units of
    /// bytes](Self::len) is zero.
    fn is_empty(&self) -> bool;

    /// Load a limb fully covered by the underlying buffer.
    ///
    /// Returns the specified limb in the host's native endianess. Use
    /// [`load_l()`](Self::load_l) instead if the limb might be the partially
    /// covered most significant one.
    ///
    /// Runs in constant time as far as branching is concerned.
    ///
    /// # Arguments
    ///
    /// * `i` - The index of the limb to load, counted from least to most
    ///   significant. Must be less than [`nlimbs()`](Self::nlimbs). The limb
    ///   must be fully contained in the underlying buffer, i.e. if `i` refers
    ///   to the most significant limb, the latter must not be a partially
    ///   covered one.
    fn load_l_full(&self, i: usize) -> LimbType;

    /// Load a limb, which might be the partially covered most significant one.
    ///
    /// Returns the specified limb in the host's native endianess. Any of its
    /// high bytes not covered by the underlying buffer read as zero.
    ///
    /// Execution time depends only on the multiprecision integer's [length in
    /// units of bytes](MpUIntCommon::len) and the `i` argument and is otherwise
    /// constant as far as branching is concerned.
    ///
    /// # Arguments
    ///
    /// * `i` - The index of the limb to load, counted from least to most
    ///   significant. Must be less than [`nlimbs()`](Self::nlimbs).
    fn load_l(&self, i: usize) -> LimbType;

    /// Test a bit of the multiprecision integer.
    ///
    /// Returns a [`LimbChoice`] representing `true` if the bit is set and
    /// `false` otherwise. Bits at positions at or beyond 8 times the
    /// multiprecision integer's [length in units of bytes](Self::len) read as
    /// unset.
    ///
    /// Execution time depends only on the multiprecision integer's [length in
    /// units of bytes](MpUIntCommon::len) and the `pos` argument and is
    /// otherwise constant as far as branching is concerned.
    ///
    /// # Arguments
    ///
    /// * `pos` - The position of the bit to test, counted from least to most
    ///   significant.
    fn test_bit(&self, pos: usize) -> LimbChoice {
        let limb_index = pos / LIMB_BITS as usize;
        if limb_index >= self.nlimbs() {
            return LimbChoice::from(0);
        }
        let pos_in_limb = pos % LIMB_BITS as usize;
        let l = self.load_l(limb_index);
        LimbChoice::from((l >> pos_in_limb) & 1)
    }

    /// Format the multiprecision integer in lowercase hexadecimal.
    ///
    /// Helper for implementing [`fmt::LowerHex`]. The digits are written from
    /// most to least significant, with a `_` separating the limbs. The most
    /// significant limb gets only as many digits as it has bytes covered by
    /// the underlying buffer. With the alternate flag (`{:#x}`), a `0x` prefix
    /// is prepended. An empty multiprecision integer is written as `(empty)`.
    ///
    /// No constant-time guarantees are made.
    ///
    /// # Arguments
    ///
    /// * `f` - The [`fmt::Formatter`] to write to.
    fn fmt_lower_hex(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn nibble_to_hexchar(nibble: u8) -> char {
            let c = match nibble {
                0x0..=0x9 => b'0' + nibble,
                0xa..=0xf => b'a' + (nibble - 0xa),
                _ => unreachable!(),
            };
            c as char
        }

        fn fmt_byte(f: &mut fmt::Formatter<'_>, v: u8) -> fmt::Result {
            <fmt::Formatter<'_> as fmt::Write>::write_char(f, nibble_to_hexchar(v >> 4))?;
            <fmt::Formatter<'_> as fmt::Write>::write_char(f, nibble_to_hexchar(v & 0xf))?;
            Ok(())
        }

        fn fmt_l(f: &mut fmt::Formatter<'_>, v: LimbType, len: usize) -> fmt::Result {
            for i in 0..len {
                fmt_byte(f, (v >> (8 * (len - i - 1))) as u8)?;
            }
            Ok(())
        }

        if f.alternate() {
            f.write_str("0x")?;
        }
        if self.is_empty() {
            f.write_str("(empty)")?;
            return Ok(());
        }

        let v = self.load_l(self.nlimbs() - 1);
        fmt_l(f, v, (self.len() - 1) % LIMB_BYTES + 1)?;

        let mut i = 0;
        while i + 1 < self.nlimbs() {
            <fmt::Formatter<'_> as fmt::Write>::write_char(f, '_')?;
            let v = self.load_l(self.nlimbs() - 2 - i);
            fmt_l(f, v, LIMB_BYTES)?;
            i += 1;
        }

        Ok(())
    }

    /// Check whether the multiprecision integer fits into a given [length in
    /// units of bytes](MpUIntCommon::len).
    ///
    /// Returns true if the multiprecision integer's [length in units of
    /// bytes](Self::len) is at most `len`. For representations whose [length in
    /// units of bytes](MpUIntCommon::len) is always a multiple of the
    /// [`LimbType`] size, like [`MpNativeEndianUIntLimbsSlice`], the length may
    /// also exceed `len` by less than a [`LimbType`]'s size, as long as all of
    /// the excess high bytes are zero. This accommodates the alignment excess
    /// of a buffer allocated for a length of `len`.
    ///
    /// Note that the relation isn't symmetric:
    /// `a.len_is_compatible_with(b.len())` doesn't imply
    /// `b.len_is_compatible_with(a.len())`. Requiring two multiprecision
    /// integers to be of equal [length in units of bytes](MpUIntCommon::len),
    /// within the alignment excess, needs both checks.
    ///
    /// In the alignment excess case, the result and the execution time depend
    /// on the value of the multiprecision integer's excess high bytes.
    ///
    /// # Arguments
    ///
    /// * `len` - The [length in units of bytes](MpUIntCommon::len) to check
    ///   against.
    fn len_is_compatible_with(&self, len: usize) -> bool {
        if self._len() <= len {
            true
        } else if !Self::SUPPORTS_UNALIGNED_BUFFER_LENGTHS && self._len() - len < LIMB_BYTES {
            // Allow for aligment excess
            self.load_l(self.nlimbs() - 1) >> (8 * (LIMB_BYTES - (self._len() - len))) == 0
        } else {
            false
        }
    }

    _mpu_try_into_native_u!(u8, try_into_u8);
    _mpu_try_into_native_u!(u16, try_into_u16);
    _mpu_try_into_native_u!(u32, try_into_u32);
    _mpu_try_into_native_u!(u64, try_into_u64);
}

/// Marker trait for read-only multiprecision integers.
///
/// Implemented by the read-only representation-specific types, i.e.
/// [`MpBigEndianUIntByteSlice`], [`MpLittleEndianUIntByteSlice`] and
/// [`MpNativeEndianUIntLimbsSlice`], and thereby distinguishes them from their
/// mutable counterparts, which implement [`MpMutUInt`] instead. It doesn't add
/// any methods on its own, all read access is provided through the
/// [`MpUIntCommon`] supertrait. Arithmetic primitives only reading from an
/// operand are generic over [`MpUIntCommon`] rather than [`MpUInt`], so that
/// mutable multiprecision integers can be passed as well.
///
/// The trait is sealed, i.e. it cannot be implemented outside of this crate.
pub trait MpUInt: MpUIntCommon {}

macro_rules! _mpu_set_to_native_u {
    ($nt:ty, $name:ident) => {
        #[doc = concat!("Set the multiprecision integer to a [`", stringify!($nt), "`] value.")]
        ///
        /// Execution time depends only on the multiprecision integer's [length
        /// in units of bytes](MpUIntCommon::len) and is otherwise constant as
        /// far as branching is concerned.
        ///
        /// # Arguments
        ///
        /// * `value` - The value to set the multiprecision integer to. The
        ///   multiprecision integer's [length in units of
        ///   bytes](MpUIntCommon::len) must be at least the native type's size
        ///   in bytes.
        fn $name(&mut self, mut value: $nt) {
            debug_assert!(self.len() >= mem::size_of::<$nt>());
            self.clear_bytes_above(mem::size_of::<$nt>());
            let native_type_nlimbs = ct_mp_nlimbs(mem::size_of::<$nt>());
            for i in 0..native_type_nlimbs {
                self.store_l(i, (value & (!(0 as LimbType) as $nt)) as LimbType);
                // This loop only gets executed more than once in case LIMB_BITS < $nt::BITS.
                // Avoid a compiler error for smaller native types due to a too large
                // shift distance.
                value >>= LIMB_BITS.min(<$nt>::BITS - 1);
            }
        }
    };
}

/// Interface to mutable multiprecision integers.
///
/// Implemented by the mutable representation-specific types, i.e.
/// [`MpMutBigEndianUIntByteSlice`], [`MpMutLittleEndianUIntByteSlice`] and
/// [`MpMutNativeEndianUIntLimbsSlice`]. In addition to the read access provided
/// through the [`MpUIntCommon`] supertrait, [`MpMutUInt`] provides write access
/// in units of [`LimbType`], as well as primitives for clearing byte ranges,
/// setting bits and for copying values from other multiprecision integers or
/// from native integers. Arithmetic primitives are generic over [`MpMutUInt`]
/// for any operand they write to.
///
/// The trait is sealed, i.e. it cannot be implemented outside of this crate.
pub trait MpMutUInt: MpUIntCommon {
    /// Store a limb fully covered by the underlying buffer.
    ///
    /// Use [`store_l()`](Self::store_l) instead if the limb might be the
    /// partially covered most significant one.
    ///
    /// Runs in constant time as far as branching is concerned.
    ///
    /// # Arguments
    ///
    /// * `i` - The index of the limb to update, counted from least to most
    ///   significant. Must be less than [`nlimbs()`](MpUIntCommon::nlimbs).
    ///   The limb must be fully contained in the underlying buffer, i.e. if `i`
    ///   refers to the most significant limb, the latter must not be a
    ///   partially covered one.
    /// * `value` - The value to store, in the host's native endianess.
    fn store_l_full(&mut self, i: usize, value: LimbType);

    /// Store a limb, which might be the partially covered most significant
    /// one.
    ///
    /// Execution time depends only on the multiprecision integer's [length in
    /// units of bytes](MpUIntCommon::len) and the `i` argument and is otherwise
    /// constant as far as branching is concerned.
    ///
    /// # Arguments
    ///
    /// * `i` - The index of the limb to update, counted from least to most
    ///   significant. Must be less than [`nlimbs()`](MpUIntCommon::nlimbs).
    /// * `value` - The value to store, in the host's native endianess. The
    ///   bits corresponding to any of the limb's excess high bytes not covered
    ///   by the underlying buffer are ignored.
    fn store_l(&mut self, i: usize, value: LimbType);

    /// Clear the multiprecision integer's high bytes.
    ///
    /// Set all bytes at positions `>= begin` to zero, with positions counted in
    /// units of bytes from least to most significant. That is, the
    /// multiprecision integer gets truncated to its `begin` least significant
    /// bytes. If `begin` is `>= len()`, nothing is cleared.
    ///
    /// Execution time depends only on the multiprecision integer's [length in
    /// units of bytes](MpUIntCommon::len) and the `begin` argument and is
    /// otherwise constant as far as branching is concerned. See
    /// [`ct_clear_bits_above_mp()`] for clearing at bit granularity, with an
    /// execution time independent of the position.
    ///
    /// # Arguments
    ///
    /// * `begin` - The position of the least significant byte to clear,
    ///   counted in units of bytes from least to most significant.
    fn clear_bytes_above(&mut self, begin: usize);

    /// Clear the multiprecision integer's low bytes.
    ///
    /// Set all bytes at positions `< end` to zero, with positions counted in
    /// units of bytes from least to most significant. If `end` is `>= len()`,
    /// all of the multiprecision integer is cleared.
    ///
    /// Execution time depends only on the multiprecision integer's [length in
    /// units of bytes](MpUIntCommon::len) and the `end` argument and is
    /// otherwise constant as far as branching is concerned. See
    /// [`ct_clear_bits_below_mp()`] for clearing at bit granularity, with an
    /// execution time independent of the position.
    ///
    /// # Arguments
    ///
    /// * `end` - The position past the most significant byte to clear, counted
    ///   in units of bytes from least to most significant.
    fn clear_bytes_below(&mut self, end: usize);

    /// Conditionally clear the multiprecision integer's high bytes.
    ///
    /// If `cond` is true, set all bytes at positions `>= begin` to zero, like
    /// [`clear_bytes_above()`](Self::clear_bytes_above). Otherwise leave the
    /// multiprecision integer unmodified.
    ///
    /// Execution time depends only on the multiprecision integer's [length in
    /// units of bytes](MpUIntCommon::len) and the `begin` argument and is
    /// otherwise constant as far as branching is concerned. In particular, it
    /// doesn't depend on `cond`.
    ///
    /// # Arguments
    ///
    /// * `begin` - The position of the least significant byte to clear,
    ///   counted in units of bytes from least to most significant.
    /// * `cond` - Whether or not to clear the bytes.
    fn clear_bytes_above_cond(&mut self, begin: usize, cond: LimbChoice) {
        if begin >= self.len() {
            return;
        }

        let mask = cond.select(!0, 0);
        let begin_limb = begin / LIMB_BYTES;
        let begin_in_limb = begin % LIMB_BYTES;
        let val = self.load_l(begin_limb);
        let first_mask = !ct_lsb_mask_l(8 * begin_in_limb as u32) | mask;
        let val = val & first_mask;
        self.store_l(begin_limb, val);

        for i in begin_limb + 1..self.nlimbs() {
            self.store_l(i, self.load_l(i) & mask);
        }
    }

    /// Copy a multiprecision integer's value.
    ///
    /// Set this multiprecision integer to the value of `src`, which may be of
    /// any representation. If `src` is shorter, the value gets zero-extended.
    /// Otherwise its value must fit into this multiprecision integer. That is,
    /// all of `src`'s bytes at positions `>= len()`, counted from least to most
    /// significant, must be zero. The [length in units of
    /// bytes](MpUIntCommon::len) of `src` itself isn't restricted.
    ///
    /// Execution time depends only on the two multiprecision integers' [lengths
    /// in units of bytes](MpUIntCommon::len) and is otherwise constant as far
    /// as branching is concerned.
    ///
    /// # Arguments
    ///
    /// * `src` - The multiprecision integer to copy the value from.
    fn copy_from<S: MpUIntCommon>(&'_ mut self, src: &S) {
        let src_nlimbs = src.nlimbs();
        let dst_nlimbs = self.nlimbs();
        debug_assert!(find_last_set_byte_mp(src) <= self.len());

        if src_nlimbs == 0 {
            self.clear_bytes_above(0);
            return;
        } else if dst_nlimbs == 0 {
            return;
        }
        let common_nlimbs = src_nlimbs.min(dst_nlimbs);
        for i in 0..common_nlimbs - 1 {
            self.store_l_full(i, src.load_l_full(i));
        }
        let high_limb = src.load_l(common_nlimbs - 1);
        debug_assert!(src_nlimbs < dst_nlimbs || (high_limb & !self.partial_high_mask()) == 0);
        self.store_l(common_nlimbs - 1, high_limb);
        self.clear_bytes_above(src.len());
    }

    /// Conditionally copy a multiprecision integer's value.
    ///
    /// If `cond` is true, set this multiprecision integer to the value of
    /// `src`, like [`copy_from()`](Self::copy_from). Otherwise leave it
    /// unmodified. The same requirements on `src` apply in either case.
    ///
    /// Execution time depends only on the two multiprecision integers' [lengths
    /// in units of bytes](MpUIntCommon::len) and is otherwise constant as far
    /// as branching is concerned. In particular, it doesn't depend on `cond`.
    ///
    /// # Arguments
    ///
    /// * `src` - The multiprecision integer to copy the value from.
    /// * `cond` - Whether or not to copy the value.
    fn copy_from_cond<S: MpUIntCommon>(&'_ mut self, src: &S, cond: LimbChoice) {
        let src_nlimbs = src.nlimbs();
        let dst_nlimbs = self.nlimbs();
        debug_assert!(find_last_set_byte_mp(src) <= self.len());

        if src_nlimbs == 0 {
            self.clear_bytes_above_cond(0, cond);
            return;
        } else if dst_nlimbs == 0 {
            return;
        }
        let common_nlimbs = src_nlimbs.min(dst_nlimbs);
        for i in 0..common_nlimbs - 1 {
            let val = cond.select(self.load_l_full(i), src.load_l_full(i));
            self.store_l_full(i, val);
        }
        let high_limb = cond.select(
            self.load_l(common_nlimbs - 1),
            src.load_l(common_nlimbs - 1),
        );
        debug_assert!(src_nlimbs < dst_nlimbs || (high_limb & !self.partial_high_mask()) == 0);
        self.store_l(common_nlimbs - 1, high_limb);
        self.clear_bytes_above_cond(src.len(), cond);
    }

    /// Set a bit of the multiprecision integer to a given value.
    ///
    /// Execution time depends only on the multiprecision integer's [length in
    /// units of bytes](MpUIntCommon::len) and the `pos` argument and is
    /// otherwise constant as far as branching is concerned. In particular, it
    /// doesn't depend on `val`.
    ///
    /// # Arguments
    ///
    /// * `pos` - The position of the bit to set, counted from least to most
    ///   significant. Must be less than 8 times the multiprecision integer's
    ///   [length in units of bytes](MpUIntCommon::len).
    /// * `val` - The value to set the bit to.
    fn set_bit_to(&mut self, pos: usize, val: bool) {
        let limb_index = pos / LIMB_BITS as usize;
        debug_assert!(limb_index < self.nlimbs());
        let pos_in_limb = pos % LIMB_BITS as usize;
        let mut l = self.load_l(limb_index);
        let bit_pos_mask = (1 as LimbType) << pos_in_limb;
        let val_mask = LimbChoice::from(val as LimbType).select(0, bit_pos_mask);
        l &= !bit_pos_mask;
        l |= val_mask;
        self.store_l(limb_index, l)
    }

    _mpu_set_to_native_u!(u8, set_to_u8);
    _mpu_set_to_native_u!(u16, set_to_u16);
    _mpu_set_to_native_u!(u32, set_to_u32);
    _mpu_set_to_native_u!(u64, set_to_u64);
}

/// Common interface to multiprecision integers backed by a single buffer
/// slice.
///
/// Implemented by all of the representation-specific types, read-only and
/// mutable, each of which wraps a single contiguous slice of `u8` or
/// [`LimbType`] elements. It's the common supertrait of [`MpUIntSlice`], for
/// the read-only types, and [`MpMutUIntSlice`], for the mutable ones. It
/// doesn't add any public methods on its own; the slice handling it stands
/// for, like splitting a multiprecision integer into a high and a low part,
/// is crate-internal.
///
/// The trait is sealed, i.e. it cannot be implemented outside of this crate.
pub trait MpUIntSliceCommon: MpUIntSliceCommonPriv + MpUIntCommon {}

/// Interface to read-only multiprecision integers backed by a single buffer
/// slice.
///
/// Implemented by the read-only representation-specific types, i.e.
/// [`MpBigEndianUIntByteSlice`], [`MpLittleEndianUIntByteSlice`] and
/// [`MpNativeEndianUIntLimbsSlice`]. In addition to what's provided through the
/// [`MpUInt`] and [`MpUIntSliceCommon`] supertraits, [`MpUIntSlice`] provides
/// for deriving new views of the same representation on the backing buffer
/// slice. See [`MpMutUIntSlice`] for the mutable counterpart.
///
/// The trait is sealed, i.e. it cannot be implemented outside of this crate.
pub trait MpUIntSlice: MpUIntSlicePriv + MpUInt {
    /// Reborrow the multiprecision integer with a lifetime bound to `self`.
    ///
    /// Returns a view of the same representation on the same backing buffer
    /// slice, but with its lifetime shortened to that of the `self` borrow.
    /// This makes it the same type as other views derived from `self`, like
    /// the ones returned by [`shrink_to()`](Self::shrink_to), so that these
    /// can be used interchangeably.
    fn coerce_lifetime(&self) -> Self::SelfT<'_>;

    /// Get a view on the multiprecision integer's low part.
    ///
    /// Returns a view of the same representation on the part of the backing
    /// buffer slice holding the `nbytes` least significant bytes, with
    /// `nbytes` aligned upwards if the representation doesn't support
    /// unaligned lengths. The multiprecision integer's value must fit into
    /// this length. That is, all of its bytes at positions `>= nbytes`, counted
    /// from least to most significant, must be zero.
    ///
    /// # Arguments
    ///
    /// * `nbytes` - The [length in units of bytes](MpUIntCommon::len) to shrink
    ///   the view to. If it's larger than the multiprecision integer's [length
    ///   in units of bytes](MpUIntCommon::len), the latter is retained.
    fn shrink_to(&self, nbytes: usize) -> Self::SelfT<'_> {
        let nbytes = nbytes.min(self._len());
        debug_assert!(nbytes >= find_last_set_byte_mp(self));
        self._shrink_to(nbytes)
    }
}

/// Interface to mutable multiprecision integers backed by a single buffer
/// slice.
///
/// Implemented by the mutable representation-specific types, i.e.
/// [`MpMutBigEndianUIntByteSlice`], [`MpMutLittleEndianUIntByteSlice`] and
/// [`MpMutNativeEndianUIntLimbsSlice`]. In addition to what's provided through
/// the [`MpMutUInt`] and [`MpUIntSliceCommon`] supertraits, [`MpMutUIntSlice`]
/// provides for deriving new mutable views of the same representation on the
/// backing buffer slice. See [`MpUIntSlice`] for the read-only counterpart.
///
/// The trait is sealed, i.e. it cannot be implemented outside of this crate.
pub trait MpMutUIntSlice: MpMutUIntSlicePriv + MpMutUInt {
    /// Reborrow the multiprecision integer with a lifetime bound to `self`.
    ///
    /// Returns a mutable view of the same representation on the same backing
    /// buffer slice, but with its lifetime shortened to that of the `self`
    /// borrow. This makes it the same type as other views derived from
    /// `self`, like the ones returned by [`shrink_to()`](Self::shrink_to), so
    /// that these can be used interchangeably. `self` remains mutably borrowed
    /// for as long as the view is alive.
    fn coerce_lifetime(&mut self) -> Self::SelfT<'_>;

    /// Get a mutable view on the multiprecision integer's low part.
    ///
    /// Returns a mutable view of the same representation on the part of the
    /// backing buffer slice holding the `nbytes` least significant bytes, with
    /// `nbytes` aligned upwards if the representation doesn't support
    /// unaligned lengths. Writes through the view modify the original
    /// multiprecision integer's low part, while its high part beyond the view
    /// is left alone. `self` remains mutably borrowed for as long as the view
    /// is alive. The multiprecision integer's value must fit into this length.
    /// That is, all of its bytes at positions `>= nbytes`, counted from least
    /// to most significant, must be zero.
    ///
    /// # Arguments
    ///
    /// * `nbytes` - The [length in units of bytes](MpUIntCommon::len) to shrink
    ///   the view to. If it's larger than the multiprecision integer's [length
    ///   in units of bytes](MpUIntCommon::len), the latter is retained.
    fn shrink_to(&mut self, nbytes: usize) -> Self::SelfT<'_> {
        let nbytes = nbytes.min(self._len());
        debug_assert!(nbytes >= find_last_set_byte_mp(self));
        self._shrink_to(nbytes)
    }
}

/// Read-only multiprecision integer stored in a big-endian byte slice.
///
/// Wraps a `u8` slice holding a multiprecision integer in big-endian order,
/// i.e. most significant byte first. The integer's [length in units of
/// bytes](MpUIntCommon::len) equals the slice's length and doesn't need to be a
/// multiple of the [`LimbType`] size.
///
/// For converting from and to the wrapped slice, the following primitives are
/// provided:
/// - [`from_bytes()`](Self::from_bytes) wraps a `u8` slice.
/// - [`as_bytes()`](Self::as_bytes) and the [`From`] implementation for
///   `&[u8]` return the wrapped slice.
/// - The [`From`] implementation for `&MpMutBigEndianUIntByteSlice` creates a
///   read-only view on a [`MpMutBigEndianUIntByteSlice`].
///
/// See [`MpMutBigEndianUIntByteSlice`] for the mutable variant.
#[derive(Clone, Copy)]
pub struct MpBigEndianUIntByteSlice<'a> {
    /// The wrapped byte slice, holding the multiprecision integer in
    /// big-endian order, i.e. most significant byte first.
    bytes: &'a [u8],
}

impl<'a> MpBigEndianUIntByteSlice<'a> {
    /// Wrap a big-endian byte slice as a multiprecision integer.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The byte slice holding the multiprecision integer in
    ///   big-endian order.
    pub fn from_bytes(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }

    /// Get the wrapped big-endian byte slice.
    ///
    /// The returned slice has the full lifetime `'a` of the wrapped one.
    pub fn as_bytes(&self) -> &'a [u8] {
        self.bytes
    }
}

impl<'a> MpUIntCommonPriv for MpBigEndianUIntByteSlice<'a> {
    const SUPPORTS_UNALIGNED_BUFFER_LENGTHS: bool = true;

    fn _len(&self) -> usize {
        self.bytes.len()
    }
}

impl<'a> MpUIntCommon for MpBigEndianUIntByteSlice<'a> {
    fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    fn load_l_full(&self, i: usize) -> LimbType {
        be_mp_load_l_full(self.bytes, i)
    }

    fn load_l(&self, i: usize) -> LimbType {
        be_mp_load_l(self.bytes, i)
    }
}

impl<'a> MpUInt for MpBigEndianUIntByteSlice<'a> {}

impl<'a> MpUIntSliceCommonPriv for MpBigEndianUIntByteSlice<'a> {
    type BackingSliceElementType = u8;

    fn n_backing_elements(&self) -> usize {
        self.bytes.len()
    }

    fn take(self, nbytes: usize) -> (Self, Self) {
        let (h, l) = self.bytes.split_at(self.bytes.len() - nbytes);
        (Self { bytes: h }, Self { bytes: l })
    }
}

impl<'a> MpUIntSliceCommon for MpBigEndianUIntByteSlice<'a> {}

impl<'a> MpUIntSlicePriv for MpBigEndianUIntByteSlice<'a> {
    type SelfT<'b>
        = MpBigEndianUIntByteSlice<'b>
    where
        Self: 'b;

    type FromSliceError = convert::Infallible;

    fn from_slice<'b: 'c, 'c>(
        s: &'b [Self::BackingSliceElementType],
    ) -> Result<Self::SelfT<'c>, Self::FromSliceError>
    where
        Self: 'c,
    {
        Ok(Self::SelfT::<'c> { bytes: s })
    }

    fn _shrink_to(&self, nbytes: usize) -> Self::SelfT<'_> {
        MpBigEndianUIntByteSlice {
            bytes: &self.bytes[self.bytes.len() - nbytes..],
        }
    }
}

impl<'a> MpUIntSlice for MpBigEndianUIntByteSlice<'a> {
    fn coerce_lifetime(&self) -> Self::SelfT<'_> {
        MpBigEndianUIntByteSlice { bytes: self.bytes }
    }
}

impl<'a> fmt::LowerHex for MpBigEndianUIntByteSlice<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_lower_hex(f)
    }
}

impl<'a, 'b> From<&'a MpMutBigEndianUIntByteSlice<'b>> for MpBigEndianUIntByteSlice<'a> {
    fn from(value: &'a MpMutBigEndianUIntByteSlice<'b>) -> Self {
        Self { bytes: value.bytes }
    }
}

impl<'a> From<MpBigEndianUIntByteSlice<'a>> for &'a [u8] {
    fn from(value: MpBigEndianUIntByteSlice<'a>) -> Self {
        value.bytes
    }
}

/// Mutable multiprecision integer stored in a big-endian byte slice.
///
/// Wraps a mutable `u8` slice holding a multiprecision integer in big-endian
/// order, i.e. most significant byte first. The integer's [length in units of
/// bytes](MpUIntCommon::len) equals the slice's length and doesn't need to be a
/// multiple of the [`LimbType`] size.
///
/// For converting from and to the wrapped slice, the following primitives are
/// provided:
/// - [`from_bytes()`](Self::from_bytes) wraps a mutable `u8` slice.
/// - [`as_bytes()`](Self::as_bytes) and [`as_bytes_mut()`](Self::as_bytes_mut),
///   as well as the [`From`] implementations of `&[u8]` and `&mut [u8]` for
///   references to a [`MpMutBigEndianUIntByteSlice`], borrow the wrapped slice.
///
/// A read-only [`MpBigEndianUIntByteSlice`] view can be obtained through the
/// latter's [`From`] implementation for `&MpMutBigEndianUIntByteSlice`.
pub struct MpMutBigEndianUIntByteSlice<'a> {
    /// The wrapped byte slice, holding the multiprecision integer in
    /// big-endian order, i.e. most significant byte first.
    bytes: &'a mut [u8],
}

impl<'a> MpMutBigEndianUIntByteSlice<'a> {
    /// Wrap a mutable big-endian byte slice as a multiprecision integer.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The byte slice holding the multiprecision integer in
    ///   big-endian order.
    pub fn from_bytes(bytes: &'a mut [u8]) -> Self {
        Self { bytes }
    }

    /// Borrow the wrapped big-endian byte slice.
    pub fn as_bytes(&self) -> &[u8] {
        self.bytes
    }

    /// Mutably borrow the wrapped big-endian byte slice.
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        self.bytes
    }
}

impl<'a> MpUIntCommonPriv for MpMutBigEndianUIntByteSlice<'a> {
    const SUPPORTS_UNALIGNED_BUFFER_LENGTHS: bool = true;

    fn _len(&self) -> usize {
        self.bytes.len()
    }
}

impl<'a> MpUIntCommon for MpMutBigEndianUIntByteSlice<'a> {
    fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    fn load_l_full(&self, i: usize) -> LimbType {
        be_mp_load_l_full(self.bytes, i)
    }

    fn load_l(&self, i: usize) -> LimbType {
        be_mp_load_l(self.bytes, i)
    }
}

impl<'a> MpMutUInt for MpMutBigEndianUIntByteSlice<'a> {
    fn store_l_full(&mut self, i: usize, value: LimbType) {
        be_mp_store_l_full(self.bytes, i, value)
    }

    fn store_l(&mut self, i: usize, value: LimbType) {
        be_mp_store_l(self.bytes, i, value)
    }

    fn clear_bytes_above(&mut self, begin: usize) {
        be_mp_clear_bytes_above(self.bytes, begin)
    }

    fn clear_bytes_below(&mut self, end: usize) {
        be_mp_clear_bytes_below(self.bytes, end)
    }
}

impl<'a> MpUIntSliceCommonPriv for MpMutBigEndianUIntByteSlice<'a> {
    type BackingSliceElementType = u8;

    fn n_backing_elements(&self) -> usize {
        self.bytes.len()
    }

    fn take(self, nbytes: usize) -> (Self, Self) {
        let (h, l) = self.bytes.split_at_mut(self.bytes.len() - nbytes);
        (Self { bytes: h }, Self { bytes: l })
    }
}

impl<'a> MpUIntSliceCommon for MpMutBigEndianUIntByteSlice<'a> {}

impl<'a> MpMutUIntSlicePriv for MpMutBigEndianUIntByteSlice<'a> {
    type SelfT<'b>
        = MpMutBigEndianUIntByteSlice<'b>
    where
        Self: 'b;

    type FromSliceError = convert::Infallible;

    fn from_slice<'b: 'c, 'c>(
        s: &'b mut [Self::BackingSliceElementType],
    ) -> Result<Self::SelfT<'c>, Self::FromSliceError>
    where
        Self: 'c,
    {
        Ok(Self::SelfT::<'c> { bytes: s })
    }

    fn _shrink_to(&mut self, nbytes: usize) -> Self::SelfT<'_> {
        let l = self.bytes.len();
        MpMutBigEndianUIntByteSlice {
            bytes: &mut self.bytes[l - nbytes..],
        }
    }
}

impl<'a> MpMutUIntSlice for MpMutBigEndianUIntByteSlice<'a> {
    fn coerce_lifetime(&mut self) -> Self::SelfT<'_> {
        MpMutBigEndianUIntByteSlice { bytes: self.bytes }
    }
}

impl<'a> fmt::LowerHex for MpMutBigEndianUIntByteSlice<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_lower_hex(f)
    }
}

impl<'a, 'b> From<&'a mut MpMutBigEndianUIntByteSlice<'b>> for &'a mut [u8] {
    fn from(value: &'a mut MpMutBigEndianUIntByteSlice<'b>) -> Self {
        value.bytes
    }
}

impl<'a, 'b> From<&'a MpMutBigEndianUIntByteSlice<'b>> for &'a [u8] {
    fn from(value: &'a MpMutBigEndianUIntByteSlice<'b>) -> Self {
        value.bytes
    }
}

/// Read-only multiprecision integer stored in a little-endian byte slice.
///
/// Wraps a `u8` slice holding a multiprecision integer in little-endian order,
/// i.e. least significant byte first. The integer's [length in units of
/// bytes](MpUIntCommon::len) equals the slice's length and doesn't need to be a
/// multiple of the [`LimbType`] size.
///
/// For converting from and to the wrapped slice, the following primitives are
/// provided:
/// - [`from_bytes()`](Self::from_bytes) wraps a `u8` slice.
/// - [`as_bytes()`](Self::as_bytes) and the [`From`] implementation for
///   `&[u8]` return the wrapped slice.
/// - The [`From`] implementation for `&MpMutLittleEndianUIntByteSlice` creates a
///   read-only view on a [`MpMutLittleEndianUIntByteSlice`].
///
/// See [`MpMutLittleEndianUIntByteSlice`] for the mutable variant.
#[derive(Clone, Copy)]
pub struct MpLittleEndianUIntByteSlice<'a> {
    /// The wrapped byte slice, holding the multiprecision integer in
    /// little-endian order, i.e. least significant byte first.
    bytes: &'a [u8],
}

impl<'a> MpLittleEndianUIntByteSlice<'a> {
    /// Wrap a little-endian byte slice as a multiprecision integer.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The byte slice holding the multiprecision integer in
    ///   little-endian order.
    pub fn from_bytes(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }

    /// Get the wrapped little-endian byte slice.
    ///
    /// The returned slice has the full lifetime `'a` of the wrapped one.
    pub fn as_bytes(&self) -> &'a [u8] {
        self.bytes
    }
}

impl<'a> MpUIntCommonPriv for MpLittleEndianUIntByteSlice<'a> {
    const SUPPORTS_UNALIGNED_BUFFER_LENGTHS: bool = true;

    fn _len(&self) -> usize {
        self.bytes.len()
    }
}

impl<'a> MpUIntCommon for MpLittleEndianUIntByteSlice<'a> {
    fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    fn load_l_full(&self, i: usize) -> LimbType {
        le_mp_load_l_full(self.bytes, i)
    }

    fn load_l(&self, i: usize) -> LimbType {
        le_mp_load_l(self.bytes, i)
    }
}

impl<'a> MpUInt for MpLittleEndianUIntByteSlice<'a> {}

impl<'a> MpUIntSliceCommonPriv for MpLittleEndianUIntByteSlice<'a> {
    type BackingSliceElementType = u8;

    fn n_backing_elements(&self) -> usize {
        self.bytes.len()
    }

    fn take(self, nbytes: usize) -> (Self, Self) {
        let (l, h) = self.bytes.split_at(nbytes);
        (Self { bytes: h }, Self { bytes: l })
    }
}

impl<'a> MpUIntSliceCommon for MpLittleEndianUIntByteSlice<'a> {}

impl<'a> MpUIntSlicePriv for MpLittleEndianUIntByteSlice<'a> {
    type SelfT<'b>
        = MpLittleEndianUIntByteSlice<'b>
    where
        Self: 'b;

    type FromSliceError = convert::Infallible;

    fn from_slice<'b: 'c, 'c>(
        s: &'b [Self::BackingSliceElementType],
    ) -> Result<Self::SelfT<'c>, Self::FromSliceError>
    where
        Self: 'c,
    {
        Ok(Self::SelfT::<'c> { bytes: s })
    }

    fn _shrink_to(&self, nbytes: usize) -> Self::SelfT<'_> {
        MpLittleEndianUIntByteSlice {
            bytes: &self.bytes[..nbytes],
        }
    }
}

impl<'a> MpUIntSlice for MpLittleEndianUIntByteSlice<'a> {
    fn coerce_lifetime(&self) -> Self::SelfT<'_> {
        MpLittleEndianUIntByteSlice { bytes: self.bytes }
    }
}

impl<'a> fmt::LowerHex for MpLittleEndianUIntByteSlice<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_lower_hex(f)
    }
}

impl<'a, 'b> From<&'a MpMutLittleEndianUIntByteSlice<'b>> for MpLittleEndianUIntByteSlice<'a> {
    fn from(value: &'a MpMutLittleEndianUIntByteSlice<'b>) -> Self {
        Self { bytes: value.bytes }
    }
}

impl<'a> From<MpLittleEndianUIntByteSlice<'a>> for &'a [u8] {
    fn from(value: MpLittleEndianUIntByteSlice<'a>) -> Self {
        value.bytes
    }
}

/// Mutable multiprecision integer stored in a little-endian byte slice.
///
/// Wraps a mutable `u8` slice holding a multiprecision integer in little-endian
/// order, i.e. least significant byte first. The integer's [length in units of
/// bytes](MpUIntCommon::len) equals the slice's length and doesn't need to be a
/// multiple of the [`LimbType`] size.
///
/// For converting from and to the wrapped slice, the following primitives are
/// provided:
/// - [`from_bytes()`](Self::from_bytes) wraps a mutable `u8` slice.
/// - [`as_bytes()`](Self::as_bytes) and [`as_bytes_mut()`](Self::as_bytes_mut),
///   as well as the [`From`] implementations of `&[u8]` and `&mut [u8]` for
///   references to a [`MpMutLittleEndianUIntByteSlice`], borrow the wrapped slice.
///
/// A read-only [`MpLittleEndianUIntByteSlice`] view can be obtained through the
/// latter's [`From`] implementation for `&MpMutLittleEndianUIntByteSlice`.
pub struct MpMutLittleEndianUIntByteSlice<'a> {
    /// The wrapped byte slice, holding the multiprecision integer in
    /// little-endian order, i.e. least significant byte first.
    bytes: &'a mut [u8],
}

impl<'a> MpMutLittleEndianUIntByteSlice<'a> {
    /// Wrap a mutable little-endian byte slice as a multiprecision integer.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The byte slice holding the multiprecision integer in
    ///   little-endian order.
    pub fn from_bytes(bytes: &'a mut [u8]) -> Self {
        Self { bytes }
    }

    /// Borrow the wrapped little-endian byte slice.
    pub fn as_bytes(&self) -> &[u8] {
        self.bytes
    }

    /// Mutably borrow the wrapped little-endian byte slice.
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        self.bytes
    }
}

impl<'a> MpUIntCommonPriv for MpMutLittleEndianUIntByteSlice<'a> {
    const SUPPORTS_UNALIGNED_BUFFER_LENGTHS: bool = true;

    fn _len(&self) -> usize {
        self.bytes.len()
    }
}

impl<'a> MpUIntCommon for MpMutLittleEndianUIntByteSlice<'a> {
    fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    fn load_l_full(&self, i: usize) -> LimbType {
        le_mp_load_l_full(self.bytes, i)
    }

    fn load_l(&self, i: usize) -> LimbType {
        le_mp_load_l(self.bytes, i)
    }
}

impl<'a> MpMutUInt for MpMutLittleEndianUIntByteSlice<'a> {
    fn store_l_full(&mut self, i: usize, value: LimbType) {
        le_mp_store_l_full(self.bytes, i, value)
    }

    fn store_l(&mut self, i: usize, value: LimbType) {
        le_mp_store_l(self.bytes, i, value)
    }

    fn clear_bytes_above(&mut self, begin: usize) {
        le_mp_clear_bytes_above(self.bytes, begin)
    }

    fn clear_bytes_below(&mut self, end: usize) {
        le_mp_clear_bytes_below(self.bytes, end)
    }
}

impl<'a> MpUIntSliceCommonPriv for MpMutLittleEndianUIntByteSlice<'a> {
    type BackingSliceElementType = u8;

    fn n_backing_elements(&self) -> usize {
        self.bytes.len()
    }

    fn take(self, nbytes: usize) -> (Self, Self) {
        let (l, h) = self.bytes.split_at_mut(nbytes);
        (Self { bytes: h }, Self { bytes: l })
    }
}

impl<'a> MpUIntSliceCommon for MpMutLittleEndianUIntByteSlice<'a> {}

impl<'a> MpMutUIntSlicePriv for MpMutLittleEndianUIntByteSlice<'a> {
    type SelfT<'b>
        = MpMutLittleEndianUIntByteSlice<'b>
    where
        Self: 'b;

    type FromSliceError = convert::Infallible;

    fn from_slice<'b: 'c, 'c>(
        s: &'b mut [Self::BackingSliceElementType],
    ) -> Result<Self::SelfT<'c>, Self::FromSliceError>
    where
        Self: 'c,
    {
        Ok(Self::SelfT::<'c> { bytes: s })
    }

    fn _shrink_to(&mut self, nbytes: usize) -> Self::SelfT<'_> {
        MpMutLittleEndianUIntByteSlice {
            bytes: &mut self.bytes[..nbytes],
        }
    }
}

impl<'a> MpMutUIntSlice for MpMutLittleEndianUIntByteSlice<'a> {
    fn coerce_lifetime(&mut self) -> Self::SelfT<'_> {
        MpMutLittleEndianUIntByteSlice { bytes: self.bytes }
    }
}

impl<'a> fmt::LowerHex for MpMutLittleEndianUIntByteSlice<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_lower_hex(f)
    }
}

impl<'a, 'b> From<&'a mut MpMutLittleEndianUIntByteSlice<'b>> for &'a mut [u8] {
    fn from(value: &'a mut MpMutLittleEndianUIntByteSlice<'b>) -> Self {
        value.bytes
    }
}

impl<'a, 'b> From<&'a MpMutLittleEndianUIntByteSlice<'b>> for &'a [u8] {
    fn from(value: &'a MpMutLittleEndianUIntByteSlice<'b>) -> Self {
        value.bytes
    }
}

/// Read-only multiprecision integer stored in a native-endian [`LimbType`]
/// slice.
///
/// Wraps a [`LimbType`] slice holding a multiprecision integer in units of
/// [`LimbType`], least significant limb first, with each limb in the host's
/// native endianess. This is the most efficient representation to operate on.
/// The integer's [length in units of bytes](MpUIntCommon::len) equals the
/// slice's length in units of bytes and thus is always a multiple of the
/// [`LimbType`] size.
///
/// For converting from and to the wrapped slice, the following primitives are
/// provided:
/// - [`from_limbs()`](Self::from_limbs) wraps a [`LimbType`] slice. Use
///   [`nlimbs_for_len()`](Self::nlimbs_for_len) for allocating a suitably
///   sized one.
/// - [`as_limbs()`](Self::as_limbs) and the [`From`] implementation for
///   `&[LimbType]` return the wrapped slice.
/// - The [`From`] implementation for `&MpMutNativeEndianUIntLimbsSlice` creates a
///   read-only view on a [`MpMutNativeEndianUIntLimbsSlice`].
///
/// See [`MpMutNativeEndianUIntLimbsSlice`] for the mutable variant.
#[derive(Clone, Copy)]
pub struct MpNativeEndianUIntLimbsSlice<'a> {
    /// The wrapped [`LimbType`] slice, holding the multiprecision integer's
    /// limbs least significant first, each in the host's native endianess.
    limbs: &'a [LimbType],
}

impl<'a> MpNativeEndianUIntLimbsSlice<'a> {
    /// Wrap a native-endian [`LimbType`] slice as a multiprecision integer.
    ///
    /// # Arguments
    ///
    /// * `limbs` - The [`LimbType`] slice holding the multiprecision integer,
    ///   least significant limb first.
    pub fn from_limbs(limbs: &'a [LimbType]) -> Self {
        Self { limbs }
    }

    /// Get the wrapped native-endian [`LimbType`] slice.
    ///
    /// The returned slice has the full lifetime `'a` of the wrapped one.
    pub fn as_limbs(&self) -> &'a [LimbType] {
        self.limbs
    }

    /// The number of [`LimbType`]s needed for a given [length in units of
    /// bytes](MpUIntCommon::len).
    ///
    /// Returns the number of [`LimbType`] elements a slice must have for
    /// holding a multiprecision integer of [length in units of
    /// bytes](MpUIntCommon::len) `nbytes`, i.e. `nbytes` converted to units of
    /// [`LimbType`], rounding up. Useful for allocating suitably sized buffers.
    ///
    /// # Arguments
    ///
    /// * `nbytes` - The multiprecision integer's [length in units of
    ///   bytes](MpUIntCommon::len).
    pub fn nlimbs_for_len(nbytes: usize) -> usize {
        Self::n_backing_elements_for_len(nbytes)
    }
}

impl<'a> MpUIntCommonPriv for MpNativeEndianUIntLimbsSlice<'a> {
    const SUPPORTS_UNALIGNED_BUFFER_LENGTHS: bool = false;

    fn _len(&self) -> usize {
        self.limbs.len() * Self::BACKING_ELEMENT_SIZE
    }
}

impl<'a> MpUIntCommon for MpNativeEndianUIntLimbsSlice<'a> {
    fn is_empty(&self) -> bool {
        self.limbs.is_empty()
    }

    #[inline(always)]
    fn load_l_full(&self, i: usize) -> LimbType {
        self.limbs[i]
    }

    #[inline(always)]
    fn load_l(&self, i: usize) -> LimbType {
        self.load_l_full(i)
    }
}

impl<'a> MpUInt for MpNativeEndianUIntLimbsSlice<'a> {}

impl<'a> MpUIntSliceCommonPriv for MpNativeEndianUIntLimbsSlice<'a> {
    type BackingSliceElementType = LimbType;

    fn n_backing_elements(&self) -> usize {
        self.limbs.len()
    }

    fn take(self, nbytes: usize) -> (Self, Self) {
        debug_assert_eq!(nbytes % LIMB_BYTES, 0);
        let (l, h) = self
            .limbs
            .split_at(Self::n_backing_elements_for_len(nbytes));
        (Self { limbs: h }, Self { limbs: l })
    }
}

impl<'a> MpUIntSliceCommon for MpNativeEndianUIntLimbsSlice<'a> {}

impl<'a> MpUIntSlicePriv for MpNativeEndianUIntLimbsSlice<'a> {
    type SelfT<'b>
        = MpNativeEndianUIntLimbsSlice<'b>
    where
        Self: 'b;

    type FromSliceError = convert::Infallible;

    fn from_slice<'b: 'c, 'c>(
        s: &'b [Self::BackingSliceElementType],
    ) -> Result<Self::SelfT<'c>, Self::FromSliceError>
    where
        Self: 'c,
    {
        Ok(Self::SelfT::<'c> { limbs: s })
    }

    fn _shrink_to(&self, nbytes: usize) -> Self::SelfT<'_> {
        let nlimbs = Self::n_backing_elements_for_len(nbytes);
        MpNativeEndianUIntLimbsSlice {
            limbs: &self.limbs[..nlimbs],
        }
    }
}

impl<'a> MpUIntSlice for MpNativeEndianUIntLimbsSlice<'a> {
    fn coerce_lifetime(&self) -> Self::SelfT<'_> {
        MpNativeEndianUIntLimbsSlice { limbs: self.limbs }
    }
}

impl<'a> fmt::LowerHex for MpNativeEndianUIntLimbsSlice<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_lower_hex(f)
    }
}

impl<'a, 'b> From<&'a MpMutNativeEndianUIntLimbsSlice<'b>> for MpNativeEndianUIntLimbsSlice<'a> {
    fn from(value: &'a MpMutNativeEndianUIntLimbsSlice<'b>) -> Self {
        Self { limbs: value.limbs }
    }
}

impl<'a> From<MpNativeEndianUIntLimbsSlice<'a>> for &'a [LimbType] {
    fn from(value: MpNativeEndianUIntLimbsSlice<'a>) -> Self {
        value.limbs
    }
}

/// Mutable multiprecision integer stored in a native-endian [`LimbType`] slice.
///
/// Wraps a mutable [`LimbType`] slice holding a multiprecision integer in units
/// of [`LimbType`], least significant limb first, with each limb in the host's
/// native endianess. This is the most efficient representation to operate on.
/// The integer's [length in units of bytes](MpUIntCommon::len) equals the
/// slice's length in units of bytes and thus is always a multiple of the
/// [`LimbType`] size.
///
/// For converting from and to the wrapped slice, the following primitives are
/// provided:
/// - [`from_limbs()`](Self::from_limbs) wraps a mutable [`LimbType`] slice. Use
///   [`nlimbs_for_len()`](Self::nlimbs_for_len) for allocating a suitably
///   sized one.
/// - [`as_limbs()`](Self::as_limbs) and [`as_limbs_mut()`](Self::as_limbs_mut),
///   as well as the [`From`] implementations of `&[LimbType]` and
///   `&mut [LimbType]` for references to a [`MpMutNativeEndianUIntLimbsSlice`],
///   borrow the wrapped slice.
///
/// A read-only [`MpNativeEndianUIntLimbsSlice`] view can be obtained through the
/// latter's [`From`] implementation for `&MpMutNativeEndianUIntLimbsSlice`.
pub struct MpMutNativeEndianUIntLimbsSlice<'a> {
    /// The wrapped [`LimbType`] slice, holding the multiprecision integer's
    /// limbs least significant first, each in the host's native endianess.
    limbs: &'a mut [LimbType],
}

impl<'a> MpMutNativeEndianUIntLimbsSlice<'a> {
    /// Wrap a mutable native-endian [`LimbType`] slice as a multiprecision
    /// integer.
    ///
    /// # Arguments
    ///
    /// * `limbs` - The [`LimbType`] slice holding the multiprecision integer,
    ///   least significant limb first.
    pub fn from_limbs(limbs: &'a mut [LimbType]) -> Self {
        Self { limbs }
    }

    /// Borrow the wrapped native-endian [`LimbType`] slice.
    pub fn as_limbs(&self) -> &[LimbType] {
        self.limbs
    }

    /// Mutably borrow the wrapped native-endian [`LimbType`] slice.
    pub fn as_limbs_mut(&mut self) -> &mut [LimbType] {
        self.limbs
    }

    /// The number of [`LimbType`]s needed for a given [length in units of
    /// bytes](MpUIntCommon::len).
    ///
    /// Returns the number of [`LimbType`] elements a slice must have for
    /// holding a multiprecision integer of [length in units of
    /// bytes](MpUIntCommon::len) `nbytes`, i.e. `nbytes` converted to units of
    /// [`LimbType`], rounding up. Useful for allocating suitably sized buffers.
    ///
    /// # Arguments
    ///
    /// * `nbytes` - The multiprecision integer's [length in units of
    ///   bytes](MpUIntCommon::len).
    pub fn nlimbs_for_len(nbytes: usize) -> usize {
        Self::n_backing_elements_for_len(nbytes)
    }
}

impl<'a> MpUIntCommonPriv for MpMutNativeEndianUIntLimbsSlice<'a> {
    const SUPPORTS_UNALIGNED_BUFFER_LENGTHS: bool = false;

    fn _len(&self) -> usize {
        self.limbs.len() * Self::BACKING_ELEMENT_SIZE
    }
}

impl<'a> MpUIntCommon for MpMutNativeEndianUIntLimbsSlice<'a> {
    fn is_empty(&self) -> bool {
        self.limbs.is_empty()
    }

    #[inline(always)]
    fn load_l_full(&self, i: usize) -> LimbType {
        self.limbs[i]
    }

    #[inline(always)]
    fn load_l(&self, i: usize) -> LimbType {
        self.load_l_full(i)
    }
}

impl<'a> MpMutUInt for MpMutNativeEndianUIntLimbsSlice<'a> {
    #[inline(always)]
    fn store_l_full(&mut self, i: usize, value: LimbType) {
        self.limbs[i] = value;
    }

    #[inline(always)]
    fn store_l(&mut self, i: usize, value: LimbType) {
        self.store_l_full(i, value);
    }

    fn clear_bytes_above(&mut self, begin: usize) {
        let mut begin_limb = begin / LIMB_BYTES;
        if begin_limb >= self.limbs.len() {
            return;
        }
        let begin_in_limb = begin % LIMB_BYTES;
        if begin_in_limb != 0 {
            self.limbs[begin_limb] &= ct_lsb_mask_l(8 * begin_in_limb as u32);
            begin_limb += 1;
        }
        self.limbs[begin_limb..].fill(0);
    }

    fn clear_bytes_below(&mut self, end: usize) {
        let end = end.min(self.len());
        let mut end_limb = ct_mp_nlimbs(end);
        let end_in_limb = end % LIMB_BYTES;
        if end_in_limb != 0 {
            end_limb -= 1;
            let mut l = self.load_l(end_limb);
            l >>= 8 * end_in_limb;
            l <<= 8 * end_in_limb;
            self.limbs[end_limb] = l;
        }
        self.limbs[..end_limb].fill(0);
    }
}

#[cfg(test)]
fn test_clear_bytes_below_with_aligned_lengths<T0: MpMutUIntSlice>() {
    let mut op0 = tst_mk_mp_backing_vec!(T0, 0);
    let mut op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    op0.clear_bytes_below(1);
    assert!(op0.is_empty());

    let mut op0 = tst_mk_mp_backing_vec!(T0, 2 * LIMB_BYTES);
    let mut op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    op0.store_l(0, !0);
    op0.store_l(1, !0);
    op0.clear_bytes_below(0);
    assert_eq!(op0.load_l(0), !0);
    assert_eq!(op0.load_l(1), !0);

    op0.clear_bytes_below(LIMB_BYTES + 1);
    assert_eq!(op0.load_l(0), 0);
    assert_eq!(op0.load_l(1), !0 << 8);

    op0.store_l(0, !0);
    op0.store_l(1, !0);
    op0.clear_bytes_below(2 * LIMB_BYTES);
    assert_eq!(op0.load_l(0), 0);
    assert_eq!(op0.load_l(1), 0);

    op0.store_l(0, !0);
    op0.store_l(1, !0);
    op0.clear_bytes_below(2 * LIMB_BYTES + 1);
    assert_eq!(op0.load_l(0), 0);
    assert_eq!(op0.load_l(1), 0);
}

#[test]
fn test_clear_bytes_below_be() {
    test_clear_bytes_below_with_aligned_lengths::<MpMutBigEndianUIntByteSlice>();
}

#[test]
fn test_clear_bytes_below_le() {
    test_clear_bytes_below_with_aligned_lengths::<MpMutLittleEndianUIntByteSlice>();
}

#[test]
fn test_clear_bytes_below_ne() {
    test_clear_bytes_below_with_aligned_lengths::<MpMutNativeEndianUIntLimbsSlice>();
}

impl<'a> MpUIntSliceCommonPriv for MpMutNativeEndianUIntLimbsSlice<'a> {
    type BackingSliceElementType = LimbType;

    fn n_backing_elements(&self) -> usize {
        self.limbs.len()
    }

    fn take(self, nbytes: usize) -> (Self, Self) {
        debug_assert_eq!(nbytes % LIMB_BYTES, 0);
        let (l, h) = self
            .limbs
            .split_at_mut(Self::n_backing_elements_for_len(nbytes));
        (Self { limbs: h }, Self { limbs: l })
    }
}

impl<'a> MpUIntSliceCommon for MpMutNativeEndianUIntLimbsSlice<'a> {}

impl<'a> MpMutUIntSlicePriv for MpMutNativeEndianUIntLimbsSlice<'a> {
    type SelfT<'b>
        = MpMutNativeEndianUIntLimbsSlice<'b>
    where
        Self: 'b;

    type FromSliceError = convert::Infallible;

    fn from_slice<'b: 'c, 'c>(
        s: &'b mut [Self::BackingSliceElementType],
    ) -> Result<Self::SelfT<'c>, Self::FromSliceError>
    where
        Self: 'c,
    {
        Ok(Self::SelfT::<'c> { limbs: s })
    }

    fn _shrink_to(&mut self, nbytes: usize) -> Self::SelfT<'_> {
        let nlimbs = Self::n_backing_elements_for_len(nbytes);
        MpMutNativeEndianUIntLimbsSlice {
            limbs: &mut self.limbs[..nlimbs],
        }
    }
}

impl<'a> MpMutUIntSlice for MpMutNativeEndianUIntLimbsSlice<'a> {
    fn coerce_lifetime(&mut self) -> Self::SelfT<'_> {
        MpMutNativeEndianUIntLimbsSlice { limbs: self.limbs }
    }
}

impl<'a> fmt::LowerHex for MpMutNativeEndianUIntLimbsSlice<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_lower_hex(f)
    }
}

impl<'a, 'b> From<&'a mut MpMutNativeEndianUIntLimbsSlice<'b>> for &'a mut [LimbType] {
    fn from(value: &'a mut MpMutNativeEndianUIntLimbsSlice<'b>) -> Self {
        value.limbs
    }
}

impl<'a, 'b> From<&'a MpMutNativeEndianUIntLimbsSlice<'b>> for &'a [LimbType] {
    fn from(value: &'a MpMutNativeEndianUIntLimbsSlice<'b>) -> Self {
        value.limbs
    }
}

/// Find a multiprecision integer's most significant non-zero limb.
///
/// Returns the position past the most significant non-zero limb in units of
/// [`LimbType`], if any, zero otherwise. That is, return the number of limbs
/// needed for representing the value.
///
/// Execution time depends on the multiprecision integer's value. Not to be
/// used with secret values.
///
/// # Arguments
///
/// * `op0` - The multiprecision integer whose most significant non-zero limb
///   to find.
fn find_last_set_limb<T0: MpUIntCommon>(op0: &T0) -> usize {
    let mut nlimbs = op0.nlimbs();
    if nlimbs == 0 {
        return 0;
    }

    if op0.load_l(nlimbs - 1) == 0 {
        nlimbs -= 1;
        while nlimbs > 0 {
            if op0.load_l_full(nlimbs - 1) != 0 {
                break;
            }
            nlimbs -= 1;
        }
    }

    nlimbs
}

#[cfg(test)]
fn test_find_last_set_limb_with_unaligned_lengths<
    T0: MpMutUIntSlice<BackingSliceElementType = u8>,
>() {
    let mut op0 = [0u8; 2 * LIMB_BYTES + 2];
    let mut op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    op0.store_l(0, 1);
    assert_eq!(find_last_set_limb(&op0), 1);

    op0.store_l(1, 1);
    assert_eq!(find_last_set_limb(&op0), 2);

    op0.store_l(2, 1);
    assert_eq!(find_last_set_limb(&op0), 3);
}

#[cfg(test)]
fn test_find_last_set_limb_with_aligned_lengths<T0: MpMutUIntSlice>() {
    let mut op0 = tst_mk_mp_backing_vec!(T0, 0);
    let op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    assert_eq!(find_last_set_limb(&op0), 0);

    let mut op0 = tst_mk_mp_backing_vec!(T0, 2 * LIMB_BYTES);
    let mut op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    assert_eq!(find_last_set_limb(&op0), 0);

    op0.store_l(0, 1);
    assert_eq!(find_last_set_limb(&op0), 1);

    op0.store_l(1, 1);
    assert_eq!(find_last_set_limb(&op0), 2);
}

#[test]
fn test_find_last_set_limb_be() {
    test_find_last_set_limb_with_unaligned_lengths::<MpMutBigEndianUIntByteSlice>();
    test_find_last_set_limb_with_aligned_lengths::<MpMutBigEndianUIntByteSlice>();
}

#[test]
fn test_find_last_set_limb_le() {
    test_find_last_set_limb_with_unaligned_lengths::<MpMutLittleEndianUIntByteSlice>();
    test_find_last_set_limb_with_aligned_lengths::<MpMutLittleEndianUIntByteSlice>();
}

#[test]
fn test_find_last_set_limb_ne() {
    test_find_last_set_limb_with_aligned_lengths::<MpMutNativeEndianUIntLimbsSlice>();
}

/// Find a multiprecision integer's most significant non-zero byte.
///
/// Returns the position past the most significant non-zero byte in units of
/// bytes, if any, zero otherwise. That is, return the number of bytes needed
/// for representing the value.
///
/// Execution time depends on the multiprecision integer's value. Not to be
/// used with secret values. See [`ct_find_last_set_byte_mp()`] for the
/// constant-time variant and [`ct_find_last_set_bit_mp()`] for finding the
/// most significant set bit instead.
///
/// # Arguments
///
/// * `op0` - The multiprecision integer whose most significant non-zero byte
///   to find.
pub fn find_last_set_byte_mp<T0: MpUIntCommon>(op0: &T0) -> usize {
    let nlimbs = find_last_set_limb(op0);
    if nlimbs == 0 {
        return 0;
    }
    let nlimbs = nlimbs - 1;
    nlimbs * LIMB_BYTES + ct_find_last_set_byte_l(op0.load_l(nlimbs))
}

#[cfg(test)]
fn test_find_last_set_byte_mp_with_unaligned_lengths<
    T0: MpMutUIntSlice<BackingSliceElementType = u8>,
>() {
    let mut op0 = [0u8; 2 * LIMB_BYTES + 2];
    let mut op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    op0.store_l(0, 1);
    assert_eq!(ct_find_last_set_byte_mp(&op0).1, 1);

    op0.store_l(1, 1);
    assert_eq!(ct_find_last_set_byte_mp(&op0).1, LIMB_BYTES + 1);

    op0.store_l(2, 1);
    assert_eq!(ct_find_last_set_byte_mp(&op0).1, 2 * LIMB_BYTES + 1);
}

#[cfg(test)]
fn test_find_last_set_byte_mp_with_aligned_lengths<T0: MpMutUIntSlice>() {
    let mut op0 = tst_mk_mp_backing_vec!(T0, 0);
    let op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    assert_eq!(ct_find_last_set_byte_mp(&op0).1, 0);

    let mut op0 = tst_mk_mp_backing_vec!(T0, 2 * LIMB_BYTES);
    let mut op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    op0.store_l(0, (1 as LimbType) << (LIMB_BITS - 1));
    assert_eq!(ct_find_last_set_byte_mp(&op0).1, LIMB_BYTES);

    op0.store_l(1, (1 as LimbType) << (LIMB_BITS - 1));
    assert_eq!(ct_find_last_set_byte_mp(&op0).1, 2 * LIMB_BYTES);
}

#[test]
fn test_find_last_set_byte_be() {
    test_find_last_set_byte_mp_with_unaligned_lengths::<MpMutBigEndianUIntByteSlice>();
    test_find_last_set_byte_mp_with_aligned_lengths::<MpMutBigEndianUIntByteSlice>();
}

#[test]
fn test_find_last_set_byte_le() {
    test_find_last_set_byte_mp_with_unaligned_lengths::<MpMutLittleEndianUIntByteSlice>();
    test_find_last_set_byte_mp_with_aligned_lengths::<MpMutLittleEndianUIntByteSlice>();
}

#[test]
fn test_find_last_set_byte_ne() {
    test_find_last_set_byte_mp_with_aligned_lengths::<MpMutNativeEndianUIntLimbsSlice>();
}

/// Find a multiprecision integer's most significant non-zero byte in constant
/// time.
///
/// Returns a pair of a [`LimbChoice`] representing whether the
/// multiprecision integer is non-zero, and the position past its most
/// significant non-zero byte in units of bytes, if any, zero otherwise. That
/// is, the latter is the number of bytes needed for representing the value.
///
/// Execution time depends only on the multiprecision integer's [length in units
/// of bytes](MpUIntCommon::len) and is otherwise constant as far as branching
/// is concerned. See [`find_last_set_byte_mp()`] for the non-constant-time
/// variant and [`ct_find_last_set_bit_mp()`] for finding the most significant
/// set bit instead.
///
/// # Arguments
///
/// * `op0` - The multiprecision integer whose most significant non-zero byte
///   to find.
pub fn ct_find_last_set_byte_mp<T0: MpUIntCommon>(op0: &T0) -> (LimbChoice, usize) {
    let mut head_is_zero = LimbChoice::from(1);
    let mut nleading_zeroes: usize = 0;
    let mut i = op0.nlimbs();
    while i > 0 {
        i -= 1;
        let op0_val = op0.load_l(i);
        nleading_zeroes += head_is_zero.select(
            0,
            LIMB_BYTES as LimbType - ct_find_last_set_byte_l(op0_val) as LimbType,
        ) as usize;
        head_is_zero &= LimbChoice::from(ct_is_zero_l(op0_val));
    }
    (!head_is_zero, op0.nlimbs() * LIMB_BYTES - nleading_zeroes)
}

#[cfg(test)]
fn test_ct_find_last_set_byte_mp_with_unaligned_lengths<
    T0: MpMutUIntSlice<BackingSliceElementType = u8>,
>() {
    let mut op0 = [0u8; 2 * LIMB_BYTES + 2];
    let mut op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    op0.store_l(0, 1);
    assert_eq!(find_last_set_byte_mp(&op0), 1);

    op0.store_l(1, 1);
    assert_eq!(find_last_set_byte_mp(&op0), LIMB_BYTES + 1);

    op0.store_l(2, 1);
    assert_eq!(find_last_set_byte_mp(&op0), 2 * LIMB_BYTES + 1);
}

#[cfg(test)]
fn test_ct_find_last_set_byte_mp_with_aligned_lengths<T0: MpMutUIntSlice>() {
    let mut op0 = tst_mk_mp_backing_vec!(T0, 0);
    let op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    assert_eq!(find_last_set_byte_mp(&op0), 0);

    let mut op0 = tst_mk_mp_backing_vec!(T0, 2 * LIMB_BYTES);
    let mut op0 = T0::from_slice(op0.as_mut_slice()).unwrap();
    op0.store_l(0, (1 as LimbType) << (LIMB_BITS - 1));
    assert_eq!(find_last_set_byte_mp(&op0), LIMB_BYTES);

    op0.store_l(1, (1 as LimbType) << (LIMB_BITS - 1));
    assert_eq!(find_last_set_byte_mp(&op0), 2 * LIMB_BYTES);
}

#[test]
fn test_ct_find_last_set_byte_be() {
    test_ct_find_last_set_byte_mp_with_unaligned_lengths::<MpMutBigEndianUIntByteSlice>();
    test_ct_find_last_set_byte_mp_with_aligned_lengths::<MpMutBigEndianUIntByteSlice>();
}

#[test]
fn test_ct_find_last_set_byte_le() {
    test_ct_find_last_set_byte_mp_with_unaligned_lengths::<MpMutLittleEndianUIntByteSlice>();
    test_ct_find_last_set_byte_mp_with_aligned_lengths::<MpMutLittleEndianUIntByteSlice>();
}

#[test]
fn test_ct_find_last_set_byte_ne() {
    test_ct_find_last_set_byte_mp_with_aligned_lengths::<MpMutNativeEndianUIntLimbsSlice>();
}

/// Find a multiprecision integer's least significant set bit in constant time.
///
/// Returns a pair of a [`LimbChoice`] representing whether the
/// multiprecision integer is non-zero, and the position of its least
/// significant set bit, if any, zero otherwise. That is, the latter is the
/// number of trailing zero bits.
///
/// Execution time depends only on the multiprecision integer's [length in units
/// of bytes](MpUIntCommon::len) and is otherwise constant as far as branching
/// is concerned.
///
/// # Arguments
///
/// * `op0` - The multiprecision integer whose least significant set bit to
///   find.
pub fn ct_find_first_set_bit_mp<T0: MpUIntCommon>(op0: &T0) -> (LimbChoice, usize) {
    let mut tail_is_zero = LimbChoice::from(1);
    let mut ntrailing_zeroes: usize = 0;
    for i in 0..op0.nlimbs() {
        let op0_val = op0.load_l(i);
        ntrailing_zeroes +=
            tail_is_zero.select(0, ct_find_first_set_bit_l(op0_val) as LimbType) as usize;
        tail_is_zero &= LimbChoice::from(ct_is_zero_l(op0_val));
    }
    (
        !tail_is_zero,
        tail_is_zero.select_usize(ntrailing_zeroes, 0),
    )
}

#[cfg(test)]
fn test_ct_find_first_set_bit_mp<T0: MpMutUIntSlice>() {
    let mut limbs = tst_mk_mp_backing_vec!(T0, 3 * LIMB_BYTES);
    let limbs = T0::from_slice(&mut limbs).unwrap();
    let (is_nonzero, first_set_bit_pos) = ct_find_first_set_bit_mp(&limbs);
    assert_eq!(is_nonzero.unwrap(), 0);
    assert_eq!(first_set_bit_pos, 0);

    for i in 0..3 * LIMB_BITS as usize {
        let mut limbs = tst_mk_mp_backing_vec!(T0, 3 * LIMB_BYTES);
        let mut limbs = T0::from_slice(&mut limbs).unwrap();
        let limb_index = i / LIMB_BITS as usize;
        let bit_pos_in_limb = i % LIMB_BITS as usize;

        limbs.store_l(limb_index, 1 << bit_pos_in_limb);
        let (is_nonzero, first_set_bit_pos) = ct_find_first_set_bit_mp(&limbs);
        assert!(is_nonzero.unwrap() != 0);
        assert_eq!(first_set_bit_pos, i);

        limbs.store_l(limb_index, !((1 << bit_pos_in_limb) - 1));
        for j in limb_index + 1..limbs.nlimbs() {
            limbs.store_l(j, !0);
        }
        let (is_nonzero, first_set_bit_pos) = ct_find_first_set_bit_mp(&limbs);
        assert!(is_nonzero.unwrap() != 0);
        assert_eq!(first_set_bit_pos, i);
    }
}

#[test]
fn test_ct_find_first_set_bit_be() {
    test_ct_find_first_set_bit_mp::<MpMutBigEndianUIntByteSlice>()
}

#[test]
fn test_ct_find_first_set_bit_le() {
    test_ct_find_first_set_bit_mp::<MpMutLittleEndianUIntByteSlice>()
}

#[test]
fn test_ct_find_first_set_bit_ne() {
    test_ct_find_first_set_bit_mp::<MpMutNativeEndianUIntLimbsSlice>()
}

/// Find a multiprecision integer's most significant set bit in constant time.
///
/// Returns a pair of a [`LimbChoice`] representing whether the
/// multiprecision integer is non-zero, and the position past its most
/// significant set bit, if any, zero otherwise. That is, the latter is the
/// effective bit width of the value.
///
/// Execution time depends only on the multiprecision integer's [length in units
/// of bytes](MpUIntCommon::len) and is otherwise constant as far as branching
/// is concerned. See [`ct_find_last_set_byte_mp()`] and its non-constant-time
/// variant [`find_last_set_byte_mp()`] for finding the most significant
/// non-zero byte instead.
///
/// # Arguments
///
/// * `op0` - The multiprecision integer whose most significant set bit to
///   find.
pub fn ct_find_last_set_bit_mp<T0: MpUIntCommon>(op0: &T0) -> (LimbChoice, usize) {
    let mut head_is_zero = LimbChoice::from(1);
    let mut nleading_zeroes: usize = 0;
    let mut i = op0.nlimbs();
    while i > 0 {
        i -= 1;
        let op0_val = op0.load_l(i);
        nleading_zeroes += head_is_zero.select(
            0,
            LIMB_BITS as LimbType - ct_find_last_set_bit_l(op0_val) as LimbType,
        ) as usize;
        head_is_zero &= LimbChoice::from(ct_is_zero_l(op0_val));
    }
    (
        !head_is_zero,
        op0.nlimbs() * LIMB_BITS as usize - nleading_zeroes,
    )
}

#[cfg(test)]
fn test_ct_find_last_set_bit_mp<T0: MpMutUIntSlice>() {
    let mut limbs = tst_mk_mp_backing_vec!(T0, 3 * LIMB_BYTES);
    let limbs = T0::from_slice(&mut limbs).unwrap();
    let (is_nonzero, first_set_bit_pos) = ct_find_last_set_bit_mp(&limbs);
    assert_eq!(is_nonzero.unwrap(), 0);
    assert_eq!(first_set_bit_pos, 0);

    for i in 0..3 * LIMB_BITS as usize {
        let mut limbs = tst_mk_mp_backing_vec!(T0, 3 * LIMB_BYTES);
        let mut limbs = T0::from_slice(&mut limbs).unwrap();
        let limb_index = i / LIMB_BITS as usize;
        let bit_pos_in_limb = i % LIMB_BITS as usize;

        limbs.store_l(limb_index, 1 << bit_pos_in_limb);
        let (is_nonzero, last_set_bit_pos) = ct_find_last_set_bit_mp(&limbs);
        assert!(is_nonzero.unwrap() != 0);
        assert_eq!(last_set_bit_pos, i + 1);

        limbs.store_l(limb_index, (1 << bit_pos_in_limb) - 1);
        for j in 0..limb_index {
            limbs.store_l(j, !0);
        }
        let (is_nonzero, last_set_bit_pos) = ct_find_last_set_bit_mp(&limbs);
        assert_eq!(is_nonzero.unwrap() != 0, i != 0);
        assert_eq!(last_set_bit_pos, i);
    }
}

#[test]
fn test_ct_find_last_set_bit_be() {
    test_ct_find_last_set_bit_mp::<MpMutBigEndianUIntByteSlice>()
}

#[test]
fn test_ct_find_last_set_bit_le() {
    test_ct_find_last_set_bit_mp::<MpMutLittleEndianUIntByteSlice>()
}

#[test]
fn test_ct_find_last_set_bit_ne() {
    test_ct_find_last_set_bit_mp::<MpMutNativeEndianUIntLimbsSlice>()
}

/// Clear a multiprecision integer's high bits in constant time.
///
/// Set all bits at positions `>= begin` to zero, with positions counted from
/// least to most significant. That is, the multiprecision integer gets
/// truncated to its `begin` least significant bits. If `begin` is at or beyond
/// the multiprecision integer's bit length, nothing is cleared.
///
/// Execution time depends only on the multiprecision integer's [length in units
/// of bytes](MpUIntCommon::len) and is otherwise constant as far as branching
/// is concerned. In particular, it doesn't depend on `begin`, which may
/// therefore be secret. See [`clear_bits_above_mp()`] for the non-constant-time
/// variant, whose execution time depends on the position, and
/// [`MpMutUInt::clear_bytes_above()`] for a variant operating at byte
/// granularity.
///
/// # Arguments
///
/// * `op0` - The multiprecision integer to clear the high bits of.
/// * `begin` - The position of the least significant bit to clear, counted
///   from least to most significant.
pub fn ct_clear_bits_above_mp<T0: MpMutUInt>(op0: &mut T0, begin: usize) {
    let first_limb_index = begin / LIMB_BITS as usize;
    let first_limb_retain_nbits = begin % LIMB_BITS as usize;
    let first_limb_mask = ct_lsb_mask_l(first_limb_retain_nbits as u32);
    let mut next_mask = !0;
    for i in 0..op0.nlimbs() {
        let is_first_limb = ct_eq_usize_usize(i, first_limb_index);
        let mask = is_first_limb.select(next_mask, first_limb_mask);
        next_mask = is_first_limb.select(next_mask, 0);
        let val = op0.load_l(i);
        op0.store_l(i, val & mask)
    }
}

#[cfg(test)]
fn test_ct_clear_bits_above_mp_common<T0: MpMutUIntSlice>(op0_len: usize) {
    fn fill_with_ones<T0: MpMutUInt>(op0: &mut T0) {
        for i in 0..op0.nlimbs() {
            if i + 1 != op0.nlimbs() {
                op0.store_l_full(i, !0);
            } else {
                op0.store_l(i, op0.partial_high_mask());
            }
        }
    }

    let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
    let mut op0 = T0::from_slice(&mut op0).unwrap();
    fill_with_ones(&mut op0);
    for begin in [
        8 * op0_len,
        8 * op0_len + 1,
        8 * op0.nlimbs() * LIMB_BYTES,
        8 * op0.nlimbs() * LIMB_BYTES + 1,
    ] {
        ct_clear_bits_above_mp(&mut op0, begin);
        for i in 0..op0.nlimbs() {
            if i + 1 != op0.nlimbs() {
                assert_eq!(op0.load_l_full(i), !0);
            } else {
                assert_eq!(op0.load_l(i), op0.partial_high_mask());
            }
        }
    }

    for j in 0..ct_mp_nlimbs(op0_len) {
        let begin = j * LIMB_BITS as usize;

        let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
        let mut op0 = T0::from_slice(&mut op0).unwrap();
        fill_with_ones(&mut op0);
        ct_clear_bits_above_mp(&mut op0, begin);
        for i in 0..j {
            assert_eq!(op0.load_l_full(i), !0);
        }

        for i in j..op0.nlimbs() {
            assert_eq!(op0.load_l(i), 0);
        }
    }

    for j in 1..ct_mp_nlimbs(op0_len) {
        let begin = j * LIMB_BITS as usize - 1;
        let begin = begin.min(8 * op0_len - 1);

        let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
        let mut op0 = T0::from_slice(&mut op0).unwrap();
        fill_with_ones(&mut op0);
        ct_clear_bits_above_mp(&mut op0, begin);
        for i in 0..j - 1 {
            assert_eq!(op0.load_l_full(i), !0);
        }

        let expected = ct_lsb_mask_l((begin % LIMB_BITS as usize) as u32);
        assert_eq!(op0.load_l(j - 1), expected);

        for i in j..op0.nlimbs() {
            assert_eq!(op0.load_l(i), 0);
        }
    }
}

#[cfg(test)]
fn test_ct_clear_bits_above_mp_with_aligned_lengths<T0: MpMutUIntSlice>() {
    test_ct_clear_bits_above_mp_common::<T0>(0);
    test_ct_clear_bits_above_mp_common::<T0>(LIMB_BYTES);
    test_ct_clear_bits_above_mp_common::<T0>(2 * LIMB_BYTES);
    test_ct_clear_bits_above_mp_common::<T0>(3 * LIMB_BYTES);
}

#[cfg(test)]
fn test_ct_clear_bits_above_mp_with_unaligned_lengths<T0: MpMutUIntSlice>() {
    test_ct_clear_bits_above_mp_common::<T0>(LIMB_BYTES - 1);
    test_ct_clear_bits_above_mp_common::<T0>(2 * LIMB_BYTES - 1);
    test_ct_clear_bits_above_mp_common::<T0>(3 * LIMB_BYTES - 1);
}

#[test]
fn test_ct_clear_bits_above_be() {
    test_ct_clear_bits_above_mp_with_aligned_lengths::<MpMutBigEndianUIntByteSlice>();
    test_ct_clear_bits_above_mp_with_unaligned_lengths::<MpMutBigEndianUIntByteSlice>();
}

#[test]
fn test_ct_clear_bits_above_le() {
    test_ct_clear_bits_above_mp_with_aligned_lengths::<MpMutLittleEndianUIntByteSlice>();
    test_ct_clear_bits_above_mp_with_unaligned_lengths::<MpMutLittleEndianUIntByteSlice>();
}

#[test]
fn test_ct_clear_bits_above_ne() {
    test_ct_clear_bits_above_mp_with_aligned_lengths::<MpMutNativeEndianUIntLimbsSlice>();
}

/// Clear a multiprecision integer's high bits.
///
/// Set all bits at positions `>= begin` to zero, with positions counted from
/// least to most significant. That is, the multiprecision integer gets
/// truncated to its `begin` least significant bits. If `begin` is at or beyond
/// the multiprecision integer's bit length, nothing is cleared.
///
/// Execution time depends only on the multiprecision integer's [length in units
/// of bytes](MpUIntCommon::len) and the `begin` argument and is otherwise
/// constant as far as branching is concerned. See [`ct_clear_bits_above_mp()`]
/// for the constant-time variant, whose execution time doesn't depend on
/// `begin`, and [`MpMutUInt::clear_bytes_above()`] for a variant operating at
/// byte granularity.
///
/// # Arguments
///
/// * `op0` - The multiprecision integer to clear the high bits of.
/// * `begin` - The position of the least significant bit to clear, counted
///   from least to most significant.
pub fn clear_bits_above_mp<T0: MpMutUInt>(op0: &mut T0, begin: usize) {
    let first_limb_index = begin / LIMB_BITS as usize;
    if op0.nlimbs() <= first_limb_index {
        return;
    }
    let first_limb_retain_nbits = begin % LIMB_BITS as usize;
    let first_limb_mask = ct_lsb_mask_l(first_limb_retain_nbits as u32);
    op0.store_l(
        first_limb_index,
        op0.load_l(first_limb_index) & first_limb_mask,
    );

    op0.clear_bytes_above(begin.div_ceil(LIMB_BITS as usize) * LIMB_BYTES);
}

#[cfg(test)]
fn test_clear_bits_above_mp_common<T0: MpMutUIntSlice>(op0_len: usize) {
    fn fill_with_ones<T0: MpMutUInt>(op0: &mut T0) {
        for i in 0..op0.nlimbs() {
            if i + 1 != op0.nlimbs() {
                op0.store_l_full(i, !0);
            } else {
                op0.store_l(i, op0.partial_high_mask());
            }
        }
    }

    let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
    let mut op0 = T0::from_slice(&mut op0).unwrap();
    fill_with_ones(&mut op0);
    for begin in [
        8 * op0_len,
        8 * op0_len + 1,
        8 * op0.nlimbs() * LIMB_BYTES,
        8 * op0.nlimbs() * LIMB_BYTES + 1,
    ] {
        clear_bits_above_mp(&mut op0, begin);
        for i in 0..op0.nlimbs() {
            if i + 1 != op0.nlimbs() {
                assert_eq!(op0.load_l_full(i), !0);
            } else {
                assert_eq!(op0.load_l(i), op0.partial_high_mask());
            }
        }
    }

    for j in 0..ct_mp_nlimbs(op0_len) {
        let begin = j * LIMB_BITS as usize;

        let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
        let mut op0 = T0::from_slice(&mut op0).unwrap();
        fill_with_ones(&mut op0);
        clear_bits_above_mp(&mut op0, begin);
        for i in 0..j {
            assert_eq!(op0.load_l_full(i), !0);
        }

        for i in j..op0.nlimbs() {
            assert_eq!(op0.load_l(i), 0);
        }
    }

    for j in 1..ct_mp_nlimbs(op0_len) {
        let begin = j * LIMB_BITS as usize - 1;
        let begin = begin.min(8 * op0_len - 1);

        let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
        let mut op0 = T0::from_slice(&mut op0).unwrap();
        fill_with_ones(&mut op0);
        clear_bits_above_mp(&mut op0, begin);
        for i in 0..j - 1 {
            assert_eq!(op0.load_l_full(i), !0);
        }

        let expected = ct_lsb_mask_l((begin % LIMB_BITS as usize) as u32);
        assert_eq!(op0.load_l(j - 1), expected);

        for i in j..op0.nlimbs() {
            assert_eq!(op0.load_l(i), 0);
        }
    }
}

#[cfg(test)]
fn test_clear_bits_above_mp_with_aligned_lengths<T0: MpMutUIntSlice>() {
    test_clear_bits_above_mp_common::<T0>(0);
    test_clear_bits_above_mp_common::<T0>(LIMB_BYTES);
    test_clear_bits_above_mp_common::<T0>(2 * LIMB_BYTES);
    test_clear_bits_above_mp_common::<T0>(3 * LIMB_BYTES);
}

#[cfg(test)]
fn test_clear_bits_above_mp_with_unaligned_lengths<T0: MpMutUIntSlice>() {
    test_clear_bits_above_mp_common::<T0>(LIMB_BYTES - 1);
    test_clear_bits_above_mp_common::<T0>(2 * LIMB_BYTES - 1);
    test_clear_bits_above_mp_common::<T0>(3 * LIMB_BYTES - 1);
}

#[test]
fn test_clear_bits_above_be() {
    test_clear_bits_above_mp_with_aligned_lengths::<MpMutBigEndianUIntByteSlice>();
    test_clear_bits_above_mp_with_unaligned_lengths::<MpMutBigEndianUIntByteSlice>();
}

#[test]
fn test_clear_bits_above_le() {
    test_clear_bits_above_mp_with_aligned_lengths::<MpMutLittleEndianUIntByteSlice>();
    test_clear_bits_above_mp_with_unaligned_lengths::<MpMutLittleEndianUIntByteSlice>();
}

#[test]
fn test_clear_bits_above_ne() {
    test_clear_bits_above_mp_with_aligned_lengths::<MpMutNativeEndianUIntLimbsSlice>();
}

/// Clear a multiprecision integer's low bits in constant time.
///
/// Set all bits at positions `< end` to zero, with positions counted from
/// least to most significant. If `end` is at or beyond the multiprecision
/// integer's bit length, all of it is cleared.
///
/// Execution time depends only on the multiprecision integer's [length in units
/// of bytes](MpUIntCommon::len) and is otherwise constant as far as branching
/// is concerned. In particular, it doesn't depend on `end`, which may therefore
/// be secret. See [`clear_bits_below_mp()`] for the non-constant-time variant,
/// whose execution time depends on the position, and
/// [`MpMutUInt::clear_bytes_below()`] for a variant operating at byte
/// granularity.
///
/// # Arguments
///
/// * `op0` - The multiprecision integer to clear the low bits of.
/// * `end` - The position past the most significant bit to clear, counted
///   from least to most significant.
pub fn ct_clear_bits_below_mp<T0: MpMutUInt>(op0: &mut T0, end: usize) {
    let last_limb_index = end / LIMB_BITS as usize;
    let last_limb_clear_nbits = end % LIMB_BITS as usize;
    let last_limb_mask = !ct_lsb_mask_l(last_limb_clear_nbits as u32);
    let mut next_mask = 0;
    for i in 0..op0.nlimbs() {
        let is_last_limb = ct_eq_usize_usize(i, last_limb_index);
        let mask = is_last_limb.select(next_mask, last_limb_mask);
        next_mask = is_last_limb.select(next_mask, !0);
        let val = op0.load_l(i);
        op0.store_l(i, val & mask)
    }
}

#[cfg(test)]
fn test_ct_clear_bits_mp_below_common<T0: MpMutUIntSlice>(op0_len: usize) {
    fn fill_with_ones<T0: MpMutUInt>(op0: &mut T0) {
        for i in 0..op0.nlimbs() {
            if i + 1 != op0.nlimbs() {
                op0.store_l_full(i, !0);
            } else {
                op0.store_l(i, op0.partial_high_mask());
            }
        }
    }

    let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
    let mut op0 = T0::from_slice(&mut op0).unwrap();
    fill_with_ones(&mut op0);
    ct_clear_bits_below_mp(&mut op0, 0);
    for i in 0..op0.nlimbs() {
        if i + 1 != op0.nlimbs() {
            assert_eq!(op0.load_l_full(i), !0);
        } else {
            assert_eq!(op0.load_l(i), op0.partial_high_mask());
        }
    }

    for j in 0..ct_mp_nlimbs(op0_len) {
        let begin = j * LIMB_BITS as usize;

        let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
        let mut op0 = T0::from_slice(&mut op0).unwrap();
        fill_with_ones(&mut op0);
        ct_clear_bits_below_mp(&mut op0, begin);
        for i in 0..j {
            assert_eq!(op0.load_l_full(i), 0);
        }

        for i in j..op0.nlimbs() {
            if i + 1 != op0.nlimbs() {
                assert_eq!(op0.load_l(i), !0);
            } else {
                assert_eq!(op0.load_l(i), op0.partial_high_mask());
            }
        }
    }

    for j in 1..ct_mp_nlimbs(op0_len) {
        let begin = j * LIMB_BITS as usize - 1;
        let begin = begin.min(8 * op0_len - 1);

        let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
        let mut op0 = T0::from_slice(&mut op0).unwrap();
        fill_with_ones(&mut op0);
        ct_clear_bits_below_mp(&mut op0, begin);
        for i in 0..j - 1 {
            assert_eq!(op0.load_l_full(i), 0);
        }

        let expected = !ct_lsb_mask_l((begin % LIMB_BITS as usize) as u32);
        assert_eq!(op0.load_l(j - 1), expected);

        for i in j..op0.nlimbs() {
            if i + 1 != op0.nlimbs() {
                assert_eq!(op0.load_l(i), !0);
            } else {
                assert_eq!(op0.load_l(i), op0.partial_high_mask());
            }
        }
    }
}

#[cfg(test)]
fn test_ct_clear_bits_below_mp_with_aligned_lengths<T0: MpMutUIntSlice>() {
    test_ct_clear_bits_mp_below_common::<T0>(0);
    test_ct_clear_bits_mp_below_common::<T0>(LIMB_BYTES);
    test_ct_clear_bits_mp_below_common::<T0>(2 * LIMB_BYTES);
    test_ct_clear_bits_mp_below_common::<T0>(3 * LIMB_BYTES);
}

#[cfg(test)]
fn test_ct_clear_bits_below_mp_with_unaligned_lengths<T0: MpMutUIntSlice>() {
    test_ct_clear_bits_mp_below_common::<T0>(LIMB_BYTES - 1);
    test_ct_clear_bits_mp_below_common::<T0>(2 * LIMB_BYTES - 1);
    test_ct_clear_bits_mp_below_common::<T0>(3 * LIMB_BYTES - 1);
}

#[test]
fn test_ct_clear_bits_below_be() {
    test_ct_clear_bits_below_mp_with_aligned_lengths::<MpMutBigEndianUIntByteSlice>();
    test_ct_clear_bits_below_mp_with_unaligned_lengths::<MpMutBigEndianUIntByteSlice>();
}

#[test]
fn test_ct_clear_bits_below_le() {
    test_ct_clear_bits_below_mp_with_aligned_lengths::<MpMutLittleEndianUIntByteSlice>();
    test_ct_clear_bits_below_mp_with_unaligned_lengths::<MpMutLittleEndianUIntByteSlice>();
}

#[test]
fn test_ct_clear_bits_below_ne() {
    test_ct_clear_bits_below_mp_with_aligned_lengths::<MpMutNativeEndianUIntLimbsSlice>();
}

/// Clear a multiprecision integer's low bits.
///
/// Set all bits at positions `< end` to zero, with positions counted from
/// least to most significant. If `end` is at or beyond the multiprecision
/// integer's bit length, all of it is cleared.
///
/// Execution time depends only on the multiprecision integer's [length in units
/// of bytes](MpUIntCommon::len) and the `end` argument and is otherwise
/// constant as far as branching is concerned. See [`ct_clear_bits_below_mp()`]
/// for the constant-time variant, whose execution time doesn't depend on `end`,
/// and [`MpMutUInt::clear_bytes_below()`] for a variant operating at byte
/// granularity.
///
/// # Arguments
///
/// * `op0` - The multiprecision integer to clear the low bits of.
/// * `end` - The position past the most significant bit to clear, counted
///   from least to most significant.
pub fn clear_bits_below_mp<T0: MpMutUInt>(op0: &mut T0, end: usize) {
    let last_limb_index = end / LIMB_BITS as usize;
    op0.clear_bytes_below(last_limb_index * LIMB_BYTES);
    if last_limb_index >= op0.nlimbs() {
        return;
    }
    let last_limb_clear_nbits = end % LIMB_BITS as usize;
    let last_limb_mask = !ct_lsb_mask_l(last_limb_clear_nbits as u32);
    op0.store_l(
        last_limb_index,
        op0.load_l(last_limb_index) & last_limb_mask,
    );
}

#[cfg(test)]
fn test_clear_bits_below_mp_common<T0: MpMutUIntSlice>(op0_len: usize) {
    fn fill_with_ones<T0: MpMutUInt>(op0: &mut T0) {
        for i in 0..op0.nlimbs() {
            if i + 1 != op0.nlimbs() {
                op0.store_l_full(i, !0);
            } else {
                op0.store_l(i, op0.partial_high_mask());
            }
        }
    }

    let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
    let mut op0 = T0::from_slice(&mut op0).unwrap();
    fill_with_ones(&mut op0);
    clear_bits_below_mp(&mut op0, 0);
    for i in 0..op0.nlimbs() {
        if i + 1 != op0.nlimbs() {
            assert_eq!(op0.load_l_full(i), !0);
        } else {
            assert_eq!(op0.load_l(i), op0.partial_high_mask());
        }
    }

    for j in 0..ct_mp_nlimbs(op0_len) {
        let begin = j * LIMB_BITS as usize;

        let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
        let mut op0 = T0::from_slice(&mut op0).unwrap();
        fill_with_ones(&mut op0);
        clear_bits_below_mp(&mut op0, begin);
        for i in 0..j {
            assert_eq!(op0.load_l_full(i), 0);
        }

        for i in j..op0.nlimbs() {
            if i + 1 != op0.nlimbs() {
                assert_eq!(op0.load_l(i), !0);
            } else {
                assert_eq!(op0.load_l(i), op0.partial_high_mask());
            }
        }
    }

    for j in 1..ct_mp_nlimbs(op0_len) {
        let begin = j * LIMB_BITS as usize - 1;
        let begin = begin.min(8 * op0_len - 1);

        let mut op0 = tst_mk_mp_backing_vec!(T0, op0_len);
        let mut op0 = T0::from_slice(&mut op0).unwrap();
        fill_with_ones(&mut op0);
        clear_bits_below_mp(&mut op0, begin);
        for i in 0..j - 1 {
            assert_eq!(op0.load_l_full(i), 0);
        }

        let expected = !ct_lsb_mask_l((begin % LIMB_BITS as usize) as u32);
        assert_eq!(op0.load_l(j - 1), expected);

        for i in j..op0.nlimbs() {
            if i + 1 != op0.nlimbs() {
                assert_eq!(op0.load_l(i), !0);
            } else {
                assert_eq!(op0.load_l(i), op0.partial_high_mask());
            }
        }
    }
}

#[cfg(test)]
fn test_clear_bits_below_mp_with_aligned_lengths<T0: MpMutUIntSlice>() {
    test_clear_bits_below_mp_common::<T0>(0);
    test_clear_bits_below_mp_common::<T0>(LIMB_BYTES);
    test_clear_bits_below_mp_common::<T0>(2 * LIMB_BYTES);
    test_clear_bits_below_mp_common::<T0>(3 * LIMB_BYTES);
}

#[cfg(test)]
fn test_clear_bits_below_mp_with_unaligned_lengths<T0: MpMutUIntSlice>() {
    test_clear_bits_below_mp_common::<T0>(LIMB_BYTES - 1);
    test_clear_bits_below_mp_common::<T0>(2 * LIMB_BYTES - 1);
    test_clear_bits_below_mp_common::<T0>(3 * LIMB_BYTES - 1);
}

#[test]
fn test_clear_bits_below_be() {
    test_clear_bits_below_mp_with_aligned_lengths::<MpMutBigEndianUIntByteSlice>();
    test_clear_bits_below_mp_with_unaligned_lengths::<MpMutBigEndianUIntByteSlice>();
}

#[test]
fn test_clear_bits_below_le() {
    test_clear_bits_below_mp_with_aligned_lengths::<MpMutLittleEndianUIntByteSlice>();
    test_clear_bits_below_mp_with_unaligned_lengths::<MpMutLittleEndianUIntByteSlice>();
}

#[test]
fn test_clear_bits_below_ne() {
    test_clear_bits_below_mp_with_aligned_lengths::<MpMutNativeEndianUIntLimbsSlice>();
}

/// Conditionally swap two multiprecision integers' values in constant time.
///
/// If `cond` is true, exchange the values of `op0` and `op1`. Otherwise leave
/// both unmodified. The two multiprecision integers may be of different
/// representations.
///
/// Execution time depends only on the multiprecision integers' [lengths in
/// units of bytes](MpUIntCommon::len) and is otherwise constant as far as
/// branching is concerned. In particular, it doesn't depend on `cond`.
///
/// # Arguments
///
/// * `op0` - The first multiprecision integer.
/// * `op1` - The second multiprecision integer. Its [length in units of
///   bytes](MpUIntCommon::len) must [fit
///   into](MpUIntCommon::len_is_compatible_with) `op0`'s and vice versa.
/// * `cond` - Whether or not to swap the values.
pub fn ct_swap_cond_mp<T0: MpMutUInt, T1: MpMutUInt>(op0: &mut T0, op1: &mut T1, cond: LimbChoice) {
    debug_assert!(op0.len_is_compatible_with(op1.len()));
    debug_assert!(op1.len_is_compatible_with(op0.len()));
    let nlimbs = op0.nlimbs();
    debug_assert_eq!(nlimbs, op1.nlimbs());
    let cond_mask = cond.select(0, !0);
    for i in 0..nlimbs {
        let mut op0_val = op0.load_l(i);
        let mut op1_val = op1.load_l(i);
        op0_val ^= op1_val;
        op1_val ^= op0_val & cond_mask;
        op0_val ^= op1_val;
        op0.store_l(i, op0_val);
        op1.store_l(i, op1_val);
    }
}

#[cfg(test)]
fn test_ct_swap_cond_mp<T0: MpMutUIntSlice, T1: MpMutUIntSlice>() {
    use super::cmp::ct_eq_mp_mp;

    let len = 2 * LIMB_BYTES - 1;
    let mut op0_orig = tst_mk_mp_backing_vec!(T0, len);
    op0_orig.fill(0xccu8.into());
    let mut op0 = op0_orig.clone();
    let op0_orig = T0::from_slice(&mut op0_orig).unwrap();
    let mut op0 = T0::from_slice(&mut op0).unwrap();

    let mut op1_orig = tst_mk_mp_backing_vec!(T1, len);
    op1_orig.fill(0xbbu8.into());
    let mut op1 = op1_orig.clone();
    let op1_orig = T1::from_slice(&mut op1_orig).unwrap();
    let mut op1 = T1::from_slice(&mut op1).unwrap();

    ct_swap_cond_mp(&mut op0, &mut op1, LimbChoice::from(0));
    assert_ne!(ct_eq_mp_mp(&op0, &op0_orig).unwrap(), 0);
    assert_ne!(ct_eq_mp_mp(&op1, &op1_orig).unwrap(), 0);

    ct_swap_cond_mp(&mut op0, &mut op1, LimbChoice::from(1));
    assert_ne!(ct_eq_mp_mp(&op0, &op1_orig).unwrap(), 0);
    assert_ne!(ct_eq_mp_mp(&op1, &op0_orig).unwrap(), 0);
}

#[test]
fn test_ct_swap_cond_be_be() {
    test_ct_swap_cond_mp::<MpMutBigEndianUIntByteSlice, MpMutBigEndianUIntByteSlice>();
}

#[test]
fn test_ct_swap_cond_le_le() {
    test_ct_swap_cond_mp::<MpMutLittleEndianUIntByteSlice, MpMutLittleEndianUIntByteSlice>();
}

#[test]
fn test_ct_swap_cond_ne_ne() {
    test_ct_swap_cond_mp::<MpMutNativeEndianUIntLimbsSlice, MpMutNativeEndianUIntLimbsSlice>();
}

/// Internal data structure describing a single one of a
/// [`CompositeLimbsBuffer`]'s constituting segments.
struct CompositeLimbsBufferSegment<'a, ST: MpUIntCommon> {
    /// The total number of limbs whose least significant bytes are held in this
    /// or less significant segments each (note that a limb may span
    /// multiple segments).
    end: usize,
    /// The actual data, interpreted as a segment within the composed
    /// multiprecision integer.
    ///
    /// The `segment` slice, if non-empty, will be made to align with the least
    /// significant limb whose least significant byte is found in this
    /// segment. That is, for e.g. [`MpBigEndianUIntByteSlice`] the slice's last
    /// byte (in memory order) corresponds to the least significant byte of the
    /// least significant limb.
    segment: ST,
    /// Continuation bytes of this or preceding, less significant segment's
    /// most significant limb.
    ///
    /// A segment's most significant limb might be covered only partially by it
    /// and extend across one or more subsequent, more significant segments.
    /// In this case its remaining, more significant continuation bytes are
    /// collected from this and the subsequent, more significant
    /// segments' `high_next_partial` slices.
    high_next_partial: ST,

    _phantom: marker::PhantomData<&'a [u8]>,
}

/// Access multiprecision integers composed of multiple virtually concatenated
/// buffer slices in units of [`LimbType`].
///
/// A [`CompositeLimbsBuffer`] provides a composed multiprecision integer view
/// on `N_SEGMENTS` virtually concatenated buffer slices, each wrapped in the
/// same representation-specific multiprecision integer slice type `ST`, like
/// e.g. [`MpBigEndianUIntByteSlice`]. Primitives are provided alongside for
/// accessing the composed integer in units of [`LimbType`].
///
/// Certain applications need to truncate the result of some multiprecision
/// integer arithmetic operation result and dismiss the rest. An example would
/// be key generation modulo some large integer by the method of oversampling. A
/// `CompositeLimbsBuffer` helps such applications to reduce the memory
/// footprint of the truncation operation: instead of allocating a smaller
/// destination buffer and copying the to be retained parts over from the
/// result, the arithmetic primitive can, if supported, operate directly on a
/// multiprecision integer composed of several independent smaller slices by
/// virtual concatenation. Assuming the individual segments' slice
/// lengths align properly with the needed and unneeded parts of the result, the
/// latter ones can get truncated away trivially when done by simply dismissing
/// the corresponding underlying buffers.
///
/// Read access is provided for any multiprecision integer slice type `ST`,
/// write access in addition if `ST` implements [`MpMutUIntSlice`].
pub(super) struct CompositeLimbsBuffer<'a, ST: MpUIntCommon, const N_SEGMENTS: usize> {
    /// The composed view's individual segments, ordered from least to most
    /// significant.
    segments: [CompositeLimbsBufferSegment<'a, ST>; N_SEGMENTS],
}

impl<'a, ST: MpUIntSliceCommon, const N_SEGMENTS: usize> CompositeLimbsBuffer<'a, ST, N_SEGMENTS> {
    /// Construct a `CompositeLimbsBuffer` view from the individual buffer
    /// segments.
    ///
    /// # Arguments
    ///
    /// * `segments` - An array of `N_SEGMENTS` multiprecision integer slices to
    ///   compose the multiprecision integer view from by virtual concatenation.
    ///   Ordered from least to most significant with respect to their position
    ///   within the resulting view.
    pub fn new(segments: [ST; N_SEGMENTS]) -> Self {
        let mut segments = <[ST; N_SEGMENTS] as IntoIterator>::into_iter(segments);
        let mut segments: [Option<ST>; N_SEGMENTS] = core::array::from_fn(|_| segments.next());
        let mut n_bytes_total = 0;
        let mut create_segment = |i: usize| {
            let segment = segments[i].take().unwrap();
            let segment_len = segment.len();
            n_bytes_total += segment_len;

            let n_high_partial = n_bytes_total % LIMB_BYTES;
            let (high_next_partial, segment) = if i + 1 != segments.len() && n_high_partial != 0 {
                let next_segment = segments[i + 1].take().unwrap();
                let next_segment_len = next_segment.len();
                let n_from_next = (LIMB_BYTES - n_high_partial).min(next_segment_len);
                let (next_segment, high_next_partial) = next_segment.take(n_from_next);
                segments[i + 1] = Some(next_segment);
                (high_next_partial, segment)
            } else {
                let (high_next_partial, segment) = segment.take(segment_len);
                (high_next_partial, segment)
            };

            let high_next_partial_len = high_next_partial.len();
            n_bytes_total += high_next_partial_len;
            let end = ct_mp_nlimbs(n_bytes_total);
            CompositeLimbsBufferSegment {
                end,
                segment,
                high_next_partial,
                _phantom: marker::PhantomData,
            }
        };

        let segments: [CompositeLimbsBufferSegment<'a, ST>; N_SEGMENTS] =
            core::array::from_fn(&mut create_segment);
        Self { segments }
    }

    /// Lookup the least significant buffer segment holding the specified limb's
    /// least significant byte.
    ///
    /// Returns a pair of segment index and, as a by-product of the search, the
    /// corresponding segment's offset within the composed multiprecision
    /// integer in units of limbs.
    ///
    /// Execution time depends on the composed multiprecision integer's
    /// underlying segment layout as well as on the limb index
    /// argument `i` as far as branching is concerned.
    ///
    /// # Arguments
    ///
    /// * `i` - The index of the limb to look up, counted from least to most
    ///   significant. Must be less than the composed multiprecision
    ///   integer's total number of limbs.
    fn limb_index_to_segment(&self, i: usize) -> (usize, usize) {
        let mut segment_offset = 0;
        for (segment_index, segment) in self.segments.iter().enumerate() {
            let segment_end = segment.end;
            if i < segment_end {
                return (segment_index, segment_offset);
            } else {
                segment_offset = segment_end;
            }
        }
        unreachable!();
    }

    /// Load a limb from the composed multiprecision integer.
    ///
    /// Execution time depends on the composed multiprecision integer's
    /// underlying segment layout as well as on the limb index
    /// argument `i`, and is otherwise constant as far as branching
    /// is concerned.
    ///
    /// # Arguments
    ///
    /// * `i` - The index of the limb to load, counted from least to most
    ///   significant. Must be less than the composed multiprecision
    ///   integer's total number of limbs.
    pub fn load(&self, i: usize) -> LimbType {
        let (segment_index, segment_offset) = self.limb_index_to_segment(i);
        let segment = &self.segments[segment_index];
        let segment_slice = &segment.segment;
        if i != segment.end - 1 || !ST::SUPPORTS_UNALIGNED_BUFFER_LENGTHS {
            segment_slice.load_l_full(i - segment_offset)
        } else if segment_index + 1 == N_SEGMENTS || segment_slice.len().is_multiple_of(LIMB_BYTES)
        {
            // The last (highest) segment's most significant bytes don't necessarily occupy
            // a full limb.
            segment_slice.load_l(i - segment_offset)
        } else {
            let mut npartial = segment_slice.len() % LIMB_BYTES;
            let mut value = segment_slice.load_l(i - segment_offset);
            let mut segment_index = segment_index;
            while npartial != LIMB_BYTES && segment_index < self.segments.len() {
                let partial = &self.segments[segment_index].high_next_partial;
                if !partial.is_empty() {
                    value |= partial.load_l(0) << (8 * npartial);
                    npartial += partial.len();
                }
                segment_index += 1;
            }
            value
        }
    }
}

impl<'a, ST: MpMutUIntSlice, const N_SEGMENTS: usize> CompositeLimbsBuffer<'a, ST, N_SEGMENTS> {
    /// Update a limb in the composed multiprecision integer.
    ///
    /// Execution time depends on the composed multiprecision integer's
    /// underlying segment layout as well as on the limb index
    /// argument `i`, and is otherwise constant as far as branching
    /// is concerned.
    ///
    /// # Arguments
    ///
    /// * `i` - The index of the limb to update, counted from least to most
    ///   significant. Must be less than the composed multiprecision
    ///   integer's total number of limbs.
    /// * `value` - The value to store in the i'th limb. If the most
    ///   significant limb is to be stored, all bytes in `value` corresponding
    ///   to its excess bytes not covered by the composed multiprecision
    ///   integer must be zero.
    pub fn store(&mut self, i: usize, value: LimbType) {
        let (segment_index, segment_offset) = self.limb_index_to_segment(i);
        let segment = &mut self.segments[segment_index];
        let segment_slice = &mut segment.segment;
        if i != segment.end - 1 || !ST::SUPPORTS_UNALIGNED_BUFFER_LENGTHS {
            segment_slice.store_l_full(i - segment_offset, value);
        } else if segment_index + 1 == N_SEGMENTS || segment_slice.len().is_multiple_of(LIMB_BYTES)
        {
            // The last (highest) part's most significant bytes don't necessarily occupy a
            // full limb.
            segment_slice.store_l(i - segment_offset, value)
        } else {
            let mut value = value;
            let mut npartial = segment_slice.len() % LIMB_BYTES;
            let value_mask = ct_lsb_mask_l(8 * npartial as u32);
            segment_slice.store_l(i - segment_offset, value & value_mask);
            value >>= 8 * npartial;
            let mut segment_index = segment_index;
            while npartial != LIMB_BYTES && segment_index < self.segments.len() {
                let partial = &mut self.segments[segment_index].high_next_partial;
                if !partial.is_empty() {
                    let value_mask = ct_lsb_mask_l(8 * partial.len() as u32);
                    partial.store_l(0, value & value_mask);
                    value >>= 8 * partial.len();
                    npartial += partial.len();
                }
                segment_index += 1;
            }
            debug_assert!(value == 0);
        }
    }
}

#[test]
fn test_composite_limbs_buffer_load_be() {
    let mut buf0: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    let buf1: [u8; 0] = [0; 0];
    let mut buf2: [u8; 2 * LIMB_BYTES + 2] = [0; 2 * LIMB_BYTES + 2];

    // 0x02 00 .. 00 01 00 .. 00
    buf0[LIMB_BYTES - 1 + LIMB_BYTES / 2] = 0x1;
    buf0[LIMB_BYTES - 1] = 0x2;

    // 0x05 04 00 .. 00 03 .. 00
    buf0[LIMB_BYTES / 2 - 1] = 0x3;
    buf0[0] = 0x4;
    buf2[1 + 2 * LIMB_BYTES] = 0x5;

    // 0x07 00 .. 00 06 00 .. 00
    buf2[1 + LIMB_BYTES + LIMB_BYTES / 2] = 0x6;
    buf2[1 + LIMB_BYTES] = 0x7;

    // 0x09 00 .. 00 08 00 .. 00
    buf2[1 + LIMB_BYTES / 2] = 0x8;
    buf2[1] = 0x9;

    // 0x00 .. 00 0x0a
    buf2[0] = 0xa;

    let buf0 = MpBigEndianUIntByteSlice::from_bytes(buf0.as_slice());
    let buf1 = MpBigEndianUIntByteSlice::from_bytes(buf1.as_slice());
    let buf2 = MpBigEndianUIntByteSlice::from_bytes(buf2.as_slice());
    let limbs = CompositeLimbsBuffer::new([buf0, buf1, buf2]);

    let l0 = limbs.load(0);
    assert_eq!(l0, 0x2 << (LIMB_BITS - 8) | 0x1 << (LIMB_BITS / 2 - 8));
    let l1 = limbs.load(1);
    assert_eq!(l1, 0x0504 << (LIMB_BITS - 16) | 0x3 << (LIMB_BITS / 2 - 8));
    let l2 = limbs.load(2);
    assert_eq!(l2, 0x7 << (LIMB_BITS - 8) | 0x6 << (LIMB_BITS / 2 - 8));
    let l3 = limbs.load(3);
    assert_eq!(l3, 0x9 << (LIMB_BITS - 8) | 0x8 << (LIMB_BITS / 2 - 8));
    let l4 = limbs.load(4);
    assert_eq!(l4, 0xa);
}

#[test]
fn test_composite_limbs_buffer_load_le() {
    let mut buf0: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    let buf1: [u8; 0] = [0; 0];
    let mut buf2: [u8; 2 * LIMB_BYTES + 2] = [0; 2 * LIMB_BYTES + 2];

    // 0x00 .. 00 01 00 .. 00 02
    buf0[LIMB_BYTES / 2 - 1] = 0x1;
    buf0[LIMB_BYTES - 1] = 0x2;

    // 0x00 .. 03 00 .. 00 04 05
    buf0[LIMB_BYTES + LIMB_BYTES / 2 - 1] = 0x3;
    buf0[2 * LIMB_BYTES - 2] = 0x4;
    buf2[0] = 0x5;

    // 0x00 .. 00 06 00 .. 00 07
    buf2[1 + LIMB_BYTES / 2 - 1] = 0x6;
    buf2[1 + LIMB_BYTES - 1] = 0x7;

    // 0x00 .. 00 08 00 .. 00 09
    buf2[1 + LIMB_BYTES + LIMB_BYTES / 2 - 1] = 0x8;
    buf2[1 + 2 * LIMB_BYTES - 1] = 0x9;

    // 0x00 .. 00 0x0a
    buf2[1 + 2 * LIMB_BYTES] = 0xa;

    let buf0 = MpLittleEndianUIntByteSlice::from_bytes(buf0.as_slice());
    let buf1 = MpLittleEndianUIntByteSlice::from_bytes(buf1.as_slice());
    let buf2 = MpLittleEndianUIntByteSlice::from_bytes(buf2.as_slice());
    let limbs = CompositeLimbsBuffer::new([buf0, buf1, buf2]);

    let l0 = limbs.load(0);
    assert_eq!(l0, 0x2 << (LIMB_BITS - 8) | 0x1 << (LIMB_BITS / 2 - 8));
    let l1 = limbs.load(1);
    assert_eq!(l1, 0x0504 << (LIMB_BITS - 16) | 0x3 << (LIMB_BITS / 2 - 8));
    let l2 = limbs.load(2);
    assert_eq!(l2, 0x7 << (LIMB_BITS - 8) | 0x6 << (LIMB_BITS / 2 - 8));
    let l3 = limbs.load(3);
    assert_eq!(l3, 0x9 << (LIMB_BITS - 8) | 0x8 << (LIMB_BITS / 2 - 8));
    let l4 = limbs.load(4);
    assert_eq!(l4, 0xa);
}

#[test]
fn test_composite_limbs_buffer_load_ne() {
    let mut buf0 = [0 as LimbType; 2];
    let buf1 = [0 as LimbType; 0];
    let mut buf2 = [0 as LimbType; 2 * LIMB_BYTES];

    buf0[0] = 0x1;
    buf0[1] = 0x2;
    buf2[0] = 0x3;
    buf2[1] = 0x4;

    let buf0 = MpNativeEndianUIntLimbsSlice::from_limbs(buf0.as_slice());
    let buf1 = MpNativeEndianUIntLimbsSlice::from_limbs(buf1.as_slice());
    let buf2 = MpNativeEndianUIntLimbsSlice::from_limbs(buf2.as_slice());
    let limbs = CompositeLimbsBuffer::new([buf0, buf1, buf2]);

    let l0 = limbs.load(0);
    assert_eq!(l0, 0x1);
    let l1 = limbs.load(1);
    assert_eq!(l1, 0x2);
    let l2 = limbs.load(2);
    assert_eq!(l2, 0x3);
    let l3 = limbs.load(3);
    assert_eq!(l3, 0x4);
}

#[cfg(test)]
fn test_composite_limbs_buffer_store_with_unaligned_lengths<
    ST: MpMutUIntSlice<BackingSliceElementType = u8>,
>() {
    debug_assert!(ST::SUPPORTS_UNALIGNED_BUFFER_LENGTHS);

    let mut buf0: [u8; 2 * LIMB_BYTES - 1] = [0; 2 * LIMB_BYTES - 1];
    let mut buf1: [u8; 0] = [0; 0];
    let mut buf2: [u8; 2 * LIMB_BYTES + 2] = [0; 2 * LIMB_BYTES + 2];
    let buf0 = ST::from_slice(&mut buf0).unwrap();
    let buf1 = ST::from_slice(&mut buf1).unwrap();
    let buf2 = ST::from_slice(&mut buf2).unwrap();
    let mut limbs = CompositeLimbsBuffer::new([buf0, buf1, buf2]);

    let l0 = 0x2 << (LIMB_BITS - 8) | 0x1 << (LIMB_BITS / 2 - 8);
    let l1 = 0x0504 << (LIMB_BITS - 16) | 0x3 << (LIMB_BITS / 2 - 8);
    let l2 = 0x7 << (LIMB_BITS - 8) | 0x6 << (LIMB_BITS / 2 - 8);
    let l3 = 0x9 << (LIMB_BITS - 8) | 0x8 << (LIMB_BITS / 2 - 8);
    let l4 = 0xa;

    limbs.store(0, l0);
    limbs.store(1, l1);
    limbs.store(2, l2);
    limbs.store(3, l3);
    limbs.store(4, l4);
    assert_eq!(l0, limbs.load(0));
    assert_eq!(l1, limbs.load(1));
    assert_eq!(l2, limbs.load(2));
    assert_eq!(l3, limbs.load(3));
    assert_eq!(l4, limbs.load(4));
}

#[cfg(test)]
fn test_composite_limbs_buffer_store_with_aligned_lengths<ST: MpMutUIntSlice>() {
    let mut buf0 = tst_mk_mp_backing_vec!(ST, 2 * LIMB_BYTES);
    let mut buf1 = tst_mk_mp_backing_vec!(ST, 0);
    let mut buf2 = tst_mk_mp_backing_vec!(ST, 2 * LIMB_BYTES);
    let buf0 = ST::from_slice(&mut buf0).unwrap();
    let buf1 = ST::from_slice(&mut buf1).unwrap();
    let buf2 = ST::from_slice(&mut buf2).unwrap();
    let mut limbs = CompositeLimbsBuffer::new([buf0, buf1, buf2]);

    let l0 = 0x2 << (LIMB_BITS - 8) | 0x1 << (LIMB_BITS / 2 - 8);
    let l1 = 0x0504 << (LIMB_BITS - 16) | 0x3 << (LIMB_BITS / 2 - 8);
    let l2 = 0x7 << (LIMB_BITS - 8) | 0x6 << (LIMB_BITS / 2 - 8);
    let l3 = 0x9 << (LIMB_BITS - 8) | 0x8 << (LIMB_BITS / 2 - 8);

    limbs.store(0, l0);
    limbs.store(1, l1);
    limbs.store(2, l2);
    limbs.store(3, l3);
    assert_eq!(l0, limbs.load(0));
    assert_eq!(l1, limbs.load(1));
    assert_eq!(l2, limbs.load(2));
    assert_eq!(l3, limbs.load(3));
}

#[test]
fn test_composite_limbs_buffer_store_be() {
    test_composite_limbs_buffer_store_with_unaligned_lengths::<MpMutBigEndianUIntByteSlice>();
    test_composite_limbs_buffer_store_with_aligned_lengths::<MpMutBigEndianUIntByteSlice>();
}

#[test]
fn test_composite_limbs_buffer_store_le() {
    test_composite_limbs_buffer_store_with_unaligned_lengths::<MpMutLittleEndianUIntByteSlice>();
    test_composite_limbs_buffer_store_with_aligned_lengths::<MpMutLittleEndianUIntByteSlice>();
}

#[test]
fn test_composite_limbs_buffer_store_ne() {
    test_composite_limbs_buffer_store_with_aligned_lengths::<MpMutNativeEndianUIntLimbsSlice>();
}

/// View a mutable [`LimbType`] slice as a mutable byte slice.
///
/// Returns a mutable byte slice covering the same memory as `limbs`, of length
/// `limbs.len()` times the [`LimbType`] size in bytes. The bytes are in memory
/// order, i.e. each limb's bytes appear in the host's native endianess.
///
/// This is useful for filling a [`LimbType`] slice, e.g. one to be wrapped in
/// a [`MpMutNativeEndianUIntLimbsSlice`], from a source producing bytes, most
/// notably a random number generator. As all bytes produced by a random number
/// generator are equally random, the host's endianess doesn't matter in this
/// case. As any bit pattern is a valid [`LimbType`] value, any byte values may
/// be written.
///
/// # Arguments
///
/// * `limbs` - The [`LimbType`] slice to view as bytes.
pub fn limb_slice_as_bytes_mut(limbs: &mut [LimbType]) -> &mut [u8] {
    let len = mem::size_of_val(limbs);
    let ptr = limbs.as_mut_ptr() as *mut u8;
    unsafe { slice::from_raw_parts_mut(ptr, len) }
}

/// View a [`LimbType`] slice as a byte slice.
///
/// Returns a byte slice covering the same memory as `limbs`, of length
/// `limbs.len()` times the [`LimbType`] size in bytes. The bytes are in memory
/// order, i.e. each limb's bytes appear in the host's native endianess.
///
/// See [`limb_slice_as_bytes_mut()`] for the mutable variant, e.g. for filling
/// a [`LimbType`] slice from a random number generator.
///
/// # Arguments
///
/// * `limbs` - The [`LimbType`] slice to view as bytes.
pub fn limb_slice_as_bytes(limbs: &[LimbType]) -> &[u8] {
    let len = mem::size_of_val(limbs);
    let ptr = limbs.as_ptr() as *const u8;
    unsafe { slice::from_raw_parts(ptr, len) }
}