decimal-scaled 0.5.0

Const-generic base-10 fixed-point decimals (D18/D38/D76/D153/D307 and the half-width tiers up to D1232) with integer-only transcendentals correctly rounded to within 0.5 ULP — exact at the type's last representable place. Deterministic across every platform; no_std-friendly.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
// SPDX-FileCopyrightText: 2026 John Moxley
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Const-generic fixed-width integers.
//!
//! A single `Uint<const LIMBS: usize>` / `Int<const LIMBS: usize>` pair
//! parameterised by the number of 64-bit little-endian limbs, replacing
//! the family of named `IntXXXX` / `UintXXXX` types. Bit width is
//! derived (`BITS = LIMBS * 64`); every width this crate uses
//! (256 … 16384 bits) is a clean multiple of 64, so the limb count is
//! the natural single parameter — it sidesteps the
//! `LIMBS = ceil(BITS / 64)` derivation that a `BITS`-parameterised type
//! cannot express on stable Rust.
//!
//! Storage is `[u64; LIMBS]`, matching the limb representation the
//! arithmetic primitives already use. Methods delegate to the
//! width-matched limb algorithms; because `LIMBS` is a compile-time
//! constant, the limb loops unroll and any `match LIMBS` arms const-fold
//! per monomorphisation — no runtime dispatch.

pub(crate) mod traits;
pub(crate) mod compute_limbs;

pub use traits::BigInt;

use crate::int::algos::div::div_fixed::div_rem_mag_fixed;
use crate::int::algos::div::div_rem::div_rem;
use crate::int::algos::support::limbs::{
    add_assign_fixed, bit_len_fixed, cmp_cross, cmp_fixed, is_zero_fixed, max_n_limbs, shl,
    shl_fixed, shr_fixed, sub_assign_fixed,
};
use crate::int::algos::mul::mul_schoolbook::{mul_low_fixed, mul_schoolbook};
use crate::int::policy::add::dispatch as add_dispatch;
use crate::int::policy::cmp::dispatch as cmp_dispatch;
use crate::int::policy::cube::dispatch as cube_dispatch;
use crate::int::policy::div_rem::dispatch as div_rem_dispatch;
use crate::int::policy::eq::dispatch as eq_dispatch;
use crate::int::policy::icbrt::dispatch as icbrt_dispatch;
use crate::int::policy::hypot::dispatch as hypot_dispatch;
use crate::int::policy::isqrt::dispatch as isqrt_dispatch;
use crate::int::policy::mul::dispatch as mul_fast;
use crate::int::policy::neg::dispatch as neg_dispatch;
use crate::int::policy::sum_sq::dispatch as sum_sq_dispatch;
use crate::int::policy::pow::dispatch as pow_dispatch;
use crate::int::policy::rem::dispatch as rem_dispatch;
use crate::int::policy::sqr::dispatch as sqr_dispatch;
use crate::int::policy::sub::dispatch as sub_dispatch;
use crate::support::int_fmt::fmt_into;
use core::cmp::Ordering;
use core::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Not, Rem, Shl, Shr, Sub};

/// Unsigned fixed-width integer of `N` little-endian 64-bit limbs.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Uint<const N: usize> {
    limbs: [u64; N],
}

/// Signed (two's-complement) fixed-width integer of `N` little-endian
/// 64-bit limbs.
//
// `PartialEq` / `PartialOrd` / `Ord` are NOT derived: a single generic
// `impl<N, M>` cross-width surface (below) covers same-width comparison
// too, so a derived same-width impl would collide. `Eq` is still derived
// (it only needs the `PartialEq<Self>` the generic impl provides).
#[derive(Clone, Copy, Eq, Hash, Debug)]
pub struct Int<const N: usize> {
    limbs: [u64; N],
}

impl<const N: usize> Uint<N> {
    /// Number of 64-bit limbs.
    pub const LIMBS: usize = N;
    /// Bit width (`LIMBS * 64`). `u32` so it composes directly with the
    /// `leading_zeros` / `count_ones` `u32` surface and matches the
    /// historic named-type `BITS` constant.
    pub const BITS: u32 = (N as u32) * 64;

    /// Additive identity.
    pub const ZERO: Self = Self { limbs: [0; N] };
    /// Multiplicative identity.
    pub const ONE: Self = {
        let mut limbs = [0u64; N];
        limbs[0] = 1;
        Self { limbs }
    };
    /// Largest representable value (all limbs set).
    pub const MAX: Self = Self {
        limbs: [u64::MAX; N],
    };

    /// Constructs from raw little-endian limbs.
    #[inline]
    pub const fn from_limbs(limbs: [u64; N]) -> Self {
        Self { limbs }
    }

    /// Borrows the raw little-endian limbs.
    #[inline]
    pub const fn as_limbs(&self) -> &[u64; N] {
        &self.limbs
    }

    /// Wrapping addition (modulo `2^BITS`).
    #[inline]
    pub fn wrapping_add(mut self, rhs: Self) -> Self {
        add_assign_fixed(&mut self.limbs, &rhs.limbs);
        self
    }

    /// Wrapping subtraction (modulo `2^BITS`).
    #[inline]
    pub fn wrapping_sub(mut self, rhs: Self) -> Self {
        sub_assign_fixed(&mut self.limbs, &rhs.limbs);
        self
    }

    /// Wrapping multiplication (modulo `2^BITS`).
    ///
    /// Schoolbook multiply truncated to the low `N` limbs. Only the
    /// product limbs that land below `2^BITS` are kept, so no
    /// `[u64; 2*N]` output buffer is needed — the higher partial
    /// products are simply never written. Carries that would land at or
    /// above limb `N` are discarded, which is exactly the modular
    /// reduction.
    #[inline]
    pub fn wrapping_mul(self, rhs: Self) -> Self {
        let mut out = [0u64; N];
        mul_low_fixed(&self.limbs, &rhs.limbs, &mut out);
        Self { limbs: out }
    }

    /// Wrapping square (`self²` modulo `2^BITS`). Named entry point for
    /// the open-coded `x * x` pattern. Thin delegator DOWN to the sqr
    /// policy (`sqr_dispatch`): half-product squaring via the
    /// `sqr_low_fixed` kernel — each cross term is formed once and doubled,
    /// so the limb-multiply count is `N(N+1)/2` rather than the `N²` of a
    /// general multiply.
    #[inline]
    pub const fn wrapping_sqr(self) -> Self {
        sqr_dispatch(self)
    }

    /// Wrapping cube (`self³` modulo `2^BITS`). Named entry point for the
    /// open-coded `x * x * x` pattern. Thin delegator DOWN to the cube
    /// policy (`cube_dispatch`): `sqr` then one multiply via the const
    /// kernels — no cheaper form exists below two multiplies.
    #[inline]
    pub const fn wrapping_cube(self) -> Self {
        cube_dispatch(self)
    }

    /// Checked addition: `None` on overflow past `2^BITS`.
    #[inline]
    pub fn checked_add(mut self, rhs: Self) -> Option<Self> {
        let carry = add_assign_fixed(&mut self.limbs, &rhs.limbs);
        if carry { None } else { Some(self) }
    }

    /// Checked subtraction: `None` if the result would be negative.
    #[inline]
    pub fn checked_sub(mut self, rhs: Self) -> Option<Self> {
        let borrow = sub_assign_fixed(&mut self.limbs, &rhs.limbs);
        if borrow { None } else { Some(self) }
    }

    /// Checked multiplication: `None` if the true product does not fit
    /// `2^BITS`.
    #[inline]
    pub fn checked_mul(self, rhs: Self) -> Option<Self> {
        let (a, b) = (&self.limbs, &rhs.limbs);
        let mut out = [0u64; N];
        let mut overflow = false;
        let mut i = 0;
        while i < N {
            let ai = a[i];
            if ai != 0 {
                let mut carry: u64 = 0;
                let mut j = 0;
                while j < N {
                    let prod = (ai as u128) * (b[j] as u128);
                    if i + j < N {
                        let v = prod + (out[i + j] as u128) + (carry as u128);
                        out[i + j] = v as u64;
                        carry = (v >> 64) as u64;
                    } else if prod != 0 || carry != 0 {
                        // Any product or carry landing at/above limb `N`
                        // means the true product exceeds the width.
                        overflow = true;
                        carry = 0;
                    }
                    j += 1;
                }
                if carry != 0 {
                    // Row carry would spill into limb `i + N >= N`.
                    overflow = true;
                }
            }
            i += 1;
        }
        if overflow {
            None
        } else {
            Some(Self { limbs: out })
        }
    }

    /// Wrapping division. Panics on a zero divisor, matching the
    /// behaviour of the primitive unsigned integer types.
    #[inline]
    pub fn wrapping_div(self, rhs: Self) -> Self {
        assert!(!rhs.is_zero(), "attempt to divide by zero");
        let mut quot = [0u64; N];
        let mut rem = [0u64; N];
        div_rem(&self.limbs, &rhs.limbs, &mut quot, &mut rem);
        Self { limbs: quot }
    }

    /// Wrapping remainder. Panics on a zero divisor, matching the
    /// behaviour of the primitive unsigned integer types.
    #[inline]
    pub fn wrapping_rem(self, rhs: Self) -> Self {
        assert!(
            !rhs.is_zero(),
            "attempt to calculate the remainder with a divisor of zero"
        );
        let mut quot = [0u64; N];
        let mut rem = [0u64; N];
        div_rem(&self.limbs, &rhs.limbs, &mut quot, &mut rem);
        Self { limbs: rem }
    }

    /// Bitwise AND.
    // Operator-named inherent kernels (bitand/bitor/bitxor/not/shl/shr):
    // deliberately NOT the std ops traits — const-usable, and `shl`/`shr` take
    // a `u32` shift rather than the `Shl<Rhs>`/`Shr<Rhs>` shape (the std ops
    // are implemented separately). Allow the look-alike-trait-method lint.
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn bitand(self, rhs: Self) -> Self {
        let mut out = [0u64; N];
        let mut i = 0;
        while i < N {
            out[i] = self.limbs[i] & rhs.limbs[i];
            i += 1;
        }
        Self { limbs: out }
    }

    /// Bitwise OR.
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn bitor(self, rhs: Self) -> Self {
        let mut out = [0u64; N];
        let mut i = 0;
        while i < N {
            out[i] = self.limbs[i] | rhs.limbs[i];
            i += 1;
        }
        Self { limbs: out }
    }

    /// Bitwise XOR.
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn bitxor(self, rhs: Self) -> Self {
        let mut out = [0u64; N];
        let mut i = 0;
        while i < N {
            out[i] = self.limbs[i] ^ rhs.limbs[i];
            i += 1;
        }
        Self { limbs: out }
    }

    /// Bitwise NOT (ones' complement).
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn not(self) -> Self {
        let mut out = [0u64; N];
        let mut i = 0;
        while i < N {
            out[i] = !self.limbs[i];
            i += 1;
        }
        Self { limbs: out }
    }

    /// Logical left shift by `shift` bits (modulo `2^BITS`).
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn shl(self, shift: u32) -> Self {
        let mut out = [0u64; N];
        shl_fixed(&self.limbs, shift, &mut out);
        Self { limbs: out }
    }

    /// Logical right shift by `shift` bits.
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn shr(self, shift: u32) -> Self {
        let mut out = [0u64; N];
        shr_fixed(&self.limbs, shift, &mut out);
        Self { limbs: out }
    }

    /// `true` when every limb is zero.
    #[inline]
    pub fn is_zero(&self) -> bool {
        is_zero_fixed(&self.limbs)
    }

    /// Bit length (significant bits): `0` for zero, else
    /// `floor(log2(self)) + 1`, equivalently `BITS - leading_zeros`.
    ///
    /// For an unsigned value there is no sign, so magnitude and stored
    /// representation coincide — `bit_length` and the `uN`-contract
    /// bit-count methods below agree by construction.
    #[inline]
    pub const fn bit_length(&self) -> u32 {
        bit_len_fixed(&self.limbs)
    }

    /// Number of leading zero bits in the `BITS`-wide representation,
    /// matching the primitive `uN::leading_zeros` contract:
    /// `BITS - bit_length`, and `BITS` for zero.
    #[inline]
    pub const fn leading_zeros(&self) -> u32 {
        Self::BITS - self.bit_length()
    }

    /// `true` when the value equals one.
    #[inline]
    pub fn is_one(&self) -> bool {
        if N == 0 || self.limbs[0] != 1 {
            return false;
        }
        let mut i = 1;
        while i < N {
            if self.limbs[i] != 0 {
                return false;
            }
            i += 1;
        }
        true
    }

    /// Wrapping exponentiation by squaring (`self^exp` modulo `2^BITS`).
    /// `self^0 == 1`. Thin delegator DOWN to the pow policy
    /// (`pow_dispatch`): binary square-and-multiply over the const
    /// kernels; optimal for the small fixed exponents the root iteration
    /// needs (`k-1`, `k`).
    #[inline]
    pub const fn wrapping_pow(self, exp: u32) -> Self {
        pow_dispatch(self, exp)
    }

    /// Exponentiation by squaring, returning `None` if the true power
    /// overflows `2^BITS`. `self^0 == 1`.
    #[inline]
    pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
        let mut acc = Self::ONE;
        let mut base = self;
        loop {
            if exp & 1 == 1 {
                acc = acc.checked_mul(base)?;
            }
            exp >>= 1;
            if exp == 0 {
                break;
            }
            base = base.checked_mul(base)?;
        }
        Some(acc)
    }

    /// Exponentiation by squaring. Routes through the pow policy
    /// (`pow_dispatch`): binary square-and-multiply at every `N`.
    /// Result is `self^exp` modulo `2^BITS`; `self^0 == 1`.
    #[inline]
    pub fn pow(self, exp: u32) -> Self {
        pow_dispatch(self, exp)
    }

    /// Integer square root: the largest `r` with `r² <= self`.
    /// Routes through the isqrt policy (`isqrt_dispatch`):
    /// `N ∈ {1, 2}` takes the hardware native path; `N >= 3` takes
    /// the Newton limb kernel.
    #[inline]
    pub fn isqrt(self) -> Self {
        isqrt_dispatch(self)
    }

    /// Integer square: `self²` modulo `2^BITS`. Routes through the sqr
    /// policy (`sqr_dispatch`): half-product squaring kernel at every `N`.
    #[inline]
    pub fn sqr(self) -> Self {
        sqr_dispatch(self)
    }

    /// Integer cube: `self³` modulo `2^BITS`. Routes through the cube
    /// policy (`cube_dispatch`): sqr-then-multiply at every `N`.
    #[inline]
    pub fn cube(self) -> Self {
        cube_dispatch(self)
    }

    /// Integer cube root: `floor(self^(1/3))`. Routes through the icbrt
    /// policy (`icbrt_dispatch`):
    /// `N ∈ {1, 2}` takes the narrow path; `N >= 3` takes the Newton
    /// limb kernel with an `f64::cbrt` seed.
    #[inline]
    pub fn icbrt(self) -> Self {
        icbrt_dispatch(self)
    }

    /// Integer `k`th root: returns `(root, exact)` where
    /// `root = floor(self^(1/k))` and `exact` is `true` iff
    /// `root^k == self`. `k` must be `>= 1`.
    ///
    /// Brent–Zimmermann RootInt (Modern Computer Arithmetic §1.5.2): the
    /// integer projection of Newton's iteration
    /// `u = ((k-1)·s + m / s^(k-1)) / k`, started from an upper bound on
    /// the root and run until the monotone-decreasing sequence first
    /// fails to decrease (`u >= s`), at which point `s` is the floor
    /// root. The seed is the no_std-safe bit-length bound
    /// `2^ceil(bit_length / k)` — a clean upper bound since
    /// `(2^ceil(L/k))^k >= 2^L > m`. `k == 2` reuses the dedicated
    /// [`Self::isqrt`]; `k == 3` is the cube root.
    pub fn root_int(self, k: u32) -> (Self, bool) {
        debug_assert!(k >= 1, "root_int requires k >= 1");
        // Degenerate / trivial roots.
        if k == 1 {
            return (self, true);
        }
        if self.is_zero() {
            return (Self::ZERO, true);
        }
        if self.is_one() {
            return (Self::ONE, true);
        }
        if k == 2 {
            let r = self.isqrt();
            return (r, r.wrapping_sqr() == self);
        }

        // Seed: 2^ceil(bit_length / k) is an upper bound on the root.
        let len = self.bit_length();
        let seed_shift = len.div_ceil(k);
        // ceil(len/k) <= len for k >= 2, so the seed fits the width.
        let mut s = Self::ONE.shl(seed_shift);

        // Newton: s decreases monotonically while above the root.
        loop {
            // t = (k-1)*s + m / s^(k-1)
            let pow_km1 = s.wrapping_pow(k - 1);
            // pow_km1 is non-zero (s >= 1), so the divide is defined.
            let quot = self.wrapping_div(pow_km1);
            let mut t = Self::ZERO;
            let mut c = 0;
            while c < k - 1 {
                t = t.wrapping_add(s);
                c += 1;
            }
            t = t.wrapping_add(quot);
            // u = t / k
            let u = t.wrapping_div(Self::from_u64(k as u64));
            if u >= s {
                break;
            }
            s = u;
        }

        let exact = s.checked_pow(k).is_some_and(|p| p == self);
        (s, exact)
    }

    /// Constructs from a `u64`, zero-extending into the high limbs.
    #[inline]
    pub(crate) fn from_u64(value: u64) -> Self {
        let mut limbs = [0u64; N];
        if N > 0 {
            limbs[0] = value;
        }
        Self { limbs }
    }

    /// Builds from an unsigned 128-bit value, zero-extending the upper
    /// limbs. **Truncating** for `Uint<1>` (the high 64 bits of `v` are
    /// discarded); use the checked `TryFrom` conversion when `v` may
    /// not fit.
    #[inline]
    pub(crate) const fn from_u128(v: u128) -> Self {
        let mut limbs = [0u64; N];
        if N > 0 {
            limbs[0] = v as u64;
        }
        if N > 1 {
            limbs[1] = (v >> 64) as u64;
        }
        Self { limbs }
    }

    /// Exact value conversion from `u128`, or `None` if `v` does not fit
    /// `Uint<N>` (only possible for `N < 2`). For `N >= 2` every `u128` fits.
    #[inline]
    pub(crate) const fn try_from_u128(v: u128) -> Option<Self> {
        if N >= 2 || v <= u64::MAX as u128 {
            Some(Self::from_u128(v))
        } else {
            None
        }
    }

    /// Reinterprets the bit pattern as the signed sibling.
    #[inline]
    pub const fn cast_signed(self) -> Int<N> {
        Int::from_limbs(self.limbs)
    }

    /// Approximate `f64` value (positive; truncated toward zero on
    /// overflow).
    pub fn as_f64(self) -> f64 {
        let radix: f64 = 18_446_744_073_709_551_616.0; // 2^64
        let mut acc = 0.0f64;
        let mut i = N;
        while i > 0 {
            i -= 1;
            acc = acc * radix + self.limbs[i] as f64;
        }
        acc
    }

    /// Set-bit count across all limbs, matching the primitive
    /// `uN::count_ones` contract.
    #[inline]
    pub const fn count_ones(self) -> u32 {
        let mut total = 0;
        let mut i = 0;
        while i < N {
            total += self.limbs[i].count_ones();
            i += 1;
        }
        total
    }

    /// `true` when exactly one bit is set.
    #[inline]
    pub const fn is_power_of_two(self) -> bool {
        self.count_ones() == 1
    }

    /// Smallest power of two `>= self` (`1` for zero), wrapping on
    /// overflow.
    pub fn next_power_of_two(self) -> Self {
        if self.is_zero() {
            return Self::ONE;
        }
        if self.is_power_of_two() {
            return self;
        }
        let bits = self.bit_length();
        let mut out = [0u64; N];
        if (bits as usize) < N * 64 {
            out[(bits / 64) as usize] = 1u64 << (bits % 64);
        }
        Self { limbs: out }
    }

    /// Parses an unsigned decimal string. Only base 10 is supported.
    pub const fn from_str_radix(s: &str, radix: u32) -> Result<Self, ()> {
        if radix != 10 {
            return Err(());
        }
        let bytes = s.as_bytes();
        if bytes.is_empty() {
            return Err(());
        }
        let mut acc = [0u64; N];
        let mut k = 0;
        while k < bytes.len() {
            let ch = bytes[k];
            if ch < b'0' || ch > b'9' {
                return Err(());
            }
            let d = (ch - b'0') as u64;
            let mut carry: u64 = d;
            let mut j = 0;
            while j < N {
                let p = (acc[j] as u128) * 10u128 + (carry as u128);
                acc[j] = p as u64;
                carry = (p >> 64) as u64;
                j += 1;
            }
            k += 1;
        }
        Ok(Self { limbs: acc })
    }
}

impl<const N: usize> Add for Uint<N> {
    type Output = Self;
    #[inline]
    fn add(self, rhs: Self) -> Self {
        self.wrapping_add(rhs)
    }
}

impl<const N: usize> Sub for Uint<N> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: Self) -> Self {
        self.wrapping_sub(rhs)
    }
}

impl<const N: usize> Mul for Uint<N> {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: Self) -> Self {
        self.wrapping_mul(rhs)
    }
}

impl<const N: usize> BitAnd for Uint<N> {
    type Output = Self;
    #[inline]
    fn bitand(self, rhs: Self) -> Self {
        Uint::bitand(self, rhs)
    }
}

impl<const N: usize> BitOr for Uint<N> {
    type Output = Self;
    #[inline]
    fn bitor(self, rhs: Self) -> Self {
        Uint::bitor(self, rhs)
    }
}

impl<const N: usize> BitXor for Uint<N> {
    type Output = Self;
    #[inline]
    fn bitxor(self, rhs: Self) -> Self {
        Uint::bitxor(self, rhs)
    }
}

impl<const N: usize> Not for Uint<N> {
    type Output = Self;
    #[inline]
    fn not(self) -> Self {
        Uint::not(self)
    }
}

impl<const N: usize> Shl<u32> for Uint<N> {
    type Output = Self;
    #[inline]
    fn shl(self, shift: u32) -> Self {
        Uint::shl(self, shift)
    }
}

impl<const N: usize> Shr<u32> for Uint<N> {
    type Output = Self;
    #[inline]
    fn shr(self, shift: u32) -> Self {
        Uint::shr(self, shift)
    }
}

// Truncating unsigned division / remainder via the dispatching divmod
// (Knuth / Burnikel–Ziegler), matching the macro `$U` operators so the
// const-generic and named unsigned types share one divide algorithm.

impl<const N: usize> Div for Uint<N> {
    type Output = Self;
    #[inline]
    fn div(self, rhs: Self) -> Self {
        let mut q = [0u64; N];
        let mut r = [0u64; N];
        div_rem_dispatch(&self.limbs, &rhs.limbs, &mut q, &mut r);
        Self { limbs: q }
    }
}

impl<const N: usize> Rem for Uint<N> {
    type Output = Self;
    #[inline]
    fn rem(self, rhs: Self) -> Self {
        let mut q = [0u64; N];
        let mut r = [0u64; N];
        div_rem_dispatch(&self.limbs, &rhs.limbs, &mut q, &mut r);
        Self { limbs: r }
    }
}

impl<const N: usize> PartialOrd for Uint<N> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<const N: usize> Ord for Uint<N> {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        match cmp_fixed(&self.limbs, &other.limbs) {
            -1 => Ordering::Less,
            1 => Ordering::Greater,
            _ => Ordering::Equal,
        }
    }
}

impl<const N: usize> Int<N> {
    /// Number of 64-bit limbs.
    pub const LIMBS: usize = N;
    /// Bit width (`LIMBS * 64`). `u32` so it composes directly with the
    /// `leading_zeros` / `count_ones` `u32` surface and matches the
    /// historic named-type `BITS` constant.
    pub const BITS: u32 = (N as u32) * 64;

    /// Additive identity.
    pub const ZERO: Self = Self { limbs: [0; N] };
    /// Multiplicative identity.
    pub const ONE: Self = {
        let mut limbs = [0u64; N];
        limbs[0] = 1;
        Self { limbs }
    };
    /// Most positive representable value (`2^(BITS-1) - 1`).
    pub const MAX: Self = {
        let mut limbs = [u64::MAX; N];
        limbs[N - 1] = i64::MAX as u64;
        Self { limbs }
    };
    /// Most negative representable value (`-2^(BITS-1)`).
    pub const MIN: Self = {
        let mut limbs = [0u64; N];
        limbs[N - 1] = 1u64 << 63;
        Self { limbs }
    };

    /// Constructs from raw little-endian two's-complement limbs.
    #[inline]
    pub const fn from_limbs(limbs: [u64; N]) -> Self {
        Self { limbs }
    }

    /// Borrows the raw little-endian limbs.
    #[inline]
    pub const fn as_limbs(&self) -> &[u64; N] {
        &self.limbs
    }

    /// `true` when every limb is zero.
    #[inline]
    pub const fn is_zero(&self) -> bool {
        is_zero_fixed(&self.limbs)
    }

    /// `true` when the value is strictly negative (top bit set).
    #[inline]
    pub const fn is_negative(&self) -> bool {
        N > 0 && (self.limbs[N - 1] >> 63) == 1
    }

    /// `true` when the value is strictly positive (non-zero and the
    /// sign bit clear).
    #[inline]
    pub const fn is_positive(&self) -> bool {
        !self.is_negative() && !self.is_zero()
    }

    /// Two's-complement wrapping negation (`!self + 1`). `MIN` negates
    /// to itself, as with the primitive signed integers.
    #[inline]
    pub const fn wrapping_neg(self) -> Self {
        neg_dispatch(self)
    }

    /// Wrapping addition (modulo `2^BITS`). Identical bit pattern to the
    /// unsigned add — two's-complement makes signed and unsigned
    /// addition the same operation.
    #[inline]
    pub const fn wrapping_add(self, rhs: Self) -> Self {
        add_dispatch(self, rhs)
    }

    /// Wrapping subtraction (modulo `2^BITS`).
    #[inline]
    pub const fn wrapping_sub(self, rhs: Self) -> Self {
        sub_dispatch(self, rhs)
    }

    /// Wrapping multiplication (modulo `2^BITS`). The low `N` limbs of a
    /// two's-complement product are independent of the operand signs, so
    /// this is the same truncated schoolbook the unsigned type uses.
    #[inline]
    pub const fn wrapping_mul(self, rhs: Self) -> Self {
        let mut out = [0u64; N];
        mul_low_fixed(&self.limbs, &rhs.limbs, &mut out);
        Self { limbs: out }
    }

    /// Absolute value (wrapping: `MIN.abs() == MIN`).
    #[inline]
    pub const fn abs(self) -> Self {
        if self.is_negative() {
            self.wrapping_neg()
        } else {
            self
        }
    }

    /// Sign: `-1`, `0`, or `1` as the value is negative, zero, or
    /// positive.
    #[inline]
    pub fn signum(&self) -> i32 {
        if self.is_zero() {
            0
        } else if self.is_negative() {
            -1
        } else {
            1
        }
    }

    /// Constructs from an `i64`, sign-extending into the high limbs.
    #[inline]
    pub(crate) const fn from_i64(value: i64) -> Self {
        // Negative values fill the upper limbs with all-ones so the
        // two's-complement representation matches at every width.
        let fill = if value < 0 { u64::MAX } else { 0 };
        let mut limbs = [fill; N];
        if N > 0 {
            limbs[0] = value as u64;
        }
        Self { limbs }
    }

    /// Constructs from an `i8` (always representable; sign-extends).
    #[inline]
    pub(crate) const fn from_i8(value: i8) -> Self {
        Self::from_i64(value as i64)
    }

    /// Constructs from an `i16` (always representable; sign-extends).
    #[inline]
    pub(crate) const fn from_i16(value: i16) -> Self {
        Self::from_i64(value as i64)
    }

    /// Constructs from an `i32` (always representable; sign-extends).
    #[inline]
    pub(crate) const fn from_i32(value: i32) -> Self {
        Self::from_i64(value as i64)
    }

    /// Constructs from a `u8` (always representable; zero-extends).
    #[inline]
    pub(crate) const fn from_u8(value: u8) -> Self {
        Self::from_u64_unsigned(value as u64)
    }

    /// Constructs from a `u16` (always representable; zero-extends).
    #[inline]
    pub(crate) const fn from_u16(value: u16) -> Self {
        Self::from_u64_unsigned(value as u64)
    }

    /// Constructs from a `u32` (always representable; zero-extends).
    #[inline]
    pub(crate) const fn from_u32(value: u32) -> Self {
        Self::from_u64_unsigned(value as u64)
    }

    /// Zero-extends an unsigned 64-bit value into limb 0. Internal helper
    /// for the unsigned `from_*` family; the public fitting check is in
    /// [`Self::try_from_u64`].
    #[inline]
    const fn from_u64_unsigned(value: u64) -> Self {
        let mut limbs = [0u64; N];
        if N > 0 {
            limbs[0] = value;
        }
        Self { limbs }
    }

    /// Exact conversion from a `u64`, or `None` if it does not fit
    /// `Int<N>`. Only `N == 1` (the `i64` floor) can fail, when the value
    /// exceeds `i64::MAX`; every wider tier holds all of `u64`.
    #[inline]
    pub(crate) const fn try_from_u64(value: u64) -> Option<Self> {
        if N >= 2 || value <= i64::MAX as u64 {
            Some(Self::from_u64_unsigned(value))
        } else {
            None
        }
    }

    /// Exact conversion from an `i128`, or `None` if it does not fit
    /// `Int<N>`. Only `N == 1` (64-bit storage) can fail; `N >= 2` holds
    /// every `i128`.
    #[inline]
    pub(crate) const fn try_from_i128(v: i128) -> Option<Self> {
        let mag = v.unsigned_abs();
        let built = Self::from_mag_limbs(&[mag as u64, (mag >> 64) as u64], v < 0);
        if N >= 2 || built.as_i128() == v {
            Some(built)
        } else {
            None
        }
    }

    /// Exact conversion from a `u128`, or `None` if it does not fit
    /// `Int<N>`. `N == 1` fails above `i64::MAX`; `N == 2` fails above
    /// `i128::MAX` (the sign bit); `N >= 3` holds every `u128`.
    #[inline]
    pub(crate) const fn try_from_u128(v: u128) -> Option<Self> {
        let built = Self::from_mag_limbs(&[v as u64, (v >> 64) as u64], false);
        if N >= 3 {
            Some(built)
        } else if built.is_negative() {
            // Magnitude landed in the sign bit of the N-limb storage.
            None
        } else if N >= 2 || built.as_i128() as u128 == v {
            Some(built)
        } else {
            None
        }
    }

    /// Lossless `i64` value, valid on the `N == 1` tier where `Int<N>`
    /// *is* an `i64`. The trait form is `From<Int<1>> for i64`.
    #[inline]
    pub(crate) const fn to_i64(self) -> i64 {
        self.as_i128() as i64
    }

    /// Lossless `i128` value, valid on the `N <= 2` tiers where every
    /// `Int<N>` fits an `i128`. The trait forms are `From<Int<1>>` /
    /// `From<Int<2>> for i128`.
    #[inline]
    pub(crate) const fn to_i128(self) -> i128 {
        self.as_i128()
    }

    /// Exact `i32` value, or `None` if out of range.
    #[inline]
    pub(crate) fn try_to_i32(self) -> Option<i32> {
        match self.to_i128_checked() {
            Some(v) if v >= i32::MIN as i128 && v <= i32::MAX as i128 => Some(v as i32),
            _ => None,
        }
    }

    /// Exact `u32` value, or `None` if negative or out of range.
    #[inline]
    pub(crate) fn try_to_u32(self) -> Option<u32> {
        match self.to_u128_checked() {
            Some(v) if v <= u32::MAX as u128 => Some(v as u32),
            _ => None,
        }
    }

    /// Exact `i64` value, or `None` if out of range.
    #[inline]
    pub(crate) fn try_to_i64(self) -> Option<i64> {
        match self.to_i128_checked() {
            Some(v) if v >= i64::MIN as i128 && v <= i64::MAX as i128 => Some(v as i64),
            _ => None,
        }
    }

    /// Exact `u64` value, or `None` if negative or out of range.
    #[inline]
    pub(crate) fn try_to_u64(self) -> Option<u64> {
        match self.to_u128_checked() {
            Some(v) if v <= u64::MAX as u128 => Some(v as u64),
            _ => None,
        }
    }

    /// Exact `i128` value, or `None` if out of range. Surface alias of
    /// [`Self::to_i128_checked`].
    #[inline]
    pub(crate) fn try_to_i128(self) -> Option<i128> {
        self.to_i128_checked()
    }

    /// Exact `u128` value, or `None` if negative or out of range. Surface
    /// alias of [`Self::to_u128_checked`].
    #[inline]
    pub(crate) fn try_to_u128(self) -> Option<u128> {
        self.to_u128_checked()
    }

    /// `true` when the value equals one.
    #[inline]
    pub fn is_one(&self) -> bool {
        if N == 0 || self.limbs[0] != 1 {
            return false;
        }
        let mut i = 1;
        while i < N {
            if self.limbs[i] != 0 {
                return false;
            }
            i += 1;
        }
        true
    }

    /// Most negative representable value (`-2^(BITS-1)`).
    #[inline]
    pub fn min_value() -> Self {
        let mut limbs = [0u64; N];
        if N > 0 {
            limbs[N - 1] = 1u64 << 63;
        }
        Self { limbs }
    }

    /// Most positive representable value (`2^(BITS-1) - 1`).
    #[inline]
    pub fn max_value() -> Self {
        let mut limbs = [u64::MAX; N];
        if N > 0 {
            limbs[N - 1] = u64::MAX >> 1;
        }
        Self { limbs }
    }

    /// Checked signed addition: `None` on two's-complement overflow.
    /// Overflow happens only when both operands share a sign and the
    /// result's sign differs from it. Routes through the add policy's
    /// checked door to the FUSED single-pass kernel (ripple + overflow
    /// verdict in one traversal) — the previous layered shape
    /// (`wrapping_add` then three sign reads then an `Option` rewrap)
    /// measured ≈2× the bare loop at 24 limbs in inter-layer moves.
    #[inline]
    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
        crate::int::policy::add::dispatch_checked(self, rhs)
    }

    /// Checked signed subtraction: `None` on two's-complement overflow
    /// (the operands' signs differ and the result takes the subtrahend's
    /// sign). Routes through the sub policy's checked door to the fused
    /// single-pass kernel — see [`Self::checked_add`].
    #[inline]
    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
        crate::int::policy::sub::dispatch_checked(self, rhs)
    }

    /// Checked signed multiplication: `None` if the true product does
    /// not fit the signed range. Computed via magnitudes so it reuses
    /// the unsigned overflow check, then re-signs.
    #[inline]
    pub fn checked_mul(self, rhs: Self) -> Option<Self> {
        if self.is_zero() || rhs.is_zero() {
            return Some(Self::ZERO);
        }
        let neg = self.is_negative() ^ rhs.is_negative();
        let ma = Uint::<N>::from_limbs(*self.abs().as_limbs());
        let mb = Uint::<N>::from_limbs(*rhs.abs().as_limbs());
        let prod = ma.checked_mul(mb)?;
        let signed = Self::from_limbs(*prod.as_limbs());
        if neg {
            let r = signed.wrapping_neg();
            // Negative magnitude must not exceed |MIN|; the round-trip
            // through wrapping_neg detects the single MIN-magnitude case.
            if r.is_negative() || r.is_zero() {
                Some(r)
            } else {
                None
            }
        } else if signed.is_negative() {
            // Positive magnitude landed in the sign bit → overflow.
            None
        } else {
            Some(signed)
        }
    }

    /// Wrapping exponentiation by squaring (`self^exp` modulo `2^BITS`).
    /// `self^0 == 1`. Thin delegator DOWN to the pow policy
    /// (`pow_dispatch`) on the unsigned reinterpretation: binary
    /// square-and-multiply over the const kernels. The low `N` limbs of a
    /// power are sign-independent, so reinterpreting as `Uint<N>` and back
    /// preserves the two's-complement result.
    #[inline]
    pub const fn wrapping_pow(self, exp: u32) -> Self {
        Self::from_limbs(*pow_dispatch(self.cast_unsigned(), exp).as_limbs())
    }

    /// Exponentiation by squaring, returning `None` on signed overflow.
    #[inline]
    pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
        let mut acc = Self::ONE;
        let mut base = self;
        loop {
            if exp & 1 == 1 {
                acc = acc.checked_mul(base)?;
            }
            exp >>= 1;
            if exp == 0 {
                break;
            }
            base = base.checked_mul(base)?;
        }
        Some(acc)
    }

    /// Wrapping square (`self²` modulo `2^BITS`). Thin delegator DOWN to
    /// the sqr policy (`sqr_dispatch`) on the unsigned reinterpretation:
    /// half-product squaring via the const kernel. The low `N` limbs of a
    /// square are sign-independent, so reinterpreting as `Uint<N>` and back
    /// preserves the two's-complement result.
    #[inline]
    pub const fn wrapping_sqr(self) -> Self {
        Self::from_limbs(*sqr_dispatch(self.cast_unsigned()).as_limbs())
    }

    /// Wrapping cube (`self³` modulo `2^BITS`). Thin delegator DOWN to the
    /// cube policy (`cube_dispatch`) on the unsigned reinterpretation:
    /// `sqr` then one multiply via the const kernels. The low `N` limbs are
    /// sign-independent, so reinterpreting as `Uint<N>` and back preserves
    /// the two's-complement result.
    #[inline]
    pub const fn wrapping_cube(self) -> Self {
        Self::from_limbs(*cube_dispatch(self.cast_unsigned()).as_limbs())
    }

    /// MAGNITUDE bit length: `0` for zero, else `floor(log2|self|) + 1`
    /// — the number of significant bits of the absolute value `|self|`.
    ///
    /// This is a *distinct concept* from the primitive bit-count methods
    /// ([`Self::leading_zeros`], [`Self::trailing_zeros`],
    /// [`Self::count_ones`], [`Self::count_zeros`]), which read the
    /// two's-complement representation. `bit_length` ignores the sign:
    /// `(-5).bit_length() == 5.bit_length() == 3`. It is kept public for
    /// internal normalisation use (root/reciprocal seeds, shift amounts).
    ///
    /// At `MIN` the magnitude is `2^(BITS-1)`, so
    /// `MIN.bit_length() == BITS` (one more than `MAX.bit_length()`,
    /// which is `BITS - 1`).
    #[inline]
    pub const fn bit_length(&self) -> u32 {
        bit_len_fixed(self.abs().as_limbs())
    }

    /// Leading zero bits of the two's-complement representation, matching
    /// the primitive `iN::leading_zeros` contract. A negative value has its
    /// sign bit (the MSB) set, so it has zero leading zeros; a non-negative
    /// value's leading-zero count is `BITS - bit_length` (`BITS` for zero).
    ///
    /// `MIN` is negative, so `MIN.leading_zeros() == 0`. `MAX` is the
    /// largest non-negative value (`0b0111…1`), so `MAX.leading_zeros()
    /// == 1`. Note this is the two's-complement count, NOT a magnitude
    /// count — contrast [`Self::bit_length`].
    #[inline]
    pub const fn leading_zeros(&self) -> u32 {
        if self.is_negative() {
            0
        } else {
            Self::BITS - self.bit_length()
        }
    }

    // ── Int<N> / Uint<N> parity surface ─────────────────────────
    //
    // The methods below give the const-generic `Int<N>` the surface the
    // kernel-facing `BigInt` trait and the public `IntXXXX` type aliases
    // expect. Most delegate to the existing inherent methods or the
    // `Uint<N>` twin.

    /// Integer constant `10`, used by decimal-scale `10^scale`
    /// rescaling.
    pub const TEN: Self = {
        let mut limbs = [0u64; N];
        if N > 0 {
            limbs[0] = 10;
        }
        Self { limbs }
    };

    /// `|self|` as the unsigned twin. `MIN` maps to `2^(BITS-1)`.
    #[inline]
    pub const fn unsigned_abs(self) -> Uint<N> {
        Uint::from_limbs(*self.abs().as_limbs())
    }

    /// Two's-complement negation. Alias of [`Self::wrapping_neg`].
    #[inline]
    pub fn negate(self) -> Self {
        self.wrapping_neg()
    }

    /// Truncating quotient and remainder `(self / rhs, self % rhs)` in a
    /// single divmod call. The quotient truncates toward zero and the
    /// remainder takes the sign of the dividend. Routes through the
    /// const-`N` fast-arm (`div_rem_mag_fixed`): native `u64` idiv at
    /// `N == 1`, native `u128` divide at `N == 2`, and the dispatching
    /// divmod (Knuth / Burnikel–Ziegler) for wider `N`. Panics on a zero
    /// divisor.
    #[inline]
    pub fn div_rem(self, rhs: Self) -> (Self, Self) {
        assert!(!rhs.is_zero(), "attempt to divide by zero");
        let neg_q = self.is_negative() ^ rhs.is_negative();
        let neg_r = self.is_negative();
        let mut quot = [0u64; N];
        let mut rem = [0u64; N];
        div_rem_mag_fixed::<N>(
            self.unsigned_abs().as_limbs(),
            rhs.unsigned_abs().as_limbs(),
            &mut quot,
            &mut rem,
        );
        let q = Self::from_mag_limbs(&quot, neg_q);
        let r = Self::from_mag_limbs(&rem, neg_r);
        (q, r)
    }

    /// Builds a signed value from a non-negative magnitude limb slice
    /// and a sign, truncating the magnitude into `N` limbs.
    #[inline]
    pub(crate) const fn from_mag_limbs(mag: &[u64], negative: bool) -> Self {
        let mut out = [0u64; N];
        let n = if mag.len() < N { mag.len() } else { N };
        let mut i = 0;
        while i < n {
            out[i] = mag[i];
            i += 1;
        }
        let v = Self { limbs: out };
        // Inherent `const` zero-check (avoids the non-const `BigInt`
        // trait method that name-resolution would otherwise pick here).
        if negative && !is_zero_fixed(&v.limbs) {
            v.wrapping_neg()
        } else {
            v
        }
    }

    /// `true` if bit `idx` of the two's-complement representation is set.
    #[inline]
    pub const fn bit(self, idx: u32) -> bool {
        let limb = (idx / 64) as usize;
        if limb >= N {
            return self.is_negative();
        }
        (self.limbs[limb] >> (idx % 64)) & 1 == 1
    }

    /// Builds from a signed 128-bit value. **Truncating** for `Int<1>`
    /// (the high 64 bits of `v` are discarded); use the checked `TryFrom`
    /// conversion when `v` may not fit.
    #[inline]
    pub(crate) const fn from_i128(v: i128) -> Self {
        // Narrow non-limb fast path (const-folds): for N<=2 write the
        // two's-complement limbs directly (truncating for N==1), skipping the
        // magnitude split + `wrapping_neg` re-sign. Bit-identical to the
        // magnitude path (two's-complement negation commutes with low-64
        // truncation).
        if N <= 2 {
            let mut limbs = [0u64; N];
            limbs[0] = v as u64;
            if N == 2 {
                limbs[1] = (v >> 64) as u64;
            }
            return Self { limbs };
        }
        let mag = v.unsigned_abs();
        Self::from_mag_limbs(&[mag as u64, (mag >> 64) as u64], v < 0)
    }

    /// Builds from an unsigned 128-bit value.
    #[inline]
    pub(crate) const fn from_u128(v: u128) -> Self {
        Self::from_mag_limbs(&[v as u64, (v >> 64) as u64], false)
    }

    /// Builds directly from the little-endian u64 limb array. Alias of
    /// [`Self::from_limbs`] under the historic `from_limbs_le` public name.
    #[inline]
    pub const fn from_limbs_le(limbs: [u64; N]) -> Self {
        Self { limbs }
    }

    /// Returns the little-endian u64 limbs by value. Symmetric with
    /// [`Self::from_limbs_le`].
    #[inline]
    pub const fn limbs_le(self) -> [u64; N] {
        self.limbs
    }

    /// `self · (n as Self)` with the sign of `self`, panicking on
    /// overflow (the default-form contract). Computes the n-by-1-word
    /// product (the same limb recurrence as `mul_schoolbook_into`) and
    /// rejects a non-zero top carry.
    #[inline]
    pub fn mul_u64(self, n: u64) -> Self {
        let mag = *self.unsigned_abs().as_limbs();
        let mut prod = [0u64; N];
        let mut carry: u64 = 0;
        let mut i = 0;
        while i < N {
            let p = (mag[i] as u128) * (n as u128) + (carry as u128);
            prod[i] = p as u64;
            carry = (p >> 64) as u64;
            i += 1;
        }
        if carry != 0 {
            panic!("Int: mul overflow");
        }
        let negative = self.is_negative();
        let r = Self::from_mag_limbs(&prod, negative);
        // `from_mag_limbs` only mishandles the `mag == 2^(BITS-1)` edge:
        // legal as MIN for `negative`, overflow otherwise.
        if !r.is_zero() && r.is_negative() != negative {
            panic!("Int: mul overflow");
        }
        r
    }

    /// Exact `i128` value, or `None` if it does not fit.
    pub fn to_i128_checked(self) -> Option<i128> {
        let negative = self.is_negative();
        let mag = *self.unsigned_abs().as_limbs();
        // First two u64 limbs make up the low u128; the rest must be 0.
        let mut i = 2;
        while i < N {
            if mag[i] != 0 {
                return None;
            }
            i += 1;
        }
        let lo = if N > 0 { mag[0] as u128 } else { 0 };
        let hi = if N > 1 { mag[1] as u128 } else { 0 };
        let lo_u128 = lo | (hi << 64);
        if negative {
            if lo_u128 <= (i128::MAX as u128) + 1 {
                Some((lo_u128 as i128).wrapping_neg())
            } else {
                None
            }
        } else if lo_u128 <= i128::MAX as u128 {
            Some(lo_u128 as i128)
        } else {
            None
        }
    }

    /// Exact `u128` value, or `None` if negative / too large.
    pub fn to_u128_checked(self) -> Option<u128> {
        if self.is_negative() {
            return None;
        }
        let mut i = 2;
        while i < N {
            if self.limbs[i] != 0 {
                return None;
            }
            i += 1;
        }
        let lo = if N > 0 { self.limbs[0] as u128 } else { 0 };
        let hi = if N > 1 { self.limbs[1] as u128 } else { 0 };
        Some(lo | (hi << 64))
    }

    /// Approximate `f64` value of `self` (lossy above 53 significant
    /// bits).
    pub fn to_f64(self) -> f64 {
        let mag = *self.unsigned_abs().as_limbs();
        let radix: f64 = 18_446_744_073_709_551_616.0; // 2^64
        let mut acc = 0.0f64;
        let mut i = N;
        while i > 0 {
            i -= 1;
            acc = acc * radix + mag[i] as f64;
        }
        if self.is_negative() { -acc } else { acc }
    }

    /// Approximate `f32` value of `self` (round-to-nearest; lossy above
    /// 24 significant bits). Routes through the `f64` accumulation to keep
    /// one summation path.
    pub fn to_f32(self) -> f32 {
        self.to_f64() as f32
    }

    /// Exact conversion from an `f64`, or `None` when `v` is NaN, ±inf,
    /// has a fractional part, or lies outside the `Int<N>` range.
    ///
    /// `const`: classification and decomposition go through the const
    /// `f64::to_bits` plus integer/bit ops only — never the non-const
    /// `is_finite` / `fract` / float-`as` paths.
    pub(crate) const fn try_from_f64(v: f64) -> Option<Self> {
        let bits = v.to_bits();
        let negative = (bits >> 63) & 1 == 1;
        let exp = ((bits >> 52) & 0x7ff) as i32;
        let mant = bits & 0x000f_ffff_ffff_ffff;
        if exp == 0x7ff {
            // NaN / ±inf.
            return None;
        }
        if exp == 0 {
            // ±0 is exact zero; a subnormal is a non-zero |v| < 1, i.e.
            // never an integer.
            return if mant == 0 { Some(Self::ZERO) } else { None };
        }
        let significand = (1u64 << 52) | mant; // 53-bit normalized value
        let shift = exp - 1075; // (exp - 1023) - 52
        Self::from_significand_shift(significand, shift, negative)
    }

    /// Exact conversion from an `f32`, or `None` on NaN, ±inf, a
    /// fractional part, or out-of-range. Decomposes via the const
    /// `f32::to_bits` (8-bit exponent, 23-bit mantissa, bias 127, 24-bit
    /// significand) with integer/bit ops only — `const` for the same
    /// reason as [`Self::try_from_f64`].
    pub(crate) const fn try_from_f32(v: f32) -> Option<Self> {
        let bits = v.to_bits();
        let negative = (bits >> 31) & 1 == 1;
        let exp = ((bits >> 23) & 0xff) as i32;
        let mant = (bits & 0x007f_ffff) as u64;
        if exp == 0xff {
            // NaN / ±inf.
            return None;
        }
        if exp == 0 {
            return if mant == 0 { Some(Self::ZERO) } else { None };
        }
        let significand = (1u64 << 23) | mant; // 24-bit normalized value
        let shift = exp - 150; // (exp - 127) - 23
        Self::from_significand_shift(significand, shift, negative)
    }

    /// Builds `Int<N>` from `(-1)^sign * significand * 2^shift`, where
    /// `significand` fits in 64 bits. Returns `None` when the value has a
    /// fractional part (`shift < 0` with low bits set) or does not fit the
    /// signed `Int<N>` range. Pure const integer/bit arithmetic — no float
    /// ops — so both float entry points are `const`.
    const fn from_significand_shift(significand: u64, shift: i32, negative: bool) -> Option<Self> {
        if shift < 0 {
            let s = (-shift) as u32;
            if s >= 64 {
                // Whole value is fractional (|v| < 1, non-zero) — not an
                // integer.
                return None;
            }
            if significand & ((1u64 << s) - 1) != 0 {
                // Fractional bits set — not an integer.
                return None;
            }
            let mag = significand >> s; // integral, fits a single limb
            let built = Self::from_mag_limbs(&[mag], negative);
            Self::accept_signed(built, negative)
        } else {
            // Place `significand` left-shifted by `shift` into an N-limb
            // magnitude, rejecting any bit that lands beyond limb N-1.
            let s = shift as u32;
            let limb_off = (s / 64) as usize;
            let bit_off = s % 64;
            let mut mag = [0u64; N];
            // Low chunk into limb `limb_off`; carry into the next limb.
            let lo = significand << bit_off;
            // The part of `significand` pushed past this limb's top.
            let hi = if bit_off == 0 {
                0
            } else {
                significand >> (64 - bit_off)
            };
            if limb_off < N {
                mag[limb_off] = lo;
            } else if lo != 0 {
                return None;
            }
            if hi != 0 {
                if limb_off + 1 < N {
                    mag[limb_off + 1] = hi;
                } else {
                    return None;
                }
            }
            let built = Self::from_mag_limbs(&mag, negative);
            Self::accept_signed(built, negative)
        }
    }

    /// Sign-overflow gate shared by the float builders: a zero is always
    /// fine; otherwise the built sign must match the requested one, which
    /// rejects a positive magnitude that wrapped into the sign bit while
    /// still admitting the exact `MIN` edge (magnitude `2^(bits-1)` with
    /// the sign set, which `wrapping_neg` reproduces as itself).
    #[inline]
    const fn accept_signed(built: Self, negative: bool) -> Option<Self> {
        // Inherent const zero-check (the `BigInt::is_zero` trait method
        // name-resolution would otherwise pick is not const).
        if is_zero_fixed(&built.limbs) {
            Some(built)
        } else if built.is_negative() != negative {
            None
        } else {
            Some(built)
        }
    }

    /// Builds from an `f64`, truncating toward zero. Saturates to
    /// `MIN` / `MAX` on out-of-range; non-finite maps to `ZERO`.
    pub fn from_f64(v: f64) -> Self {
        if !v.is_finite() {
            return Self::ZERO;
        }
        let negative = v < 0.0;
        let mut m = if negative { -v } else { v };
        let radix: f64 = 18_446_744_073_709_551_616.0; // 2^64
        let mut limbs = [0u64; N];
        let mut i = 0;
        while m >= 1.0 && i < N {
            let rem = m % radix;
            limbs[i] = rem as u64;
            m = (m - rem) / radix;
            i += 1;
        }
        if m >= 1.0 {
            return if negative {
                Self::min_value()
            } else {
                Self::max_value()
            };
        }
        Self::from_mag_limbs(&limbs, negative)
    }

    /// Parses a signed decimal magnitude from `s`. Accepts an optional
    /// leading `-`, then ASCII digits. Only `radix == 10` is supported;
    /// any other value returns `Err(())`.
    pub const fn from_str_radix(s: &str, radix: u32) -> Result<Self, ()> {
        if radix != 10 {
            return Err(());
        }
        let bytes = s.as_bytes();
        let (negative, start): (bool, usize) = if !bytes.is_empty() && bytes[0] == b'-' {
            (true, 1)
        } else {
            (false, 0)
        };
        if start >= bytes.len() {
            return Err(());
        }
        // acc = acc * 10 + d per digit, truncating into N limbs — the
        // same Horner recurrence the macro runs through `mul_schoolbook`
        // + `add_assign`, but the low-N-limb multiply-by-10 is
        // folded into one n-by-1-word pass (no `2*N` staging buffer).
        let mut acc = [0u64; N];
        let mut k = start;
        while k < bytes.len() {
            let ch = bytes[k];
            if ch < b'0' || ch > b'9' {
                return Err(());
            }
            let d = (ch - b'0') as u64;
            let mut carry: u64 = d;
            let mut j = 0;
            while j < N {
                let p = (acc[j] as u128) * 10u128 + (carry as u128);
                acc[j] = p as u64;
                carry = (p >> 64) as u64;
                j += 1;
            }
            k += 1;
        }
        Ok(Self::from_mag_limbs(&acc, negative))
    }

    // ── Named-type API parity (the `IntXXXX` alias surface) ─────
    //
    // The methods below complete the inherent surface the `IntXXXX = Int<N>`
    // type aliases expose, so every named-type call site keeps resolving.

    /// Integer power: `self^exp` (wrapping on overflow). Alias of
    /// [`Self::wrapping_pow`] under the `pow` name.
    #[inline]
    pub const fn pow(self, exp: u32) -> Self {
        self.wrapping_pow(exp)
    }

    /// Integer square root of the magnitude (`floor(sqrt(|self|))`),
    /// returned non-negative. Delegates to the unsigned sibling which
    /// routes through `isqrt_dispatch`.
    #[inline]
    pub fn isqrt(self) -> Self {
        Self::from_limbs(*self.unsigned_abs().isqrt().as_limbs())
    }

    /// Integer square: `self²` modulo `2^BITS`. Routes through the sqr
    /// policy (`sqr_dispatch`) on the unsigned reinterpretation, then
    /// reinterprets back as signed. Equivalent to `wrapping_sqr`.
    #[inline]
    pub fn sqr(self) -> Self {
        self.wrapping_sqr()
    }

    /// Integer cube: `self³` modulo `2^BITS`. Routes through the cube
    /// policy (`cube_dispatch`) on the unsigned reinterpretation, then
    /// reinterprets back as signed. Equivalent to `wrapping_cube`.
    #[inline]
    pub fn cube(self) -> Self {
        self.wrapping_cube()
    }

    /// Integer cube root of the magnitude (`floor(cbrt(|self|))`),
    /// returned non-negative. Delegates to the unsigned sibling which
    /// routes through `icbrt_dispatch`.
    #[inline]
    pub fn icbrt(self) -> Self {
        Self::from_limbs(*self.unsigned_abs().icbrt().as_limbs())
    }

    /// Integer hypotenuse: `round(sqrt(self^2 + other^2))` without
    /// intermediate overflow of the radicand. Routes through the hypot
    /// policy (`hypot_dispatch`): the radicand `self^2 + other^2` is formed
    /// in a wider limb scratch buffer and the floor root is taken via the
    /// integer slice `isqrt`, then a single round step under `mode` lands
    /// the result. Returns [`None`] when the rounded result does not fit
    /// the signed range of `Int<N>` (true overflow). The sign of each
    /// operand drops out of the squaring; `hypot(0, 0) = 0` and
    /// `hypot(0, x) = |x|`.
    #[inline]
    #[must_use]
    pub(crate) fn hypot(
        self,
        other: Self,
        mode: crate::support::rounding::RoundingMode,
    ) -> Option<Self>
    where
        crate::int::types::compute_limbs::Limbs<N>: crate::int::types::compute_limbs::ComputeLimbs,
    {
        hypot_dispatch::<N>(self, other, mode)
    }

    /// Sum of squares: `self^2 + other^2`, the sqrt-free magnitude
    /// primitive. Routes through the sum-of-squares policy
    /// (`sum_sq_dispatch`): the radicand is formed in a wider limb scratch
    /// buffer (the same former [`Self::hypot`] roots), so there is no
    /// intermediate truncation. Returns [`None`] when `self^2 + other^2`
    /// exceeds the signed range of `Int<N>` (true overflow). The sign of
    /// each operand drops out of the squaring, so the result is always
    /// non-negative. Comparing two `sum_sq` values orders the same as
    /// comparing the corresponding [`Self::hypot`] values (the root is
    /// monotonic), which is why a distance comparison can skip the root.
    #[inline]
    #[must_use]
    pub(crate) fn sum_sq(self, other: Self) -> Option<Self>
    where
        crate::int::types::compute_limbs::Limbs<N>: crate::int::types::compute_limbs::ComputeLimbs,
    {
        sum_sq_dispatch::<N>(self, other)
    }

    /// Reinterprets the bit pattern as the unsigned sibling.
    #[inline]
    pub const fn cast_unsigned(self) -> Uint<N> {
        Uint::from_limbs(self.limbs)
    }

    /// Approximate `f64` value. Alias of [`Self::to_f64`], matching the
    /// macro's `as_f64` name.
    #[inline]
    pub fn as_f64(self) -> f64 {
        self.to_f64()
    }

    /// Count of set bits across the two's-complement representation,
    /// matching the primitive `iN::count_ones` contract — the limbs are
    /// read as stored, so negative values count their sign-extended
    /// one-bits. `(-1).count_ones() == BITS` (all-ones), and
    /// `MIN.count_ones() == 1` (only the sign bit). This is a
    /// two's-complement count, not a magnitude count.
    #[inline]
    pub const fn count_ones(self) -> u32 {
        let mut total = 0;
        let mut i = 0;
        while i < N {
            total += self.limbs[i].count_ones();
            i += 1;
        }
        total
    }

    /// Count of clear bits across the two's-complement representation,
    /// matching the primitive `iN::count_zeros` contract
    /// (`BITS - count_ones`). `(-1).count_zeros() == 0` and
    /// `MIN.count_zeros() == BITS - 1`.
    #[inline]
    pub const fn count_zeros(self) -> u32 {
        Self::BITS - self.count_ones()
    }

    /// Number of trailing zero bits of the two's-complement
    /// representation, matching the primitive `iN::trailing_zeros`
    /// contract; `BITS` for zero. `MIN` has only its sign bit set, so
    /// `MIN.trailing_zeros() == BITS - 1`. This reads the stored limbs,
    /// not the magnitude — contrast [`Self::bit_length`].
    #[inline]
    pub const fn trailing_zeros(self) -> u32 {
        let mut i = 0;
        while i < N {
            if self.limbs[i] != 0 {
                return i as u32 * 64 + self.limbs[i].trailing_zeros();
            }
            i += 1;
        }
        Self::BITS
    }

    /// Checked negation: `None` exactly at `MIN` (whose negation
    /// overflows the signed range).
    #[inline]
    pub const fn checked_neg(self) -> Option<Self> {
        if eq_dispatch(self, Self::MIN) {
            None
        } else {
            Some(self.wrapping_neg())
        }
    }

    /// Checked division: `None` on a zero divisor.
    #[inline]
    pub const fn checked_div(self, rhs: Self) -> Option<Self> {
        if is_zero_fixed(&rhs.limbs) {
            None
        } else {
            Some(self.wrapping_div(rhs))
        }
    }

    /// Checked remainder: `None` on a zero divisor, and `None` for the
    /// `MIN % -1` overflow case (the paired division `MIN / -1` overflows
    /// the signed range), matching the primitive integer contract.
    #[inline]
    pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
        if is_zero_fixed(&rhs.limbs) || self.is_min_neg_one(rhs) {
            // Zero divisor, or the `MIN % -1` overflow case (its paired
            // `MIN / -1` division overflows the signed range).
            None
        } else {
            Some(self.wrapping_rem(rhs))
        }
    }

    /// `true` when `self == MIN` and `rhs == -1` — the remainder/division
    /// overflow case where `MIN / -1` exceeds the signed range.
    #[inline]
    const fn is_min_neg_one(self, rhs: Self) -> bool {
        cmp_fixed(&self.limbs, &Self::MIN.limbs) == 0
            && cmp_fixed(&rhs.wrapping_neg().limbs, &Self::ONE.limbs) == 0
    }

    /// Euclidean division: the quotient that leaves a non-negative
    /// remainder.
    #[inline]
    pub const fn div_euclid(self, rhs: Self) -> Self {
        let q = self.wrapping_div(rhs);
        let r = self.wrapping_rem(rhs);
        if r.is_negative() {
            if rhs.is_negative() {
                q.wrapping_add(Self::ONE)
            } else {
                q.wrapping_sub(Self::ONE)
            }
        } else {
            q
        }
    }

    /// Euclidean remainder — always non-negative.
    #[inline]
    pub const fn rem_euclid(self, rhs: Self) -> Self {
        let r = self.wrapping_rem(rhs);
        if r.is_negative() {
            r.wrapping_add(rhs.abs())
        } else {
            r
        }
    }

    /// Wrapping addition paired with the two's-complement overflow flag.
    #[inline]
    pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
        let r = self.wrapping_add(rhs);
        let sa = self.is_negative();
        let sb = rhs.is_negative();
        let sr = r.is_negative();
        (r, sa == sb && sr != sa)
    }

    /// Wrapping subtraction paired with the two's-complement overflow
    /// flag.
    #[inline]
    pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
        let r = self.wrapping_sub(rhs);
        let sa = self.is_negative();
        let sb = rhs.is_negative();
        let sr = r.is_negative();
        (r, sa != sb && sr != sa)
    }

    /// Wrapping negation paired with the overflow flag (`true` only at
    /// `MIN`).
    #[inline]
    pub const fn overflowing_neg(self) -> (Self, bool) {
        let ov = cmp_fixed(&self.limbs, &Self::MIN.limbs) == 0;
        (self.wrapping_neg(), ov)
    }

    /// Wrapping remainder paired with an overflow flag. The flag is `true`
    /// only for `MIN % -1` (whose paired division overflows the signed
    /// range), in which case the remainder is `0`; otherwise `false`.
    #[inline]
    pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
        if self.is_min_neg_one(rhs) {
            (Self::ZERO, true)
        } else {
            (self.wrapping_rem(rhs), false)
        }
    }

    /// Saturating addition: clamps to `MIN` / `MAX` on overflow.
    #[inline]
    pub const fn saturating_add(self, rhs: Self) -> Self {
        match self.checked_add(rhs) {
            Some(v) => v,
            None => {
                if self.is_negative() {
                    Self::MIN
                } else {
                    Self::MAX
                }
            }
        }
    }

    /// Saturating subtraction: clamps to `MIN` / `MAX` on overflow.
    #[inline]
    pub const fn saturating_sub(self, rhs: Self) -> Self {
        match self.checked_sub(rhs) {
            Some(v) => v,
            None => {
                if self.is_negative() {
                    Self::MIN
                } else {
                    Self::MAX
                }
            }
        }
    }

    /// Saturating negation: `MIN` saturates to `MAX`.
    #[inline]
    pub const fn saturating_neg(self) -> Self {
        match self.checked_neg() {
            Some(v) => v,
            None => Self::MAX,
        }
    }

    /// Rotates the bits left by `n` (modulo `BITS`).
    #[inline]
    pub fn rotate_left(self, n: u32) -> Self {
        let bits = Self::BITS;
        let n = n % bits;
        if n == 0 {
            return self;
        }
        let u = self.cast_unsigned();
        Self::from_limbs(((u.shl(n)) | (u.shr(bits - n))).limbs)
    }

    /// Rotates the bits right by `n` (modulo `BITS`).
    #[inline]
    pub fn rotate_right(self, n: u32) -> Self {
        self.rotate_left(Self::BITS - (n % Self::BITS))
    }

    /// Truncating cast to `u128` (low 128 magnitude bits, sign ignored).
    /// **Truncating** — discards any higher limbs and the sign; use
    /// [`Self::to_u128_checked`] (or `TryFrom`) when the value may not
    /// fit or may be negative.
    #[inline]
    pub(crate) const fn as_u128(self) -> u128 {
        let mag = *self.unsigned_abs().as_limbs();
        let lo = if N > 0 { mag[0] as u128 } else { 0 };
        let hi = if N > 1 { mag[1] as u128 } else { 0 };
        lo | (hi << 64)
    }

    /// Truncating cast to `i128` (low 128 bits, sign-applied).
    /// **Truncating** — for `Int<3+>` any value outside the `i128` range
    /// loses its high limbs; use [`Self::to_i128_checked`] (or `TryFrom`)
    /// when the value may not fit.
    #[inline]
    pub(crate) const fn as_i128(self) -> i128 {
        // Narrow non-limb fast path (const-folds per monomorphisation): for
        // N<=2 the limbs ARE the i64/i128 two's-complement value, so skip the
        // `unsigned_abs`/`wrapping_neg` sign-magnitude round trip (which costs
        // two `neg_dispatch` calls on a negative operand). Always fits i128
        // for N<=2; bit-identical to the magnitude path below.
        if N <= 2 {
            if N == 1 {
                return (self.limbs[0] as i64) as i128;
            }
            let lo = self.limbs[0] as u128;
            let hi = self.limbs[1] as u128;
            return (lo | (hi << 64)) as i128;
        }
        let mag = *self.unsigned_abs().as_limbs();
        let lo = if N > 0 { mag[0] as u128 } else { 0 };
        let hi = if N > 1 { mag[1] as u128 } else { 0 };
        let combined = lo | (hi << 64);
        if self.is_negative() {
            (combined as i128).wrapping_neg()
        } else {
            combined as i128
        }
    }

    /// Widening / narrowing cast to any other [`BigInt`] type, via the
    /// shared magnitude + sign bridge. Matches the macro's
    /// `resize::<T>()` signature so the decimal-tier code that calls
    /// `storage.resize::<$Wider>()` resolves against `Int<N>`.
    #[inline]
    pub(crate) fn resize<T: crate::int::types::traits::BigInt>(self) -> T {
        use crate::int::types::traits::BigInt as _;
        self.resize_to::<T>()
    }

    /// Truncating division toward zero. Panics on a zero divisor.
    /// Matches the macro's `wrapping_div` (single-limb-aware
    /// `div_rem`, not the dispatching `div_rem`).
    #[inline]
    pub const fn wrapping_div(self, rhs: Self) -> Self {
        if is_zero_fixed(&rhs.limbs) {
            panic!("attempt to divide by zero");
        }
        let negative = self.is_negative() ^ rhs.is_negative();
        let mut q = [0u64; N];
        let mut r = [0u64; N];
        div_rem(
            self.unsigned_abs().as_limbs(),
            rhs.unsigned_abs().as_limbs(),
            &mut q,
            &mut r,
        );
        Self::from_mag_limbs(&q, negative)
    }

    /// Truncating remainder; result carries the sign of `self`. Panics
    /// on a zero divisor. Matches the macro's `wrapping_rem`.
    #[inline]
    pub const fn wrapping_rem(self, rhs: Self) -> Self {
        if is_zero_fixed(&rhs.limbs) {
            panic!("attempt to calculate the remainder with a divisor of zero");
        }
        let mut q = [0u64; N];
        let mut r = [0u64; N];
        div_rem(
            self.unsigned_abs().as_limbs(),
            rhs.unsigned_abs().as_limbs(),
            &mut q,
            &mut r,
        );
        Self::from_mag_limbs(&r, self.is_negative())
    }

    /// Full `self · rhs` product widened into a `W: BigInt`, in one
    /// step (no double trip through the magnitude staging buffer). Used
    /// by the wide-tier `Mul` operator to compute
    /// `Storage * Storage → Wider`. Matches the macro's `widen_mul`.
    #[inline]
    pub(crate) fn widen_mul<W>(self, rhs: Self) -> W
    where
        W: crate::int::types::traits::BigInt,
        W::Scratch: crate::int::types::compute_limbs::ComputeLimbs,
        crate::int::types::compute_limbs::Limbs<N>: crate::int::types::compute_limbs::ComputeLimbs,
    {
        use crate::int::types::compute_limbs::{ComputeLimbs, Limbs};
        let negative = self.is_negative() ^ rhs.is_negative();
        let a = *self.unsigned_abs().as_limbs();
        let b = *rhs.unsigned_abs().as_limbs();
        // Full product spans 2·N u64 limbs — sized exactly by the source's
        // `ComputeLimbs::double_buffered_u64()` (no build-max blanket). Route through
        // the equal-length multiply dispatcher: both operands are `[u64; N]`,
        // so this is the single site every wide tier's full product flows
        // through. The dispatcher base-cases to schoolbook below
        // `KARATSUBA_THRESHOLD_U64` (every shipped tier) and engages the
        // non-allocating Karatsuba kernel at or above it.
        let mut prod_buf = <Limbs<N> as ComputeLimbs>::double_buffered_u64();
        let prod = prod_buf.as_mut();
        mul_fast::<N>(&a, &b, &mut prod[..2 * N]);
        // Pack the `2·N`-u64 product into `N` u128 limbs for the kept
        // `BigInt::from_mag_sign_u128` bridge. The result `W` holds the
        // product, so its scratch carrier's `single_u128()` buffer (`≥ N`)
        // sizes the packed magnitude exactly.
        let mut u128_buf = <W::Scratch as ComputeLimbs>::single_u128();
        let u128_prod = u128_buf.as_mut();
        let mut i = 0;
        while i < N {
            u128_prod[i] = (prod[2 * i] as u128) | ((prod[2 * i + 1] as u128) << 64);
            i += 1;
        }
        W::from_mag_sign_u128(&u128_prod[..N], negative)
    }
}

impl<const N: usize> Int<N> {
    /// Const cross-width signed comparison `Int<N>` vs `Int<M>`, returning
    /// `core::cmp::Ordering`. No widening copy is made: the sign is
    /// compared first (a negative value is always less than a non-negative
    /// one); when the signs agree the magnitudes are compared
    /// length-aware via [`cmp_cross`] over the `unsigned_abs`
    /// limbs (the longer magnitude's surplus high limbs must be zero for
    /// equality, else it is the larger). For two negatives the larger
    /// magnitude is the smaller value, so the magnitude order is flipped.
    #[inline]
    pub(crate) const fn cmp_cross<const M: usize>(self, other: Int<M>) -> Ordering {
        let sn = self.is_negative();
        let so = other.is_negative();
        if sn && !so {
            return Ordering::Less;
        }
        if !sn && so {
            return Ordering::Greater;
        }
        // Same sign: compare magnitudes length-aware.
        let a = self.unsigned_abs();
        let b = other.unsigned_abs();
        let c = cmp_cross(a.as_limbs(), b.as_limbs());
        // For two negatives the larger magnitude is the smaller value.
        let c = if sn { -c } else { c };
        if c < 0 {
            Ordering::Less
        } else if c > 0 {
            Ordering::Greater
        } else {
            Ordering::Equal
        }
    }
}

impl<const N: usize> Int<N> {
    /// Const cross-width, cross-*scale* signed comparison: compares
    /// `self` against `other · 10^scale_diff`, returning
    /// [`core::cmp::Ordering`]. Used by the decimal layer to compare two
    /// `D<Int<_>, S>` values at *different* `SCALE`s without materialising
    /// a widened product (no `generic_const_exprs`, no computed type).
    ///
    /// # Approach (scale-down-with-remainder, overflow-free)
    ///
    /// Rather than scale `other` *up* by `10^scale_diff` (which can
    /// overflow `M`'s width), this scales `self` *down* by the same
    /// factor — division can never overflow. With magnitudes
    /// `|self| = q · 10^scale_diff + r` (`0 ≤ r < 10^scale_diff`):
    ///
    /// * compare the quotient `q` against `|other|`;
    /// * on a magnitude tie, a nonzero remainder `r` means `|self|` is the
    ///   larger magnitude (it carries extra low digits `other` lacks).
    ///
    /// Signs are resolved first (a negative is always less than a
    /// non-negative); for two negatives the larger magnitude is the
    /// smaller value, so the magnitude order is flipped. `scale_diff == 0`
    /// degenerates to a plain cross-width magnitude compare.
    ///
    /// `const`, `core`-only, no allocation: the `10^scale_diff` divisor and
    /// the quotient/remainder are built in fixed staging buffers (the same
    /// `max_n_limbs(4)` width the wide tiers stage products through — `288`
    /// limbs at xx-wide, scaling down with `MAX_WORK_N`), and the division
    /// reuses [`div_rem`].
    pub(crate) const fn cmp_cross_scaled<const M: usize>(
        self,
        other: Int<M>,
        scale_diff: u32,
    ) -> Ordering {
        let sn = self.is_negative();
        let so = other.is_negative();
        if sn && !so {
            return Ordering::Less;
        }
        if !sn && so {
            return Ordering::Greater;
        }

        // Same sign (or one/both zero): compare magnitudes. `mag_cmp` is
        // the i32 sign of `|self|` − `|other| · 10^scale_diff`.
        let a = self.unsigned_abs();
        let b = other.unsigned_abs();

        let mag_cmp = if scale_diff == 0 {
            cmp_cross(a.as_limbs(), b.as_limbs())
        } else {
            // Build the divisor 10^scale_diff in a fixed staging buffer.
            // `max_n_limbs(4)` (= 288 at xx-wide) is the wide-tier staging
            // width, tracking MAX_WORK_N so a narrower build does not carry
            // the widest tier's buffer; it covers every shipped width/scale.
            let mut pow = [0u64; max_n_limbs(4)];
            pow[0] = 1;
            let mut e = 0;
            while e < scale_diff {
                // pow *= 10, propagating carry across limbs.
                let mut carry: u128 = 0;
                let mut i = 0;
                while i < pow.len() {
                    let prod = (pow[i] as u128) * 10u128 + carry;
                    pow[i] = prod as u64;
                    carry = prod >> 64;
                    i += 1;
                }
                e += 1;
            }

            // |self| = q · 10^scale_diff + r.
            let mut q = [0u64; max_n_limbs(4)];
            let mut r = [0u64; max_n_limbs(4)];
            div_rem(a.as_limbs(), &pow, &mut q, &mut r);

            // Compare quotient against |other|; tie-break on remainder.
            let c = cmp_cross(&q, b.as_limbs());
            if c != 0 {
                c
            } else {
                // Quotients equal: a nonzero remainder makes |self| larger.
                let mut rk = 0;
                let mut nz = false;
                while rk < r.len() {
                    if r[rk] != 0 {
                        nz = true;
                        break;
                    }
                    rk += 1;
                }
                if nz {
                    1
                } else {
                    0
                }
            }
        };

        // For two negatives, the larger magnitude is the smaller value.
        let c = if sn { -mag_cmp } else { mag_cmp };
        if c < 0 {
            Ordering::Less
        } else if c > 0 {
            Ordering::Greater
        } else {
            Ordering::Equal
        }
    }
}

impl<const N: usize> Int<N> {
    /// Const EXACT comparison of the decimal value `self / 10^scale`
    /// against the exact dyadic value of an `f64`, returning
    /// [`core::cmp::Ordering`]. This is *value* equality, NOT a lossy
    /// round-trip: an `f64` has an exact rational value `m · 2^e`, and
    /// this compares `self / 10^scale` against it by cross-multiplying to
    /// integers (overflow-free in fixed staging buffers, riding
    /// [`cmp_cross`]).
    ///
    /// `value` MUST be finite — the caller rejects `NaN` / `±inf` before
    /// calling (those compare unequal to every decimal).
    ///
    /// # Approach
    ///
    /// Decompose `value = (-1)^sign · m · 2^e` from its IEEE-754 bits
    /// (`m` the 53-bit-or-subnormal integer mantissa, `e` the unbiased
    /// power-of-two exponent). The magnitudes satisfy
    /// `|self| / 10^scale  ==  m · 2^e` iff:
    ///
    /// * `e ≥ 0`:  `|self|          ==  m · 2^e · 10^scale`
    /// * `e < 0`:  `|self| · 2^(−e)  ==  m · 10^scale`
    ///
    /// both sides being non-negative integers. Signs are resolved first
    /// (a negative is always less than a non-negative; for two negatives
    /// the magnitude order is flipped). `m == 0` is the float zero.
    pub(crate) const fn cmp_f64_exact(self, scale: u32, value: f64) -> Ordering {
        let bits = value.to_bits();
        let fsign = (bits >> 63) != 0;
        let exp_field = ((bits >> 52) & 0x7ff) as i32;
        let frac = bits & 0x000f_ffff_ffff_ffff;
        // Mantissa `m` and unbiased power-of-two exponent `e`.
        let (m, e): (u64, i32) = if exp_field == 0 {
            // Subnormal (or zero): no implicit leading bit.
            (frac, -1074)
        } else {
            (frac | 0x0010_0000_0000_0000, exp_field - 1075)
        };

        let sn = self.is_negative();
        let fzero = m == 0;
        // Resolve signs. The float's zero has no sign for ordering.
        if fzero {
            // value == 0: compare against self's sign / zeroness.
            let self_limbs = self.as_limbs();
            let mut nz = false;
            let mut k = 0;
            while k < self_limbs.len() {
                if self_limbs[k] != 0 {
                    nz = true;
                    break;
                }
                k += 1;
            }
            if !nz {
                return Ordering::Equal;
            }
            return if sn { Ordering::Less } else { Ordering::Greater };
        }
        if sn && !fsign {
            return Ordering::Less;
        }
        if !sn && fsign {
            return Ordering::Greater;
        }

        // Same sign, both nonzero: compare magnitudes.
        // Build the two non-negative integer sides in fixed staging
        // buffers (288 u64 limbs covers every shipped width / scale /
        // f64 exponent: D307 magnitude ≤ 16 limbs, 10^scale ≤ 16 limbs,
        // 2^1074 ≤ 17 limbs — products stay well under 288).
        let a = self.unsigned_abs();
        let a_limbs = a.as_limbs();

        // 10^scale in a buffer.
        let mut pow10 = [0u64; 288];
        pow10[0] = 1;
        let mut pe = 0;
        while pe < scale {
            let mut carry: u128 = 0;
            let mut i = 0;
            while i < pow10.len() {
                let prod = (pow10[i] as u128) * 10u128 + carry;
                pow10[i] = prod as u64;
                carry = prod >> 64;
                i += 1;
            }
            pe += 1;
        }

        let m_limbs = [m];

        let mut lhs = [0u64; 288];
        let mut rhs = [0u64; 288];

        if e >= 0 {
            // lhs = |self|; rhs = m · 2^e · 10^scale.
            let mut i = 0;
            while i < a_limbs.len() {
                lhs[i] = a_limbs[i];
                i += 1;
            }
            // tmp = m · 10^scale
            let mut tmp = [0u64; 288];
            mul_schoolbook(&m_limbs, &pow10, &mut tmp);
            // rhs = tmp << e
            shl(&tmp, e as u32, &mut rhs);
        } else {
            // lhs = |self| · 2^(−e); rhs = m · 10^scale.
            shl(a_limbs, (-e) as u32, &mut lhs);
            mul_schoolbook(&m_limbs, &pow10, &mut rhs);
        }

        let mag_cmp = cmp_cross(&lhs, &rhs);
        // For two negatives the larger magnitude is the smaller value.
        let c = if sn { -mag_cmp } else { mag_cmp };
        if c < 0 {
            Ordering::Less
        } else if c > 0 {
            Ordering::Greater
        } else {
            Ordering::Equal
        }
    }
}

// One generic comparison surface across widths. The `N == M` case is
// covered here too, so `Int<N>` carries no separate same-width
// `PartialEq` / `PartialOrd` / `Ord` impl (a derived or hand-written
// same-width comparison would collide — E0119). `Eq` is still derived:
// it only requires the `PartialEq<Self>` this generic impl provides.
impl<const N: usize, const M: usize> PartialEq<Int<M>> for Int<N> {
    #[inline]
    fn eq(&self, other: &Int<M>) -> bool {
        self.cmp_cross(*other) == Ordering::Equal
    }
}

impl<const N: usize, const M: usize> PartialOrd<Int<M>> for Int<N> {
    #[inline]
    fn partial_cmp(&self, other: &Int<M>) -> Option<Ordering> {
        Some(self.cmp_cross(*other))
    }
}

// `i128` interop for the 128-bit storage `Int<2>` (D38's backend).
// `Int<2>` *is* an `i128`, so the comparison is the direct `as_i128`
// value — no widening round-trip. This lets `to_bits()` results compare
// against `i128` literals without an explicit conversion at the call
// site. Deliberately `Int<2>`-only: for wider tiers an `i128` comparison
// would be a lossy narrowing and is not offered.
// `Int<2>` *is* a 128-bit integer, so the conversion to `i128` is exact
// (the trait form of `as_i128`). Enables `i128::from(int2)` / `.into()`.
impl From<Int<2>> for i128 {
    #[inline]
    fn from(v: Int<2>) -> i128 {
        v.as_i128()
    }
}

impl PartialEq<i128> for Int<2> {
    #[inline]
    fn eq(&self, other: &i128) -> bool {
        self.as_i128() == *other
    }
}
impl PartialEq<Int<2>> for i128 {
    #[inline]
    fn eq(&self, other: &Int<2>) -> bool {
        *self == other.as_i128()
    }
}
impl PartialOrd<i128> for Int<2> {
    #[inline]
    fn partial_cmp(&self, other: &i128) -> Option<Ordering> {
        self.as_i128().partial_cmp(other)
    }
}
impl PartialOrd<Int<2>> for i128 {
    #[inline]
    fn partial_cmp(&self, other: &Int<2>) -> Option<Ordering> {
        self.partial_cmp(&other.as_i128())
    }
}

// `i64` interop for the 64-bit storage `Int<1>` (D18's backend). `Int<1>`
// *is* an `i64`, so the bridge is the direct value (its `as_i128()` is the
// sign-extended `i64`) — letting `to_bits()` results compare against `i64`
// literals without an explicit conversion. Deliberately `Int<1>`-only.
impl From<Int<1>> for i64 {
    #[inline]
    fn from(v: Int<1>) -> i64 {
        v.as_i128() as i64
    }
}
// `Int<1>` is 64-bit, so widening to `i128` is exact.
impl From<Int<1>> for i128 {
    #[inline]
    fn from(v: Int<1>) -> i128 {
        v.as_i128()
    }
}
impl PartialEq<i64> for Int<1> {
    #[inline]
    fn eq(&self, other: &i64) -> bool {
        self.as_i128() == *other as i128
    }
}
impl PartialEq<Int<1>> for i64 {
    #[inline]
    fn eq(&self, other: &Int<1>) -> bool {
        *self as i128 == other.as_i128()
    }
}
impl PartialOrd<i64> for Int<1> {
    #[inline]
    fn partial_cmp(&self, other: &i64) -> Option<Ordering> {
        self.as_i128().partial_cmp(&(i128::from(*other)))
    }
}
impl PartialOrd<Int<1>> for i64 {
    #[inline]
    fn partial_cmp(&self, other: &Int<1>) -> Option<Ordering> {
        i128::from(*self).partial_cmp(&other.as_i128())
    }
}

impl<const N: usize> Ord for Int<N> {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        // Same-width total order, routing through the cmp policy dispatcher
        // so the algorithm seam exists at a single point and the `const {
        // select::<N>() }` block folds the choice per monomorphisation.
        cmp_dispatch(*self, *other)
    }
}

impl<const N: usize> Add for Int<N> {
    type Output = Self;
    #[inline]
    fn add(self, rhs: Self) -> Self {
        add_dispatch(self, rhs)
    }
}

impl<const N: usize> Sub for Int<N> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: Self) -> Self {
        self.wrapping_sub(rhs)
    }
}

impl<const N: usize> Mul for Int<N> {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: Self) -> Self {
        self.wrapping_mul(rhs)
    }
}

impl<const N: usize> BitAnd for Int<N> {
    type Output = Self;
    #[inline]
    fn bitand(self, rhs: Self) -> Self {
        let mut out = [0u64; N];
        let mut i = 0;
        while i < N {
            out[i] = self.limbs[i] & rhs.limbs[i];
            i += 1;
        }
        Self { limbs: out }
    }
}

impl<const N: usize> BitOr for Int<N> {
    type Output = Self;
    #[inline]
    fn bitor(self, rhs: Self) -> Self {
        let mut out = [0u64; N];
        let mut i = 0;
        while i < N {
            out[i] = self.limbs[i] | rhs.limbs[i];
            i += 1;
        }
        Self { limbs: out }
    }
}

impl<const N: usize> BitXor for Int<N> {
    type Output = Self;
    #[inline]
    fn bitxor(self, rhs: Self) -> Self {
        let mut out = [0u64; N];
        let mut i = 0;
        while i < N {
            out[i] = self.limbs[i] ^ rhs.limbs[i];
            i += 1;
        }
        Self { limbs: out }
    }
}

impl<const N: usize> Not for Int<N> {
    type Output = Self;
    #[inline]
    fn not(self) -> Self {
        let mut out = [0u64; N];
        let mut i = 0;
        while i < N {
            out[i] = !self.limbs[i];
            i += 1;
        }
        Self { limbs: out }
    }
}

impl<const N: usize> Shl<u32> for Int<N> {
    type Output = Self;
    #[inline]
    fn shl(self, shift: u32) -> Self {
        let mut out = [0u64; N];
        shl_fixed(&self.limbs, shift, &mut out);
        Self { limbs: out }
    }
}

impl<const N: usize> Shr<u32> for Int<N> {
    type Output = Self;
    #[inline]
    fn shr(self, shift: u32) -> Self {
        // Arithmetic (sign-preserving) right shift — matches Rust's signed
        // `>>` and the prior macro `Int*` types the transcendental range
        // reduction relies on. Two's-complement: x >> s == !((!x) >> s) for x < 0.
        let neg = self.is_negative();
        let src = if neg { !self } else { self };
        let mut out = [0u64; N];
        shr_fixed(&src.limbs, shift, &mut out);
        let shifted = Self { limbs: out };
        if neg { !shifted } else { shifted }
    }
}

impl<const N: usize> Neg for Int<N> {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self {
        self.wrapping_neg()
    }
}

// ── Div / Rem ───────────────────────────────────────────────────────
//
// Truncating signed division / remainder, delegating to the dispatching
// `div_rem` so the operators share the macro types' divide algorithm
// (`div_rem_dispatch`: Knuth / Burnikel–Ziegler for multi-limb
// divisors). These supertraits are what `BigInt` requires.

impl<const N: usize> Div for Int<N> {
    type Output = Self;
    #[inline]
    fn div(self, rhs: Self) -> Self {
        self.div_rem(rhs).0
    }
}

impl<const N: usize> Rem for Int<N> {
    type Output = Self;
    #[inline]
    fn rem(self, rhs: Self) -> Self {
        rem_dispatch(self, rhs)
    }
}

// ── Display / FromStr ───────────────────────────────────────────────
//
// Delegate to the shared limb fmt / parse path, so the const-generic
// surface round-trips identically across every width.

impl<const N: usize> core::fmt::Display for Uint<N>
where
    crate::int::types::compute_limbs::Limbs<N>: crate::int::types::compute_limbs::ComputeLimbs,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // Exact per-`N` decimal output buffer (`20N + 2` bytes), drawn from
        // the `Limbs<N>` scratch carrier; the formatter writes the base-10
        // digits from its tail.
        let mut buf =
            <crate::int::types::compute_limbs::Limbs<N> as crate::int::types::compute_limbs::ComputeLimbs>::digit_formatting_limbs_u8();
        let s = fmt_into::<N>(&self.limbs, 10, true, buf.as_mut());
        f.pad_integral(true, "", s)
    }
}

impl<const N: usize> core::fmt::Display for Int<N>
where
    crate::int::types::compute_limbs::Limbs<N>: crate::int::types::compute_limbs::ComputeLimbs,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mag = *self.unsigned_abs().as_limbs();
        // Exact per-`N` decimal output buffer (`20N + 2` bytes): an `Int<N>`
        // is `64N` bits, so its base-10 form is `⌈64·N·log10(2)⌉ ≈ 19.27·N`
        // digits, comfortably within `20N + 2`. Drawn from the `Limbs<N>`
        // scratch carrier; the formatter writes the digits from its tail.
        let mut buf =
            <crate::int::types::compute_limbs::Limbs<N> as crate::int::types::compute_limbs::ComputeLimbs>::digit_formatting_limbs_u8();
        let s = fmt_into::<N>(&mag, 10, true, buf.as_mut());
        f.pad_integral(!self.is_negative() || self.is_zero(), "", s)
    }
}

impl<const N: usize> core::str::FromStr for Int<N> {
    type Err = ();
    #[inline]
    fn from_str(s: &str) -> Result<Self, ()> {
        Self::from_str_radix(s, 10)
    }
}

// ── Radix formatting (raw two's-complement bit pattern) ─────────────
//
// `LowerHex` / `UpperHex` / `Octal` / `Binary` print the raw limb bit
// pattern (not a signed magnitude), matching the macro `$S` impls. Each
// draws its output buffer exact-per-`N` from the `Limbs<N>` scratch carrier:
// hex (`16N` digits) fits the `digit_formatting_limbs_u8` decimal buffer
// (`20N + 2`); octal (`⌈64N/3⌉`) and binary (`64N`, one byte per bit) take
// the wider `bit_formatting_limbs_u8` buffer (`64N + 2`).

impl<const N: usize> core::fmt::LowerHex for Int<N>
where
    crate::int::types::compute_limbs::Limbs<N>: crate::int::types::compute_limbs::ComputeLimbs,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut buf =
            <crate::int::types::compute_limbs::Limbs<N> as crate::int::types::compute_limbs::ComputeLimbs>::digit_formatting_limbs_u8();
        let s = fmt_into::<N>(&self.limbs, 16, true, buf.as_mut());
        f.pad_integral(true, "0x", s)
    }
}

impl<const N: usize> core::fmt::UpperHex for Int<N>
where
    crate::int::types::compute_limbs::Limbs<N>: crate::int::types::compute_limbs::ComputeLimbs,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut buf =
            <crate::int::types::compute_limbs::Limbs<N> as crate::int::types::compute_limbs::ComputeLimbs>::digit_formatting_limbs_u8();
        let s = fmt_into::<N>(&self.limbs, 16, false, buf.as_mut());
        f.pad_integral(true, "0x", s)
    }
}

impl<const N: usize> core::fmt::Octal for Int<N>
where
    crate::int::types::compute_limbs::Limbs<N>: crate::int::types::compute_limbs::ComputeLimbs,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut buf =
            <crate::int::types::compute_limbs::Limbs<N> as crate::int::types::compute_limbs::ComputeLimbs>::bit_formatting_limbs_u8();
        let s = fmt_into::<N>(&self.limbs, 8, true, buf.as_mut());
        f.pad_integral(true, "0o", s)
    }
}

impl<const N: usize> core::fmt::Binary for Int<N>
where
    crate::int::types::compute_limbs::Limbs<N>: crate::int::types::compute_limbs::ComputeLimbs,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut buf =
            <crate::int::types::compute_limbs::Limbs<N> as crate::int::types::compute_limbs::ComputeLimbs>::bit_formatting_limbs_u8();
        let s = fmt_into::<N>(&self.limbs, 2, true, buf.as_mut());
        f.pad_integral(true, "0b", s)
    }
}

// ── Width conversion: widen (lossless) / narrow (fallible) ─────────
//
// `Uint<N>` and `Uint<M>` are different-sized stack types, so a value
// conversion builds a fresh `[u64; M]` — there is no heap allocation,
// and reinterpreting across widths via `transmute` would be unsound
// (different size and layout). `resize` writes each destination limb
// exactly once via `array::from_fn`; `widen` is the infallible extend
// and `narrow` the information-preserving truncation. Stable Rust
// cannot constrain `M >= N` / `M <= N` in the type system, so the
// direction is enforced by `debug_assert!` plus, for `narrow`, the
// `Option` return.

impl<const N: usize> Uint<N> {
    /// Resizes to `M` limbs: zero-extends when widening, drops the high
    /// limbs when narrowing. Direction-agnostic and infallible.
    ///
    /// Named `resize_n` (not `resize`) so the const-generic width bridge
    /// does not collide with the type-generic `Int::resize` the named-
    /// type API expects.
    #[inline]
    pub const fn resize_n<const M: usize>(self) -> Uint<M> {
        let mut out = [0u64; M];
        let mut i = 0;
        while i < M {
            if i < N {
                out[i] = self.limbs[i];
            }
            i += 1;
        }
        Uint::from_limbs(out)
    }

    /// Widens to a wider `Uint<M>` (`M >= N`), zero-extending the new
    /// high limbs. Lossless.
    #[inline]
    pub fn widen<const M: usize>(self) -> Uint<M> {
        debug_assert!(M >= N, "widen requires M >= N");
        self.resize_n::<M>()
    }

    /// Narrows to a narrower `Uint<M>` (`M <= N`). Returns `None` if any
    /// discarded high limb is non-zero (the value does not fit `M`).
    #[inline]
    pub fn narrow<const M: usize>(self) -> Option<Uint<M>> {
        debug_assert!(M <= N, "narrow requires M <= N");
        let keep = if M < N { M } else { N };
        let mut i = keep;
        while i < N {
            if self.limbs[i] != 0 {
                return None;
            }
            i += 1;
        }
        Some(self.resize_n::<M>())
    }
}

impl<const N: usize> Int<N> {
    /// Resizes to `M` limbs: sign-extends when widening, drops the high
    /// limbs when narrowing. Direction-agnostic and infallible
    /// (narrowing may change the represented value).
    ///
    /// Named `resize_n` (not `resize`) so the const-generic width bridge
    /// does not collide with the type-generic `Int::resize` the named-
    /// type API expects (the magnitude-bridge cast over any `BigInt`).
    ///
    /// Infallible two's-complement width conversion `Int<N> -> Int<M>`,
    /// const and direction-agnostic. Copies the overlapping limbs; when
    /// widening, fills the new high limbs with the sign (all-ones if the
    /// source is negative, else zero); when narrowing, drops the surplus
    /// high limbs (which may change the represented value). This is the
    /// canonical internal resize that the const fallible `try_narrow` and
    /// the `Int<->Int` magnitude bridge build on.
    #[inline]
    pub(crate) const fn resize_n<const M: usize>(self) -> Int<M> {
        let fill = if self.is_negative() { u64::MAX } else { 0 };
        let mut out = [0u64; M];
        let mut i = 0;
        while i < M {
            out[i] = if i < N { self.limbs[i] } else { fill };
            i += 1;
        }
        Int::from_limbs(out)
    }

    /// Const fallible narrow `Int<N> -> Int<M>` (`1 <= M <= N`). Returns
    /// `Some` only when every discarded high limb is a pure sign-extension
    /// of the narrowed value's top bit — i.e. the value fits `M` limbs as
    /// two's complement — and `None` otherwise. The const base for the
    /// future public fallible narrow.
    #[inline]
    pub(crate) const fn try_narrow<const M: usize>(self) -> Option<Int<M>> {
        debug_assert!(M >= 1 && M <= N, "try_narrow requires 1 <= M <= N");
        let sign_fill = if (self.limbs[M - 1] >> 63) == 1 {
            u64::MAX
        } else {
            0
        };
        let mut i = M;
        while i < N {
            if self.limbs[i] != sign_fill {
                return None;
            }
            i += 1;
        }
        Some(self.resize_n::<M>())
    }

    /// Widens to a wider `Int<M>` (`M >= N`), sign-extending. Lossless.
    #[inline]
    pub fn widen<const M: usize>(self) -> Int<M> {
        debug_assert!(M >= N, "widen requires M >= N");
        self.resize_n::<M>()
    }

    /// Narrows to a narrower `Int<M>` (`1 <= M <= N`). Returns `None`
    /// unless every discarded high limb is a pure sign-extension of the
    /// narrowed value's top bit — i.e. the value fits `M` limbs as
    /// two's complement.
    #[inline]
    pub fn narrow<const M: usize>(self) -> Option<Int<M>> {
        self.try_narrow::<M>()
    }
}



// ── std-aligned primitive conversions ───────────────────────────────
// Infallible widening (the source always fits `Int<N>` / `Uint<N>` for
// N >= 1, judged against the `N == 1` = `i64` floor) is `From`. Fallible
// narrowing (the value may exceed the target range) is `TryFrom`,
// returning [`ConvertError::Overflow`]. Each impl is a thin one-line
// delegate to the inherent const base. `Into` / `TryInto` come for free.

// ── IN: primitive → Int<N> ───────────────────────────────────────────
macro_rules! int_from_signed {
    ($($prim:ty => $base:ident),+) => {$(
        impl<const N: usize> From<$prim> for Int<N> {
            #[inline]
            fn from(v: $prim) -> Self { Self::$base(v) }
        }
    )+};
}
int_from_signed!(i8 => from_i8, i16 => from_i16, i32 => from_i32, i64 => from_i64);

macro_rules! int_from_unsigned {
    ($($prim:ty => $base:ident),+) => {$(
        impl<const N: usize> From<$prim> for Int<N> {
            #[inline]
            fn from(v: $prim) -> Self { Self::$base(v) }
        }
    )+};
}
int_from_unsigned!(u8 => from_u8, u16 => from_u16, u32 => from_u32);

macro_rules! uint_from_unsigned {
    ($($prim:ty),+) => {$(
        impl<const N: usize> From<$prim> for Uint<N> {
            #[inline]
            fn from(v: $prim) -> Self { Self::from_u64(v as u64) }
        }
    )+};
}
uint_from_unsigned!(u8, u16, u32, u64);

// Fallible IN: `u64` can overflow `Int<1>`; `i128` / `u128` can overflow
// the narrow tiers (see the inherent `try_from_*`).
impl<const N: usize> TryFrom<u64> for Int<N> {
    type Error = crate::support::error::ConvertError;
    #[inline]
    fn try_from(v: u64) -> Result<Self, Self::Error> {
        Self::try_from_u64(v).ok_or(crate::support::error::ConvertError::Overflow)
    }
}

impl<const N: usize> TryFrom<i128> for Int<N> {
    type Error = crate::support::error::ConvertError;
    #[inline]
    fn try_from(v: i128) -> Result<Self, Self::Error> {
        Self::try_from_i128(v).ok_or(crate::support::error::ConvertError::Overflow)
    }
}

impl<const N: usize> TryFrom<u128> for Int<N> {
    type Error = crate::support::error::ConvertError;
    #[inline]
    fn try_from(v: u128) -> Result<Self, Self::Error> {
        Self::try_from_u128(v).ok_or(crate::support::error::ConvertError::Overflow)
    }
}

// ── OUT: Int<N> → primitive ──────────────────────────────────────────
// `i64` / `i128` are always representable on the fitting tiers, so those
// are infallible `From` (declared above: `From<Int<1>> for i64`,
// `From<Int<1>>` / `From<Int<2>> for i128`). The std blanket
// `impl<T,U: From<T>> TryFrom<T> for U` then derives the matching
// `TryFrom` for those tiers, so a generic `TryFrom<Int<N>> for i64`/`i128`
// is omitted to avoid the coherence conflict. The remaining widths /
// targets are genuinely fallible:
impl<const N: usize> TryFrom<Int<N>> for i32 {
    type Error = crate::support::error::ConvertError;
    #[inline]
    fn try_from(v: Int<N>) -> Result<Self, Self::Error> {
        v.try_to_i32().ok_or(crate::support::error::ConvertError::Overflow)
    }
}

impl<const N: usize> TryFrom<Int<N>> for u32 {
    type Error = crate::support::error::ConvertError;
    #[inline]
    fn try_from(v: Int<N>) -> Result<Self, Self::Error> {
        v.try_to_u32().ok_or(crate::support::error::ConvertError::Overflow)
    }
}

impl<const N: usize> TryFrom<Int<N>> for u64 {
    type Error = crate::support::error::ConvertError;
    #[inline]
    fn try_from(v: Int<N>) -> Result<Self, Self::Error> {
        v.try_to_u64().ok_or(crate::support::error::ConvertError::Overflow)
    }
}

impl<const N: usize> TryFrom<Int<N>> for u128 {
    type Error = crate::support::error::ConvertError;
    #[inline]
    fn try_from(v: Int<N>) -> Result<Self, Self::Error> {
        v.try_to_u128().ok_or(crate::support::error::ConvertError::Overflow)
    }
}

impl<const N: usize> TryFrom<u128> for Uint<N> {
    type Error = crate::support::error::ConvertError;
    #[inline]
    fn try_from(v: u128) -> Result<Self, Self::Error> {
        Self::try_from_u128(v).ok_or(crate::support::error::ConvertError::Overflow)
    }
}

// ── Floats ───────────────────────────────────────────────────────────
// Float → Int<N> is fallible (NaN, ±inf, non-integer, out-of-range), so
// `TryFrom`. There is no `From<Int<N>> for f64/f32`: that direction is
// lossy above the mantissa width and is offered only as the inherent
// `to_f64` / `to_f32` round-to-nearest methods.
impl<const N: usize> TryFrom<f64> for Int<N> {
    type Error = crate::support::error::ConvertError;
    #[inline]
    fn try_from(v: f64) -> Result<Self, Self::Error> {
        Self::try_from_f64(v).ok_or(crate::support::error::ConvertError::Overflow)
    }
}

impl<const N: usize> TryFrom<f32> for Int<N> {
    type Error = crate::support::error::ConvertError;
    #[inline]
    fn try_from(v: f32) -> Result<Self, Self::Error> {
        Self::try_from_f32(v).ok_or(crate::support::error::ConvertError::Overflow)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::int::algos::mul::mul_schoolbook::{mul_low_fixed, mul_schoolbook_fixed};

    #[test]
    fn try_from_i128_detects_narrow_overflow() {
        // Int<2> (128-bit) holds every i128.
        assert_eq!(Int::<2>::try_from_i128(i128::MAX), Some(Int::<2>::from_i128(i128::MAX)));
        assert_eq!(Int::<2>::try_from_i128(i128::MIN), Some(Int::<2>::from_i128(i128::MIN)));
        // Int<1> (64-bit) holds only the i64 range.
        assert_eq!(Int::<1>::try_from_i128(i64::MAX as i128 + 1), None);
        assert_eq!(Int::<1>::try_from_i128(i64::MIN as i128 - 1), None);
        assert_eq!(
            Int::<1>::try_from_i128(i64::MAX as i128),
            Some(Int::<1>::from_i64(i64::MAX))
        );
        // TryFrom mirrors it.
        assert!(<Int<1> as TryFrom<i128>>::try_from(i64::MAX as i128 + 1).is_err());
        assert_eq!(<Int<2> as TryFrom<i128>>::try_from(-5_i128), Ok(Int::<2>::from_i64(-5)));
    }

    #[test]
    fn try_from_u128_detects_narrow_overflow() {
        // Uint twin: every u128 fits Uint<2+>; Uint<1> only holds u64.
        assert_eq!(Uint::<2>::try_from_u128(u128::MAX), Some(Uint::<2>::from_u128(u128::MAX)));
        assert_eq!(Uint::<1>::try_from_u128(u64::MAX as u128 + 1), None);
        assert_eq!(Uint::<1>::try_from_u128(u64::MAX as u128), Some(Uint::<1>::from_u64(u64::MAX)));
        assert!(<Uint<1> as TryFrom<u128>>::try_from(u64::MAX as u128 + 1).is_err());
        // Int<N> u128 entry: Int<1> fails above i64::MAX, Int<2> above i128::MAX.
        assert_eq!(Int::<1>::try_from_u128(u64::MAX as u128), None);
        assert_eq!(Int::<2>::try_from_u128(u128::MAX), None);
        assert_eq!(Int::<3>::try_from_u128(u128::MAX), Some(Int::<3>::from_u128(u128::MAX)));
        assert!(<Int<2> as TryFrom<u128>>::try_from(u128::MAX).is_err());
    }

    #[test]
    fn try_from_u64_and_out_conversions_at_edges() {
        // u64 entry: Int<1> rejects above i64::MAX, wider tiers accept.
        assert!(<Int<1> as TryFrom<u64>>::try_from(u64::MAX).is_err());
        assert_eq!(<Int<2> as TryFrom<u64>>::try_from(u64::MAX), Ok(Int::<2>::from_u128(u64::MAX as u128)));
        // OUT lossless: Int<1> -> i64, Int<2> -> i128 are exact From.
        assert_eq!(i128::from(Int::<2>::MAX), i128::MAX);
        assert_eq!(i128::from(Int::<2>::MIN), i128::MIN);
        assert_eq!(i64::from(Int::<1>::from_i64(-123)), -123_i64);
        // OUT fallible: a wide value out of i128 range rejects (inherent
        // base; i128 has no generic TryFrom — it is From-derived on N<=2).
        let big = Int::<3>::from_u128(u128::MAX);
        assert_eq!(big.try_to_i128(), None);
        assert_eq!(<i32 as TryFrom<Int<4>>>::try_from(Int::<4>::from_i64(-7)), Ok(-7_i32));
        assert!(<u32 as TryFrom<Int<4>>>::try_from(Int::<4>::from_i64(-1)).is_err());
    }

    #[test]
    fn float_conversions_reject_and_round_trip() {
        // Rejections.
        assert_eq!(Int::<2>::try_from_f64(f64::NAN), None);
        assert_eq!(Int::<2>::try_from_f64(f64::INFINITY), None);
        assert_eq!(Int::<2>::try_from_f64(f64::NEG_INFINITY), None);
        assert_eq!(Int::<2>::try_from_f64(0.5), None);
        assert_eq!(Int::<2>::try_from_f64(3.5), None);
        assert_eq!(Int::<2>::try_from_f32(f32::NAN), None);
        assert_eq!(Int::<2>::try_from_f32(f32::INFINITY), None);
        assert_eq!(Int::<2>::try_from_f32(0.5), None);
        assert_eq!(Int::<2>::try_from_f32(3.5), None);
        assert_eq!(Int::<1>::try_from_f64(1e30), None); // out of i64 range
        // ±0 maps to ZERO.
        assert_eq!(Int::<2>::try_from_f64(0.0), Some(Int::<2>::ZERO));
        assert_eq!(Int::<2>::try_from_f64(-0.0), Some(Int::<2>::ZERO));
        assert_eq!(Int::<2>::try_from_f32(0.0), Some(Int::<2>::ZERO));
        assert_eq!(Int::<2>::try_from_f32(-0.0), Some(Int::<2>::ZERO));
        // In-range integers round-trip exactly.
        assert_eq!(Int::<4>::try_from_f64(42.0), Some(Int::<4>::from_i64(42)));
        assert_eq!(Int::<4>::try_from_f64(-42.0), Some(Int::<4>::from_i64(-42)));
        assert_eq!(Int::<4>::try_from_f32(7.0), Some(Int::<4>::from_i64(7)));
        assert_eq!(Int::<4>::try_from_f32(-7.0), Some(Int::<4>::from_i64(-7)));
        // TryFrom mirrors the helper.
        assert!(<Int<2> as TryFrom<f64>>::try_from(f64::NAN).is_err());
        assert_eq!(<Int<2> as TryFrom<f64>>::try_from(-9.0), Ok(Int::<2>::from_i64(-9)));
        assert_eq!(<Int<2> as TryFrom<f32>>::try_from(-9.0), Ok(Int::<2>::from_i64(-9)));
        // OUT to_f64 / to_f32 round-trip small values.
        assert_eq!(Int::<4>::from_i64(123).to_f64(), 123.0);
        assert_eq!(Int::<4>::from_i64(-123).to_f64(), -123.0);
        assert_eq!(Int::<4>::from_i64(123).to_f32(), 123.0_f32);
    }

    #[test]
    fn float_conversions_wide_and_boundaries() {
        // A large exact integer (2^64) needs two limbs: it overflows
        // Int<1> but fits Int<2>.
        let big = 2f64.powi(64); // exactly representable
        assert_eq!(Int::<1>::try_from_f64(big), None);
        assert_eq!(
            Int::<2>::try_from_f64(big),
            Some(Int::<2>::from_u128(1u128 << 64))
        );

        // 2^63 is exactly i64::MAX + 1 — just over the Int<1> positive
        // range, so it must reject.
        let two_63 = 2f64.powi(63);
        assert_eq!(Int::<1>::try_from_f64(two_63), None);
        // i64::MAX itself (2^63 - 1) is not f64-exact, but 2^63 - 2^10 is;
        // confirm a representable value strictly below the cap fits.
        let near_max = (i64::MAX - 1023) as f64; // exact in f64
        assert_eq!(near_max as i64, i64::MAX - 1023);
        assert_eq!(
            Int::<1>::try_from_f64(near_max),
            Some(Int::<1>::from_i64(i64::MAX - 1023))
        );

        // The MIN edge: -2^63 == i64::MIN fits Int<1> exactly.
        let min_edge = -(2f64.powi(63));
        assert_eq!(
            Int::<1>::try_from_f64(min_edge),
            Some(Int::<1>::from_i64(i64::MIN))
        );
        // One magnitude bit past the negative edge does not fit.
        assert_eq!(Int::<1>::try_from_f64(-(2f64.powi(64))), None);

        // f32 analogues: 2^24 fits Int<1>; the round-trip is exact.
        let two_24 = 2f32.powi(24);
        assert_eq!(
            Int::<1>::try_from_f32(two_24),
            Some(Int::<1>::from_i64(1 << 24))
        );
    }

    #[test]
    fn float_conversions_are_const() {
        // Proves the float→int path is usable in const context.
        const X: Option<Int<2>> = Int::<2>::try_from_f64(42.0);
        const Y: Option<Int<2>> = Int::<2>::try_from_f32(42.0);
        assert_eq!(X, Some(Int::<2>::from_i64(42)));
        assert_eq!(Y, Some(Int::<2>::from_i64(42)));
    }

    #[test]
    fn from_traits_are_infallible_for_fitting_prims() {
        assert_eq!(Int::<1>::from(-7_i32), Int::<1>::from_i64(-7));
        assert_eq!(Int::<4>::from(42_i64), Int::<4>::from_i64(42));
        assert_eq!(Uint::<1>::from(7_u32), Uint::<1>::from_u64(7));
        assert_eq!(Uint::<4>::from(u64::MAX), Uint::<4>::from_u64(u64::MAX));
    }

    /// The `BigInt` / `BigInt` surface must compile and
    /// behave through a fully generic bound, for both signed and
    /// unsigned fixed-width integers.
    #[test]
    fn fixed_int_trait_surface() {
        fn exercises<T: BigInt>(seven: T, three: T) {
            assert_eq!(T::LIMBS as u32 * 64, T::BITS);
            assert!(T::ZERO.is_zero());
            assert!(T::ONE.is_one());
            assert!(!T::ZERO.is_one());

            // Operators via the supertrait bounds.
            let ten = seven + three;
            assert_eq!(ten - three, seven);
            assert_eq!(ten, seven.wrapping_add(three));
            assert_eq!(seven.wrapping_sub(three) + three, seven);

            // Bitwise / shift surface.
            let _ = (seven & three) | (seven ^ three);
            let _ = !T::ZERO;
            assert_eq!((T::ONE << 4) >> 4, T::ONE);

            // Checked arithmetic returns Some for in-range work.
            assert_eq!(seven.checked_add(three), Some(ten));
            assert!(seven.checked_mul(three).is_some());

            // Powers and optimisable functions agree with each other.
            assert_eq!(three.sqr(), three * three);
            assert_eq!(three.cube(), three * three * three);
            assert_eq!(three.pow(2), three.sqr());
            assert_eq!(three.wrapping_pow(3), three.cube());
            assert_eq!(three.checked_pow(2), Some(three.sqr()));

            // bit_length / leading_zeros consistency.
            assert_eq!(T::ONE.bit_length(), 1);
            assert_eq!(T::ZERO.bit_length(), 0);
            assert_eq!(T::ONE.leading_zeros(), T::BITS - 1);

            // Reductions and the limb round-trip.
            let items = [T::ONE, T::ONE, T::ONE];
            assert_eq!(T::sum(items), three);
            assert_eq!(T::product([three, T::ONE]), three);
            assert_eq!(T::from_limbs(seven.to_limbs()), seven);
        }

        exercises(Int::<4>::from_i64(7), Int::<4>::from_i64(3));
        exercises(Int::<6>::from_i64(7), Int::<6>::from_i64(3));
    }

    /// The truncated low-`N` product must equal the low `N` limbs of
    /// the full `2N`-limb schoolbook product, across widths and edges.
    #[test]
    fn limbs_mul_low_matches_full_product_low_half() {
        fn check<const N: usize, const D: usize>(a: [u64; N], b: [u64; N]) {
            debug_assert!(D == 2 * N);
            let mut full = [0u64; D];
            mul_schoolbook_fixed::<N, D>(&a, &b, &mut full);
            let mut low = [0u64; N];
            mul_low_fixed::<N>(&a, &b, &mut low);
            let mut expected = [0u64; N];
            expected.copy_from_slice(&full[..N]);
            assert_eq!(low, expected, "low-half mismatch for {a:?} * {b:?}");
        }

        // Width 4 (256-bit): zero, one, MAX, cross-limb spans.
        check::<4, 8>([0, 0, 0, 0], [0, 0, 0, 0]);
        check::<4, 8>([1, 0, 0, 0], [u64::MAX, u64::MAX, u64::MAX, u64::MAX]);
        check::<4, 8>([u64::MAX; 4], [u64::MAX; 4]);
        check::<4, 8>([0, 1, 0, 0], [0, 1, 0, 0]); // 2^64 * 2^64
        check::<4, 8>(
            [0xDEAD_BEEF, 0xCAFE_F00D, 0x1234, 0x5678_9ABC],
            [0xFEED_FACE, 0x0BAD_C0DE, 0x9999, 0x0000_0001],
        );
        // Width 2 and width 6 to exercise other monomorphisations.
        check::<2, 4>([u64::MAX, u64::MAX], [3, 0]);
        check::<6, 12>([7, 8, 9, 10, 11, 12], [1, 2, 3, 4, 5, 6]);
    }

    /// The dedicated squaring kernel must be bit-exact against the
    /// general truncated product `x · x` at every width and edge case.
    #[test]
    fn dedicated_sqr_matches_general_mul() {
        fn check<const N: usize>(x: [u64; N]) {
            let a = Uint::<N>::from_limbs(x);
            assert_eq!(
                a.wrapping_sqr(),
                a.wrapping_mul(a),
                "sqr != mul(self,self) for {x:?}"
            );
        }

        // Width 4: 0, 1, MAX, single-limb, cross-limb, full-width.
        check::<4>([0, 0, 0, 0]);
        check::<4>([1, 0, 0, 0]);
        check::<4>([u64::MAX; 4]);
        check::<4>([0x1234_5678, 0, 0, 0]);
        check::<4>([u64::MAX, u64::MAX, 0, 0]);
        check::<4>([0xDEAD_BEEF_CAFE_F00D, 0x0123_4567_89AB_CDEF, 0xFEDC, 0x99]);
        // Carry-heavy: every limb all-ones but the top.
        check::<4>([u64::MAX, u64::MAX, u64::MAX, 0]);
        // Other widths / monomorphisations.
        check::<1>([u64::MAX]);
        check::<2>([u64::MAX, u64::MAX]);
        check::<6>([7, 8, 9, 10, 11, 12]);
        check::<8>([u64::MAX, 1, u64::MAX, 2, u64::MAX, 3, u64::MAX, 4]);
        // A pseudo-random sweep across width 5.
        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };
        for _ in 0..64 {
            check::<5>([next(), next(), next(), next(), next()]);
        }
    }

    #[test]
    fn uint_sqr_cube_match_naive() {
        let x = Uint::<4>::from_limbs([123_456_789, 0, 0, 0]);
        assert_eq!(x.wrapping_sqr(), x.wrapping_mul(x));
        assert_eq!(x.wrapping_cube(), x.wrapping_mul(x).wrapping_mul(x));

        // A value spanning two limbs, to exercise cross-limb products.
        let y = Uint::<4>::from_limbs([0xDEAD_BEEF_CAFE, 0x1234_5678, 0, 0]);
        assert_eq!(y.wrapping_sqr(), y.wrapping_mul(y));
        assert_eq!(y.wrapping_cube(), y.wrapping_mul(y).wrapping_mul(y));
    }

    /// `root_int(k)` must return `floor(m^(1/k))` with the correct
    /// exactness flag: `root^k <= m < (root+1)^k`, and `exact` iff
    /// `root^k == m`. Checked against a brute-force reference for small
    /// `m` and `k in {2,3,5}` across widths, plus cross-checking k=2
    /// against the shipped isqrt and large perfect-power exactness.
    // Exercises Int<8> roots (isqrt/icbrt work widths) beyond the narrow
    // build's int-kernel scratch; runs where the wide tiers are compiled.
    #[cfg(feature = "_wide-support")]
    #[test]
    fn root_int_floor_and_exactness() {
        // Brute-force floor kth root of a small u128.
        fn brute(m: u128, k: u32) -> (u128, bool) {
            if m == 0 {
                return (0, true);
            }
            let mut r: u128 = 0;
            // Smallest r with (r+1)^k > m, capped to avoid overflow.
            while {
                let next = r + 1;
                next.checked_pow(k).is_some_and(|p| p <= m)
            } {
                r += 1;
            }
            (r, r.pow(k) == m)
        }

        fn check<const N: usize>(m: u128, k: u32) {
            let lo = (m & 0xFFFF_FFFF_FFFF_FFFF) as u64;
            let hi = (m >> 64) as u64;
            let mut limbs = [0u64; N];
            limbs[0] = lo;
            if N > 1 {
                limbs[1] = hi;
            }
            let n = Uint::<N>::from_limbs(limbs);
            let (root, exact) = n.root_int(k);
            let (eroot, eexact) = brute(m, k);
            let root_lo = root.as_limbs()[0] as u128
                | ((if N > 1 { root.as_limbs()[1] as u128 } else { 0 }) << 64);
            assert_eq!(root_lo, eroot, "root mismatch for m={m}, k={k}");
            assert_eq!(exact, eexact, "exact flag mismatch for m={m}, k={k}");

            // The defining bracket, computed in-width.
            let rk = root.pow(k);
            assert!(rk <= n, "root^k > m for m={m}, k={k}");
            let next = root.wrapping_add(Uint::<N>::ONE);
            // (root+1)^k overflowing the width still satisfies > m.
            if let Some(p) = next.checked_pow(k) { assert!(p > n, "(root+1)^k <= m for m={m}, k={k}") }
        }

        let samples: [u128; 14] = [
            0,
            1,
            2,
            7,
            8,
            9,
            26,
            27,
            28,
            1000,
            1023,
            1024,
            1_000_000,
            u64::MAX as u128,
        ];
        for &m in &samples {
            for k in [2u32, 3, 5] {
                check::<4>(m, k);
                check::<2>(m, k);
                check::<8>(m, k);
            }
        }

        // k=2 cross-check against shipped isqrt for a wide value.
        let big = Uint::<4>::from_limbs([0xFFFF_FFFF_FFFF_FFFF, 0x1234_5678, 0, 0]);
        assert_eq!(big.root_int(2).0, big.isqrt());

        // Large exact perfect cube: (2^40)^3 = 2^120.
        let base = Uint::<4>::ONE.shl(40);
        let cube = base.wrapping_cube();
        let (r, exact) = cube.root_int(3);
        assert_eq!(r, base);
        assert!(exact);
        // One less than a perfect cube is not exact and floors down.
        let (r2, exact2) = cube.wrapping_sub(Uint::<4>::ONE).root_int(3);
        assert_eq!(r2, base.wrapping_sub(Uint::<4>::ONE));
        assert!(!exact2);
    }

    #[test]
    fn uint_widen_zero_extends() {
        let a = Uint::<2>::from_limbs([7, 8]);
        let w = a.widen::<4>();
        assert_eq!(*w.as_limbs(), [7, 8, 0, 0]);
        assert_eq!(a.resize_n::<4>(), w);
    }

    #[test]
    fn uint_narrow_checks_dropped_limbs() {
        let fits = Uint::<4>::from_limbs([7, 8, 0, 0]);
        assert_eq!(*fits.narrow::<2>().unwrap().as_limbs(), [7, 8]);

        let too_big = Uint::<4>::from_limbs([7, 8, 1, 0]);
        assert!(too_big.narrow::<2>().is_none());

        // widen → narrow round-trips losslessly.
        let a = Uint::<2>::from_limbs([3, 4]);
        assert_eq!(a.widen::<4>().narrow::<2>().unwrap(), a);
    }

    #[test]
    fn int_widen_sign_extends() {
        // -1 is all-ones; sign-extension keeps it all-ones at any width.
        let neg = Int::<2>::from_i64(-1);
        assert_eq!(*neg.widen::<4>().as_limbs(), [u64::MAX; 4]);
        assert_eq!(neg.widen::<4>(), Int::<4>::from_i64(-1));
        // Positive values zero-extend.
        let pos = Int::<2>::from_i64(5);
        assert_eq!(*pos.widen::<4>().as_limbs(), [5, 0, 0, 0]);
    }

    #[test]
    fn int_narrow_requires_sign_consistency() {
        // Negative value whose dropped limbs are all the sign fill: fits.
        let neg = Int::<4>::from_i64(-1);
        assert_eq!(neg.narrow::<2>().unwrap(), Int::<2>::from_i64(-1));
        // Positive magnitude with a non-sign high limb: does not fit.
        let big = Int::<4>::from_limbs([0, 0, 1, 0]);
        assert!(big.narrow::<2>().is_none());
        // Negative top bit but a dropped limb that isn't all-ones: no fit.
        let weird = Int::<4>::from_limbs([1, 0, 0, u64::MAX]);
        assert!(weird.narrow::<2>().is_none());
        // Small value round-trips.
        let p = Int::<2>::from_i64(42);
        assert_eq!(p.widen::<4>().narrow::<2>().unwrap(), p);
    }

    #[test]
    fn int_resize_const_two_complement() {
        // Widen round-trips: positive zero-extends, value preserved.
        let pos = Int::<2>::from_i64(123);
        let wide: Int<4> = pos.resize_n::<4>();
        assert_eq!(*wide.as_limbs(), [123, 0, 0, 0]);
        assert_eq!(wide.resize_n::<2>(), pos);

        // Sign-extend of negatives: high limbs all-ones, value preserved.
        let neg = Int::<2>::from_i64(-7);
        let wneg: Int<4> = neg.resize_n::<4>();
        assert_eq!(*wneg.as_limbs(), [(-7i64) as u64, u64::MAX, u64::MAX, u64::MAX]);
        assert_eq!(wneg, Int::<4>::from_i64(-7));

        // Truncate drops the surplus high limbs.
        let v = Int::<4>::from_limbs([1, 2, 3, 4]);
        assert_eq!(*v.resize_n::<2>().as_limbs(), [1, 2]);

        // try_narrow Some/None at the signed boundary.
        // -1 narrows: dropped limbs are the sign fill.
        assert_eq!(Int::<4>::from_i64(-1).try_narrow::<2>().unwrap(), Int::<2>::from_i64(-1));
        // A positive value with a set high limb does not fit.
        assert!(Int::<4>::from_limbs([0, 0, 1, 0]).try_narrow::<2>().is_none());
        // 2^63 is positive and fits Int<2> but NOT Int<1>: narrowing to
        // one limb would set the top bit, flipping it negative, and the
        // dropped high limb (0) is not the negative sign fill — so None.
        let too_big = Int::<2>::from_limbs([0x8000_0000_0000_0000, 0]);
        assert!(too_big.try_narrow::<1>().is_none());
        // i64::MIN genuinely fits Int<1>: try_narrow returns Some.
        let min2 = Int::<2>::from_i64(i64::MIN);
        assert_eq!(min2.try_narrow::<1>().unwrap(), Int::<1>::from_i64(i64::MIN));
        // Its widening then narrowing round-trips.
        assert_eq!(min2.resize_n::<4>().try_narrow::<2>().unwrap(), min2);

        // Const evaluation smoke: resize_n is usable in const context.
        const W: Int<4> = Int::<2>::from_i64(-7).resize_n::<4>();
        assert_eq!(W, Int::<4>::from_i64(-7));
    }

    #[test]
    fn bit_count_is_const() {
        // const-smoke: these compile only if the inherent methods are
        // `const fn`. Called fully-qualified so the inherent `&self` impl
        // is selected over the (non-const) `BigInt` trait method of the
        // same name, which takes `self` by value and would otherwise win
        // value-receiver method resolution.
        const Z: u32 = Int::<2>::leading_zeros(&Int::<2>::MAX);
        const BL: u32 = Int::<2>::bit_length(&Int::<2>::MAX);
        const UZ: u32 = Uint::<2>::leading_zeros(&Uint::<2>::MAX);
        const UBL: u32 = Uint::<2>::bit_length(&Uint::<2>::MAX);
        // Int<2>::MAX is positive with the sign bit clear: 1 leading zero,
        // bit_length = 127.
        assert_eq!(Z, 1);
        assert_eq!(BL, 127);
        // Uint<2>::MAX is all-ones: 0 leading zeros, full 128-bit length.
        assert_eq!(UZ, 0);
        assert_eq!(UBL, 128);
    }

    #[test]
    fn int_cross_width_comparison() {
        // Equal values across widths compare ==.
        let a = Int::<1>::from_i64(5);
        let b = Int::<2>::from_i64(5);
        assert!(a == b);
        assert!(b == a);
        assert_eq!(a.partial_cmp(&b), Some(Ordering::Equal));

        // Ordering across widths.
        let small = Int::<1>::from_i64(3);
        let big = Int::<2>::from_i64(100);
        assert!(small < big);
        assert!(big > small);

        // A value only fitting the wider type still orders right: 2^70
        // lives in Int<2> (and up) but exceeds Int<1>; it must compare
        // greater than any Int<1>.
        let huge = Int::<2>::from_limbs([0, 64]); // 64 * 2^64 = 2^70
        assert!(huge > Int::<1>::MAX);
        assert!(Int::<1>::from_i64(-1) < huge);

        // Negatives: -1 (Int<1>) vs 1 (Int<2>) — neg < pos.
        assert!(Int::<1>::from_i64(-1) < Int::<2>::from_i64(1));
        // Two negatives across widths: larger magnitude is the smaller.
        assert!(Int::<1>::from_i64(-100) < Int::<2>::from_i64(-3));
        assert!(Int::<2>::from_i64(-3) > Int::<1>::from_i64(-100));
        // Equal negatives across widths.
        assert!(Int::<1>::from_i64(-7) == Int::<2>::from_i64(-7));

        // Same-type Ord still sorts a Vec.
        let mut v = vec![
            Int::<2>::from_i64(3),
            Int::<2>::from_i64(-10),
            Int::<2>::from_i64(0),
            Int::<2>::from_i64(7),
        ];
        v.sort();
        assert_eq!(
            v,
            vec![
                Int::<2>::from_i64(-10),
                Int::<2>::from_i64(0),
                Int::<2>::from_i64(3),
                Int::<2>::from_i64(7),
            ]
        );
    }

    #[test]
    fn consts_and_round_trip() {
        assert_eq!(Uint::<4>::LIMBS, 4);
        assert_eq!(Uint::<4>::BITS, 256);
        assert_eq!(*Uint::<4>::ZERO.as_limbs(), [0, 0, 0, 0]);
        assert_eq!(*Uint::<4>::ONE.as_limbs(), [1, 0, 0, 0]);
        assert_eq!(*Uint::<4>::MAX.as_limbs(), [u64::MAX; 4]);

        let v = Uint::<4>::from_limbs([7, 8, 9, 10]);
        assert_eq!(*v.as_limbs(), [7, 8, 9, 10]);
    }

    #[test]
    fn widths_have_expected_bits() {
        assert_eq!(Int::<4>::BITS, 256);
        assert_eq!(Int::<64>::BITS, 4096);
        assert_eq!(Uint::<16>::LIMBS, 16);
    }

    #[test]
    fn wrapping_sub_borrows_across_limbs() {
        // 2^64 - 1 ... computed as 0 - 1 wrapping, then check a clean borrow.
        let a = Uint::<4>::from_limbs([0, 1, 0, 0]);
        let d = a.wrapping_sub(Uint::<4>::ONE);
        assert_eq!(*d.as_limbs(), [u64::MAX, 0, 0, 0]);

        // 0 - 1 wraps to all-ones (modulo 2^256).
        let wrap = Uint::<4>::ZERO.wrapping_sub(Uint::<4>::ONE);
        assert_eq!(*wrap.as_limbs(), [u64::MAX; 4]);
    }

    #[test]
    fn unsigned_ordering() {
        let small = Uint::<4>::from_limbs([5, 0, 0, 0]);
        let big = Uint::<4>::from_limbs([0, 1, 0, 0]); // 2^64 > 5
        assert!(small < big);
        assert!(big > small);
        assert_eq!(small, small);
        assert!(Uint::<4>::ZERO < Uint::<4>::MAX);
        // round-trips through derived PartialOrd helpers
        assert_eq!(small.max(big), big);
    }

    #[test]
    fn wrapping_add_carries_across_limbs() {
        // (2^64 - 1) + 1 carries into the next limb.
        let a = Uint::<4>::from_limbs([u64::MAX, 0, 0, 0]);
        let sum = a.wrapping_add(Uint::<4>::ONE);
        assert_eq!(*sum.as_limbs(), [0, 1, 0, 0]);

        // All-ones + 1 wraps to zero (modulo 2^256).
        let wrap = Uint::<4>::MAX.wrapping_add(Uint::<4>::ONE);
        assert_eq!(*wrap.as_limbs(), [0, 0, 0, 0]);
    }

    #[test]
    fn uint_wrapping_mul_cross_limb_product() {
        // 2^64 * 2^64 = 2^128 — lands exactly in limb 2.
        let a = Uint::<4>::from_limbs([0, 1, 0, 0]);
        let p = a.wrapping_mul(a);
        assert_eq!(*p.as_limbs(), [0, 0, 1, 0]);

        // (2^64 - 1) * 3 = 3*2^64 - 3 = [u64::MAX - 2, 2, 0, 0].
        let m = Uint::<4>::from_limbs([u64::MAX, 0, 0, 0]);
        let three = Uint::<4>::from_limbs([3, 0, 0, 0]);
        let q = m.wrapping_mul(three);
        assert_eq!(*q.as_limbs(), [u64::MAX - 2, 2, 0, 0]);

        // Multiply by one is identity.
        let v = Uint::<4>::from_limbs([7, 8, 9, 10]);
        assert_eq!(v.wrapping_mul(Uint::<4>::ONE), v);
    }

    #[test]
    fn uint_wrapping_mul_truncates_modulo_width() {
        // 2^192 * 2^192 = 2^384, fully above 2^256 → wraps to zero.
        let hi = Uint::<4>::from_limbs([0, 0, 0, 1]);
        assert_eq!(hi.wrapping_mul(hi), Uint::<4>::ZERO);

        // MAX * MAX mod 2^256: (2^256 - 1)^2 = 2^512 - 2^257 + 1.
        // mod 2^256 that is 1 (since 2^512 and 2^257 are both 0 mod
        // 2^256). So the low limb is 1, the rest zero.
        let r = Uint::<4>::MAX.wrapping_mul(Uint::<4>::MAX);
        assert_eq!(*r.as_limbs(), [1, 0, 0, 0]);
    }

    #[test]
    fn uint_checked_add_sub_overflow() {
        assert_eq!(
            Uint::<4>::ONE.checked_add(Uint::<4>::ONE),
            Some(Uint::<4>::from_limbs([2, 0, 0, 0]))
        );
        // MAX + 1 overflows.
        assert_eq!(Uint::<4>::MAX.checked_add(Uint::<4>::ONE), None);

        assert_eq!(
            Uint::<4>::from_limbs([5, 0, 0, 0]).checked_sub(Uint::<4>::from_limbs([3, 0, 0, 0])),
            Some(Uint::<4>::from_limbs([2, 0, 0, 0]))
        );
        // 0 - 1 underflows.
        assert_eq!(Uint::<4>::ZERO.checked_sub(Uint::<4>::ONE), None);
    }

    #[test]
    fn uint_checked_mul_overflow() {
        // 2^64 * 2^64 = 2^128 fits in 256 bits.
        let a = Uint::<4>::from_limbs([0, 1, 0, 0]);
        assert_eq!(a.checked_mul(a), Some(Uint::<4>::from_limbs([0, 0, 1, 0])));
        // 2^192 * 2^192 overflows 256 bits.
        let hi = Uint::<4>::from_limbs([0, 0, 0, 1]);
        assert_eq!(hi.checked_mul(hi), None);
        // MAX * 2 overflows.
        assert_eq!(
            Uint::<4>::MAX.checked_mul(Uint::<4>::from_limbs([2, 0, 0, 0])),
            None
        );
    }

    #[test]
    fn uint_div_rem_with_remainder() {
        // 1000 / 7 = 142 r 6.
        let n = Uint::<4>::from_limbs([1000, 0, 0, 0]);
        let d = Uint::<4>::from_limbs([7, 0, 0, 0]);
        assert_eq!(*n.wrapping_div(d).as_limbs(), [142, 0, 0, 0]);
        assert_eq!(*n.wrapping_rem(d).as_limbs(), [6, 0, 0, 0]);

        // 2^128 / 2^64 = 2^64, remainder 0.
        let big = Uint::<4>::from_limbs([0, 0, 1, 0]);
        let by = Uint::<4>::from_limbs([0, 1, 0, 0]);
        assert_eq!(*big.wrapping_div(by).as_limbs(), [0, 1, 0, 0]);
        assert!(big.wrapping_rem(by).is_zero());
    }

    #[test]
    #[should_panic(expected = "divide by zero")]
    fn uint_div_by_zero_panics() {
        let _ = Uint::<4>::ONE.wrapping_div(Uint::<4>::ZERO);
    }

    #[test]
    fn uint_bitwise_ops() {
        let a = Uint::<4>::from_limbs([0b1100, 0xFF, 0, 0]);
        let b = Uint::<4>::from_limbs([0b1010, 0x0F, 0, 0]);
        assert_eq!(*(a & b).as_limbs(), [0b1000, 0x0F, 0, 0]);
        assert_eq!(*(a | b).as_limbs(), [0b1110, 0xFF, 0, 0]);
        assert_eq!(*(a ^ b).as_limbs(), [0b0110, 0xF0, 0, 0]);
        assert_eq!(*(!Uint::<4>::ZERO).as_limbs(), [u64::MAX; 4]);
    }

    #[test]
    fn uint_shifts() {
        let one = Uint::<4>::ONE;
        // 1 << 64 lands in limb 1.
        assert_eq!(*(one << 64).as_limbs(), [0, 1, 0, 0]);
        // 1 << 130 = limb 2 bit 2.
        assert_eq!(*(one << 130).as_limbs(), [0, 0, 0b100, 0]);
        // Right shift back.
        let v = Uint::<4>::from_limbs([0, 0, 0b100, 0]);
        assert_eq!(*(v >> 130).as_limbs(), [1, 0, 0, 0]);
        // Shift past the width drops everything.
        assert_eq!(one << 256, Uint::<4>::ZERO);
    }

    #[test]
    fn uint_is_zero_bitlen_leading_zeros() {
        assert!(Uint::<4>::ZERO.is_zero());
        assert!(!Uint::<4>::ONE.is_zero());
        assert_eq!(Uint::<4>::ZERO.bit_length(), 0);
        assert_eq!(Uint::<4>::ONE.bit_length(), 1);
        // 2^64 has bit length 65.
        let b = Uint::<4>::from_limbs([0, 1, 0, 0]);
        assert_eq!(b.bit_length(), 65);
        assert_eq!(b.leading_zeros(), 256 - 65);
        assert_eq!(Uint::<4>::ZERO.leading_zeros(), 256);
        assert_eq!(Uint::<4>::MAX.leading_zeros(), 0);
    }

    #[test]
    fn uint_operator_traits_delegate() {
        let a = Uint::<4>::from_limbs([10, 0, 0, 0]);
        let b = Uint::<4>::from_limbs([3, 0, 0, 0]);
        assert_eq!(*(a + b).as_limbs(), [13, 0, 0, 0]);
        assert_eq!(*(a - b).as_limbs(), [7, 0, 0, 0]);
        assert_eq!(*(a * b).as_limbs(), [30, 0, 0, 0]);
    }

    #[test]
    fn int_from_i64_sign_extends() {
        // Positive: only the low limb is set.
        assert_eq!(*Int::<4>::from_i64(5).as_limbs(), [5, 0, 0, 0]);
        // -1 sign-extends to all-ones.
        assert_eq!(*Int::<4>::from_i64(-1).as_limbs(), [u64::MAX; 4]);
        // -2 → low limb u64::MAX - 1, upper limbs all-ones.
        assert_eq!(
            *Int::<4>::from_i64(-2).as_limbs(),
            [u64::MAX - 1, u64::MAX, u64::MAX, u64::MAX]
        );
        assert!(Int::<4>::from_i64(-1).is_negative());
        assert!(Int::<4>::from_i64(1).is_positive());
        assert!(Int::<4>::from_i64(0).is_zero());
    }

    #[test]
    fn int_wrapping_neg_two_complement() {
        let five = Int::<4>::from_i64(5);
        let neg_five = five.wrapping_neg();
        assert_eq!(neg_five, Int::<4>::from_i64(-5));
        // Negating twice returns the original.
        assert_eq!(neg_five.wrapping_neg(), five);
        // -1 negates to 1.
        assert_eq!(Int::<4>::from_i64(-1).wrapping_neg(), Int::<4>::ONE);
        // Neg operator delegates.
        assert_eq!(-five, neg_five);
    }

    #[test]
    fn int_add_sub_mul_with_signs() {
        let a = Int::<4>::from_i64(7);
        let b = Int::<4>::from_i64(-3);
        // 7 + (-3) = 4
        assert_eq!(a.wrapping_add(b), Int::<4>::from_i64(4));
        // 7 - (-3) = 10
        assert_eq!(a.wrapping_sub(b), Int::<4>::from_i64(10));
        // 7 * (-3) = -21
        assert_eq!(a.wrapping_mul(b), Int::<4>::from_i64(-21));
        // (-3) * (-3) = 9
        assert_eq!(b.wrapping_mul(b), Int::<4>::from_i64(9));
        // operator delegation
        assert_eq!(a + b, Int::<4>::from_i64(4));
        assert_eq!(a - b, Int::<4>::from_i64(10));
        assert_eq!(a * b, Int::<4>::from_i64(-21));
    }

    #[test]
    fn int_mul_crosses_limbs_with_sign() {
        // 2^64 * (-1) = -2^64.
        let big = Int::<4>::from_i64(0).wrapping_add(Int::<4>::from_limbs([0, 1, 0, 0]));
        let neg = big.wrapping_mul(Int::<4>::from_i64(-1));
        assert_eq!(neg, big.wrapping_neg());
        // -2^64 should be [0, u64::MAX, u64::MAX, u64::MAX].
        assert_eq!(*neg.as_limbs(), [0, u64::MAX, u64::MAX, u64::MAX]);
    }

    #[test]
    fn int_abs_signum() {
        assert_eq!(Int::<4>::from_i64(-9).abs(), Int::<4>::from_i64(9));
        assert_eq!(Int::<4>::from_i64(9).abs(), Int::<4>::from_i64(9));
        assert_eq!(Int::<4>::from_i64(-9).signum(), -1);
        assert_eq!(Int::<4>::from_i64(9).signum(), 1);
        assert_eq!(Int::<4>::from_i64(0).signum(), 0);
    }

    #[test]
    fn int_from_i128_round_trips() {
        for v in [
            0i128,
            1,
            -1,
            42,
            -42,
            i64::MAX as i128,
            i64::MIN as i128,
            i128::MAX,
            i128::MIN,
            123_456_789_012_345_678,
        ] {
            let a = Int::<4>::from_i128(v);
            assert_eq!(a.to_i128_checked(), Some(v), "round-trip i128 {v}");
            let b = Int::<8>::from_i128(v);
            assert_eq!(b.to_i128_checked(), Some(v), "round-trip i128 {v} (N=8)");
        }
        // from_u128 of a value above i128::MAX is not representable as i128.
        let big = Int::<4>::from_u128(u128::MAX);
        assert_eq!(big.to_i128_checked(), None);
        assert_eq!(big.to_u128_checked(), Some(u128::MAX));
        // Negative has no u128.
        assert_eq!(Int::<4>::from_i128(-1).to_u128_checked(), None);
    }

    #[test]
    fn int_from_str_radix_and_display_round_trip() {
        let cases = [
            "0",
            "1",
            "-1",
            "42",
            "-42",
            "1000000000000000000000",
            "-340282366920938463463374607431768211455",
        ];
        for s in cases {
            let v = Int::<4>::from_str_radix(s, 10).unwrap();
            assert_eq!(format!("{v}"), s, "display round-trip {s}");
            // FromStr delegates to from_str_radix(_, 10).
            let v2: Int<4> = s.parse().unwrap();
            assert_eq!(v, v2);
        }
        // Non-base-10 and malformed input reject.
        assert!(Int::<4>::from_str_radix("10", 16).is_err());
        assert!(Int::<4>::from_str_radix("12x", 10).is_err());
        assert!(Int::<4>::from_str_radix("", 10).is_err());
        assert!(Int::<4>::from_str_radix("-", 10).is_err());
    }

    #[test]
    fn int_div_rem_signs_match_truncating() {
        // Truncating division: quotient truncates toward zero, remainder
        // carries the sign of the dividend.
        let cases: [(i128, i128); 6] = [
            (1000, 7),
            (-1000, 7),
            (1000, -7),
            (-1000, -7),
            (7, 1000),
            (-7, 1000),
        ];
        for (a, b) in cases {
            let (q, r) = Int::<4>::from_i128(a).div_rem(Int::<4>::from_i128(b));
            assert_eq!(q.to_i128_checked(), Some(a / b), "quot {a}/{b}");
            assert_eq!(r.to_i128_checked(), Some(a % b), "rem {a}%{b}");
        }
    }

    #[test]
    #[should_panic(expected = "divide by zero")]
    fn int_div_rem_by_zero_panics() {
        let _ = Int::<4>::ONE.div_rem(Int::<4>::ZERO);
    }

    #[test]
    fn int_bit_reads_twos_complement() {
        let v = Int::<4>::from_i128(0b1010);
        assert!(!v.bit(0));
        assert!(v.bit(1));
        assert!(!v.bit(2));
        assert!(v.bit(3));
        // Above the value's set bits: clear for positive.
        assert!(!v.bit(200));
        // Negative: high bits read as the sign extension (all ones).
        let neg = Int::<4>::from_i128(-1);
        assert!(neg.bit(0));
        assert!(neg.bit(255));
        assert!(neg.bit(1000)); // out of range → sign bit
    }

    #[test]
    fn int_mul_u64_matches_wide_mul() {
        let v = Int::<4>::from_i128(123_456_789);
        assert_eq!(
            v.mul_u64(1000),
            Int::<4>::from_i128(123_456_789_000)
        );
        // Sign preserved.
        let n = Int::<4>::from_i128(-123_456_789);
        assert_eq!(
            n.mul_u64(1000),
            Int::<4>::from_i128(-123_456_789_000)
        );
        // Times zero / one.
        assert_eq!(v.mul_u64(0), Int::<4>::ZERO);
        assert_eq!(v.mul_u64(1), v);
    }

    #[test]
    #[should_panic(expected = "mul overflow")]
    fn int_mul_u64_overflow_panics() {
        // max_value * 2 overflows the signed range.
        let _ = Int::<4>::max_value().mul_u64(2);
    }

    #[test]
    fn int_div_rem_operators_match_div_rem() {
        // The Div / Rem operators must agree with the inherent div_rem,
        // which is what BigInt requires as supertraits.
        let a = Int::<4>::from_i128(-1000);
        let b = Int::<4>::from_i128(7);
        assert_eq!(a / b, Int::<4>::from_i128(-1000 / 7));
        assert_eq!(a % b, Int::<4>::from_i128(-1000 % 7));
        let (q, r) = a.div_rem(b);
        assert_eq!(a / b, q);
        assert_eq!(a % b, r);
    }

    // Exercises Int<8> isqrt (work width 9) beyond the narrow build's scratch.
    #[cfg(feature = "_wide-support")]
    #[test]
    fn int_wide_storage_surface() {
        use crate::int::types::traits::BigInt;
        fn exercises<T: BigInt>() {
            assert!(<T as BigInt>::ZERO == <T as BigInt>::from_i128(0));
            assert!(<T as BigInt>::ONE == <T as BigInt>::from_i128(1));
            assert!(<T as BigInt>::TEN == <T as BigInt>::from_i128(10));

            let twelve = <T as BigInt>::from_i128(12);
            let three = <T as BigInt>::from_i128(3);
            // pow / isqrt
            assert!(three.pow(3) == <T as BigInt>::from_i128(27));
            assert!(<T as BigInt>::from_i128(144).isqrt() == <T as BigInt>::from_i128(12));
            // div_rem
            let (q, r) = twelve.div_rem(<T as BigInt>::from_i128(5));
            assert!(q == <T as BigInt>::from_i128(2));
            assert!(r == <T as BigInt>::from_i128(2));
            // bit / leading_zeros
            assert!(twelve.bit(2) && twelve.bit(3) && !twelve.bit(0));
            assert!(<T as BigInt>::ONE.leading_zeros() == <T as BigInt>::BITS - 1);
            // mul_u64 / f64 round-trips
            assert!(twelve.mul_u64(10) == <T as BigInt>::from_i128(120));
            assert!(twelve.to_f64() == 12.0);
            assert!(<T as BigInt>::from_f64_val(7.9) == <T as BigInt>::from_i128(7));
        }
        exercises::<Int<4>>();
        exercises::<Int<8>>();

        // resize_to widens/narrows across the family.
        let v = Int::<4>::from_i128(-123_456_789);
        let w: Int<8> = BigInt::resize_to(v);
        assert_eq!(w.to_i128_checked(), Some(-123_456_789));
        let back: Int<4> = BigInt::resize_to(w);
        assert_eq!(back, v);
    }

    // Perfect-square round-trip at Int<8> exceeds the narrow build's scratch.
    #[cfg(feature = "_wide-support")]
    #[test]
    fn int_isqrt_matches_uint_magnitude() {
        use crate::int::types::traits::BigInt;
        // Signed isqrt is the magnitude isqrt (macro parity).
        let n = Int::<4>::from_i128(1_000_000_000_000);
        let r = BigInt::isqrt(n);
        assert_eq!(r, Int::<4>::from_i128(1_000_000));
        // Perfect square round-trip at width 8.
        let big = Int::<8>::from_i128(987_654_321);
        let sq = big.checked_mul(big).unwrap();
        assert_eq!(BigInt::isqrt(sq), big);
    }

    /// `Uint<N>::sqr` must equal `x * x` at every tested width; the policy
    /// dispatcher must agree with `wrapping_sqr`.
    #[test]
    fn uint_sqr_policy_matches_wrapping_sqr() {
        fn check<const N: usize>(limbs: [u64; N]) {
            let x = Uint::<N>::from_limbs(limbs);
            assert_eq!(x.sqr(), x.wrapping_sqr(), "sqr mismatch at {limbs:?}");
            assert_eq!(x.sqr(), x.wrapping_mul(x), "sqr != x*x at {limbs:?}");
        }
        // Width 1
        check::<1>([0]);
        check::<1>([1]);
        check::<1>([u64::MAX]);
        check::<1>([12345]);
        // Width 2
        check::<2>([0, 0]);
        check::<2>([1, 0]);
        check::<2>([u64::MAX, u64::MAX]);
        check::<2>([0xDEAD_BEEF, 0x1234]);
        // Width 4
        check::<4>([u64::MAX, u64::MAX, u64::MAX, u64::MAX]);
        check::<4>([0x1234_5678_9ABC_DEF0, 0xFEDC_BA98, 0, 0]);
        // Width 6
        check::<6>([7, 8, 9, 10, 11, 12]);
    }

    /// `Uint<N>::cube` must equal `x * x * x` at every tested width.
    #[test]
    fn uint_cube_policy_matches_wrapping_cube() {
        fn check<const N: usize>(limbs: [u64; N]) {
            let x = Uint::<N>::from_limbs(limbs);
            assert_eq!(x.cube(), x.wrapping_cube(), "cube mismatch at {limbs:?}");
            assert_eq!(
                x.cube(),
                x.wrapping_mul(x).wrapping_mul(x),
                "cube != x*x*x at {limbs:?}"
            );
        }
        check::<1>([0]);
        check::<1>([1]);
        check::<1>([3]);
        check::<1>([u64::MAX]);
        check::<2>([0, 0]);
        check::<2>([1, 0]);
        check::<2>([100, 0]);
        check::<2>([u64::MAX, u64::MAX]);
        check::<4>([5, 0, 0, 0]);
        check::<4>([0x1234, 0x5678, 0, 0]);
    }

    /// `Int<N>::sqr` and `Int<N>::cube` must match their wrapping siblings.
    #[test]
    fn int_sqr_cube_match_wrapping() {
        fn check<const N: usize>(v: i128) {
            let x = Int::<N>::from_i128(v);
            assert_eq!(x.sqr(), x.wrapping_sqr(), "int sqr mismatch v={v}");
            assert_eq!(x.cube(), x.wrapping_cube(), "int cube mismatch v={v}");
        }
        for v in [0i128, 1, -1, 12, -12, 100, -100, 1_000_000, -1_000_000] {
            check::<4>(v);
            check::<8>(v);
        }
    }

    /// `Uint<N>::icbrt` must return `floor(x^(1/3))` for a range of
    /// values: perfect cubes, non-cubes, 0, 1, and large values.
    #[test]
    fn uint_icbrt_floor_correctness() {
        // Brute-force floor cube-root of a u64, used as oracle for small inputs.
        fn brute_cbrt(n: u64) -> u64 {
            if n == 0 {
                return 0;
            }
            let mut r: u64 = 0;
            while (r + 1).checked_mul((r + 1) * (r + 1) + r + 1)
                .is_some_and(|p| p <= n)
                || (r + 1).checked_pow(3).is_some_and(|p| p <= n)
            {
                r += 1;
            }
            r
        }

        fn check<const N: usize>(n: u64) {
            let x = Uint::<N>::from_u64(n);
            let root = x.icbrt();
            let root_u64 = root.as_limbs()[0];
            let expected = brute_cbrt(n);
            assert_eq!(root_u64, expected, "icbrt({n}) = {root_u64}, expected {expected}");
            // Higher limbs of root must be zero for a u64 input.
            for i in 1..N {
                assert_eq!(root.as_limbs()[i], 0, "icbrt({n}) high limb {i} nonzero");
            }
        }

        // Perfect cubes.
        for n in [0u64, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000,
                  1_000_000_000u64, 8_000_000_000u64] {
            check::<1>(n);
            check::<2>(n);
            check::<4>(n);
        }

        // Non-cubes (floor must be correct).
        for n in [2u64, 3, 4, 5, 6, 7, 9, 10, 26, 28, 63, 65, 999,
                  1_000_000_001u64] {
            check::<1>(n);
            check::<2>(n);
            check::<4>(n);
        }

        // Boundary cases: 0 and 1.
        check::<1>(0);
        check::<1>(1);
        check::<4>(0);
        check::<4>(1);

        // Large 64-bit values.
        for n in [u64::MAX, u64::MAX - 1, u64::MAX - 100, 1 << 60, 1 << 48] {
            check::<2>(n);
            check::<4>(n);
        }
    }

    /// `Uint<N>::icbrt` for values spanning multiple limbs (N >= 3 path).
    /// The cube root of a 2-limb value still fits in a single u64; we
    /// verify the floor identity `r³ <= x < (r+1)³`.
    #[test]
    fn uint_icbrt_wide_floor_identity() {
        fn check_wide<const N: usize>(limbs: [u64; N]) {
            let x = Uint::<N>::from_limbs(limbs);
            let r = x.icbrt();
            // Verify r³ <= x.
            let r3 = r.wrapping_pow(3);
            assert!(
                r3 <= x,
                "icbrt violated: r³ > x for {limbs:?}"
            );
            // Verify (r+1)³ > x (i.e. r is the floor).
            let r1 = r.wrapping_add(Uint::<N>::ONE);
            let r1_3 = r1.wrapping_pow(3);
            // (r+1)³ wraps to 0 only if r+1 itself wraps (i.e. r == MAX),
            // which for a cube root of a representable value cannot happen.
            assert!(
                r1_3 > x || r1 == Uint::<N>::ZERO,
                "icbrt not floor: (r+1)³ <= x for {limbs:?}"
            );
        }

        // Perfect cubes in 2 limbs (root fits one limb).
        // 10^18 cubed = 10^54 — too large; use modest values.
        // 1_000_000^3 = 10^18, which fits 2 limbs (u64 goes to ~1.8 * 10^19).
        let m = 1_000_000u64;
        let m3 = m * m * m; // 10^18, fits u64
        check_wide::<4>([m3, 0, 0, 0]);
        check_wide::<4>([m3 + 1, 0, 0, 0]);
        check_wide::<4>([m3 - 1, 0, 0, 0]);

        // A 2-limb value: combine two u64 halves.
        let hi = 1u64;
        let lo = 0u64;
        check_wide::<4>([lo, hi, 0, 0]); // 2^64

        check_wide::<4>([u64::MAX, u64::MAX, 0, 0]); // near 2^128

        // Width 6 (N >= 3, Newton path for sure).
        check_wide::<6>([m3, 0, 0, 0, 0, 0]);
        check_wide::<6>([u64::MAX, u64::MAX, u64::MAX, 0, 0, 0]); // near 2^192
    }

    /// `Int<N>::icbrt` must return the unsigned cube root of the magnitude.
    #[test]
    fn int_icbrt_magnitude() {
        for v in [0i128, 1, -1, 8, -8, 27, -27, 1000, -1000] {
            let x = Int::<4>::from_i128(v);
            let expected = Int::<4>::from_i128((v.unsigned_abs() as f64).cbrt() as i128);
            let got = x.icbrt();
            assert_eq!(got, expected, "int icbrt({v}) mismatch");
        }
    }

    #[test]
    fn int_wideint_mag_sign_round_trips() {
        use crate::int::types::traits::BigInt;
        // mag_into_u128 / from_mag_sign_u128 round-trip for signed
        // values, including the magnitude + sign split.
        for v in [0i128, 1, -1, 123_456_789_012_345_678, -987_654_321] {
            let a = Int::<4>::from_i128(v);
            let mut mag = [0u128; 2];
            let neg = a.mag_into_u128(&mut mag);
            assert_eq!(neg, a.is_negative());
            assert_eq!(Int::<4>::from_mag_sign_u128(&mag, neg), a, "mag/sign {v}");
        }
        // U128_LIMBS = ceil(N/2): even and odd N.
        assert_eq!(<Int<4> as BigInt>::U128_LIMBS, 2);
        assert_eq!(<Int<3> as BigInt>::U128_LIMBS, 2);
        assert_eq!(<Int<8> as BigInt>::U128_LIMBS, 4);

        // mag_into_u128 / from_mag_sign_u128 round-trip (the hot-path
        // buffer bypass), including the odd-N tail at N=3.
        let v3 = Int::<3>::from_i128(-170_141_183_460_469_231_731);
        let mut buf = [0u128; 2];
        let neg = v3.mag_into_u128(&mut buf);
        assert_eq!(Int::<3>::from_mag_sign_u128(&buf, neg), v3);

        let v4 = Int::<4>::from_i128(i128::MIN);
        let mut buf4 = [0u128; 2];
        let neg4 = v4.mag_into_u128(&mut buf4);
        assert_eq!(Int::<4>::from_mag_sign_u128(&buf4, neg4), v4);
    }

    #[test]
    fn int_to_from_f64_and_negate_ten() {
        assert_eq!(Int::<4>::from_i64(5).to_f64(), 5.0);
        assert_eq!(Int::<4>::from_i64(-5).to_f64(), -5.0);
        assert_eq!(Int::<4>::from_f64(42.9), Int::<4>::from_i64(42));
        assert_eq!(Int::<4>::from_f64(-42.9), Int::<4>::from_i64(-42));
        // Non-finite maps to ZERO.
        assert_eq!(Int::<4>::from_f64(f64::NAN), Int::<4>::ZERO);
        // negate is wrapping_neg; TEN const is 10.
        assert_eq!(Int::<4>::from_i64(5).negate(), Int::<4>::from_i64(-5));
        assert_eq!(Int::<4>::TEN, Int::<4>::from_i64(10));
        // from_limbs_le / limbs_le round-trip.
        let v = Int::<4>::from_i128(-9_876_543_210);
        assert_eq!(Int::<4>::from_limbs_le(v.limbs_le()), v);
    }

    #[test]
    fn int_signed_ordering() {
        let neg = Int::<4>::from_i64(-5);
        let zero = Int::<4>::ZERO;
        let pos = Int::<4>::from_i64(5);
        // Negative < zero < positive even though -5's limbs are larger
        // unsigned than 5's.
        assert!(neg < zero);
        assert!(zero < pos);
        assert!(neg < pos);
        // Two negatives compare by magnitude with sign accounted for.
        assert!(Int::<4>::from_i64(-10) < Int::<4>::from_i64(-1));
        assert_eq!(neg.max(pos), pos);
        assert_eq!(neg.min(pos), neg);
        assert_eq!(pos.cmp(&pos), Ordering::Equal);
    }
}

/// Feasibility proof for the unified narrow-tier divide path: the same
/// `widen_mul` → `div_wide_pow10` pipeline the wide tiers already
/// run must produce the correct `(a · b) / 10^scale` at the narrow
/// limb widths `N = 1` (`Int64`) and `N = 2` (`Int128`) that the
/// D18/D38-unify steps will rewire onto. This locks in the
/// `widen_mul::<wider>` then `div_wide_pow10::<wider>`
/// composition before any decimal type is rewired; it is additive and
/// asserts only — no behaviour is changed here.
#[cfg(all(test, feature = "wide"))]
mod unified_mg_feasibility {
    use super::Int;
    use crate::algos::support::mg_divide::div_wide_pow10;
    use crate::int::types::compute_limbs::{ComputeLimbs, Limbs};
    use crate::int::types::traits::BigInt;
    use crate::support::rounding::RoundingMode;

    /// `(a · b) / 10^scale` through the unified pipeline, computed as
    /// `Int<N>::widen_mul::<Int<M>>` (full product into the wider type)
    /// then `div_wide_pow10::<Int<M>>`. The wider type's u128 magnitude
    /// width is read from its scratch carrier's [`ComputeLimbs`] buffer
    /// (`single_u128`) inside the divide — the `Limbs<N>` carrier IS the
    /// mechanism for the wider work intermediate, so no work-width const
    /// parameter is named. Returns the scaled wider-width quotient.
    fn scaled<const N: usize, const M: usize>(a: Int<N>, b: Int<N>, scale: u32) -> Int<M>
    where
        Limbs<N>: ComputeLimbs,
        Int<M>: BigInt,
        Limbs<M>: ComputeLimbs,
        <Int<M> as BigInt>::Scratch: ComputeLimbs,
    {
        let prod: Int<M> = a.widen_mul::<Int<M>>(b);
        div_wide_pow10::<Int<M>>(prod, scale, RoundingMode::HalfToEven)
    }

    /// N = 2 → widen to N = 4, scale 5 (the plan's anchor case).
    #[test]
    fn n2_widen4_scale5() {
        let a = Int::<2>::from_i64(123456789);
        let b = Int::<2>::from_i64(987654321);
        let got = scaled::<2, 4>(a, b, 5);
        assert_eq!(got, Int::<4>::from_i64(1219326311126));
    }

    /// N = 1 → widen to N = 2, scale 3 (the plan's anchor case).
    #[test]
    fn n1_widen2_scale3() {
        let a = Int::<1>::from_i64(123456);
        let b = Int::<1>::from_i64(654321);
        let got = scaled::<1, 2>(a, b, 3);
        assert_eq!(got, Int::<2>::from_i64(80779853));
    }

    /// Round-trip: `(x · 10^k) / 10^k == x` at both narrow widths. The
    /// widen_mul forms `x · 10^k` exactly in the wider type and the MG
    /// divide undoes it with no residue.
    #[test]
    fn round_trip_mul_then_div() {
        // N = 1 → 2: x = 4242, k = 4.
        let x1 = 4242i64;
        let ten_pow_4 = Int::<1>::from_i64(10_000);
        let rt1 = scaled::<1, 2>(Int::<1>::from_i64(x1), ten_pow_4, 4);
        assert_eq!(rt1, Int::<2>::from_i64(x1));

        // N = 2 → 4: x = 9_876_543_210, k = 7.
        let x2 = 9_876_543_210i64;
        let ten_pow_7 = Int::<2>::from_i64(10_000_000);
        let rt2 = scaled::<2, 4>(Int::<2>::from_i64(x2), ten_pow_7, 7);
        assert_eq!(rt2, Int::<4>::from_i64(x2));
    }

    /// Scale-0 identity: callers short-circuit `scale == 0` as a no-op
    /// (`div_wide_pow10` is only ever invoked for `1..=38`), so the
    /// scaled value at scale 0 is exactly the full widen_mul product.
    /// This locks that contract for the narrow widths.
    #[test]
    fn scale_zero_is_widen_mul_identity() {
        // N = 1 → 2.
        let a1 = Int::<1>::from_i64(123456);
        let b1 = Int::<1>::from_i64(654321);
        let prod1: Int<2> = a1.widen_mul::<Int<2>>(b1);
        assert_eq!(prod1, Int::<2>::from_i64(123456 * 654321));

        // N = 2 → 4.
        let a2 = Int::<2>::from_i64(123456789);
        let b2 = Int::<2>::from_i64(987654321);
        let prod2: Int<4> = a2.widen_mul::<Int<4>>(b2);
        assert_eq!(prod2, Int::<4>::from_i64(123456789i64 * 987654321i64));
    }

    /// Max-operand case at each narrow width: the widest product the
    /// source width can hold must widen and scale without truncation.
    #[test]
    fn max_operand_each_width() {
        // N = 1: u64::MAX-ish operands. Use the largest i64 magnitudes
        // whose product the widen_mul (into N = 2) holds exactly, then
        // scale by 10^9 and check against the u128 reference.
        let a1 = Int::<1>::from_i64(i64::MAX);
        let b1 = Int::<1>::from_i64(i64::MAX);
        let got1 = scaled::<1, 2>(a1, b1, 9);
        let exact1 = (i64::MAX as i128) * (i64::MAX as i128);
        let pow9 = 1_000_000_000i128;
        let q1 = exact1 / pow9;
        let r1 = exact1 % pow9;
        // HalfToEven bump when the remainder is past the halfway point.
        let half = pow9 / 2;
        let expect1 = if r1 > half || (r1 == half && (q1 & 1) == 1) {
            q1 + 1
        } else {
            q1
        };
        assert_eq!(got1, Int::<2>::from_i128(expect1));

        // N = 2: the most-positive signed operand (2^127 - 1) squared,
        // widened into N = 4, then scaled by 10^20. Compare against the
        // exact reference reconstructed from the full 256-bit product.
        let big = Int::<2>::MAX; // 2^127 - 1
        let got2 = scaled::<2, 4>(big, big, 20);
        let prod2: Int<4> = big.widen_mul::<Int<4>>(big);
        // Exact (2^127 - 1)^2 / 10^20, HalfToEven, via the wider type's
        // own div_rem against 10^20 built in Int<4>.
        let pow20 = Int::<4>::TEN.pow(20);
        let (q2, r2) = prod2.div_rem(pow20);
        let half20 = pow20.div_rem(Int::<4>::from_i64(2)).0;
        let expect2 = match r2.cmp(&half20) {
            core::cmp::Ordering::Greater => q2.wrapping_add(Int::<4>::ONE),
            core::cmp::Ordering::Equal => {
                if (q2.as_limbs()[0] & 1) == 1 {
                    q2.wrapping_add(Int::<4>::ONE)
                } else {
                    q2
                }
            }
            core::cmp::Ordering::Less => q2,
        };
        assert_eq!(got2, expect2);
    }
}

#[cfg(test)]
mod bit_count_contract_tests {
    use super::{Int, Uint};

    /// `Int<N>`'s four bit-count methods must match the `iN`
    /// two's-complement contract at every edge, and `bit_length` must
    /// stay magnitude-based. Where the value fits a primitive we assert
    /// against `i64`/`i128`; otherwise against the known answer.
    #[test]
    fn int_bit_counts_match_signed_contract_at_edges() {
        // ── Int<1> (64-bit): cross-check directly against i64. ──
        for v in [0_i64, 1, -1, i64::MAX, i64::MIN, 42, -42, 1 << 40, -(1 << 40)] {
            let x = Int::<1>::from_i64(v);
            assert_eq!(x.leading_zeros(), v.leading_zeros(), "i64 lz {v}");
            assert_eq!(x.trailing_zeros(), v.trailing_zeros(), "i64 tz {v}");
            assert_eq!(x.count_ones(), v.count_ones(), "i64 popcount {v}");
            assert_eq!(x.count_zeros(), v.count_zeros(), "i64 cz {v}");
            // bit_length is magnitude-based: significant bits of |v|.
            let mag_bits = 64 - v.unsigned_abs().leading_zeros();
            assert_eq!(x.bit_length(), mag_bits, "i64 bit_length {v}");
        }

        // ── Int<2> (128-bit): cross-check directly against i128. ──
        for v in [
            0_i128,
            1,
            -1,
            i128::MAX,
            i128::MIN,
            (1_i128 << 64),       // 2^64 — limb boundary
            (1_i128 << 64) - 1,   // 2^64 - 1 — fills the low limb
            -(1_i128 << 64),
            i64::MAX as i128,
            i64::MIN as i128,
        ] {
            let x = Int::<2>::from_i128(v);
            assert_eq!(x.leading_zeros(), v.leading_zeros(), "i128 lz {v}");
            assert_eq!(x.trailing_zeros(), v.trailing_zeros(), "i128 tz {v}");
            assert_eq!(x.count_ones(), v.count_ones(), "i128 popcount {v}");
            assert_eq!(x.count_zeros(), v.count_zeros(), "i128 cz {v}");
            let mag_bits = 128 - v.unsigned_abs().leading_zeros();
            assert_eq!(x.bit_length(), mag_bits, "i128 bit_length {v}");
        }

        // ── Int<4> (256-bit): values beyond i128 — assert the known
        //    two's-complement answer directly. ──
        const B: u32 = Int::<4>::BITS; // 256

        // Zero: BITS leading zeros, BITS trailing zeros, no ones,
        // BITS clear bits, zero magnitude bits.
        let z = Int::<4>::ZERO;
        assert_eq!(z.leading_zeros(), B);
        assert_eq!(z.trailing_zeros(), B);
        assert_eq!(z.count_ones(), 0);
        assert_eq!(z.count_zeros(), B);
        assert_eq!(z.bit_length(), 0);

        // One.
        let one = Int::<4>::ONE;
        assert_eq!(one.leading_zeros(), B - 1);
        assert_eq!(one.trailing_zeros(), 0);
        assert_eq!(one.count_ones(), 1);
        assert_eq!(one.count_zeros(), B - 1);
        assert_eq!(one.bit_length(), 1);

        // -1 == all ones in two's complement: sign bit set so zero
        // leading zeros, every bit a one, zero trailing zeros.
        // Magnitude is 1, so bit_length is 1.
        let neg_one = Int::<4>::from_i64(-1);
        assert_eq!(*neg_one.as_limbs(), [u64::MAX; 4]);
        assert_eq!(neg_one.leading_zeros(), 0);
        assert_eq!(neg_one.trailing_zeros(), 0);
        assert_eq!(neg_one.count_ones(), B);
        assert_eq!(neg_one.count_zeros(), 0);
        assert_eq!(neg_one.bit_length(), 1);

        // MAX == 0b0111…1: top bit clear, the rest set.
        let max = Int::<4>::MAX;
        assert_eq!(max.leading_zeros(), 1);
        assert_eq!(max.trailing_zeros(), 0);
        assert_eq!(max.count_ones(), B - 1);
        assert_eq!(max.count_zeros(), 1);
        assert_eq!(max.bit_length(), B - 1); // magnitude is 2^(B-1) - 1

        // MIN == 0b1000…0: only the sign bit set. Negative → zero
        // leading zeros; the single set bit is the top one, so
        // trailing_zeros == BITS-1; magnitude |MIN| == 2^(B-1).
        let min = Int::<4>::MIN;
        assert_eq!(min.leading_zeros(), 0);
        assert_eq!(min.trailing_zeros(), B - 1);
        assert_eq!(min.count_ones(), 1);
        assert_eq!(min.count_zeros(), B - 1);
        assert_eq!(min.bit_length(), B); // |MIN| = 2^(B-1) ⇒ B significant bits

        // Limb-boundary magnitudes: 2^64 and 2^64 - 1 in Int<4>.
        let two_64 = Int::<4>::from_u128(1u128 << 64);
        assert_eq!(two_64.trailing_zeros(), 64);
        assert_eq!(two_64.count_ones(), 1);
        assert_eq!(two_64.leading_zeros(), B - 65);
        assert_eq!(two_64.bit_length(), 65);

        let two_64_m1 = Int::<4>::from_u128((1u128 << 64) - 1);
        assert_eq!(two_64_m1.trailing_zeros(), 0);
        assert_eq!(two_64_m1.count_ones(), 64);
        assert_eq!(two_64_m1.leading_zeros(), B - 64);
        assert_eq!(two_64_m1.bit_length(), 64);
    }

    /// `Uint<N>`'s bit-count surface (`leading_zeros`, `count_ones`,
    /// `bit_length`) must match the `uN` contract at the edges.
    #[test]
    fn uint_bit_counts_match_unsigned_contract_at_edges() {
        // ── Uint<1> (64-bit): cross-check against u64. ──
        for v in [0_u64, 1, u64::MAX, 42, 1 << 40] {
            let x = Uint::<1>::from_u64(v);
            assert_eq!(x.leading_zeros(), v.leading_zeros(), "u64 lz {v}");
            assert_eq!(x.count_ones(), v.count_ones(), "u64 popcount {v}");
            // For unsigned, bit_length == BITS - leading_zeros.
            assert_eq!(x.bit_length(), 64 - v.leading_zeros(), "u64 bit_length {v}");
        }

        // ── Uint<2> (128-bit): cross-check against u128, incl. limb
        //    boundary 2^64 / 2^64 - 1. ──
        for v in [0_u128, 1, u128::MAX, 1u128 << 64, (1u128 << 64) - 1] {
            let x = Uint::<2>::from_u128(v);
            assert_eq!(x.leading_zeros(), v.leading_zeros(), "u128 lz {v}");
            assert_eq!(x.count_ones(), v.count_ones(), "u128 popcount {v}");
            assert_eq!(x.bit_length(), 128 - v.leading_zeros(), "u128 bit_length {v}");
        }

        // ── Uint<4> (256-bit): values beyond u128 — known answers. ──
        const B: u32 = Uint::<4>::BITS; // 256
        let zero = Uint::<4>::ZERO;
        assert_eq!(zero.leading_zeros(), B);
        assert_eq!(zero.count_ones(), 0);
        assert_eq!(zero.bit_length(), 0);

        // All-ones (Uint MAX): no leading zeros, every bit set.
        let umax = Uint::<4>::from_limbs([u64::MAX; 4]);
        assert_eq!(umax.leading_zeros(), 0);
        assert_eq!(umax.count_ones(), B);
        assert_eq!(umax.bit_length(), B);

        // 2^64 across the low limb boundary.
        let two_64 = Uint::<4>::from_u128(1u128 << 64);
        assert_eq!(two_64.count_ones(), 1);
        assert_eq!(two_64.leading_zeros(), B - 65);
        assert_eq!(two_64.bit_length(), 65);
    }
}

/// Behavioural sanity checks for the const-generic `Int<N>` / `Uint<N>`
/// public surface, exercising the limb kernels end-to-end through the
/// type API (add/sub/neg, mul/div/rem, overflow, parse/pow, ordering /
/// resize, isqrt / f64, the unsigned bit helpers, and `as_u128`).
#[cfg(test)]
mod hint_tests {
    use super::{Int, Uint};

    #[test]
    fn signed_add_sub_neg() {
        let a = Int::<4>::from_i128(5);
        let b = Int::<4>::from_i128(3);
        assert_eq!(a.wrapping_add(b), Int::<4>::from_i128(8));
        assert_eq!(a.wrapping_sub(b), Int::<4>::from_i128(2));
        assert_eq!(b.wrapping_sub(a), Int::<4>::from_i128(-2));
        assert_eq!(a.negate(), Int::<4>::from_i128(-5));
        assert_eq!(Int::<4>::ZERO.negate(), Int::<4>::ZERO);
    }

    #[test]
    fn signed_mul_div_rem() {
        let six = Int::<8>::from_i128(6);
        let two = Int::<8>::from_i128(2);
        let three = Int::<8>::from_i128(3);
        assert_eq!(six.wrapping_mul(three), Int::<8>::from_i128(18));
        assert_eq!(six.wrapping_div(two), three);
        assert_eq!(
            Int::<8>::from_i128(7).wrapping_rem(three),
            Int::<8>::from_i128(1)
        );
        assert_eq!(
            Int::<8>::from_i128(-7).wrapping_rem(three),
            Int::<8>::from_i128(-1)
        );
        assert_eq!(six.negate().wrapping_mul(three), Int::<8>::from_i128(-18));
    }

    #[test]
    fn checked_overflow() {
        assert_eq!(Int::<4>::MAX.checked_add(Int::<4>::ONE), None);
        assert_eq!(Int::<4>::MIN.checked_sub(Int::<4>::ONE), None);
        assert_eq!(Int::<4>::MIN.checked_neg(), None);
        assert_eq!(
            Int::<4>::from_i128(2).checked_add(Int::<4>::from_i128(3)),
            Some(Int::<4>::from_i128(5))
        );
    }

    #[test]
    fn from_str_and_pow() {
        let ten = Int::<16>::from_str_radix("10", 10).unwrap();
        assert_eq!(ten, Int::<16>::from_i128(10));
        assert_eq!(ten.pow(3), Int::<16>::from_i128(1000));
        let big = Int::<16>::from_str_radix("10", 10).unwrap().pow(40);
        let from_str =
            Int::<16>::from_str_radix("10000000000000000000000000000000000000000", 10).unwrap();
        assert_eq!(big, from_str);
        assert_eq!(
            Int::<4>::from_str_radix("-42", 10).unwrap(),
            Int::<4>::from_i128(-42)
        );
    }

    #[test]
    fn ordering_and_resize() {
        assert!(Int::<4>::from_i128(-1) < Int::<4>::ZERO);
        assert!(Int::<4>::MIN < Int::<4>::MAX);
        let v = Int::<4>::from_i128(-123_456_789);
        let wide: Int<16> = v.resize();
        let back: Int<4> = wide.resize();
        assert_eq!(back, v);
        assert_eq!(wide, Int::<16>::from_i128(-123_456_789));
    }

    // Int<8> isqrt (work width 9) exceeds the narrow build's int scratch.
    #[cfg(feature = "_wide-support")]
    #[test]
    fn isqrt_and_f64() {
        assert_eq!(Int::<8>::from_i128(144).isqrt(), Int::<8>::from_i128(12));
        assert_eq!(Int::<4>::from_i128(1_000_000).as_f64(), 1_000_000.0);
        assert_eq!(Int::<4>::from_f64(-2_500.0), Int::<4>::from_i128(-2500));
    }

    /// `Uint<4>` (the unsigned macro emission) supports the same
    /// bit/sign-manipulation surface as the signed sibling.
    #[test]
    fn uint256_is_zero_and_bit_helpers() {
        let zero = Uint::<4>::ZERO;
        let one = Uint::<4>::from_str_radix("1", 10).unwrap();
        let two = Uint::<4>::from_str_radix("2", 10).unwrap();
        assert!(zero.is_zero());
        assert!(!one.is_zero());
        assert!(one.is_power_of_two());
        assert!(two.is_power_of_two());
        let three = Uint::<4>::from_str_radix("3", 10).unwrap();
        assert!(!three.is_power_of_two());
        assert_eq!(zero.next_power_of_two(), one);
        assert_eq!(one.next_power_of_two(), one);
        let four = Uint::<4>::from_str_radix("4", 10).unwrap();
        assert_eq!(three.next_power_of_two(), four);
        assert_eq!(zero.count_ones(), 0);
        assert_eq!(one.count_ones(), 1);
        assert_eq!(zero.leading_zeros(), Uint::<4>::BITS);
        assert_eq!(one.leading_zeros(), Uint::<4>::BITS - 1);
    }

    #[test]
    fn uint256_parse_arithmetic_and_pow() {
        assert!(Uint::<4>::from_str_radix("10", 2).is_err());
        assert!(Uint::<4>::from_str_radix("1a", 10).is_err());
        let two = Uint::<4>::from_str_radix("2", 10).unwrap();
        let three = Uint::<4>::from_str_radix("3", 10).unwrap();
        let six = Uint::<4>::from_str_radix("6", 10).unwrap();
        let seven = Uint::<4>::from_str_radix("7", 10).unwrap();
        assert_eq!(three - two, Uint::<4>::from_str_radix("1", 10).unwrap());
        assert_eq!(six / two, three);
        assert_eq!(seven % three, Uint::<4>::from_str_radix("1", 10).unwrap());
        let five = Uint::<4>::from_str_radix("5", 10).unwrap();
        let four = Uint::<4>::from_str_radix("4", 10).unwrap();
        let one = Uint::<4>::from_str_radix("1", 10).unwrap();
        assert_eq!(five & four, four);
        assert_eq!(five | one, five);
        assert_eq!(five ^ four, one);
        let p10 = two.pow(10);
        assert_eq!(p10, Uint::<4>::from_str_radix("1024", 10).unwrap());
        let signed = three.cast_signed();
        assert_eq!(signed, Int::<4>::from_i128(3));
    }

    /// `Int::<4>::bit` reports the two's-complement bit at any index.
    #[test]
    fn signed_bit_and_trailing_zeros() {
        let v = Int::<4>::from_i128(0b1100);
        assert!(v.bit(2));
        assert!(v.bit(3));
        assert!(!v.bit(0));
        assert!(!v.bit(1));
        assert!(!v.bit(1000));
        let n = Int::<4>::from_i128(-1);
        assert!(n.bit(1000));
        assert_eq!(Int::<4>::from_i128(8).trailing_zeros(), 3);
        assert_eq!(Int::<4>::ZERO.trailing_zeros(), Int::<4>::BITS);
    }

    /// `Int::<4>::as_u128` returns the low 128 magnitude bits.
    #[test]
    fn as_u128_returns_low_magnitude_bits() {
        let src = Int::<4>::from_i128(123_456_789);
        let dst: u128 = src.as_u128();
        assert_eq!(dst, 123_456_789);
        let dst: u128 = Int::<4>::ZERO.as_u128();
        assert_eq!(dst, 0);
    }
}