noprop 0.2.1

Property-based testing with plain functions, ordinary control flow, and no dependencies
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
//! Value generators. See [`crate::docs::generator_authoring`] for the
//! authoring guide (composition patterns, bounded rejection, `NonZero`
//! recipes, floats).

use std::ops::{Bound, RangeBounds};
use std::panic::Location;

use crate::TestCaseContext;

/// Read `N` bytes from `ctx` without recording. Used by every primitive
/// so that composite generators (non-zero variants, `sample_char`,
/// floats, `sample_choice`) can consume randomness without producing
/// intermediate trace entries for the raw byte source.
///
/// `#[track_caller]` so an exploratory-draw-cap rejection reports the
/// user's `sample_*` call site rather than this helper (see
/// [`TestCaseContext::fill`] and `within_generated_draw_cap`).
#[track_caller]
fn raw_bytes<const N: usize>(ctx: &mut TestCaseContext) -> [u8; N] {
    let mut buf = [0u8; N];
    ctx.fill(&mut buf);
    buf
}

// === Bounded rejection sampling ===

/// Shared attempt limit for every internal bounded rejection loop in
/// this module. Chosen so that a per-attempt rejection rate up to 50%
/// (the worst case for [`sample_below`]) still exhausts with
/// probability `< 2⁻⁶⁴`.
pub(crate) const DEFAULT_MAX_ATTEMPTS: usize = 64;

/// Repeatedly invoke `attempt` up to `max_attempts` times until it
/// returns `Some`, then return that value. On exhaustion (all attempts
/// returned `None`) this calls
/// [`TestCaseContext::reject_case`](crate::TestCaseContext::reject_case), which unwinds out to
/// the enclosing [`Runner::run`](crate::Runner::run) and marks the
/// current iteration as rejected — so this function's return type is
/// `T`, not `Option<T>`.
///
/// The helper is the noprop-endorsed way to write bounded rejection
/// sampling. Prefer it over hand-written `loop { … }` retries: those
/// can spin forever on choice sequences where every draw fails the
/// predicate, and cannot signal iteration-level rejection to the
/// runner. Use `reject_case` directly only when the whole iteration is
/// unsuitable after sampling has already finished.
///
/// # Behavior
///
/// - The first `Some(value)` returned by `attempt` is passed through
///   unchanged; subsequent attempts are not tried.
/// - `None` is treated as a rejected attempt and the next attempt is
///   tried.
/// - `max_attempts` counts the total attempts including the first, so
///   `max_attempts == 1` gives one shot; `max_attempts == 0` is a
///   programmer error and panics.
/// - An attempt that consumes zero draws (a drawless filter, e.g. a
///   pure predicate over external state) is allowed.
/// - The closure may itself call `sample_with_rejection` — nested
///   calls are supported.
/// - A user panic inside the closure (other than the private
///   iteration-rejection marker sent by `reject_case`) propagates
///   verbatim; the runner's own `catch_unwind` handles it as a
///   property failure.
///
/// # Determinism note
///
/// This is a control-flow boundary, not a value primitive. The
/// accepted `T` is not recorded as a new `GeneratedValue` entry — the
/// primitives called inside `attempt` are still recorded normally, so
/// the trace shows the actual draws rather than a redundant wrapper.
///
/// # Panics
///
/// Panics if `max_attempts == 0`.
///
/// # Examples
///
/// ```
/// # let _: noprop::RunResult = noprop::Runner::new(0).run(1, |ctx| {
/// // Sample an even u32 in at most 8 attempts. If all 8 attempts are
/// // odd (probability 1/256), the iteration is rejected and Runner
/// // tries the next one.
/// let even = noprop::sample_with_rejection(ctx, 8, |ctx| {
///     let x = noprop::sample_u32(ctx);
///     if x % 2 == 0 { Some(x) } else { None }
/// });
/// assert_eq!(even % 2, 0);
/// # Ok(())
/// # });
/// ```
#[track_caller]
pub fn sample_with_rejection<T, F>(
    ctx: &mut TestCaseContext,
    max_attempts: usize,
    mut attempt: F,
) -> T
where
    F: FnMut(&mut TestCaseContext) -> Option<T>,
{
    assert!(
        max_attempts > 0,
        "sample_with_rejection: max_attempts must be > 0"
    );
    for _ in 0..max_attempts {
        if let Some(value) = attempt(ctx) {
            return value;
        }
    }
    // Exhausted. Inside a Runner, unwind to reject the iteration as
    // documented. Outside a Runner the raw `reject_case` panic would
    // read as "reject_case can only be called inside a Runner", which
    // is technically true but does not name the primitive the user
    // actually called; emit a sample_with_rejection-specific message
    // instead so `sample_char` / `sample_string` / `sample_f32` etc.
    // (which all go through here) surface a helpful diagnostic.
    if !ctx.is_inside_runner() {
        panic!(
            "noprop::sample_with_rejection: all {max_attempts} attempts were rejected. \
             Outside a Runner::run closure there is no iteration boundary to unwind to, \
             so exhaustion cannot be reported as a rejection. Wrap the call in a Runner, \
             raise max_attempts, or ensure at least one attempt returns Some(_)."
        );
    }
    ctx.reject_case()
}

// === Bounded-domain sampler ===

/// Sample a uniform `u64` in `[0, n)` using rejection sampling.
///
/// Uses `u64` as a pointer-width-independent working domain, so every
/// finite-domain selection primitive draws with the same pattern.
/// Draws are consumed from the RNG only via [`raw_bytes`], so rejected
/// attempts do not appear in the value trace (rejection span metadata
/// is still recorded in Recording mode).
///
/// Panics in debug builds if `n == 0`. Callers must guarantee `n > 0`.
///
/// The internal rejection loop is bounded at `DEFAULT_MAX_ATTEMPTS`
/// via [`sample_with_rejection`]. Per-attempt rejection rate is at
/// most `(u64::MAX % n + 1) / 2⁶⁴`, which peaks near 50% when `n` is
/// just above a power of two; the probability of exhausting 64
/// attempts is therefore `< 2⁻⁶⁴`.
#[track_caller]
fn sample_below(ctx: &mut TestCaseContext, n: u64) -> u64 {
    debug_assert!(n > 0, "sample_below: n must be non-zero");
    if n == 1 {
        return 0;
    }
    // We want to sample uniformly from [0, n) by drawing x from
    // [0, 2^64) and returning x % n. To avoid modulo bias we must only
    // accept draws that fall in a range whose size is a multiple of n.
    //
    // Let r = u64::MAX % n. Then 2^64 mod n = (r + 1) mod n:
    //   - If r == n - 1, n divides 2^64: every draw is unbiased.
    //   - Otherwise the unbiased zone has 2^64 - (r + 1) = u64::MAX - r
    //     values, i.e. accept iff x < u64::MAX - r.
    let r = u64::MAX % n;
    if r == n - 1 {
        return u64::from_le_bytes(raw_bytes(ctx)) % n;
    }
    let bound = u64::MAX - r;
    sample_with_rejection(ctx, DEFAULT_MAX_ATTEMPTS, |ctx| {
        let x = u64::from_le_bytes(raw_bytes(ctx));
        (x < bound).then_some(x % n)
    })
}

// === Selection helpers ===

/// Pick one element from `choices` uniformly at random.
///
/// This is the noprop counterpart to picking from a fixed list. Use it
/// when the alternatives are *values*; for branching between code paths
/// (calling different generators, taking different actions), use `match`
/// on [`sample_usize_in`] or [`sample_weighted_index`] instead — see the
/// module docstring.
///
/// # Panics
///
/// Panics if `choices` is empty.
///
/// # Determinism note
///
/// Uses the same rejection-sampling core as [`sample_usize_in`]. For
/// most slice lengths the rejection rate is negligible, but the number
/// of RNG bytes consumed by a call is not fixed, so the exact output
/// stream for a given seed depends on the slice length.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// // Explicit list of ints
/// let _n = noprop::sample_choice(&mut ctx, &[1, 2, 3, 5, 8]);
/// // ASCII digit from a byte string literal
/// let _d = noprop::sample_choice(&mut ctx, b"0123456789") as char;
/// // Non-ASCII via array literal
/// let _c = noprop::sample_choice(&mut ctx, &['α', 'β', 'γ']);
/// ```
#[track_caller]
pub fn sample_choice<T: Clone + std::fmt::Debug + 'static>(
    ctx: &mut TestCaseContext,
    choices: &[T],
) -> T {
    assert!(!choices.is_empty(), "sample_choice: empty slice");
    let loc = Location::caller();
    let idx = sample_below(ctx, choices.len() as u64) as usize;
    let v = choices[idx].clone();
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `usize` inside `range`.
///
/// Accepts any `RangeBounds<usize>` — `a..b`, `a..=b`, `..b`, `a..`,
/// `..`, and so on. The typical use is picking a collection length,
/// slice index, loop count, or small branch discriminator without
/// having to write `% N` (which is both easy to overflow at
/// `usize::MAX` and biased when the divisor does not evenly divide the
/// integer domain).
///
/// For `u64` ranges — inexpressible in `usize` on 32-bit targets, and
/// a cast from `usize` on 64-bit targets — see [`sample_u64_in`].
///
/// # Panics
///
/// Panics if `range` is empty (e.g. `5..5`, `5..=4`, `..0`, or an
/// excluded start of `usize::MAX`).
///
/// # Determinism note
///
/// Uses rejection sampling internally. Most calls accept the first
/// draw, but the exact byte count consumed depends on the range width,
/// so changing the range can shift subsequent RNG output for the same
/// seed. This is a deliberate correction over the earlier `sample_usize
/// % (max + 1)` recipe, which was both bias-prone and overflow-prone.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
///
/// let idx = noprop::sample_usize_in(&mut ctx, 0..10);
/// assert!(idx < 10);
///
/// let day = noprop::sample_usize_in(&mut ctx, 1..=31);
/// assert!((1..=31).contains(&day));
/// ```
#[track_caller]
pub fn sample_usize_in<R: RangeBounds<usize>>(ctx: &mut TestCaseContext, range: R) -> usize {
    let loc = Location::caller();
    let lo = match range.start_bound() {
        Bound::Included(&s) => s,
        Bound::Excluded(&s) => s.checked_add(1).expect("sample_usize_in: empty range"),
        Bound::Unbounded => 0,
    };
    let hi = match range.end_bound() {
        Bound::Included(&e) => e,
        Bound::Excluded(&e) => e.checked_sub(1).expect("sample_usize_in: empty range"),
        Bound::Unbounded => usize::MAX,
    };
    assert!(lo <= hi, "sample_usize_in: empty range");
    let v = if lo == 0 && hi == usize::MAX {
        // Full pointer-width range: a raw byte draw is already unbiased,
        // and hi - lo + 1 would wrap. This is a plain integer draw.
        usize::from_le_bytes(raw_bytes(ctx))
    } else {
        // hi - lo cannot overflow because hi >= lo, and (hi - lo) + 1
        // cannot overflow because we excluded the only case where
        // hi - lo == usize::MAX. Cast to u64 is safe on every Rust
        // target (usize width <= 64).
        let width = (hi - lo) as u64 + 1;
        lo + sample_below(ctx, width) as usize
    };
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `u64` inside `range`.
///
/// Accepts any `RangeBounds<u64>` — `a..b`, `a..=b`, `..b`, `a..`,
/// `..`, and so on. The typical use is sampling protocol fields or
/// timestamps that need a `u64` result type (e.g. a 33-bit MPEG-2
/// timestamp) without a cast or bit mask: a bit mask can only express
/// zero-offset power-of-two ranges and is biased for any other width,
/// while `sample_usize_in` returns `usize` — a cast on 64-bit targets,
/// and a range that does not fit at all on 32-bit targets.
///
/// # Panics
///
/// Panics if `range` is empty (e.g. `5..5`, `5..=4`, `..0`, or an
/// excluded start of `u64::MAX`).
///
/// # Determinism note
///
/// Uses rejection sampling internally. Most calls accept the first
/// draw, but the exact byte count consumed depends on the range width,
/// so changing the range can shift subsequent RNG output for the same
/// seed. Any full-width range (covering the entire `u64` domain) is a
/// plain integer draw consuming exactly 8 bytes, so it is
/// byte-equivalent to [`sample_u64`].
///
/// # Relation to the typed `_in` family
///
/// [`sample_usize_in`] already covers `u8` / `u16` / `u32` on every
/// 32/64-bit target (`usize` is at least 32 bits there), and `u64` on
/// 64-bit targets — but its result type is `usize`, so a `u64` field
/// needs a cast and 32-bit targets cannot express a `u64` range at
/// all. `sample_u64_in` exists for exactly those cases. For a narrower
/// result type, prefer the sampler whose name matches the field:
/// [`sample_u8_in`], [`sample_u16_in`], [`sample_u32_in`],
/// [`sample_i8_in`], [`sample_i16_in`], or [`sample_i32_in`]. A `u128`
/// range would need 128-bit rejection sampling without a demonstrated
/// demand, so it is not provided.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
///
/// // MPEG-2 33-bit timestamp.
/// let ts = noprop::sample_u64_in(&mut ctx, 0..(1u64 << 33));
/// assert!(ts < (1u64 << 33));
///
/// // Arbitrary protocol field range.
/// let field = noprop::sample_u64_in(&mut ctx, 100..=999);
/// assert!((100..=999).contains(&field));
/// ```
#[track_caller]
pub fn sample_u64_in<R: RangeBounds<u64>>(ctx: &mut TestCaseContext, range: R) -> u64 {
    let loc = Location::caller();
    let lo = match range.start_bound() {
        Bound::Included(&s) => s,
        Bound::Excluded(&s) => s.checked_add(1).expect("sample_u64_in: empty range"),
        Bound::Unbounded => 0,
    };
    let hi = match range.end_bound() {
        Bound::Included(&e) => e,
        Bound::Excluded(&e) => e.checked_sub(1).expect("sample_u64_in: empty range"),
        Bound::Unbounded => u64::MAX,
    };
    assert!(lo <= hi, "sample_u64_in: empty range");
    let v = if lo == 0 && hi == u64::MAX {
        // Full-width range: a raw byte draw is already unbiased, and
        // hi - lo + 1 would wrap. This is a plain integer draw,
        // byte-equivalent to sample_u64.
        u64::from_le_bytes(raw_bytes(ctx))
    } else {
        // hi - lo cannot overflow because hi >= lo, and (hi - lo) + 1
        // cannot overflow because we excluded the only case where
        // hi - lo == u64::MAX.
        let width = hi - lo + 1;
        lo + sample_below(ctx, width)
    };
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `u8` inside `range`, with the result type the
/// caller needs so no cast appears at the call site.
///
/// Accepts any `RangeBounds<u8>`. The range and the result share one
/// type, so a bound that does not fit a `u8` field is a compile error
/// rather than a silent truncation of a wider sample.
///
/// # Panics
///
/// Panics if `range` is empty (e.g. `5..5`, `5..=4`, `..0`, or an
/// excluded start of `u8::MAX`).
///
/// # Determinism note
///
/// See [`sample_u64_in`]: the byte count consumed depends on the range
/// width, so changing the range can shift subsequent RNG output for
/// the same seed.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
///
/// let version = noprop::sample_u8_in(&mut ctx, 0..2);
/// assert!(version < 2);
///
/// let len = noprop::sample_u8_in(&mut ctx, 1..=4);
/// assert!((1..=4).contains(&len));
/// ```
#[track_caller]
pub fn sample_u8_in<R: RangeBounds<u8>>(ctx: &mut TestCaseContext, range: R) -> u8 {
    let loc = Location::caller();
    let lo = match range.start_bound() {
        Bound::Included(&s) => s,
        Bound::Excluded(&s) => s.checked_add(1).expect("sample_u8_in: empty range"),
        Bound::Unbounded => u8::MIN,
    };
    let hi = match range.end_bound() {
        Bound::Included(&e) => e,
        Bound::Excluded(&e) => e.checked_sub(1).expect("sample_u8_in: empty range"),
        Bound::Unbounded => u8::MAX,
    };
    assert!(lo <= hi, "sample_u8_in: empty range");
    // Widen to u64 before subtracting so the arithmetic is exact for
    // the full u8 domain; the sample is within `lo..=hi`, so narrowing
    // back cannot truncate.
    let v = (lo as u64 + sample_below(ctx, hi as u64 - lo as u64 + 1)) as u8;
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `u16` inside `range`, with the result type the
/// caller needs so no cast appears at the call site.
///
/// Accepts any `RangeBounds<u16>`. See [`sample_u8_in`] for the shared
/// rule that the range and the result share one type.
///
/// # Panics
///
/// Panics if `range` is empty (e.g. `5..5`, `5..=4`, `..0`, or an
/// excluded start of `u16::MAX`).
///
/// # Determinism note
///
/// See [`sample_u64_in`].
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
///
/// let count = noprop::sample_u16_in(&mut ctx, 1..=8);
/// assert!((1..=8).contains(&count));
/// ```
#[track_caller]
pub fn sample_u16_in<R: RangeBounds<u16>>(ctx: &mut TestCaseContext, range: R) -> u16 {
    let loc = Location::caller();
    let lo = match range.start_bound() {
        Bound::Included(&s) => s,
        Bound::Excluded(&s) => s.checked_add(1).expect("sample_u16_in: empty range"),
        Bound::Unbounded => u16::MIN,
    };
    let hi = match range.end_bound() {
        Bound::Included(&e) => e,
        Bound::Excluded(&e) => e.checked_sub(1).expect("sample_u16_in: empty range"),
        Bound::Unbounded => u16::MAX,
    };
    assert!(lo <= hi, "sample_u16_in: empty range");
    let v = (lo as u64 + sample_below(ctx, hi as u64 - lo as u64 + 1)) as u16;
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `u32` inside `range`, with the result type the
/// caller needs so no cast appears at the call site.
///
/// Accepts any `RangeBounds<u32>`. See [`sample_u8_in`] for the shared
/// rule that the range and the result share one type.
///
/// # Panics
///
/// Panics if `range` is empty (e.g. `5..5`, `5..=4`, `..0`, or an
/// excluded start of `u32::MAX`).
///
/// # Determinism note
///
/// See [`sample_u64_in`].
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
///
/// let track_id = noprop::sample_u32_in(&mut ctx, 1..=1_000);
/// assert!((1..=1_000).contains(&track_id));
/// ```
#[track_caller]
pub fn sample_u32_in<R: RangeBounds<u32>>(ctx: &mut TestCaseContext, range: R) -> u32 {
    let loc = Location::caller();
    let lo = match range.start_bound() {
        Bound::Included(&s) => s,
        Bound::Excluded(&s) => s.checked_add(1).expect("sample_u32_in: empty range"),
        Bound::Unbounded => u32::MIN,
    };
    let hi = match range.end_bound() {
        Bound::Included(&e) => e,
        Bound::Excluded(&e) => e.checked_sub(1).expect("sample_u32_in: empty range"),
        Bound::Unbounded => u32::MAX,
    };
    assert!(lo <= hi, "sample_u32_in: empty range");
    let v = (lo as u64 + sample_below(ctx, hi as u64 - lo as u64 + 1)) as u32;
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `i8` inside `range`.
///
/// Accepts any `RangeBounds<i8>`, including the full `i8::MIN..=i8::MAX`
/// domain. Sampling goes through an unsigned offset so a signed range
/// never overflows while being normalized.
///
/// # Panics
///
/// Panics if `range` is empty (e.g. `5..5`, `5..=4`, `i8::MIN..i8::MIN`,
/// or an excluded start of `i8::MAX`).
///
/// # Determinism note
///
/// See [`sample_u64_in`].
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
///
/// let delta = noprop::sample_i8_in(&mut ctx, -128..=127);
/// assert!((-128..=127).contains(&delta));
/// ```
#[track_caller]
pub fn sample_i8_in<R: RangeBounds<i8>>(ctx: &mut TestCaseContext, range: R) -> i8 {
    let loc = Location::caller();
    let lo = match range.start_bound() {
        Bound::Included(&s) => s,
        Bound::Excluded(&s) => s.checked_add(1).expect("sample_i8_in: empty range"),
        Bound::Unbounded => i8::MIN,
    };
    let hi = match range.end_bound() {
        Bound::Included(&e) => e,
        Bound::Excluded(&e) => e.checked_sub(1).expect("sample_i8_in: empty range"),
        Bound::Unbounded => i8::MAX,
    };
    assert!(lo <= hi, "sample_i8_in: empty range");
    // Offset from `lo` in u64 so a full-width signed range works; the
    // span fits a u8, which fits a u64.
    let width = (hi as i64 - lo as i64) as u64 + 1;
    let v = (lo as i64 + sample_below(ctx, width) as i64) as i8;
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `i16` inside `range`.
///
/// Accepts any `RangeBounds<i16>`, including the full signed domain.
/// See [`sample_i8_in`] for the unsigned-offset rule.
///
/// # Panics
///
/// Panics if `range` is empty (e.g. `5..5`, `5..=4`, or an excluded
/// start of `i16::MAX`).
///
/// # Determinism note
///
/// See [`sample_u64_in`].
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
///
/// let diff = noprop::sample_i16_in(&mut ctx, -300..=300);
/// assert!((-300..=300).contains(&diff));
/// ```
#[track_caller]
pub fn sample_i16_in<R: RangeBounds<i16>>(ctx: &mut TestCaseContext, range: R) -> i16 {
    let loc = Location::caller();
    let lo = match range.start_bound() {
        Bound::Included(&s) => s,
        Bound::Excluded(&s) => s.checked_add(1).expect("sample_i16_in: empty range"),
        Bound::Unbounded => i16::MIN,
    };
    let hi = match range.end_bound() {
        Bound::Included(&e) => e,
        Bound::Excluded(&e) => e.checked_sub(1).expect("sample_i16_in: empty range"),
        Bound::Unbounded => i16::MAX,
    };
    assert!(lo <= hi, "sample_i16_in: empty range");
    let width = (hi as i64 - lo as i64) as u64 + 1;
    let v = (lo as i64 + sample_below(ctx, width) as i64) as i16;
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `i32` inside `range`.
///
/// Accepts any `RangeBounds<i32>`, including the full `i32::MIN..=i32::MAX`
/// domain. See [`sample_i8_in`] for the unsigned-offset rule.
///
/// # Panics
///
/// Panics if `range` is empty (e.g. `5..5`, `5..=4`, or an excluded
/// start of `i32::MAX`).
///
/// # Determinism note
///
/// See [`sample_u64_in`].
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
///
/// let diff = noprop::sample_i32_in(&mut ctx, -128..=127);
/// assert!((-128..=127).contains(&diff));
///
/// // The full signed domain is a valid range, not an overflow.
/// let any = noprop::sample_i32_in(&mut ctx, ..);
/// let _ = any;
/// ```
#[track_caller]
pub fn sample_i32_in<R: RangeBounds<i32>>(ctx: &mut TestCaseContext, range: R) -> i32 {
    let loc = Location::caller();
    let lo = match range.start_bound() {
        Bound::Included(&s) => s,
        Bound::Excluded(&s) => s.checked_add(1).expect("sample_i32_in: empty range"),
        Bound::Unbounded => i32::MIN,
    };
    let hi = match range.end_bound() {
        Bound::Included(&e) => e,
        Bound::Excluded(&e) => e.checked_sub(1).expect("sample_i32_in: empty range"),
        Bound::Unbounded => i32::MAX,
    };
    assert!(lo <= hi, "sample_i32_in: empty range");
    // The span of any i32 range fits a u32, so it fits a u64; the
    // difference is taken in i64 to avoid `hi - lo` overflow.
    let width = (hi as i64 - lo as i64) as u64 + 1;
    let v = (lo as i64 + sample_below(ctx, width) as i64) as i32;
    ctx.record_generated(&v, loc);
    v
}

/// An exact rational probability `numerator / denominator`.
///
/// The ratio is valid by construction: `denominator` is non-zero and
/// `numerator <= denominator`, so the probability always lies in
/// `[0, 1]`.
///
/// A ratio is a probability, not a fraction of other quantities:
/// `Ratio::new(1, 3)` means exactly one-in-three — the sampling core
/// compares against `denominator` directly, so the value stays exact
/// rather than a `0.333…`-close float.
///
/// # Choosing the constructor
///
/// The two entry points map to the two shapes real callers hit:
///
/// - [`Ratio::one_nth(n)`](Ratio::one_nth) for the common `1/N`
///   probability. One argument, so no numerator/denominator confusion.
/// - [`Ratio::new(m, n)`](Ratio::new) for a general `m/n` with `m > 1`,
///   as a compile-time literal (numerator-first, matching the
///   mathematical convention).
///
/// Both panic on invalid inputs with a `#[track_caller]` message. That
/// suits compile-time literals — a bad literal is a caller bug that
/// should surface loudly, not a value to branch on. For a runtime value
/// that may be out of range, clamp or validate it yourself before
/// calling `Ratio::new`, for example:
///
/// ```
/// let (n, d) = (3u32, 2u32); // could be anything at runtime
/// let (n, d) = match (n, d) {
///     (0, 0) => (0, 1),
///     (_, 0) => (1, 1),
///     (n, d) if n > d => (d, d),
///     pair => pair,
/// };
/// let r = noprop::Ratio::new(n, d);
/// # let _ = r;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ratio {
    numerator: u32,
    denominator: u32,
}

impl Ratio {
    /// Construct a ratio `numerator / denominator`.
    ///
    /// Intended for compile-time literals where the value is known to
    /// be in range. For `1/N` prefer [`Ratio::one_nth`], which takes a
    /// single argument.
    ///
    /// # Panics
    ///
    /// Panics with a `#[track_caller]` message when the inputs do not
    /// describe a probability:
    ///
    /// - `denominator == 0`
    /// - `numerator > denominator`
    ///
    /// # Examples
    ///
    /// ```
    /// let r = noprop::Ratio::new(2, 3);
    /// # let _ = r;
    /// ```
    #[track_caller]
    pub const fn new(numerator: u32, denominator: u32) -> Self {
        if denominator == 0 {
            panic!("Ratio::new: denominator must be non-zero");
        }
        if numerator > denominator {
            panic!("Ratio::new: numerator must not exceed denominator");
        }
        Self {
            numerator,
            denominator,
        }
    }

    /// Construct the `1/n` ratio.
    ///
    /// The one-argument shortcut for the `1/N` probabilities that
    /// dominate real usage (`Ratio::one_nth(10)` for 1-in-10,
    /// `Ratio::one_nth(2)` for a coin flip).
    ///
    /// # Panics
    ///
    /// Panics with a `#[track_caller]` message when `n == 0`.
    ///
    /// # Examples
    ///
    /// ```
    /// let r = noprop::Ratio::one_nth(10); // 10%
    /// # let _ = r;
    /// ```
    #[track_caller]
    pub const fn one_nth(n: u32) -> Self {
        if n == 0 {
            panic!("Ratio::one_nth: n must be non-zero");
        }
        Self {
            numerator: 1,
            denominator: n,
        }
    }
}

/// Return `true` with probability `ratio`.
///
/// The typical use is weighting a two-way branch by an exact rational
/// probability instead of a floating-point one, so that
/// e.g. `sample_ratio(ctx, Ratio::one_nth(3))` is exactly one-in-three,
/// not `0.333…`-close.
///
/// # Determinism note
///
/// The degenerate cases `numerator == 0` (always `false`) and
/// `numerator == denominator` (always `true`) consume no RNG bytes, so
/// tuning a weight down to 0 or up to 100% does not shift subsequent
/// output. All other cases consume RNG bytes through the shared
/// rejection sampler, so tuning `numerator` / `denominator` in that
/// range may shift the choice sequence.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// // 1 in 3 chance of true.
/// let _b = noprop::sample_ratio(&mut ctx, noprop::Ratio::one_nth(3));
/// // Always false; consumes no RNG.
/// assert!(!noprop::sample_ratio(&mut ctx, noprop::Ratio::new(0, 5)));
/// // Always true; consumes no RNG.
/// assert!(noprop::sample_ratio(&mut ctx, noprop::Ratio::new(5, 5)));
/// ```
#[track_caller]
pub fn sample_ratio(ctx: &mut TestCaseContext, ratio: Ratio) -> bool {
    let loc = Location::caller();
    let v = if ratio.numerator == 0 {
        false
    } else if ratio.numerator == ratio.denominator {
        true
    } else {
        sample_below(ctx, ratio.denominator as u64) < ratio.numerator as u64
    };
    ctx.record_generated(&v, loc);
    v
}

/// Return a value from `boundaries` with probability `ratio`, otherwise
/// draw from `sample`.
///
/// This packages the boundary-mixing recipe — an exact-ratio two-way
/// branch between a fixed candidate list and a base generator — into
/// one call. The distribution is readable from the arguments: with
/// probability `ratio` the value is drawn uniformly from `boundaries`,
/// and otherwise it is whatever `sample` produces. The base generator
/// stays untouched, so a `sample_u32`-based property continues to draw
/// uniformly except for the explicitly requested boundary mass.
///
/// `boundaries` may carry domain-level values that an automatic
/// type-level bias could not reach (e.g. an MP4 size field crossing
/// `u32::MAX`, an MTU, a page size).
///
/// This call is a convenience wrapper for the equivalent plain-Rust
/// form
///
/// ```text
/// if sample_ratio(ctx, ratio) {
///     sample_choice(ctx, boundaries)
/// } else {
///     sample(ctx)
/// }
/// ```
///
/// — provided so the boundary-mix recipe fits in one call. The two
/// forms consume the same bytes for the same seed (see the example).
///
/// # Panics
///
/// Panics if `boundaries` is empty, before any RNG bytes are drawn.
///
/// # Determinism note
///
/// The draw order is fixed: the ratio branch first, then either the
/// boundary choice or the `sample` call. A degenerate ratio (0% or
/// 100%) and a one-element boundary slice consume no RNG bytes, so a
/// hand-written recipe built on `sample_usize_in` can be replaced with
/// this helper without shifting the choice sequence. (A `sample_bool`-based
/// recipe is not byte-equivalent: the ratio draws through the shared
/// rejection sampler.)
///
/// The call records two trace entries — the ratio's `bool` and the
/// chosen value (boundary or `sample`'s draw) — matching what a
/// hand-written recipe (`if sample_ratio { sample_choice } else
/// { sample }`) would also record.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// // 10% of the time a boundary value, otherwise uniform.
/// let helper = noprop::sample_with_boundaries(
///     &mut ctx,
///     &[0, 1500, u32::MAX],
///     noprop::Ratio::one_nth(10),
///     noprop::sample_u32,
/// );
///
/// // The helper is exactly the plain-Rust `if` form below: the same
/// // seed draws the same bytes, so the values agree.
/// let mut hand_ctx = noprop::TestCaseContext::new(0);
/// let hand_written =
///     if noprop::sample_ratio(&mut hand_ctx, noprop::Ratio::one_nth(10)) {
///         noprop::sample_choice(&mut hand_ctx, &[0, 1500, u32::MAX])
///     } else {
///         noprop::sample_u32(&mut hand_ctx)
///     };
/// assert_eq!(helper, hand_written);
/// ```
#[track_caller]
pub fn sample_with_boundaries<T, F>(
    ctx: &mut TestCaseContext,
    boundaries: &[T],
    ratio: Ratio,
    sample: F,
) -> T
where
    T: Clone + std::fmt::Debug + 'static,
    F: FnOnce(&mut TestCaseContext) -> T,
{
    assert!(
        !boundaries.is_empty(),
        "sample_with_boundaries: empty boundaries"
    );
    if sample_ratio(ctx, ratio) {
        sample_choice(ctx, boundaries)
    } else {
        sample(ctx)
    }
}

/// Pick an index from `weights` with probability proportional to each
/// weight.
///
/// The typical use is picking a branch or command variant with an
/// uneven distribution (e.g. 10× more `read` operations than `write`).
/// The chosen index is returned so the caller can `match` on it and
/// call the corresponding generator or action — the weight list carries
/// no values of its own.
///
/// # Panics
///
/// - Panics if `weights` is empty.
/// - Panics if every weight is `0` (no branch is selectable).
/// - Panics if the sum of weights overflows `u64` (in practice this
///   requires a `weights` slice that cannot fit in addressable memory).
///
/// # Determinism note
///
/// Uses the shared rejection sampler on the sum of weights, so the
/// exact number of RNG bytes consumed depends on that sum. Adding a
/// zero-weighted variant to the slice does not change the RNG stream
/// (the sampler is called with the same sum), and never affects the
/// returned index distribution either.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// // Roughly 50% branch 0, 30% branch 1, 20% branch 2.
/// let idx = noprop::sample_weighted_index(&mut ctx, &[5, 3, 2]);
/// assert!(idx < 3);
/// ```
#[track_caller]
pub fn sample_weighted_index(ctx: &mut TestCaseContext, weights: &[u32]) -> usize {
    let loc = Location::caller();
    assert!(!weights.is_empty(), "sample_weighted_index: empty weights");
    let mut total: u64 = 0;
    for &w in weights {
        total = total
            .checked_add(w as u64)
            .expect("sample_weighted_index: weight sum overflows u64");
    }
    assert!(total > 0, "sample_weighted_index: all weights are zero");
    let mut pick = sample_below(ctx, total);
    let mut chosen = weights.len(); // sentinel; overwritten below
    for (i, &w) in weights.iter().enumerate() {
        let w = w as u64;
        if pick < w {
            chosen = i;
            break;
        }
        pick -= w;
    }
    // Every non-zero-weight index is reachable and pick < total, so the
    // loop must have hit the `pick < w` branch at least once.
    debug_assert!(chosen < weights.len());
    ctx.record_generated(&chosen, loc);
    chosen
}

// === Byte generators ===

/// Uniformly-distributed fixed-size byte array.
///
/// The generic parameter `N` sets the array length at compile time, so
/// the whole result is stack-allocated and recorded as a single trace
/// entry (`[u8; N] = [...]`) rather than N separate `u8` entries.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// let key: [u8; 32] = noprop::sample_bytes(&mut ctx);
/// assert_eq!(key.len(), 32);
/// ```
#[track_caller]
pub fn sample_bytes<const N: usize>(ctx: &mut TestCaseContext) -> [u8; N] {
    let loc = Location::caller();
    let bytes = raw_bytes::<N>(ctx);
    ctx.record_generated(&bytes, loc);
    bytes
}

/// Uniformly-distributed `Vec<u8>` of length `len`.
///
/// Use this when the byte-buffer length is known only at runtime
/// (`sample_bytes_vec(ctx, sample_usize_in(ctx, 0..1024))`). The whole
/// buffer is recorded as a single trace entry.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// let bytes = noprop::sample_bytes_vec(&mut ctx, 100);
/// assert_eq!(bytes.len(), 100);
/// ```
#[track_caller]
pub fn sample_bytes_vec(ctx: &mut TestCaseContext, len: usize) -> Vec<u8> {
    let loc = Location::caller();
    let mut bytes = vec![0u8; len];
    ctx.fill(&mut bytes);
    ctx.record_generated(&bytes, loc);
    bytes
}

// === Boolean generator ===

/// Uniformly-distributed `bool`.
#[track_caller]
pub fn sample_bool(ctx: &mut TestCaseContext) -> bool {
    let loc = Location::caller();
    // Consume one byte so this primitive shares the "read a fixed-size
    // byte slice" shape with the integer generators.
    let v = raw_bytes::<1>(ctx)[0] & 1 != 0;
    ctx.record_generated(&v, loc);
    v
}

// === Integer generators ===
//
// All primitives draw randomness through `TestCaseContext::fill` (LE bytes ->
// `from_le_bytes`) so that every primitive consumes a fixed-size byte
// slice from the RNG. This keeps every generator compatible with a
// future bytes-based shrink implementation that swaps the RNG for a
// byte reader.

/// Uniformly-distributed `u8`.
#[track_caller]
pub fn sample_u8(ctx: &mut TestCaseContext) -> u8 {
    let loc = Location::caller();
    let v = raw_bytes::<1>(ctx)[0];
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `u16`.
#[track_caller]
pub fn sample_u16(ctx: &mut TestCaseContext) -> u16 {
    let loc = Location::caller();
    let v = u16::from_le_bytes(raw_bytes(ctx));
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `u32`.
#[track_caller]
pub fn sample_u32(ctx: &mut TestCaseContext) -> u32 {
    let loc = Location::caller();
    let v = u32::from_le_bytes(raw_bytes(ctx));
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `u64`.
#[track_caller]
pub fn sample_u64(ctx: &mut TestCaseContext) -> u64 {
    let loc = Location::caller();
    let v = u64::from_le_bytes(raw_bytes(ctx));
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `u128`.
#[track_caller]
pub fn sample_u128(ctx: &mut TestCaseContext) -> u128 {
    let loc = Location::caller();
    let v = u128::from_le_bytes(raw_bytes(ctx));
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `usize`.
#[track_caller]
pub fn sample_usize(ctx: &mut TestCaseContext) -> usize {
    let loc = Location::caller();
    let v = usize::from_le_bytes(raw_bytes(ctx));
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `i8`.
#[track_caller]
pub fn sample_i8(ctx: &mut TestCaseContext) -> i8 {
    let loc = Location::caller();
    let v = raw_bytes::<1>(ctx)[0] as i8;
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `i16`.
#[track_caller]
pub fn sample_i16(ctx: &mut TestCaseContext) -> i16 {
    let loc = Location::caller();
    let v = i16::from_le_bytes(raw_bytes(ctx));
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `i32`.
#[track_caller]
pub fn sample_i32(ctx: &mut TestCaseContext) -> i32 {
    let loc = Location::caller();
    let v = i32::from_le_bytes(raw_bytes(ctx));
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `i64`.
#[track_caller]
pub fn sample_i64(ctx: &mut TestCaseContext) -> i64 {
    let loc = Location::caller();
    let v = i64::from_le_bytes(raw_bytes(ctx));
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `i128`.
#[track_caller]
pub fn sample_i128(ctx: &mut TestCaseContext) -> i128 {
    let loc = Location::caller();
    let v = i128::from_le_bytes(raw_bytes(ctx));
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `isize`.
#[track_caller]
pub fn sample_isize(ctx: &mut TestCaseContext) -> isize {
    let loc = Location::caller();
    let v = isize::from_le_bytes(raw_bytes(ctx));
    ctx.record_generated(&v, loc);
    v
}

// === Character generators ===
//
// For character subsets beyond the ones below (alphanumeric, hexdigit,
// etc.), compose with `sample_choice` over a byte-string literal, for
// example:
//
//     let d = sample_choice(ctx, b"0123456789") as char;
//     let a = sample_choice(ctx, b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") as char;

/// Uniformly-distributed `char` over the valid Unicode scalar values
/// (`0..=0x10FFFF`, excluding the surrogate range `0xD800..=0xDFFF`).
///
/// Uses [`sample_with_rejection`] with the shared internal 64-attempt
/// bound: rejection sampling on a 21-bit mask, ~47% per-attempt
/// rejection rate, so `P(all 64 fail) < 10⁻²⁰`.
#[track_caller]
pub fn sample_char(ctx: &mut TestCaseContext) -> char {
    let loc = Location::caller();
    let c = sample_with_rejection(ctx, DEFAULT_MAX_ATTEMPTS, |ctx| {
        let n = u32::from_le_bytes(raw_bytes(ctx)) & 0x1F_FFFF;
        char::from_u32(n)
    });
    ctx.record_generated(&c, loc);
    c
}

/// Uniformly-distributed ASCII `char` (`0x00..=0x7F`, including control
/// characters).
#[track_caller]
pub fn sample_ascii_char(ctx: &mut TestCaseContext) -> char {
    let loc = Location::caller();
    let v = (raw_bytes::<1>(ctx)[0] & 0x7F) as char;
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed printable ASCII `char` (`0x20..=0x7E`, space
/// through `~`, excluding control characters and DEL).
///
/// The 95 printable characters do not evenly divide the integer domain,
/// so a naive `% 95` would be biased. Uses the same bounded
/// rejection-sampling core as [`sample_usize_in`] and
/// [`sample_choice`] to keep the distribution uniform; for this bound
/// the per-attempt rejection rate is `< 2⁻⁵⁸`, so a rejected attempt
/// is effectively never observed.
///
/// # Determinism note
///
/// Each character consumes an 8-byte bounded draw (a rejected attempt,
/// which is effectively never observed, consumes another 8 bytes).
/// This is a deliberate correction over the earlier `% 95` mapping of a
/// 4-byte draw, which was biased; for the same seed the value stream
/// therefore differs from earlier releases.
#[track_caller]
pub fn sample_ascii_printable_char(ctx: &mut TestCaseContext) -> char {
    let loc = Location::caller();
    let v = (0x20 + sample_below(ctx, 95)) as u8 as char;
    ctx.record_generated(&v, loc);
    v
}

// === String generators ===
//
// Length is measured in Unicode code points (equal to `.chars().count()`
// of the returned `String`). Random-length strings compose from
// `sample_usize_in` + one of these primitives, matching the
// `sample_bytes_vec(ctx, len)` shape:
//
//     let n = noprop::sample_usize_in(ctx, 0..=max_len);
//     let s = noprop::sample_string(ctx, n);
//
// A higher-order `sample_string_of(ctx, len, |ctx| ...)` helper is
// deliberately not provided: `(0..len).map(|_| ...).collect()` is
// short enough that a helper would only obscure the imperative
// generator's control flow.

/// Uniformly-distributed `String` of exactly `len` Unicode scalar
/// values. Each code point is produced by calling [`sample_char`] once.
///
/// `len` is a code-point count, not a UTF-8 byte count. The returned
/// string's `.chars().count()` equals `len`; its byte length is up to
/// `4 * len`.
///
/// For random-length strings, wrap this call with [`sample_usize_in`]
/// (see the module-level "String generators" note). For a byte buffer,
/// use [`sample_bytes_vec`]. For a single character, use [`sample_char`].
///
/// # Trace
///
/// One trace entry is recorded per call (`alloc::string::String =
/// "..."`, Rust `Debug` escape). Because [`sample_char`] internally
/// uses a bounded rejection loop, each call to `sample_string`
/// consumes up to `len × 64` internal attempts and, in Recording
/// mode, opens at least `len` attempt spans in the choice sequence
/// (one per accepted character; each rejected attempt adds another
/// span).
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// let s = noprop::sample_string(&mut ctx, 10);
/// assert_eq!(s.chars().count(), 10);
/// ```
#[track_caller]
pub fn sample_string(ctx: &mut TestCaseContext, len: usize) -> String {
    let loc = Location::caller();
    let s: String = (0..len).map(|_| sample_char_raw(ctx)).collect();
    ctx.record_generated(&s, loc);
    s
}

/// Uniformly-distributed ASCII `String` of exactly `len` code points
/// (`0x00..=0x7F`, including control characters). Each character is
/// produced by calling [`sample_ascii_char`] once.
///
/// The returned string's byte length equals `len` (ASCII is 1 byte per
/// code point). For printable ASCII only, use
/// [`sample_ascii_printable_string`].
///
/// # Trace
///
/// One trace entry is recorded per call. Unlike [`sample_string`],
/// this primitive uses no internal rejection loop, so it consumes
/// exactly `len` bytes from the RNG and opens no attempt spans.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// let s = noprop::sample_ascii_string(&mut ctx, 8);
/// assert_eq!(s.len(), 8);
/// assert!(s.chars().all(|c| c.is_ascii()));
/// ```
#[track_caller]
pub fn sample_ascii_string(ctx: &mut TestCaseContext, len: usize) -> String {
    let loc = Location::caller();
    let s: String = (0..len).map(|_| sample_ascii_char_raw(ctx)).collect();
    ctx.record_generated(&s, loc);
    s
}

/// Uniformly-distributed printable-ASCII `String` of exactly `len`
/// code points (`0x20..=0x7E`, space through `~`). Each character is
/// produced by calling [`sample_ascii_printable_char`] once.
///
/// The returned string's byte length equals `len`. For arbitrary
/// ASCII (including control characters), use [`sample_ascii_string`].
///
/// # Trace
///
/// One trace entry is recorded per call. Each character is drawn via
/// the same bounded rejection-sampling core as
/// [`sample_ascii_printable_char`], so a call consumes `len × 8` RNG
/// bytes in the common case (a rejected attempt — probability
/// `< 2⁻⁵⁸` per character — consumes another 8 bytes) and, in
/// Recording mode, opens at least `len` attempt spans in the choice
/// sequence (one per accepted character; each rejected attempt adds
/// another span). Rejected attempts do not appear in the value trace.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// let s = noprop::sample_ascii_printable_string(&mut ctx, 12);
/// assert_eq!(s.len(), 12);
/// assert!(s.chars().all(|c| (0x20..=0x7E).contains(&(c as u32))));
/// ```
#[track_caller]
pub fn sample_ascii_printable_string(ctx: &mut TestCaseContext, len: usize) -> String {
    let loc = Location::caller();
    let s: String = (0..len)
        .map(|_| sample_ascii_printable_char_raw(ctx))
        .collect();
    ctx.record_generated(&s, loc);
    s
}

/// Internal helpers that mirror the public `sample_*_char` primitives
/// but skip the per-character `record_generated` call. Used inside
/// `sample_*_string` so the trace shows one `String` entry rather
/// than `len` `char` entries.
#[track_caller]
fn sample_char_raw(ctx: &mut TestCaseContext) -> char {
    sample_with_rejection(ctx, DEFAULT_MAX_ATTEMPTS, |ctx| {
        let n = u32::from_le_bytes(raw_bytes(ctx)) & 0x1F_FFFF;
        char::from_u32(n)
    })
}

fn sample_ascii_char_raw(ctx: &mut TestCaseContext) -> char {
    (raw_bytes::<1>(ctx)[0] & 0x7F) as char
}

fn sample_ascii_printable_char_raw(ctx: &mut TestCaseContext) -> char {
    (0x20 + sample_below(ctx, 95)) as u8 as char
}

// === Floating-point generators ===

/// Uniformly-distributed `f32` in `[min, max)`.
///
/// NaN and infinities are excluded from the output range. To include
/// them (or any specific special value), pick from a fixed set with
/// [`sample_choice`]:
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// let _x = noprop::sample_choice(
///     &mut ctx,
///     &[f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0],
/// );
/// ```
///
/// For an arbitrary `f32` bit pattern (including NaN, infinities, and
/// subnormals):
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// let _x = f32::from_bits(noprop::sample_u32(&mut ctx));
/// ```
///
/// For the full finite domain without a specific range, use
/// [`sample_f32`].
///
/// # Panics
///
/// Panics if `min` or `max` is not finite, if `min >= max`, or if
/// `max - min` overflows to infinity (in that case the finite-output
/// guarantee cannot be honoured; split the range or sample at bit level
/// via [`sample_f32`] / `f32::from_bits`).
#[track_caller]
pub fn sample_f32_in(ctx: &mut TestCaseContext, min: f32, max: f32) -> f32 {
    assert!(
        min.is_finite() && max.is_finite(),
        "sample_f32_in: min and max must be finite"
    );
    assert!(min < max, "sample_f32_in: min must be less than max");
    let span = max - min;
    assert!(
        span.is_finite(),
        "sample_f32_in: max - min must be finite (max - min = {span}); split the range"
    );
    let loc = Location::caller();
    // Build a 24-bit uniform value in [0, 1): construct a float in
    // [1, 2) by injecting 23 random bits into the mantissa of a fixed
    // exponent, then subtract 1. This is bias-free (every representable
    // value in [0, 1) with 24-bit precision is equally likely).
    let bits = 0x3F80_0000 | (u32::from_le_bytes(raw_bytes(ctx)) >> 9);
    let unit = f32::from_bits(bits) - 1.0;
    // `min + span * unit` is bounded by `min + span * (1 - 2⁻²³) < max`
    // in real arithmetic, but the final float rounding can push the
    // result up to `max` itself (up to half of the draws when
    // `span == ulp(min)`, ~6% when `span` sits at the bottom of an
    // exponent band). Clamp with `next_down(max)` so the [min, max)
    // half-open contract holds. The excess mass this adds to the
    // clamped value is at most one 24-bit unit of the domain and never
    // exits `[min, max)`.
    let v = (min + span * unit).min(max.next_down());
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `f64` in `[min, max)`.
///
/// Same conventions as [`sample_f32_in`]: NaN and infinities are excluded from
/// the output. Use [`sample_choice`] to include specific special values, or
/// `f64::from_bits(sample_u64(ctx))` for an arbitrary bit pattern. For the
/// full finite domain without a specific range, use [`sample_f64`].
///
/// # Panics
///
/// Panics if `min` or `max` is not finite, if `min >= max`, or if
/// `max - min` overflows to infinity (in that case the finite-output
/// guarantee cannot be honoured; split the range or sample at bit level
/// via [`sample_f64`] / `f64::from_bits`).
#[track_caller]
pub fn sample_f64_in(ctx: &mut TestCaseContext, min: f64, max: f64) -> f64 {
    assert!(
        min.is_finite() && max.is_finite(),
        "sample_f64_in: min and max must be finite"
    );
    assert!(min < max, "sample_f64_in: min must be less than max");
    let span = max - min;
    assert!(
        span.is_finite(),
        "sample_f64_in: max - min must be finite (max - min = {span}); split the range"
    );
    let loc = Location::caller();
    // Same construction as sample_f32 but with 53-bit precision. The
    // same next_down clamp applies for the same rounding reason (see
    // sample_f32_in).
    let bits = 0x3FF0_0000_0000_0000 | (u64::from_le_bytes(raw_bytes(ctx)) >> 12);
    let unit = f64::from_bits(bits) - 1.0;
    let v = (min + span * unit).min(max.next_down());
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed finite `f32` over the full finite domain
/// (excludes `NaN` and `±∞`; includes normals, subnormals, and both
/// signed zeros).
///
/// This is the common shape for roundtrip / serialization property
/// tests, where NaN and infinity are typically outside the format's
/// support. For an arbitrary bit pattern (including NaN / ±∞), use
/// `f32::from_bits(noprop::sample_u32(ctx))` instead. For a specific
/// finite subrange, use [`sample_f32_in`].
///
/// # Implementation
///
/// Rejection sampling over 32-bit patterns via
/// [`sample_with_rejection`]. Only ~0.4 % of `u32` bit patterns decode
/// to non-finite `f32` (all `NaN`s plus `±∞`), so the shared 64-attempt
/// bound is effectively unreachable (`P(all 64 fail) < 10⁻¹⁵²`).
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// let x = noprop::sample_f32(&mut ctx);
/// assert!(x.is_finite());
/// ```
#[track_caller]
pub fn sample_f32(ctx: &mut TestCaseContext) -> f32 {
    let loc = Location::caller();
    let v = sample_with_rejection(ctx, DEFAULT_MAX_ATTEMPTS, |ctx| {
        let candidate = f32::from_bits(u32::from_le_bytes(raw_bytes(ctx)));
        candidate.is_finite().then_some(candidate)
    });
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed finite `f64` over the full finite domain.
/// Same conventions and rationale as [`sample_f32`]; the
/// rejection rate over `u64` bit patterns is even lower (~2⁻¹¹ of
/// patterns are non-finite).
///
/// For an arbitrary bit pattern, use
/// `f64::from_bits(noprop::sample_u64(ctx))`. For a specific finite
/// subrange, use [`sample_f64_in`].
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// let x = noprop::sample_f64(&mut ctx);
/// assert!(x.is_finite());
/// ```
#[track_caller]
pub fn sample_f64(ctx: &mut TestCaseContext) -> f64 {
    let loc = Location::caller();
    let v = sample_with_rejection(ctx, DEFAULT_MAX_ATTEMPTS, |ctx| {
        let candidate = f64::from_bits(u64::from_le_bytes(raw_bytes(ctx)));
        candidate.is_finite().then_some(candidate)
    });
    ctx.record_generated(&v, loc);
    v
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Assert that `ctx` and `fresh` (built from the same seed) still
    /// produce identical output — used by the "consumes no RNG state"
    /// tests. Compares an 8-byte `fill` from each context.
    fn assert_state_unadvanced(ctx: &mut TestCaseContext, fresh: &mut TestCaseContext) {
        let mut a = [0u8; 8];
        let mut b = [0u8; 8];
        ctx.fill(&mut a);
        fresh.fill(&mut b);
        assert_eq!(a, b, "ctx advanced when it should not have");
    }

    #[test]
    fn primitives_are_deterministic() {
        let mut a = TestCaseContext::new(123);
        let mut b = TestCaseContext::new(123);
        assert_eq!(sample_bool(&mut a), sample_bool(&mut b));
        assert_eq!(sample_u8(&mut a), sample_u8(&mut b));
        assert_eq!(sample_u16(&mut a), sample_u16(&mut b));
        assert_eq!(sample_u32(&mut a), sample_u32(&mut b));
        assert_eq!(sample_u64(&mut a), sample_u64(&mut b));
        assert_eq!(sample_u128(&mut a), sample_u128(&mut b));
        assert_eq!(sample_usize(&mut a), sample_usize(&mut b));
        assert_eq!(sample_i8(&mut a), sample_i8(&mut b));
        assert_eq!(sample_i16(&mut a), sample_i16(&mut b));
        assert_eq!(sample_i32(&mut a), sample_i32(&mut b));
        assert_eq!(sample_i64(&mut a), sample_i64(&mut b));
        assert_eq!(sample_i128(&mut a), sample_i128(&mut b));
        assert_eq!(sample_isize(&mut a), sample_isize(&mut b));
    }

    #[test]
    fn bool_produces_both_values() {
        let mut ctx = TestCaseContext::new(1);
        let (mut t, mut f) = (false, false);
        for _ in 0..64 {
            match sample_bool(&mut ctx) {
                true => t = true,
                false => f = true,
            }
            if t && f {
                return;
            }
        }
        panic!("bool samples covered only one value");
    }

    #[test]
    fn u8_covers_both_halves_of_range() {
        let mut ctx = TestCaseContext::new(1);
        let (mut low, mut high) = (false, false);
        for _ in 0..64 {
            let v = sample_u8(&mut ctx);
            low |= v < 128;
            high |= v >= 128;
            if low && high {
                return;
            }
        }
        panic!("u8 samples covered only one half of the range");
    }

    #[test]
    fn i8_can_be_negative_and_nonnegative() {
        let mut ctx = TestCaseContext::new(1);
        let (mut neg, mut nonneg) = (false, false);
        for _ in 0..64 {
            let v = sample_i8(&mut ctx);
            neg |= v < 0;
            nonneg |= v >= 0;
            if neg && nonneg {
                return;
            }
        }
        panic!("i8 samples covered only one sign");
    }

    #[test]
    fn sample_choice_returns_only_from_slice() {
        let mut ctx = TestCaseContext::new(1);
        let choices = [10, 20, 30];
        for _ in 0..256 {
            assert!(choices.contains(&sample_choice(&mut ctx, &choices)));
        }
    }

    #[test]
    fn sample_choice_can_hit_every_element() {
        let mut ctx = TestCaseContext::new(1);
        let choices = [10, 20, 30];
        let mut seen = [false; 3];
        for _ in 0..256 {
            let v = sample_choice(&mut ctx, &choices);
            let idx = choices
                .iter()
                .position(|&x| x == v)
                .expect("sampled value must come from the choices array");
            seen[idx] = true;
            if seen.iter().all(|&s| s) {
                return;
            }
        }
        panic!("sample_choice did not cover all elements");
    }

    #[test]
    #[should_panic(expected = "empty slice")]
    fn sample_choice_panics_on_empty() {
        let mut ctx = TestCaseContext::new(0);
        let empty: [u32; 0] = [];
        let _ = sample_choice(&mut ctx, &empty);
    }

    #[test]
    fn sample_choice_works_with_clone_only_types() {
        // Verify T: Clone + Debug bound accepts non-Copy types with Debug.
        let mut ctx = TestCaseContext::new(1);
        let choices = vec![String::from("a"), String::from("b"), String::from("c")];
        let picked = sample_choice(&mut ctx, &choices);
        assert!(choices.contains(&picked));
    }

    #[test]
    fn char_generators_are_deterministic() {
        let mut a = TestCaseContext::new(789);
        let mut b = TestCaseContext::new(789);
        assert_eq!(sample_char(&mut a), sample_char(&mut b));
        assert_eq!(sample_ascii_char(&mut a), sample_ascii_char(&mut b));
        assert_eq!(
            sample_ascii_printable_char(&mut a),
            sample_ascii_printable_char(&mut b)
        );
    }

    #[test]
    fn sample_ascii_char_always_in_ascii_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let c = sample_ascii_char(&mut ctx);
            assert!(c.is_ascii());
        }
    }

    #[test]
    fn sample_ascii_printable_char_always_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let c = sample_ascii_printable_char(&mut ctx);
            let n = c as u32;
            assert!((0x20..=0x7E).contains(&n));
        }
    }

    #[test]
    fn sample_ascii_printable_char_matches_unbiased_core() {
        // 95 does not divide 2^64, so an unbiased printable draw must
        // come from the shared rejection-sampling core. Two same-seed
        // contexts advance in lockstep — each draws the same PRNG value
        // per character — so the direct `sample_below(95)` stream must
        // equal the char primitive's stream. The old `% 95` mapping
        // reduced only the low 32 bits of the draw, so the same draw
        // maps to a different character with probability 94/95, failing
        // this test on the first draw. A biased `% 95` over the full
        // 64-bit draw would not be detected here; that property rests
        // on the shared rejection-sampling core.
        let mut core = TestCaseContext::new(0x9E37_79B9_7F4A_7C15);
        let mut sampler = TestCaseContext::new(0x9E37_79B9_7F4A_7C15);
        for _ in 0..1024 {
            let expected = (0x20 + sample_below(&mut core, 95)) as u8 as char;
            assert_eq!(sample_ascii_printable_char(&mut sampler), expected);
        }
    }

    #[test]
    fn sample_ascii_printable_char_is_roughly_uniform() {
        let mut ctx = TestCaseContext::new(7);
        let mut counts = [0usize; 95];
        let total = 190_000;
        for _ in 0..total {
            let idx = (sample_ascii_printable_char(&mut ctx) as u32 - 0x20) as usize;
            counts[idx] += 1;
        }
        // The seed is fixed, so a generous slack of 10% makes this
        // deterministic rather than flaky.
        let expected = total / 95;
        for (i, c) in counts.iter().enumerate() {
            assert!(
                c.abs_diff(expected) < expected / 10,
                "bucket {i} count off: {c} vs {expected}"
            );
        }
    }

    // === sample_string / sample_ascii_string / sample_ascii_printable_string ===

    #[test]
    fn sample_string_returns_requested_code_point_count() {
        let mut ctx = TestCaseContext::new(1);
        for len in [0, 1, 7, 32] {
            let s = sample_string(&mut ctx, len);
            assert_eq!(
                s.chars().count(),
                len,
                "sample_string(ctx, {len}) chars().count() differed"
            );
        }
    }

    #[test]
    fn sample_ascii_string_returns_ascii_bytes_of_requested_length() {
        let mut ctx = TestCaseContext::new(1);
        for len in [0, 1, 7, 32] {
            let s = sample_ascii_string(&mut ctx, len);
            assert_eq!(s.chars().count(), len);
            assert_eq!(s.len(), len, "ASCII code point count == byte count");
            assert!(s.is_ascii());
        }
    }

    #[test]
    fn sample_ascii_printable_string_returns_printable_range() {
        let mut ctx = TestCaseContext::new(1);
        for len in [0, 1, 7, 32] {
            let s = sample_ascii_printable_string(&mut ctx, len);
            assert_eq!(s.chars().count(), len);
            assert_eq!(s.len(), len);
            assert!(
                s.chars().all(|c| (0x20..=0x7E).contains(&(c as u32))),
                "found non-printable in {s:?}"
            );
        }
    }

    #[test]
    fn sample_ascii_printable_string_matches_unbiased_core() {
        // The string path must draw each character from the same
        // unbiased core as the char primitive; see
        // `sample_ascii_printable_char_matches_unbiased_core`.
        let mut core = TestCaseContext::new(0xDEAD_BEEF_CAFE_F00D);
        let mut sampler = TestCaseContext::new(0xDEAD_BEEF_CAFE_F00D);
        for len in [1, 7, 32] {
            let expected: String = (0..len)
                .map(|_| (0x20 + sample_below(&mut core, 95)) as u8 as char)
                .collect();
            assert_eq!(sample_ascii_printable_string(&mut sampler, len), expected);
        }
    }

    #[test]
    fn string_generators_are_deterministic() {
        let mut a = TestCaseContext::new(0x517A_2E70);
        let mut b = TestCaseContext::new(0x517A_2E70);
        for len in [0, 3, 16] {
            assert_eq!(sample_string(&mut a, len), sample_string(&mut b, len));
            assert_eq!(
                sample_ascii_string(&mut a, len),
                sample_ascii_string(&mut b, len)
            );
            assert_eq!(
                sample_ascii_printable_string(&mut a, len),
                sample_ascii_printable_string(&mut b, len)
            );
        }
    }

    #[test]
    fn sample_string_zero_length_is_empty() {
        let mut ctx = TestCaseContext::new(1);
        assert_eq!(sample_string(&mut ctx, 0), "");
        assert_eq!(sample_ascii_string(&mut ctx, 0), "");
        assert_eq!(sample_ascii_printable_string(&mut ctx, 0), "");
    }

    #[test]
    fn sample_char_produces_varied_values() {
        // Valid Unicode scalar space is ~1.1M chars, so 256 samples should
        // be nearly all distinct (collision probability is negligible).
        let mut ctx = TestCaseContext::new(1);
        let mut seen = std::collections::HashSet::new();
        for _ in 0..256 {
            seen.insert(sample_char(&mut ctx));
        }
        assert!(
            seen.len() > 200,
            "sample_char produced too few distinct values: {}",
            seen.len()
        );
    }

    #[test]
    fn float_generators_are_deterministic() {
        let mut a = TestCaseContext::new(999);
        let mut b = TestCaseContext::new(999);
        assert_eq!(
            sample_f32_in(&mut a, 0.0, 1.0),
            sample_f32_in(&mut b, 0.0, 1.0)
        );
        assert_eq!(
            sample_f64_in(&mut a, -100.0, 100.0),
            sample_f64_in(&mut b, -100.0, 100.0)
        );
    }

    #[test]
    fn sample_f32_in_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let v = sample_f32_in(&mut ctx, 10.0, 20.0);
            assert!((10.0..20.0).contains(&v), "out of range: {v}");
        }
    }

    #[test]
    fn sample_f64_in_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let v = sample_f64_in(&mut ctx, -1.0, 1.0);
            assert!((-1.0..1.0).contains(&v), "out of range: {v}");
        }
    }

    #[test]
    fn sample_f32_in_covers_both_halves_of_range() {
        let mut ctx = TestCaseContext::new(1);
        let (mut low, mut high) = (false, false);
        for _ in 0..64 {
            let v = sample_f32_in(&mut ctx, 0.0, 1.0);
            low |= v < 0.5;
            high |= v >= 0.5;
            if low && high {
                return;
            }
        }
        panic!("sample_f32_in covered only one half of the range");
    }

    #[test]
    #[should_panic(expected = "must be less than")]
    fn sample_f32_in_panics_when_min_equals_max() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_f32_in(&mut ctx, 5.0, 5.0);
    }

    #[test]
    #[should_panic(expected = "must be finite")]
    fn sample_f32_in_panics_on_nan() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_f32_in(&mut ctx, f32::NAN, 1.0);
    }

    #[test]
    #[should_panic(expected = "must be finite")]
    fn sample_f32_in_panics_on_infinity() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_f32_in(&mut ctx, 0.0, f32::INFINITY);
    }

    #[test]
    #[should_panic(expected = "must be finite")]
    fn sample_f64_in_panics_on_nan() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_f64_in(&mut ctx, 0.0, f64::NAN);
    }

    #[test]
    #[should_panic(expected = "must be finite")]
    fn sample_f64_in_panics_on_infinity() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_f64_in(&mut ctx, 0.0, f64::INFINITY);
    }

    #[test]
    #[should_panic(expected = "must be less than")]
    fn sample_f64_in_panics_when_min_equals_max() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_f64_in(&mut ctx, 5.0, 5.0);
    }

    #[test]
    #[should_panic(expected = "max - min must be finite")]
    fn sample_f32_in_panics_when_span_overflows() {
        // Individually-finite bounds whose difference overflows to +INF.
        // Without the guard this would return NaN (for unit == 0.0) or
        // +/-INF (for unit > 0.0), violating the finite-output contract.
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_f32_in(&mut ctx, f32::MIN, f32::MAX);
    }

    #[test]
    #[should_panic(expected = "max - min must be finite")]
    fn sample_f64_in_panics_when_span_overflows() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_f64_in(&mut ctx, f64::MIN, f64::MAX);
    }

    #[test]
    fn sample_f32_in_stays_finite_at_widest_admissible_span() {
        // The widest range whose span is still finite: 0.0..f32::MAX
        // (span == f32::MAX). Every drawn value must be finite.
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let v = sample_f32_in(&mut ctx, 0.0, f32::MAX);
            assert!(v.is_finite(), "expected finite, got {v}");
            assert!((0.0..f32::MAX).contains(&v), "out of range: {v}");
        }
    }

    #[test]
    fn sample_f64_in_stays_finite_at_widest_admissible_span() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let v = sample_f64_in(&mut ctx, 0.0, f64::MAX);
            assert!(v.is_finite(), "expected finite, got {v}");
            assert!((0.0..f64::MAX).contains(&v), "out of range: {v}");
        }
    }

    #[test]
    fn sample_f32_in_stays_strictly_below_max_at_ulp_span() {
        // Regression: `min + span * unit` used to round up to `max`
        // itself when `span == ulp(min)` - up to ~50% of draws exited
        // the documented [min, max) contract. Verify the next_down
        // clamp holds the upper bound strictly.
        let mut ctx = TestCaseContext::new(1);
        let min = 1.0f32;
        let max = 1.0f32 + 2f32.powi(-23);
        for _ in 0..10_000 {
            let v = sample_f32_in(&mut ctx, min, max);
            assert!(v >= min, "v={v} < min={min}");
            assert!(v < max, "v={v} reached the excluded upper bound {max}");
        }
    }

    #[test]
    fn sample_f32_in_stays_strictly_below_max_across_exponent_band() {
        // Regression: at min=2^20, max=2^20+1 the ulp is 2^-3 = 0.125,
        // so ~6% of draws used to round up to `max`. Verify the clamp
        // catches those too.
        let mut ctx = TestCaseContext::new(1);
        let (min, max) = (2f32.powi(20), 2f32.powi(20) + 1.0);
        for _ in 0..10_000 {
            let v = sample_f32_in(&mut ctx, min, max);
            assert!(v < max, "v={v} reached the excluded upper bound {max}");
        }
    }

    #[test]
    fn sample_f64_in_stays_strictly_below_max_at_ulp_span() {
        // Same regression as sample_f32_in_stays_strictly_below_max_
        // at_ulp_span but at 53-bit precision.
        let mut ctx = TestCaseContext::new(1);
        let min = 1.0f64;
        let max = 1.0f64 + 2f64.powi(-52);
        for _ in 0..10_000 {
            let v = sample_f64_in(&mut ctx, min, max);
            assert!(v >= min, "v={v} < min={min}");
            assert!(v < max, "v={v} reached the excluded upper bound {max}");
        }
    }

    // === sample_f32 / sample_f64 (full finite domain) ===

    #[test]
    fn sample_f32_always_returns_finite() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..10_000 {
            let v = sample_f32(&mut ctx);
            assert!(v.is_finite(), "expected finite, got {v:?}");
            assert!(!v.is_nan(), "expected non-NaN, got {v:?}");
        }
    }

    #[test]
    fn sample_f64_always_returns_finite() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..10_000 {
            let v = sample_f64(&mut ctx);
            assert!(v.is_finite(), "expected finite, got {v:?}");
            assert!(!v.is_nan(), "expected non-NaN, got {v:?}");
        }
    }

    #[test]
    fn full_domain_float_generators_are_deterministic() {
        let mut a = TestCaseContext::new(0xF10A_7000);
        let mut b = TestCaseContext::new(0xF10A_7000);
        for _ in 0..64 {
            assert_eq!(sample_f32(&mut a), sample_f32(&mut b));
            assert_eq!(sample_f64(&mut a), sample_f64(&mut b));
        }
    }

    #[test]
    fn sample_f32_covers_both_signs() {
        // ~half of finite f32 patterns are negative (the sign bit is
        // uniform over accepted candidates).
        let mut ctx = TestCaseContext::new(2);
        let (mut pos, mut neg) = (false, false);
        for _ in 0..256 {
            let v = sample_f32(&mut ctx);
            if v > 0.0 {
                pos = true;
            } else if v < 0.0 {
                neg = true;
            }
            if pos && neg {
                return;
            }
        }
        panic!("sample_f32 did not cover both signs");
    }

    // === sample_below ===

    #[test]
    fn sample_below_one_returns_zero_without_drawing() {
        // n == 1 has a single legal value, so no RNG bytes must be consumed.
        let mut ctx = TestCaseContext::new(1);
        let mut fresh = TestCaseContext::new(1);
        assert_eq!(sample_below(&mut ctx, 1), 0);
        assert_state_unadvanced(&mut ctx, &mut fresh);
    }

    #[test]
    fn sample_below_stays_in_range() {
        let mut ctx = TestCaseContext::new(42);
        for _ in 0..10_000 {
            let v = sample_below(&mut ctx, 7);
            assert!(v < 7);
        }
    }

    #[test]
    fn sample_below_hits_every_value() {
        let mut ctx = TestCaseContext::new(42);
        let mut seen = [false; 5];
        for _ in 0..1024 {
            let v = sample_below(&mut ctx, 5) as usize;
            seen[v] = true;
            if seen.iter().all(|&s| s) {
                return;
            }
        }
        panic!("sample_below did not cover all values");
    }

    #[test]
    fn sample_below_is_roughly_uniform_on_non_divisor() {
        // 3 does not divide 2^64, so the sampler must actively reject.
        // Verify that a large batch of draws is roughly balanced.
        let mut ctx = TestCaseContext::new(7);
        let mut counts = [0usize; 3];
        let total = 30_000;
        for _ in 0..total {
            counts[sample_below(&mut ctx, 3) as usize] += 1;
        }
        // Expected ~10_000 per bucket. Allow a very generous slack.
        let expected = total / 3;
        for c in counts {
            assert!(
                c.abs_diff(expected) < expected / 10,
                "bucket count off: {c} vs {expected}"
            );
        }
    }

    #[test]
    fn sample_below_accepts_full_u64_domain() {
        // u64::MAX is odd (not a multiple of 2), so this exercises the
        // rejection path with the widest possible bound.
        let mut ctx = TestCaseContext::new(1);
        let _v = sample_below(&mut ctx, u64::MAX);
    }

    // === sample_usize_in ===

    #[test]
    fn sample_usize_in_exclusive_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let v = sample_usize_in(&mut ctx, 10..20);
            assert!((10..20).contains(&v));
        }
    }

    #[test]
    fn sample_usize_in_inclusive_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let v = sample_usize_in(&mut ctx, 10..=20);
            assert!((10..=20).contains(&v));
        }
    }

    #[test]
    fn sample_usize_in_single_element_returns_that_element() {
        let mut ctx = TestCaseContext::new(1);
        // 5..=5 is one element; the runner should return it without
        // consuming any RNG.
        let mut fresh = TestCaseContext::new(1);
        assert_eq!(sample_usize_in(&mut ctx, 5..=5), 5);
        assert_state_unadvanced(&mut ctx, &mut fresh);
    }

    #[test]
    fn sample_usize_in_hits_both_endpoints() {
        let mut ctx = TestCaseContext::new(1);
        let (mut lo, mut hi) = (false, false);
        for _ in 0..1024 {
            let v = sample_usize_in(&mut ctx, 0..=3);
            lo |= v == 0;
            hi |= v == 3;
            if lo && hi {
                return;
            }
        }
        panic!("sample_usize_in did not cover both endpoints");
    }

    #[test]
    fn sample_usize_in_full_range_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..100 {
            let _v = sample_usize_in(&mut ctx, ..);
            // Any usize is in range; just verify no panic.
        }
    }

    #[test]
    fn sample_usize_in_inclusive_up_to_max_stays_in_range() {
        // Exercises the max - lo + 1 arithmetic on the widest non-full
        // range so it must not overflow.
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..100 {
            let v = sample_usize_in(&mut ctx, 1..=usize::MAX);
            assert!(v >= 1);
        }
    }

    #[test]
    fn sample_usize_in_unbounded_end_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..100 {
            let v = sample_usize_in(&mut ctx, 100..);
            assert!(v >= 100);
        }
    }

    #[test]
    fn sample_usize_in_is_deterministic() {
        let mut a = TestCaseContext::new(999);
        let mut b = TestCaseContext::new(999);
        for _ in 0..64 {
            assert_eq!(
                sample_usize_in(&mut a, 0..137),
                sample_usize_in(&mut b, 0..137)
            );
        }
    }

    #[test]
    #[should_panic(expected = "empty range")]
    fn sample_usize_in_panics_on_empty_exclusive() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_usize_in(&mut ctx, 5..5);
    }

    #[test]
    #[should_panic(expected = "empty range")]
    fn sample_usize_in_panics_on_reversed_inclusive() {
        let mut ctx = TestCaseContext::new(0);
        #[expect(
            clippy::reversed_empty_ranges,
            reason = "the reversed range is the panic condition under test"
        )]
        let _ = sample_usize_in(&mut ctx, 5..=4);
    }

    #[test]
    #[should_panic(expected = "empty range")]
    fn sample_usize_in_panics_on_zero_exclusive_end() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_usize_in(&mut ctx, ..0);
    }

    #[test]
    #[should_panic(expected = "empty range")]
    fn sample_usize_in_panics_on_excluded_max_start() {
        let mut ctx = TestCaseContext::new(0);
        // An excluded start of usize::MAX would need start + 1, which
        // overflows — semantically the range is empty.
        let _ = sample_usize_in(
            &mut ctx,
            (
                std::ops::Bound::Excluded(usize::MAX),
                std::ops::Bound::<usize>::Unbounded,
            ),
        );
    }

    // === sample_u64_in ===

    #[test]
    fn sample_u64_in_exclusive_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let v = sample_u64_in(&mut ctx, 10..20);
            assert!((10..20).contains(&v));
        }
    }

    #[test]
    fn sample_u64_in_inclusive_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let v = sample_u64_in(&mut ctx, 10..=20);
            assert!((10..=20).contains(&v));
        }
    }

    #[test]
    fn sample_u64_in_single_element_returns_that_element() {
        let mut ctx = TestCaseContext::new(1);
        // 5..=5 is one element; the runner should return it without
        // consuming any RNG.
        let mut fresh = TestCaseContext::new(1);
        assert_eq!(sample_u64_in(&mut ctx, 5..=5), 5);
        assert_state_unadvanced(&mut ctx, &mut fresh);
    }

    #[test]
    fn sample_u64_in_hits_both_endpoints() {
        let mut ctx = TestCaseContext::new(1);
        let (mut lo, mut hi) = (false, false);
        for _ in 0..1024 {
            let v = sample_u64_in(&mut ctx, 0..=3);
            lo |= v == 0;
            hi |= v == 3;
            if lo && hi {
                return;
            }
        }
        panic!("sample_u64_in did not cover both endpoints");
    }

    #[test]
    fn sample_u64_in_full_range_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..100 {
            let _v = sample_u64_in(&mut ctx, ..);
            // Any u64 is in range; just verify no panic.
        }
    }

    #[test]
    fn sample_u64_in_inclusive_up_to_max_stays_in_range() {
        // Exercises the max - lo + 1 arithmetic on the widest non-full
        // range so it must not overflow.
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..100 {
            let v = sample_u64_in(&mut ctx, 1..=u64::MAX);
            assert!(v >= 1);
        }
    }

    #[test]
    fn sample_u64_in_unbounded_end_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..100 {
            let v = sample_u64_in(&mut ctx, 100..);
            assert!(v >= 100);
        }
    }

    #[test]
    fn sample_u64_in_is_deterministic() {
        let mut a = TestCaseContext::new(999);
        let mut b = TestCaseContext::new(999);
        for _ in 0..64 {
            assert_eq!(sample_u64_in(&mut a, 0..137), sample_u64_in(&mut b, 0..137));
        }
    }

    #[test]
    #[should_panic(expected = "empty range")]
    fn sample_u64_in_panics_on_empty_exclusive() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_u64_in(&mut ctx, 5..5);
    }

    #[test]
    #[should_panic(expected = "empty range")]
    fn sample_u64_in_panics_on_reversed_inclusive() {
        let mut ctx = TestCaseContext::new(0);
        #[expect(
            clippy::reversed_empty_ranges,
            reason = "the reversed range is the panic condition under test"
        )]
        let _ = sample_u64_in(&mut ctx, 5..=4);
    }

    #[test]
    #[should_panic(expected = "empty range")]
    fn sample_u64_in_panics_on_zero_exclusive_end() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_u64_in(&mut ctx, ..0);
    }

    #[test]
    #[should_panic(expected = "empty range")]
    fn sample_u64_in_panics_on_excluded_max_start() {
        let mut ctx = TestCaseContext::new(0);
        // An excluded start of u64::MAX would need start + 1, which
        // overflows — semantically the range is empty.
        let _ = sample_u64_in(
            &mut ctx,
            (
                std::ops::Bound::Excluded(u64::MAX),
                std::ops::Bound::<u64>::Unbounded,
            ),
        );
    }

    // === typed `_in` samplers ===

    #[test]
    fn typed_in_samplers_stay_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..256 {
            assert!((10..20).contains(&sample_u8_in(&mut ctx, 10..20)));
            assert!((10..=20).contains(&sample_u16_in(&mut ctx, 10..=20)));
            assert!((10..=20).contains(&sample_u32_in(&mut ctx, 10..=20)));
            assert!((-10..0).contains(&sample_i8_in(&mut ctx, -10..0)));
            assert!((-10..=0).contains(&sample_i16_in(&mut ctx, -10..=0)));
            assert!((-10..=0).contains(&sample_i32_in(&mut ctx, -10..=0)));
        }
    }

    #[test]
    fn typed_in_samplers_full_width_stay_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..64 {
            let _ = sample_u8_in(&mut ctx, ..);
            let _ = sample_u16_in(&mut ctx, ..);
            let _ = sample_u32_in(&mut ctx, ..);
            // The full signed domain must not overflow while normalizing.
            let _ = sample_i8_in(&mut ctx, i8::MIN..=i8::MAX);
            let _ = sample_i16_in(&mut ctx, i16::MIN..=i16::MAX);
            let _ = sample_i32_in(&mut ctx, i32::MIN..=i32::MAX);
        }
    }

    #[test]
    fn typed_in_samplers_inclusive_max_stays_in_range() {
        // Exercises the width + 1 arithmetic on the widest non-full
        // range for each type, so it must not overflow.
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..64 {
            assert!(sample_u8_in(&mut ctx, 1..=u8::MAX) >= 1);
            assert!(sample_u16_in(&mut ctx, 1..=u16::MAX) >= 1);
            assert!(sample_u32_in(&mut ctx, 1..=u32::MAX) >= 1);
            assert!(sample_i8_in(&mut ctx, i8::MIN..=i8::MAX - 1) < i8::MAX);
            assert!(sample_i16_in(&mut ctx, i16::MIN..=i16::MAX - 1) < i16::MAX);
            assert!(sample_i32_in(&mut ctx, i32::MIN..=i32::MAX - 1) < i32::MAX);
        }
    }

    #[test]
    fn typed_in_samplers_single_element_returns_that_element() {
        let mut ctx = TestCaseContext::new(1);
        assert_eq!(sample_u8_in(&mut ctx, 5..=5), 5);
        assert_eq!(sample_u16_in(&mut ctx, 5..=5), 5);
        assert_eq!(sample_u32_in(&mut ctx, 5..=5), 5);
        assert_eq!(sample_i8_in(&mut ctx, -5..=-5), -5);
        assert_eq!(sample_i16_in(&mut ctx, -5..=-5), -5);
        assert_eq!(sample_i32_in(&mut ctx, -5..=-5), -5);
    }

    #[test]
    fn typed_in_samplers_hit_both_endpoints() {
        let mut ctx = TestCaseContext::new(1);
        let (mut lo, mut hi) = (false, false);
        for _ in 0..1024 {
            let v = sample_i8_in(&mut ctx, -2..=2);
            lo |= v == -2;
            hi |= v == 2;
            if lo && hi {
                return;
            }
        }
        panic!("sample_i8_in did not cover both endpoints");
    }

    #[test]
    fn typed_in_samplers_are_deterministic() {
        let mut a = TestCaseContext::new(999);
        let mut b = TestCaseContext::new(999);
        for _ in 0..64 {
            assert_eq!(sample_u8_in(&mut a, 0..137), sample_u8_in(&mut b, 0..137));
            assert_eq!(
                sample_i32_in(&mut a, -100..=100),
                sample_i32_in(&mut b, -100..=100)
            );
        }
    }

    #[test]
    #[should_panic(expected = "sample_u8_in: empty range")]
    fn sample_u8_in_panics_on_empty_exclusive() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_u8_in(&mut ctx, 5..5);
    }

    #[test]
    #[should_panic(expected = "sample_u8_in: empty range")]
    fn sample_u8_in_panics_on_excluded_max_start() {
        let mut ctx = TestCaseContext::new(0);
        // An excluded start of u8::MAX would need start + 1, which
        // overflows — semantically the range is empty.
        let _ = sample_u8_in(
            &mut ctx,
            (
                std::ops::Bound::Excluded(u8::MAX),
                std::ops::Bound::<u8>::Unbounded,
            ),
        );
    }

    #[test]
    #[should_panic(expected = "sample_i8_in: empty range")]
    fn sample_i8_in_panics_on_reversed_inclusive() {
        let mut ctx = TestCaseContext::new(0);
        #[expect(
            clippy::reversed_empty_ranges,
            reason = "the reversed range is the panic condition under test"
        )]
        let _ = sample_i8_in(&mut ctx, 5..=4);
    }

    #[test]
    #[should_panic(expected = "sample_i32_in: empty range")]
    fn sample_i32_in_panics_on_reversed_exclusive() {
        let mut ctx = TestCaseContext::new(0);
        // `..0` is `i32::MIN..0`, which is non-empty for a signed type;
        // an actually empty exclusive range is one where lo == hi.
        let _ = sample_i32_in(&mut ctx, 0..0);
    }

    // === Ratio ===

    #[test]
    fn ratio_new_accepts_valid() {
        let ratio = Ratio::new(1, 3);
        assert_eq!(ratio.numerator, 1);
        assert_eq!(ratio.denominator, 3);
        assert_eq!(Ratio::new(0, 5).numerator, 0);
        assert_eq!(Ratio::new(5, 5).denominator, 5);
    }

    #[test]
    #[should_panic(expected = "Ratio::new: denominator must be non-zero")]
    fn ratio_new_panics_on_zero_denominator() {
        let _ = Ratio::new(1, 0);
    }

    #[test]
    #[should_panic(expected = "Ratio::new: denominator must be non-zero")]
    fn ratio_new_panics_on_zero_zero() {
        let _ = Ratio::new(0, 0);
    }

    #[test]
    #[should_panic(expected = "Ratio::new: numerator must not exceed denominator")]
    fn ratio_new_panics_when_numerator_exceeds_denominator() {
        let _ = Ratio::new(2, 1);
    }

    #[test]
    #[should_panic(expected = "Ratio::new: numerator must not exceed denominator")]
    fn ratio_new_panics_when_numerator_exceeds_denominator_larger() {
        let _ = Ratio::new(11, 10);
    }

    #[test]
    fn ratio_one_nth_matches_new_1_over_n() {
        assert_eq!(Ratio::one_nth(2), Ratio::new(1, 2));
        assert_eq!(Ratio::one_nth(3), Ratio::new(1, 3));
        assert_eq!(Ratio::one_nth(10), Ratio::new(1, 10));
        assert_eq!(Ratio::one_nth(100), Ratio::new(1, 100));
    }

    #[test]
    #[should_panic(expected = "Ratio::one_nth: n must be non-zero")]
    fn ratio_one_nth_panics_on_zero() {
        let _ = Ratio::one_nth(0);
    }

    // === sample_ratio ===

    #[test]
    fn sample_ratio_zero_numerator_always_false_and_draws_nothing() {
        let mut ctx = TestCaseContext::new(1);
        let mut fresh = TestCaseContext::new(1);
        for _ in 0..64 {
            assert!(!sample_ratio(&mut ctx, Ratio::new(0, 10)));
        }
        // No RNG bytes consumed.
        assert_state_unadvanced(&mut ctx, &mut fresh);
    }

    #[test]
    fn sample_ratio_full_numerator_always_true_and_draws_nothing() {
        let mut ctx = TestCaseContext::new(1);
        let mut fresh = TestCaseContext::new(1);
        for _ in 0..64 {
            assert!(sample_ratio(&mut ctx, Ratio::new(7, 7)));
        }
        assert_state_unadvanced(&mut ctx, &mut fresh);
    }

    #[test]
    fn sample_ratio_produces_both_outcomes() {
        let mut ctx = TestCaseContext::new(1);
        let (mut t, mut f) = (false, false);
        for _ in 0..256 {
            match sample_ratio(&mut ctx, Ratio::one_nth(2)) {
                true => t = true,
                false => f = true,
            }
            if t && f {
                return;
            }
        }
        panic!("sample_ratio did not produce both outcomes");
    }

    #[test]
    fn sample_ratio_is_deterministic() {
        let mut a = TestCaseContext::new(999);
        let mut b = TestCaseContext::new(999);
        for _ in 0..64 {
            assert_eq!(
                sample_ratio(&mut a, Ratio::new(3, 7)),
                sample_ratio(&mut b, Ratio::new(3, 7))
            );
        }
    }

    #[test]
    fn sample_ratio_biased_matches_expected_frequency() {
        // 1-in-10 draws should sit near 10% out of 10_000 samples.
        let mut ctx = TestCaseContext::new(1);
        let mut trues: usize = 0;
        let total: usize = 10_000;
        for _ in 0..total {
            if sample_ratio(&mut ctx, Ratio::one_nth(10)) {
                trues += 1;
            }
        }
        let expected = total / 10;
        // ±10% (100 out of 1000) is ~3σ for a Bernoulli(0.1) with
        // n=10_000 (σ ≈ 30), so the fixed-seed run has comfortable
        // headroom while still catching regressions that halve the
        // biasing.
        assert!(
            trues.abs_diff(expected) < expected / 10,
            "sample_ratio(Ratio::one_nth(10)) frequency off: {trues}/{total}"
        );
    }

    // === sample_with_boundaries ===

    #[test]
    fn sample_with_boundaries_full_ratio_always_boundary() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..64 {
            let v = sample_with_boundaries(&mut ctx, &[7, 8], Ratio::new(2, 2), sample_u32);
            assert!(v == 7 || v == 8, "unexpected value: {v}");
        }
    }

    #[test]
    fn sample_with_boundaries_zero_ratio_always_uniform() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..64 {
            let v = sample_with_boundaries(&mut ctx, &[7, 8], Ratio::new(0, 3), sample_u32);
            assert!(v != 7 && v != 8, "unexpected boundary value: {v}");
        }
    }

    #[test]
    fn sample_with_boundaries_produces_both_paths() {
        let mut ctx = TestCaseContext::new(1);
        let (mut boundary, mut uniform) = (false, false);
        for _ in 0..256 {
            let v = sample_with_boundaries(&mut ctx, &[u32::MAX], Ratio::one_nth(2), sample_u32);
            if v == u32::MAX {
                boundary = true;
            } else {
                uniform = true;
            }
            if boundary && uniform {
                return;
            }
        }
        panic!("sample_with_boundaries did not take both paths");
    }

    #[test]
    fn sample_with_boundaries_boundary_frequency_matches_ratio() {
        // 1-in-10 boundary draws should sit near 10% out of 10_000
        // samples. A one-element boundary consumes no RNG bytes, so the
        // count measures the ratio branch alone; the uniform path
        // hitting the sentinel is negligible (2^-32 per draw).
        let mut ctx = TestCaseContext::new(1);
        let mut boundary: usize = 0;
        let total: usize = 10_000;
        for _ in 0..total {
            let v = sample_with_boundaries(&mut ctx, &[u32::MAX], Ratio::one_nth(10), sample_u32);
            if v == u32::MAX {
                boundary += 1;
            }
        }
        let expected = total / 10;
        // ±10% (~3σ) - see sample_ratio_biased_matches_expected_frequency
        // for the rationale.
        assert!(
            boundary.abs_diff(expected) < expected / 10,
            "sample_with_boundaries(one_nth(10)) frequency off: {boundary}/{total}"
        );
    }

    #[test]
    fn sample_with_boundaries_boundary_path_hits_every_element() {
        // The boundary path must draw uniformly from `boundaries`: a
        // bug that always returns the first element must be caught.
        let mut ctx = TestCaseContext::new(1);
        let mut seen = [false; 2];
        for _ in 0..256 {
            let v = sample_with_boundaries(&mut ctx, &[7, 8], Ratio::new(2, 2), sample_u32);
            match v {
                7 => seen[0] = true,
                8 => seen[1] = true,
                _ => panic!("unexpected value: {v}"),
            }
            if seen.iter().all(|&s| s) {
                return;
            }
        }
        panic!("sample_with_boundaries boundary path did not cover all elements");
    }

    #[test]
    fn sample_with_boundaries_is_deterministic() {
        let mut a = TestCaseContext::new(1234);
        let mut b = TestCaseContext::new(1234);
        for _ in 0..64 {
            assert_eq!(
                sample_with_boundaries(&mut a, &[0, 1], Ratio::one_nth(4), sample_u64),
                sample_with_boundaries(&mut b, &[0, 1], Ratio::one_nth(4), sample_u64)
            );
        }
    }

    #[test]
    fn sample_with_boundaries_recipe_is_byte_equivalent() {
        // The helper must reproduce the hand-written recipe from the
        // boundary-bias evaluation exactly, so rewriting a generator
        // with the helper does not shift the choice sequence.
        let mut a = TestCaseContext::new(42);
        let mut b = TestCaseContext::new(42);
        for _ in 0..256 {
            let hand_written = if sample_usize_in(&mut a, 0..10) == 0 {
                0
            } else {
                sample_u32(&mut a)
            };
            let helper = sample_with_boundaries(&mut b, &[0], Ratio::one_nth(10), sample_u32);
            assert_eq!(hand_written, helper, "streams diverged");
        }
    }

    #[test]
    #[should_panic(expected = "empty boundaries")]
    fn sample_with_boundaries_panics_on_empty_boundaries() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_with_boundaries(&mut ctx, &[] as &[u32], Ratio::one_nth(2), sample_u32);
    }

    // === sample_weighted_index ===

    #[test]
    fn sample_weighted_index_stays_in_range() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let idx = sample_weighted_index(&mut ctx, &[1, 2, 3, 4]);
            assert!(idx < 4);
        }
    }

    #[test]
    fn sample_weighted_index_hits_every_nonzero_index() {
        let mut ctx = TestCaseContext::new(1);
        let weights = [1, 1, 1];
        let mut seen = [false; 3];
        for _ in 0..1024 {
            seen[sample_weighted_index(&mut ctx, &weights)] = true;
            if seen.iter().all(|&s| s) {
                return;
            }
        }
        panic!("sample_weighted_index did not cover all non-zero indices");
    }

    #[test]
    fn sample_weighted_index_skips_zero_weight_slot() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..1000 {
            let idx = sample_weighted_index(&mut ctx, &[3, 0, 5]);
            assert_ne!(idx, 1, "index 1 has weight 0 and must never be picked");
        }
    }

    #[test]
    fn sample_weighted_index_single_nonzero_always_returns_it() {
        let mut ctx = TestCaseContext::new(1);
        for _ in 0..100 {
            assert_eq!(sample_weighted_index(&mut ctx, &[0, 0, 42, 0]), 2);
        }
    }

    #[test]
    fn sample_weighted_index_is_deterministic() {
        let mut a = TestCaseContext::new(123);
        let mut b = TestCaseContext::new(123);
        let weights = [4, 1, 2, 3];
        for _ in 0..64 {
            assert_eq!(
                sample_weighted_index(&mut a, &weights),
                sample_weighted_index(&mut b, &weights)
            );
        }
    }

    #[test]
    fn sample_weighted_index_frequencies_approximate_weights() {
        // Weights 1:2:3 → ~1/6, 2/6, 3/6 of samples.
        let mut ctx = TestCaseContext::new(1);
        let weights = [1, 2, 3];
        let mut counts = [0usize; 3];
        let total = 12_000;
        for _ in 0..total {
            counts[sample_weighted_index(&mut ctx, &weights)] += 1;
        }
        // Expected 2000 / 4000 / 6000. Allow ±10% slack (roughly 3σ
        // for the smallest bucket, which is the tightest constraint).
        for (i, (&c, &w)) in counts.iter().zip(weights.iter()).enumerate() {
            let expected = total * w as usize / 6;
            assert!(
                c.abs_diff(expected) < expected / 10,
                "index {i}: got {c}, expected ~{expected}"
            );
        }
    }

    #[test]
    #[should_panic(expected = "empty weights")]
    fn sample_weighted_index_panics_on_empty() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_weighted_index(&mut ctx, &[]);
    }

    #[test]
    #[should_panic(expected = "all weights are zero")]
    fn sample_weighted_index_panics_when_all_weights_zero() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_weighted_index(&mut ctx, &[0, 0, 0]);
    }

    // === sample_with_rejection basic behavior ===

    #[test]
    #[should_panic(expected = "max_attempts must be > 0")]
    fn sample_with_rejection_panics_on_zero_max_attempts() {
        let mut ctx = TestCaseContext::new(0);
        let _: u32 = sample_with_rejection(&mut ctx, 0, |_| Some(1));
    }

    #[test]
    #[should_panic(expected = "noprop::sample_with_rejection")]
    fn sample_with_rejection_exhaustion_outside_runner_names_the_primitive() {
        // When every attempt is rejected and the context is not inside
        // a Runner, the panic must identify sample_with_rejection as
        // the culprit rather than surfacing the internal reject_case
        // "not inside a Runner" message, which would misdirect a user
        // who never called reject_case.
        let mut ctx = TestCaseContext::new(0);
        let _: u32 = sample_with_rejection(&mut ctx, 3, |_ctx| None);
    }

    #[test]
    fn sample_with_rejection_returns_first_accepted_value() {
        let mut ctx = TestCaseContext::new(0);
        let v = sample_with_rejection(&mut ctx, 8, |_ctx| Some(42u32));
        assert_eq!(v, 42);
    }

    #[test]
    fn sample_with_rejection_skips_rejected_attempts_and_returns_accepted() {
        let mut ctx = TestCaseContext::new(0);
        let counter = std::cell::Cell::new(0usize);
        let v = sample_with_rejection(&mut ctx, 8, |_ctx| {
            let n = counter.get();
            counter.set(n + 1);
            // Accept on the 4th attempt (0-indexed: 3rd retry).
            if n == 3 { Some(n as u32) } else { None }
        });
        assert_eq!(v, 3);
        assert_eq!(counter.get(), 4);
    }
}