noprop 0.0.2

Imperative property-based testing library with no dependencies, no macros, no unsafe, and no implicit I/O
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
//! Value generators.
//!
//! Every generator has the shape `fn sample_X(ctx: &mut TestCaseContext) -> X`. User
//! code composes generators with plain Rust — closures, `match`, `for`,
//! iterators — so property tests read like ordinary Rust code, and user
//! generators (`fn sample_person(ctx: &mut TestCaseContext) -> Person`) have the
//! same shape as the built-in ones.
//!
//! # Composing generators
//!
//! To build a generator whose output depends on another's, just call
//! them sequentially inside a plain function or closure:
//!
//! ```
//! use noprop::TestCaseContext;
//!
//! fn sample_bounded_vec(ctx: &mut TestCaseContext) -> Vec<u32> {
//!     // Pick a length first, then a Vec of that length.
//!     let len = noprop::sample_usize_in(ctx, 0..10);
//!     (0..len).map(|_| noprop::sample_u32(ctx)).collect()
//! }
//!
//! let mut ctx = TestCaseContext::new(0);
//! let _v: Vec<u32> = sample_bounded_vec(&mut ctx);
//! ```
//!
//! For "one-of-N" branching between code paths, `match` on a small
//! random value produced by [`sample_usize_in`]:
//!
//! ```
//! let mut ctx = noprop::TestCaseContext::new(0);
//! let _x: u32 = match noprop::sample_usize_in(&mut ctx, 0..3) {
//!     0 => 0,
//!     1 => noprop::sample_u32(&mut ctx),
//!     _ => u32::MAX,
//! };
//! ```
//!
//! To weight the branches unevenly, use [`sample_weighted_index`] (or
//! [`sample_ratio`] for a two-way split):
//!
//! ```
//! let mut ctx = noprop::TestCaseContext::new(0);
//! // Pick branch 0 with weight 5, branch 1 with weight 3, branch 2 with weight 2.
//! let _x: u32 = match noprop::sample_weighted_index(&mut ctx, &[5, 3, 2]) {
//!     0 => 0,
//!     1 => noprop::sample_u32(&mut ctx),
//!     _ => u32::MAX,
//! };
//! ```
//!
//! To pick one value from a fixed list, use [`sample_choice`]:
//!
//! ```
//! let mut ctx = noprop::TestCaseContext::new(0);
//! let _n = noprop::sample_choice(&mut ctx, &[1, 2, 3, 5, 8]);
//! let _digit = noprop::sample_choice(&mut ctx, b"0123456789") as char;
//! ```
//!
//! For bounded retry (filter-style generation), combine a range iterator
//! with `.find()`:
//!
//! ```
//! let mut ctx = noprop::TestCaseContext::new(0);
//! let even: Option<u32> = (0..100)
//!     .map(|_| noprop::sample_u32(&mut ctx))
//!     .find(|x| x % 2 == 0);
//! # assert!(even.is_some());
//! ```
//!
//! # Bounded rejection sampling
//!
//! When a generator has to keep drawing until it hits a value that
//! satisfies some predicate, use
//! [`sample_with_rejection`](crate::sample_with_rejection) rather than
//! a hand-written `loop { … }`. Unbounded manual retries can wedge on
//! specific choice sequences; the helper enforces a `max_attempts`
//! bound and, on exhaustion, calls
//! [`TestCaseContext::reject_case`](crate::TestCaseContext::reject_case) so the enclosing
//! [`Runner::run`](crate::Runner::run) discards the iteration and
//! moves on. Prefer valid-by-construction generators when the accepted
//! rate is very low.
//!
//! # Note on `sample_below` migration
//!
//! [`sample_usize_in`], [`sample_ratio`], [`sample_weighted_index`],
//! and [`sample_choice`] all share an internal rejection sampler that
//! is bounded at 64 attempts per call. The rejection rate is at worst
//! ~50% (only when the requested domain is barely under a power of
//! two), so the probability of exhausting all 64 attempts is `< 2⁻⁶⁴`
//! — astronomically unreachable in practice. If it does trigger, the
//! outcome depends on where the call sits: inside a
//! [`Runner::run`](crate::Runner::run) the four APIs above indirectly
//! reject the iteration (via
//! [`TestCaseContext::reject_case`](crate::TestCaseContext::reject_case)); outside a runner
//! the call panics with a Runner-only message. This is a semantic
//! change from the previous unbounded loop, kept explicit here rather
//! than repeated in every affected function's rustdoc.
//!
//! # Sampling non-zero integers
//!
//! noprop deliberately does not ship dedicated `sample_non_zero_*`
//! primitives. The `NonZero<_>` domain is not one shape — callers make
//! a real trade-off between distribution uniformity and unconditional
//! termination — so `NonZero` is left as a two-line recipe over the
//! plain integer sampler. Pick one of the two:
//!
//! **Uniform, may reject the iteration.** Use
//! [`sample_with_rejection`](crate::sample_with_rejection) to redraw
//! until the sampled integer is non-zero. `P(zero)` is at most `1/256`
//! per attempt (worst case, `u8`), so the shared 64-attempt bound is
//! effectively unreachable — but on exhaustion the iteration is
//! rejected, so this recipe requires a [`Runner`](crate::Runner) around
//! it.
//!
//! ```
//! # let _: noprop::Result<()> = noprop::Runner::new(0, 1).run(|ctx| {
//! use std::num::NonZeroU32;
//! let n = noprop::sample_with_rejection(ctx, 64, |ctx| {
//!     NonZeroU32::new(noprop::sample_u32(ctx))
//! });
//! assert!(n.get() != 0);
//! # Ok(())
//! # });
//! ```
//!
//! **Biased, always terminates in one draw.** Map the underlying
//! integer's zero value onto `1` explicitly. This shifts a small
//! amount of probability mass onto `1` (worst case `+1/256` for `u8`)
//! but avoids any retry loop and works outside a `Runner`.
//!
//! ```
//! use std::num::NonZeroU32;
//! let mut ctx = noprop::TestCaseContext::new(0);
//! let v = noprop::sample_u32(&mut ctx);
//! let n = NonZeroU32::new(if v == 0 { 1 } else { v })
//!     .expect("v was remapped away from zero");
//! assert!(n.get() != 0);
//! ```
//!
//! `wrapping_add(1)` is *not* a correct substitute — it wraps
//! `u_::MAX` back to `0`, reintroducing the very case the mapping is
//! meant to eliminate. `saturating_add(1)` avoids `0` on unsigned
//! types but overweights the maximum, and does not work on signed
//! types at all. The explicit `if v == 0 { 1 } else { v }` shows the
//! chosen remapping target in the code.
//!
//! For signed types, note that the full `NonZero<i_>` domain is
//! `MIN..=-1` ∪ `1..=MAX`. A single `1..=MAX` range would silently
//! drop the negative half, so the uniform recipe (rejection sampling
//! over `sample_i32`, etc.) is the only way to cover both signs
//! uniformly.
//!
//! Note that neither recipe records the resulting `NonZero<_>` as its
//! own trace entry — the underlying integer sample is what appears in
//! the failure trace. Wrap the value manually with
//! [`sample_choice`](crate::sample_choice) or a custom
//! `#[track_caller]` helper if you want a `NonZero`-typed trace entry
//! at the call site.

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

use crate::TestCaseContext;
use crate::rng::{AttemptVerdict, ChoiceMeta};

/// 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.
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. In recording
///   mode its span is stored with `start_draw == end_draw`.
/// - The closure may itself call `sample_with_rejection` — nested
///   attempts are supported and recorded with parent/child linkage in
///   recording mode.
/// - 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::Result<()> = noprop::Runner::new(0, 1).run(|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 {
        let id = ctx.begin_attempt();
        match attempt(ctx) {
            Some(value) => {
                ctx.end_attempt(id, AttemptVerdict::Accepted);
                return value;
            }
            None => {
                ctx.end_attempt(id, AttemptVerdict::Rejected);
            }
        }
    }
    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 the same
/// draw pattern applies to every finite-domain selection primitive
/// (`sample_usize_in`, `sample_ratio`, `sample_weighted_index`,
/// `sample_choice`).
/// 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 {
    sample_below_with_meta(ctx, n, ChoiceMeta::Bounded { bound: n })
}

/// `sample_below` with an explicit [`ChoiceMeta`] for the draws it
/// consumes. `sample_choice` uses this to tag its index draw as a
/// `Choice` instead of a plain `Bounded` draw, so the metadata records
/// the primitive that produced it rather than the shared core.
#[track_caller]
fn sample_below_with_meta(ctx: &mut TestCaseContext, n: u64, meta: ChoiceMeta) -> 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 {
        ctx.set_next_choice_meta(meta);
        return u64::from_le_bytes(raw_bytes(ctx)) % n;
    }
    let bound = u64::MAX - r;
    sample_with_rejection(ctx, DEFAULT_MAX_ATTEMPTS, |ctx| {
        ctx.set_next_choice_meta(meta);
        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_with_meta(
        ctx,
        choices.len() as u64,
        ChoiceMeta::Choice { len: choices.len() },
    ) 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).
///
/// # 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.
        ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
        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
}

/// Return `true` with probability `numerator / denominator`.
///
/// 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, 1, 3)` is exactly one-in-three, not
/// `0.333…`-close.
///
/// # Panics
///
/// - Panics if `denominator == 0`.
/// - Panics if `numerator > denominator`.
///
/// # 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, and the exact byte count depends on
/// `denominator`.
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// // 1 in 3 chance of true.
/// let _b = noprop::sample_ratio(&mut ctx, 1, 3);
/// // Always false; consumes no RNG.
/// assert!(!noprop::sample_ratio(&mut ctx, 0, 5));
/// // Always true; consumes no RNG.
/// assert!(noprop::sample_ratio(&mut ctx, 5, 5));
/// ```
#[track_caller]
pub fn sample_ratio(ctx: &mut TestCaseContext, numerator: u32, denominator: u32) -> bool {
    let loc = Location::caller();
    assert!(
        denominator != 0,
        "sample_ratio: denominator must be non-zero"
    );
    assert!(
        numerator <= denominator,
        "sample_ratio: numerator ({numerator}) must be <= denominator ({denominator})"
    );
    let v = if numerator == 0 {
        false
    } else if numerator == denominator {
        true
    } else {
        sample_below(ctx, denominator as u64) < numerator as u64
    };
    ctx.record_generated(&v, loc);
    v
}

/// 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 change the sampler input
/// (the slice length grows) even though it never affects the returned
/// index distribution.
///
/// # 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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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();
    ctx.set_next_choice_meta(crate::rng::ChoiceMeta::Integer);
    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).
#[track_caller]
pub fn sample_ascii_printable_char(ctx: &mut TestCaseContext) -> char {
    let loc = Location::caller();
    // 95 characters. Use u32 for negligible modulo bias
    // (2^32 mod 95 = 6, so bias factor is at most 1 + 1/45210182).
    let v = (0x20 + u32::from_le_bytes(raw_bytes(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 `len` attempt spans in the choice sequence — one per
/// character.
///
/// # 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; no attempt spans are opened.
///
/// # 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 + u32::from_le_bytes(raw_bytes(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_finite`].
///
/// # Panics
///
/// Panics if `min` or `max` is not finite, or if `min >= max`.
#[track_caller]
pub fn sample_f32(ctx: &mut TestCaseContext, min: f32, max: f32) -> f32 {
    assert!(
        min.is_finite() && max.is_finite(),
        "sample_f32: min and max must be finite"
    );
    assert!(min < max, "sample_f32: min must be less than max");
    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;
    let v = min + (max - min) * unit;
    ctx.record_generated(&v, loc);
    v
}

/// Uniformly-distributed `f64` in `[min, max)`.
///
/// Same conventions as [`sample_f32`]: 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_finite`].
///
/// # Panics
///
/// Panics if `min` or `max` is not finite, or if `min >= max`.
#[track_caller]
pub fn sample_f64(ctx: &mut TestCaseContext, min: f64, max: f64) -> f64 {
    assert!(
        min.is_finite() && max.is_finite(),
        "sample_f64: min and max must be finite"
    );
    assert!(min < max, "sample_f64: min must be less than max");
    let loc = Location::caller();
    // Same construction as sample_f32 but with 53-bit precision.
    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 + (max - min) * unit;
    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`].
///
/// # 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_finite(&mut ctx);
/// assert!(x.is_finite());
/// ```
#[track_caller]
pub fn sample_f32_finite(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_finite`]; 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`].
///
/// # Examples
///
/// ```
/// let mut ctx = noprop::TestCaseContext::new(0);
/// let x = noprop::sample_f64_finite(&mut ctx);
/// assert!(x.is_finite());
/// ```
#[track_caller]
pub fn sample_f64_finite(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 `fill` outputs rather than the removed
    /// `TestCaseContext::next_u64`.
    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).unwrap();
            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));
        }
    }

    // === 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 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(&mut a, 0.0, 1.0), sample_f32(&mut b, 0.0, 1.0));
        assert_eq!(
            sample_f64(&mut a, -100.0, 100.0),
            sample_f64(&mut b, -100.0, 100.0)
        );
    }

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

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

    #[test]
    fn sample_f32_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(&mut ctx, 0.0, 1.0);
            low |= v < 0.5;
            high |= v >= 0.5;
            if low && high {
                return;
            }
        }
        panic!("sample_f32 covered only one half of the range");
    }

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

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

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

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

    // === sample_f32_finite / sample_f64_finite ===

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

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

    #[test]
    fn finite_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_finite(&mut a), sample_f32_finite(&mut b));
            assert_eq!(sample_f64_finite(&mut a), sample_f64_finite(&mut b));
        }
    }

    #[test]
    fn sample_f32_finite_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_finite(&mut ctx);
            if v > 0.0 {
                pos = true;
            } else if v < 0.0 {
                neg = true;
            }
            if pos && neg {
                return;
            }
        }
        panic!("sample_f32_finite 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)]
        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_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, 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, 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, 1, 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, 3, 7), sample_ratio(&mut b, 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, 1, 10) {
                trues += 1;
            }
        }
        let expected = total / 10;
        assert!(
            trues.abs_diff(expected) < expected / 2,
            "sample_ratio(1, 10) frequency off: {trues}/{total}"
        );
    }

    #[test]
    #[should_panic(expected = "denominator must be non-zero")]
    fn sample_ratio_panics_on_zero_denominator() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_ratio(&mut ctx, 0, 0);
    }

    #[test]
    #[should_panic(expected = "must be <= denominator")]
    fn sample_ratio_panics_when_numerator_exceeds_denominator() {
        let mut ctx = TestCaseContext::new(0);
        let _ = sample_ratio(&mut ctx, 11, 10);
    }

    // === 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 ±30% slack.
        for (i, (&c, &w)) in counts.iter().zip(weights.iter()).enumerate() {
            let expected = total * w as usize / 6;
            assert!(
                c.abs_diff(expected) * 100 < expected * 30,
                "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]);
    }

    // === choice sequence record / replay through the sampling primitives ===
    //
    // These tests exercise if / match / loop control flow combined with
    // sample_below, sample_char, sample_with_rejection (as the uniform
    // NonZero recipe), and sample_bytes_vec inside a single recorded
    // case that must replay bit-exactly.

    use crate::rng::{ChoiceSequence, RecordingSession, ReplayError, ReplaySession};

    /// Composite generator that mixes every rejection-loop and variable-length
    /// path: `sample_below` (via `sample_usize_in`), `sample_char`,
    /// an inline uniform-NonZero recipe via `sample_with_rejection`,
    /// `sample_bytes_vec`, plus `if` / `match` / loop control flow.
    /// Returns a shape summary that a strict replay must reproduce
    /// bit-exactly.
    fn composite_case(
        ctx: &mut TestCaseContext,
    ) -> (Vec<char>, Vec<std::num::NonZero<u8>>, Vec<u8>, u32) {
        let branch = sample_usize_in(ctx, 0..3);
        let chars = if branch == 0 {
            Vec::new()
        } else {
            (0..branch).map(|_| sample_char(ctx)).collect()
        };
        let nz_count = sample_usize_in(ctx, 1..=4);
        let mut nzs = Vec::with_capacity(nz_count);
        for _ in 0..nz_count {
            let nz = sample_with_rejection(ctx, DEFAULT_MAX_ATTEMPTS, |ctx| {
                std::num::NonZero::new(sample_u8(ctx))
            });
            nzs.push(nz);
        }
        let buf_len = sample_usize_in(ctx, 0..=16);
        let bytes = sample_bytes_vec(ctx, buf_len);
        let tail = match sample_usize_in(ctx, 0..3) {
            0 => sample_u32(ctx),
            1 => sample_u32(ctx).wrapping_add(1),
            _ => 0,
        };
        (chars, nzs, bytes, tail)
    }

    #[test]
    fn replay_reproduces_composite_generator_bit_exact() {
        for seed in [1u64, 42, 0xDEAD_BEEF, 0xFEED_FACE] {
            let (expected, seq) = RecordingSession::new(seed).run(composite_case);
            let replayed = ReplaySession::new(seq)
                .run(composite_case)
                .expect("replay of same generator must succeed");
            assert_eq!(replayed, expected, "seed {seed:#x}");
        }
    }

    #[test]
    fn replay_stops_generator_on_first_structural_mismatch() {
        // Record two 1-byte draws, then replay a generator that first
        // consumes one then asks for a 4-byte draw against the second
        // recorded 1-byte draw. `DrawLengthMismatch` must fire AND the
        // "unreachable" flag must stay false, proving the generator
        // body did not continue past the mismatch.
        let (_, seq) = RecordingSession::new(1).run(|ctx| {
            let _ = sample_u8(ctx);
            let _ = sample_u8(ctx);
        });
        let flag = std::cell::Cell::new(false);
        let result = ReplaySession::new(seq).run(|ctx| {
            let _ = sample_u8(ctx); // matches first recorded draw
            let _ = sample_u32(ctx); // 4 bytes vs recorded 1 → mismatch
            flag.set(true); // must not run
        });
        assert!(
            matches!(
                result,
                Err(ReplayError::DrawLengthMismatch {
                    expected: 1,
                    actual: 4,
                })
            ),
            "unexpected replay result: {result:?}"
        );
        assert!(!flag.get(), "generator continued past replay mismatch");
    }

    #[test]
    fn replay_after_sample_bytes_vec_matches_bytes() {
        // sample_bytes_vec issues a single TestCaseContext::fill of arbitrary length —
        // the recorded draw's length must match at replay time.
        let (recorded, seq) = RecordingSession::new(7).run(|ctx| sample_bytes_vec(ctx, 100));
        let replayed = ReplaySession::new(seq)
            .run(|ctx| sample_bytes_vec(ctx, 100))
            .expect("same-length replay must succeed");
        assert_eq!(replayed, recorded);
    }

    #[test]
    fn recorded_composite_case_matches_plain_prng() {
        // Recording must not shift the byte stream: the composite case
        // recorded from a given seed must equal the same closure run
        // against a plain TestCaseContext::new(seed).
        let seed = 0xABCD_1234u64;
        let (recorded_value, _seq) = RecordingSession::new(seed).run(composite_case);
        let mut prng = TestCaseContext::new(seed);
        let plain_value = composite_case(&mut prng);
        assert_eq!(recorded_value, plain_value);
    }

    #[test]
    fn empty_sequence_replay_succeeds_when_generator_draws_nothing() {
        let seq = ChoiceSequence::default();
        let result = ReplaySession::new(seq).run(|_ctx| 7u32);
        assert_eq!(result, Ok(7));
    }

    // === 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]
    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);
    }

    #[test]
    fn sample_with_rejection_records_nested_spans_in_recording_mode() {
        let (v, seq): ((u8, u8), _) = RecordingSession::new(1).run(|ctx| {
            sample_with_rejection(ctx, 8, |ctx| {
                let x = sample_u8(ctx);
                let y = sample_with_rejection(ctx, 8, |ctx| Some(sample_u8(ctx)));
                Some((x, y))
            })
        });
        assert_eq!(v.0, seq.draws()[0][0]);
        assert_eq!(v.1, seq.draws()[1][0]);
        // Two spans total: outer accepted, inner accepted; inner's parent is outer.
        assert_eq!(seq.spans().len(), 2);
        assert_eq!(seq.spans()[0].parent, None);
        assert_eq!(seq.spans()[0].verdict, AttemptVerdict::Accepted);
        assert_eq!(seq.spans()[1].parent, Some(0));
        assert_eq!(seq.spans()[1].verdict, AttemptVerdict::Accepted);
    }

    #[test]
    fn sample_with_rejection_records_rejected_spans_in_recording_mode() {
        let (v, seq) = RecordingSession::new(2).run(|ctx| {
            let counter = std::cell::Cell::new(0);
            sample_with_rejection(ctx, 8, |_ctx| {
                let n = counter.get();
                counter.set(n + 1);
                if n < 2 { None } else { Some(n as u32) }
            })
        });
        assert_eq!(v, 2);
        // 3 spans: reject, reject, accept.
        assert_eq!(seq.spans().len(), 3);
        assert_eq!(seq.spans()[0].verdict, AttemptVerdict::Rejected);
        assert_eq!(seq.spans()[1].verdict, AttemptVerdict::Rejected);
        assert_eq!(seq.spans()[2].verdict, AttemptVerdict::Accepted);
        assert!(seq.spans().iter().all(|s| s.parent.is_none()));
    }

    #[test]
    fn sample_with_rejection_allows_drawless_rejected_attempts() {
        // A pure predicate over external state — no draws.
        let (v, seq) = RecordingSession::new(1).run(|ctx| {
            let counter = std::cell::Cell::new(0);
            sample_with_rejection(ctx, 4, |_ctx| {
                let n = counter.get();
                counter.set(n + 1);
                if n < 2 { None } else { Some(n as u32) }
            })
        });
        assert_eq!(v, 2);
        assert_eq!(seq.spans().len(), 3);
        for span in seq.spans() {
            assert_eq!(span.start_draw, span.end_draw); // no draws consumed
        }
        assert!(seq.draws().is_empty());
    }
}