checkito 5.0.0

A safe, efficient and simple QuickCheck-inspired library to generate shrinkable random data mainly oriented towards generative/property/exploratory testing.
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
use crate::{
    GENERATES, Generate, Shrink,
    primitive::{Range, u8::U8},
    utility,
};
use core::{
    iter::{FusedIterator, repeat_n},
    mem::replace,
    ops::{self, Bound},
};
use fastrand::Rng;
use std::ops::RangeBounds;

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Sizes {
    range: Range<f64>,
    scale: f64,
}

#[derive(Clone, Debug, PartialEq)]
pub struct State {
    mode: Mode,
    sizes: Sizes,
    index: usize,
    count: usize,
    limit: usize,
    depth: usize,
    seed: u64,
}

#[derive(Clone, Debug)]
pub struct States {
    indices: ops::Range<usize>,
    modes: Modes,
}

#[derive(Copy, Clone, Debug)]
pub(crate) enum Modes {
    Random {
        count: usize,
        sizes: Sizes,
        seed: u64,
    },
    Exhaustive(usize),
}

#[derive(Clone, Debug)]
pub struct Weight<T: ?Sized> {
    weight: f64,
    generator: T,
}

impl<T> Weight<T> {
    pub const fn weight(&self) -> f64 {
        self.weight
    }

    pub const fn value(&self) -> &T {
        &self.generator
    }

    pub const fn as_ref(&self) -> Weight<&T> {
        Weight {
            weight: self.weight,
            generator: &self.generator,
        }
    }

    pub const fn as_mut(&mut self) -> Weight<&mut T> {
        Weight {
            weight: self.weight,
            generator: &mut self.generator,
        }
    }

    pub fn into_value(self) -> T {
        self.generator
    }

    pub fn map<U: Generate>(self, map: impl FnOnce(T) -> U) -> Weight<U> {
        Weight {
            weight: self.weight,
            generator: map(self.generator),
        }
    }
}

impl<G: Generate> Weight<G> {
    pub const fn new(weight: f64, generator: G) -> Self {
        Self {
            weight: if weight.is_nan() {
                0.0
            } else {
                utility::f64::max(weight, 0.0)
            },
            generator,
        }
    }

    pub const fn one(generator: G) -> Self {
        Self {
            weight: 1.0,
            generator,
        }
    }
}

impl<G: Generate + ?Sized> Weight<G> {
    pub(crate) fn cardinality(&self) -> Option<u128> {
        self.generator.cardinality()
    }
}

pub struct With<'a> {
    state: &'a mut State,
    sizes: Sizes,
    depth: usize,
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Mode {
    Random(Rng),
    Exhaustive(u128),
}

impl State {
    pub(crate) fn random(index: usize, count: usize, size: Sizes, seed: u64) -> Self {
        Self {
            mode: Mode::Random(Rng::with_seed(seed.wrapping_add(index as _))),
            sizes: Sizes::from_ratio(index, count, size),
            index,
            count,
            limit: 0,
            depth: 0,
            seed,
        }
    }

    pub(crate) const fn exhaustive(index: usize, count: usize) -> Self {
        Self {
            mode: Mode::Exhaustive(index as _),
            sizes: Sizes::DEFAULT,
            index,
            count,
            limit: 0,
            depth: 0,
            seed: 0,
        }
    }

    pub(crate) fn any_exhaustive<T, I: IntoIterator<Item = (Option<u128>, T), IntoIter: Clone>>(
        index: &mut u128,
        cardinalities: I,
    ) -> Option<T> {
        let mut last = (usize::MAX, false);
        for (i, pair) in cardinalities.into_iter().enumerate().cycle() {
            if last.0 < i {
                last.0 = i;
            } else if replace(&mut last.1, true) {
                // A full cycle completed without progress.
                break;
            } else {
                last.0 = i;
            }

            match pair.0 {
                Some(0) => continue,
                Some(cardinality) if *index < cardinality => return Some(pair.1),
                Some(cardinality) => {
                    *index -= cardinality;
                    last.1 = false;
                }
                None => return Some(pair.1),
            }
        }
        None
    }

    #[inline]
    pub const fn size(&self) -> f64 {
        self.sizes.start()
    }

    #[inline]
    pub const fn scale(&self) -> f64 {
        self.sizes.scale
    }

    #[inline]
    pub const fn sizes(&self) -> Sizes {
        self.sizes
    }

    #[inline]
    pub const fn limit(&self) -> usize {
        self.limit
    }

    #[inline]
    pub const fn depth(&self) -> usize {
        self.depth
    }

    #[inline]
    pub const fn seed(&self) -> u64 {
        self.seed
    }

    #[inline]
    pub const fn index(&self) -> usize {
        self.index
    }

    #[inline]
    pub const fn count(&self) -> usize {
        self.count
    }

    #[inline]
    pub const fn with(&mut self) -> With<'_> {
        With::new(self)
    }

    #[inline]
    pub const fn descend(&mut self) -> With<'_> {
        let with = self.with();
        with.state.depth += 1;
        with.state.limit += 1;
        with
    }

    #[inline]
    pub const fn dampen(&mut self, deepest: usize, limit: usize, pressure: f64) -> With<'_> {
        let with = self.with();
        let old = with.state.sizes();
        let new = if with.state.depth >= deepest || with.state.limit >= limit {
            0.0
        } else {
            old.start() / utility::f64::max(with.state.depth as f64 * pressure, 1.0)
        };
        with.state.sizes = Sizes::new(new, old.end(), old.scale());
        with
    }

    #[inline]
    pub fn bool(&mut self) -> bool {
        self.u8(Range(U8::ZERO, U8::ONE)) == 1
    }

    #[inline]
    pub fn char<R: Into<Range<char>>>(&mut self, range: R) -> char {
        let Range(start, end) = range.into();
        let value = self.u32(Range(start as u32, end as u32));
        char::from_u32(value).unwrap_or(char::REPLACEMENT_CHARACTER)
    }

    pub fn any_uniform<I: IntoIterator<IntoIter: ExactSizeIterator + Clone, Item: Generate>>(
        &mut self,
        generators: I,
    ) -> Option<I::Item> {
        let mut generators = generators.into_iter();
        match &mut self.mode {
            Mode::Random(_) => {
                let count = generators.len().checked_sub(1)?;
                let index = self.with().size(1.0).usize(Range(0, count));
                generators.nth(index)
            }
            Mode::Exhaustive(index) => Self::any_exhaustive(
                index,
                generators.map(|generator| (generator.cardinality(), generator)),
            ),
        }
    }

    pub fn any_weighted<G: Generate, I: IntoIterator<IntoIter: Clone, Item = Weight<G>>>(
        &mut self,
        generators: I,
    ) -> Option<G> {
        let generators = generators.into_iter();
        match &mut self.mode {
            Mode::Random(_) => {
                let total = generators
                    .clone()
                    .map(|Weight { weight, .. }| weight)
                    .sum::<f64>()
                    .min(f64::MAX);
                debug_assert!(total.is_finite());
                let random = self.with().size(1.0).f64(0.0..=total);
                debug_assert!(random.is_finite());
                let mut sum = 0.0f64;
                for Weight { weight, generator } in generators {
                    sum += weight;
                    if weight >= 0.0 && random <= sum {
                        return Some(generator);
                    }
                }
                None
            }
            Mode::Exhaustive(index) => Self::any_exhaustive(
                index,
                generators.map(|weight| (weight.cardinality(), weight.into_value())),
            ),
        }
    }

    pub(crate) fn repeat<G: Generate + Clone>(
        &mut self,
        generator: G,
        range: Range<usize>,
    ) -> impl Iterator<Item = G> {
        let count = match &mut self.mode {
            Mode::Random(_) => self.usize(range),
            Mode::Exhaustive(index) => match generator.cardinality() {
                Some(cardinality) => {
                    // Exhaustive `repeat` chooses a *length* first, then generates
                    // that many items. The selected length must be deterministic for
                    // a given exhaustive `index`.
                    //
                    // For a generator with cardinality `c`:
                    // - length `L` contributes `c^L` distinct combinations.
                    // - so lengths form geometric "buckets" of sizes `c^start, c^(start+1), ...
                    //   c^end`.
                    //
                    // This branch maps the current global exhaustive `index` to the
                    // correct length bucket without scanning linearly.
                    let (start, end) = (range.start(), range.end());
                    // `block` is the size of the first bucket (`c^start`).
                    // We keep it optional: `None` means power overflowed, so we
                    // gracefully fall back to the minimum length.
                    let block = match cardinality {
                        _ if start == 0 => Some(1),
                        0 => Some(0),
                        1 => Some(1),
                        _ => u32::try_from(start)
                            .ok()
                            .and_then(|start| cardinality.checked_pow(start)),
                    };

                    match (cardinality, block) {
                        // Cannot represent `c^start` => conservative fallback.
                        (_, None) => {
                            // Keep the index untouched so sibling generators can
                            // still consume from it.
                            start
                        }
                        // No values can be produced for positive lengths.
                        // Keep behavior conservative and deterministic.
                        (0, Some(_)) => {
                            // No repeat combinations exist in this range. Keep the
                            // index untouched so sibling generators still vary.
                            start
                        }
                        // Each length has exactly one combination, so buckets are
                        // uniform and we can compute the offset directly.
                        (1, Some(_)) => {
                            // `Range<usize>` normalizes bounds so `start <= end`.
                            // Therefore the bucket width is always at least 1.
                            let width = end.saturating_sub(start).saturating_add(1);
                            let total = width as u128;
                            let local = *index % total;
                            *index /= total;
                            let offset = usize::try_from(local).unwrap_or(0);
                            start.saturating_add(offset)
                        }
                        // General case (`c >= 2`): use geometric prefix sums +
                        // binary search to find the selected bucket in O(log width).
                        // Then consume all previous buckets from the index so nested
                        // generation uses an index local to the chosen length.
                        (cardinality, Some(block)) => {
                            let width = end.saturating_sub(start).saturating_add(1);
                            let total = geometric_sum(cardinality, block, width);
                            match total {
                                Some(total @ 1..) => {
                                    let local = *index % total;
                                    let outer = *index / total;
                                    let terms =
                                        select_geometric_terms(local, width, cardinality, block);
                                    let terms_before = terms.saturating_sub(1);
                                    let consumed = geometric_sum(cardinality, block, terms_before)
                                        .unwrap_or(local);
                                    let inner = local.saturating_sub(consumed);
                                    let place = u32::try_from(terms_before)
                                        .ok()
                                        .and_then(|offset| cardinality.checked_pow(offset))
                                        .unwrap_or(1);
                                    *index = outer.saturating_mul(place).saturating_add(inner);
                                    start.saturating_add(terms_before)
                                }
                                Some(0) | None => start,
                            }
                        }
                    }
                }
                // If cardinality is not known, we cannot compute deterministic
                // geometric buckets for lengths. Reuse the repeat-range generator
                // in exhaustive mode, which is deterministic for a given index.
                None => range.generate(self).item(),
            },
        };
        repeat_n(generator, count)
    }
}

const fn consume(index: &mut u128, start: u128, end: u128) -> u128 {
    let range = u128::wrapping_sub(end, start).saturating_add(1);
    let index = replace(index, index.saturating_div(range)) % range;
    u128::wrapping_add(start, index)
}

/// Maps a zero-anchored exhaustive index to a `(offset, is_negative)` pair
/// for generating small-magnitude values first.
///
/// - `positive`: number of steps available in the positive direction.
/// - `negative`: number of steps available in the negative direction.
///
/// Ordering: anchor, +1, −1, +2, −2, … until the shorter side is exhausted,
/// then the remaining steps from the longer side.
const fn small_first(value: u128, positive: u128, negative: u128) -> (u128, bool) {
    let minimum = if positive < negative {
        positive
    } else {
        negative
    };
    let offset = value.div_ceil(2);
    if offset <= minimum {
        // Interleaved zone: odd → positive offset, even → negative offset.
        // k == 0 (local == 0) falls here and yields offset 0 (the anchor).
        (offset, value % 2 == 0)
    } else {
        // Past the shorter side: continue monotonically on the longer side.
        (value - minimum, positive < negative)
    }
}

/// Computes the number of exhaustive items covered by the first `terms`
/// length-buckets when bucket sizes grow geometrically.
///
/// In plain terms: for repeated generation, each extra length can contribute
/// many more combinations than the previous one (`cardinality` times more).
/// This helper answers “how many total combinations are there up to this
/// length?” using checked arithmetic so overflow is reported as `None`.
fn geometric_sum(cardinality: u128, block: u128, terms: usize) -> Option<u128> {
    if terms == 0 {
        return Some(0);
    }
    if cardinality == 1 {
        return u128::try_from(terms).ok();
    }
    let terms = u32::try_from(terms).ok()?;
    let factor = cardinality.checked_pow(terms)?.checked_sub(1)?;
    block.checked_mul(factor)?.checked_div(cardinality - 1)
}

/// Finds how many geometric buckets are needed so their cumulative size is
/// strictly greater than `index`.
///
/// This lets exhaustive `repeat` choose the output length in `O(log width)`
/// instead of scanning every possible length in `start..=end`.
///
/// If cumulative sums overflow, we conservatively treat that as “large enough”,
/// which keeps the search deterministic and avoids linear work.
fn select_geometric_terms(index: u128, width: usize, cardinality: u128, block: u128) -> usize {
    if width <= 1 {
        return 1;
    }

    let mut low = 1usize;
    let mut high = width;
    while low < high {
        let mid = low + (high - low) / 2;
        let enough = match geometric_sum(cardinality, block, mid) {
            Some(sum) => index < sum,
            None => true,
        };
        if enough {
            high = mid;
        } else {
            low = mid.saturating_add(1);
        }
    }
    low
}

impl<'a> With<'a> {
    pub(crate) const fn new(state: &'a mut State) -> Self {
        Self {
            sizes: state.sizes(),
            depth: state.depth(),
            state,
        }
    }

    #[inline]
    pub const fn size(self, size: f64) -> Self {
        let scale = self.sizes.scale();
        self.sizes(Sizes::new(size, size, scale))
    }

    #[inline]
    pub const fn sizes(self, sizes: Sizes) -> Self {
        self.state.sizes = sizes;
        self
    }

    #[inline]
    pub const fn scale(self, scale: f64) -> Self {
        self.state.sizes.scale = scale;
        self
    }

    #[inline]
    pub const fn depth(self, depth: usize) -> Self {
        self.state.depth = depth;
        self
    }
}

impl ops::Deref for With<'_> {
    type Target = State;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.state
    }
}

impl ops::DerefMut for With<'_> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.state
    }
}

impl AsRef<State> for With<'_> {
    #[inline]
    fn as_ref(&self) -> &State {
        self.state
    }
}

impl AsMut<State> for With<'_> {
    #[inline]
    fn as_mut(&mut self) -> &mut State {
        self.state
    }
}

impl Drop for With<'_> {
    #[inline]
    fn drop(&mut self) {
        self.state.depth = self.depth;
        self.state.sizes = self.sizes;
    }
}

pub(crate) fn seed() -> u64 {
    fastrand::u64(..)
}

macro_rules! range {
    ($name: ident, $range: ty, $up: expr, $down: expr) => {
        impl From<$range> for Range<$name> {
            fn from(value: $range) -> Self {
                let mut start = match value.start_bound() {
                    Bound::Included(&bound) => (bound, false),
                    Bound::Excluded(&bound) => (bound, true),
                    Bound::Unbounded => ($name::MIN, false),
                };
                let mut end = match value.end_bound() {
                    Bound::Included(&bound) => (bound, false),
                    Bound::Excluded(&bound) => (bound, true),
                    Bound::Unbounded => ($name::MAX, false),
                };
                if start.0 > end.0 {
                    (start, end) = (end, start);
                }
                if start.1 {
                    start.0 = $up(start.0);
                }
                if end.1 {
                    end.0 = $down(end.0);
                }
                Self(
                    start.0.clamp($name::MIN, end.0),
                    end.0.clamp(start.0, $name::MAX),
                )
            }
        }
    };
}

macro_rules! ranges {
    ($name: ident, $up: expr, $down: expr) => {
        impl From<$name> for Range<$name> {
            fn from(value: $name) -> Self {
                Self(value, value)
            }
        }

        range!($name, ops::Range<$name>, $up, $down);
        range!($name, ops::RangeTo<$name>, $up, $down);
        range!($name, ops::RangeInclusive<$name>, $up, $down);
        range!($name, ops::RangeToInclusive<$name>, $up, $down);
        range!($name, ops::RangeFrom<$name>, $up, $down);
        range!($name, ops::RangeFull, $up, $down);
    };
}

macro_rules! integer {
    ($integer: ident, $positive: ident, $constant: ident) => {
        ranges!($integer, |value| $integer::saturating_add(value, 1), |value| $integer::saturating_sub(value, 1));

        impl State {
            #[inline]
            pub fn $integer<R: Into<Range<$integer>>>(&mut self, range: R) -> $integer {
                #[inline]
                const fn divide(left: $positive, right: $positive) -> $positive {
                    let value = left / right;
                    let remain = left % right;
                    if remain > 0 {
                        value + 1
                    } else {
                        value
                    }
                }

                #[inline]
                fn shrink(range: $positive, size: f64, scale: f64) -> $positive {
                    if range == 0 || size <= 0.0 {
                        0
                    } else if size >= 1.0 {
                        range
                    } else {
                        // This adjustment of the size tries to prevent large ranges (such as `u64`)
                        // from rushing into huge values as soon as the `size > 0`.
                        let log = $positive::BITS - 1 - range.leading_zeros();
                        let power = size.powf(log as f64 / scale).recip();
                        divide(range, power as _)
                    }
                }

                fn generate(state: &mut State, Range(start, end): Range<$integer>) -> $integer {
                    let size = state.size();
                    let scale = state.scale();
                    match &mut state.mode {
                        Mode::Random(..) | Mode::Exhaustive(..) if start == end => start,
                        Mode::Random(random) => {
                            let range = shrink($positive::wrapping_sub(end as _, start as _), size, scale);
                            let value = random.$positive(0..=range) as $integer;
                            #[allow(unused_comparisons)]
                            if start >= 0 {
                                debug_assert!(end > 0);
                                start.wrapping_add(value)
                            } else if end <= 0 {
                                debug_assert!(start < 0);
                                end.wrapping_sub(value)
                            } else {
                                debug_assert!(start < 0);
                                debug_assert!(end > 0);
                                // Centers the range around zero as much as possible.
                                let center = (range / 2) as $integer;
                                let remain = (range % 2) as $integer;
                                let shift = (start + center).max(0) + (end - center - remain).min(0);
                                let wrap = value.wrapping_add(shift).wrapping_sub(center);
                                debug_assert!(wrap >= start && wrap <= end);
                                wrap
                            }
                        }
                        Mode::Exhaustive(index) => {
                            // Generate small values (near zero) first by reordering the
                            // exhaustive index instead of enumerating linearly from `start`.
                            let range = (start as u128, end as u128);
                            let total = u128::wrapping_sub(range.1, range.0);
                            let local = consume(index, 0, total);
                            #[allow(unused_comparisons)]
                            if start >= 0 {
                                // Entirely non-negative: ascending from start.
                                u128::wrapping_add(range.0, local) as $integer
                            } else if end <= 0 {
                                // Entirely non-positive: descending from end (closest to zero).
                                u128::wrapping_sub(range.1, local) as $integer
                            } else {
                                // Spans zero: 0, 1, -1, 2, -2, … via small_first.
                                let (value, negative) = small_first(local, end as u128, 0u128.wrapping_sub(range.0));
                                if negative {
                                    0u128.wrapping_sub(value) as $integer
                                } else {
                                    value as $integer
                                }
                            }
                        }
                    }
                }
                generate(self, range.into())
            }
        }
    };
    ($([$integer: ident, $positive: ident, $constant: ident]),*) => {
        $(integer!($integer, $positive, $constant);)*
    }
}

macro_rules! floating {
    ($number: ident, $bits: ident) => {
        ranges!($number, utility::$number::next_up, utility::$number::next_down);

        impl State {
            #[inline]
            pub fn $number<R: Into<Range<$number>>>(&mut self, range: R) -> $number {
                #[inline]
                fn shrink(range: $number, size: f64, scale: f64) -> $number {
                    if range == 0.0 || size <= 0.0 {
                        0.0
                    } else if size >= 1.0 {
                        range
                    } else {
                        let log = range.abs().log2();
                        let power = (log as f64 / scale).max(1.0);
                        let pow = size.powf(power);
                        range * pow as $number
                    }
                }

                fn generate(state: &mut State, Range(start, end): Range<$number>) -> $number {
                    assert!(start.is_finite() && end.is_finite());

                    let size = state.size();
                    let scale = state.scale();
                    match &mut state.mode {
                        Mode::Random(..) | Mode::Exhaustive(..) if start == end => start,
                        Mode::Random(random) => {
                            if start >= 0.0 {
                                debug_assert!(end > 0.0);
                                start + random.$number() * shrink(end - start, size, scale)
                            } else if end <= 0.0 {
                                debug_assert!(start < 0.0);
                                end - random.$number() * shrink(end - start, size, scale)
                            } else {
                                debug_assert!(start < 0.0);
                                debug_assert!(end > 0.0);
                                // Chooses either the positive or negative range based on the ratio between the 2.
                                let (small, big) = if -start < end { (start, end) } else { (end, start) };
                                let ratio = (small / big).abs().clamp(1e-3, 1e3);
                                let random = random.$number() * (1.0 + ratio);
                                if random <= 1.0 {
                                    random * shrink(big, size, scale)
                                } else {
                                    (random - 1.0) / ratio * shrink(small, size, scale)
                                }
                            }
                        }
                        Mode::Exhaustive(index) => {
                            // Generate small-magnitude values first by working in the
                            // total-order bit space.  The transformation mirrors the
                            // integer strategy: non-positive ranges start from the
                            // end closest to zero; ranges spanning zero interleave
                            // positive and negative values by magnitude.
                            let range = (
                                utility::$number::to_bits(start) as u128,
                                utility::$number::to_bits(end) as u128
                            );
                            let total = range.1 - range.0;
                            let local = consume(index, 0, total);
                            if start >= 0.0 {
                                // Entirely non-negative: go upward from start.
                                utility::$number::from_bits((range.0 + local) as _)
                            } else if end <= 0.0 {
                                // Entirely non-positive: go downward from end (closest to 0).
                                utility::$number::from_bits((range.1 - local) as _)
                            } else {
                                // Spans zero: 0.0, +ε, -ε, +2ε, -2ε, … via small_first.
                                let zero = utility::$number::to_bits(0.0) as u128;
                                let (value, negative) = small_first(local, range.1 - zero, zero - range.0);
                                if negative {
                                    utility::$number::from_bits((zero - value) as _)
                                } else {
                                    utility::$number::from_bits((zero + value) as _)
                                }
                            }
                        }
                    }
                }
                generate(self, range.into())
            }
        }
    };
    ($([$number: ident, $bits: ident]),*) => {
        $(floating!($number, $bits);)*
    }
}

ranges!(
    char,
    |value: char| {
        let up = u32::saturating_add(value as u32, 1);
        // Skip over the surrogate range U+D800..=U+DFFF when stepping up.
        let up = if (0xD800..=0xDFFF).contains(&up) {
            0xE000
        } else {
            up
        };
        // `up` may exceed 0x10FFFF only when `value` is `char::MAX`; saturate
        // to `char::MAX` so that stepping past the end stays in range.
        char::from_u32(up).unwrap_or(char::MAX)
    },
    |value: char| {
        let down = u32::saturating_sub(value as u32, 1);
        // Skip over the surrogate range U+D800..=U+DFFF when stepping down.
        let down = if (0xD800..=0xDFFF).contains(&down) {
            0xD7FF
        } else {
            down
        };
        // After the surrogate skip, `down` is always a valid code point; the
        // fallback to `char::MIN` is a safety net that should never be reached.
        char::from_u32(down).unwrap_or(char::MIN)
    }
);
integer!(
    [u8, u8, U8],
    [u16, u16, U16],
    [u32, u32, U32],
    [u64, u64, U64],
    [u128, u128, U128],
    [usize, usize, Usize],
    [i8, u8, I8],
    [i16, u16, I16],
    [i32, u32, I32],
    [i64, u64, I64],
    [i128, u128, I128],
    [isize, usize, Isize]
);

floating!([f32, i32], [f64, i64]);

impl Modes {
    pub(crate) fn with(
        count: usize,
        sizes: Sizes,
        seed: u64,
        cardinality: Option<u128>,
        exhaustive: Option<bool>,
    ) -> Self {
        match exhaustive {
            Some(true) => Modes::Exhaustive(count),
            Some(false) => Modes::Random { count, sizes, seed },
            None => match cardinality.map(usize::try_from) {
                Some(Ok(cardinality)) if cardinality <= count => Modes::Exhaustive(cardinality),
                _ => Modes::Random { count, sizes, seed },
            },
        }
    }

    pub(crate) fn state(self, index: usize) -> Option<State> {
        match self {
            Modes::Random { count, sizes, seed } if index < count => {
                Some(State::random(index, count, sizes, seed))
            }
            Modes::Exhaustive(count) if index < count => Some(State::exhaustive(index, count)),
            Modes::Random { .. } | Modes::Exhaustive(..) => None,
        }
    }
}

impl Default for Modes {
    fn default() -> Self {
        Modes::Random {
            count: GENERATES,
            sizes: Sizes::default(),
            seed: seed(),
        }
    }
}

impl From<Modes> for States {
    fn from(modes: Modes) -> Self {
        let count = match modes {
            Modes::Random { count, .. } => count,
            Modes::Exhaustive(count) => count,
        };
        States {
            indices: 0..count,
            modes,
        }
    }
}

impl Default for States {
    fn default() -> Self {
        Modes::default().into()
    }
}

impl Iterator for States {
    type Item = State;

    fn next(&mut self) -> Option<Self::Item> {
        self.modes.state(self.indices.next()?)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.indices.size_hint()
    }

    fn count(self) -> usize {
        self.indices.count()
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.modes.state(self.indices.nth(n)?)
    }

    fn last(self) -> Option<Self::Item> {
        self.modes.state(self.indices.last()?)
    }
}

impl ExactSizeIterator for States {
    fn len(&self) -> usize {
        self.indices.len()
    }
}

impl DoubleEndedIterator for States {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.modes.state(self.indices.next_back()?)
    }

    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.modes.state(self.indices.nth_back(n)?)
    }
}

impl FusedIterator for States {}

impl Sizes {
    pub(crate) const DEFAULT: Self = Self::new(0.0, 1.0, Self::SCALE);
    pub(crate) const SCALE: f64 = 6.0;

    #[inline]
    pub(crate) const fn new(start: f64, end: f64, scale: f64) -> Self {
        assert!(start.is_finite() && end.is_finite() && scale.is_finite());
        Self {
            range: Range(
                utility::f64::clamp(utility::f64::min(start, end), 0.0, 1.0),
                utility::f64::clamp(utility::f64::max(start, end), 0.0, 1.0),
            ),
            scale: utility::f64::clamp(scale, 1.0, f64::MAX),
        }
    }

    #[inline]
    pub(crate) const fn from_ratio(index: usize, count: usize, size: Self) -> Self {
        let (start, end) = (size.start(), size.end());
        if count <= 1 {
            Self::new(end, end, Self::SCALE)
        } else {
            let range = end - start;
            // This size calculation ensures that 25% of samples are fully sized.
            let ratio = index as f64 / count as f64 * 1.25;
            let size = utility::f64::clamp(start + ratio * range, 0.0, end);
            Self::new(size, end, Self::SCALE)
        }
    }

    #[inline]
    pub const fn scale(&self) -> f64 {
        self.scale
    }

    #[inline]
    pub const fn start(&self) -> f64 {
        self.range.0
    }

    #[inline]
    pub const fn end(&self) -> f64 {
        self.range.1
    }
}

impl Default for Sizes {
    fn default() -> Self {
        Self::new(0.0, 1.0, Self::SCALE)
    }
}

impl<R: Into<Range<f64>>> From<R> for Sizes {
    fn from(value: R) -> Self {
        let range = value.into();
        Self::new(range.start(), range.end(), Self::SCALE)
    }
}

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

    #[test]
    fn any_weighted_does_not_panic_with_random_weights() {
        let mut random = Rng::new();
        for count in 1usize..=1000 {
            let generators = Iterator::map(1..=count, |i| {
                Weight::new(i as f64 / random.f64() / random.f64() + f64::EPSILON, i)
            })
            .collect::<Vec<_>>();
            let mut state = State::random(0, 1, Sizes::DEFAULT, random.u64(..));
            assert!(state.any_weighted(generators).unwrap() <= count);
        }
    }

    #[test]
    fn is_within_bounds() {
        for i in 0..=100 {
            let mut state = State::random(i, 100, Sizes::DEFAULT, 0);
            let value = state.i8(-128..=1);
            assert!(value >= -128 && value <= 1);
        }
    }

    #[test]
    fn random_is_exhaustive() {
        fn check<T: Ord>(count: usize, generate: impl Fn(&mut State) -> T) {
            check_with(count, generate, T::cmp);
        }

        fn check_with<T>(
            count: usize,
            generate: impl Fn(&mut State) -> T,
            compare: impl Fn(&T, &T) -> Ordering,
        ) {
            let mut state = State::random(1, 1, 1.0.into(), 0);
            let mut values =
                Iterator::map(0..count * 25, |_| generate(&mut state)).collect::<Vec<_>>();
            values.sort_by(&compare);
            values.dedup_by(|left, right| compare(left, right) == Ordering::Equal);
            assert_eq!(values.len(), count);
        }

        check(2, |state| state.bool());
        check(26, |state| state.char('a'..='z'));
        check(8, |state| state.char('1'..'9'));
        check(256, |state| state.u8(..));
        check(256, |state| state.i8(..));
        check(65536, |state| state.u16(..));
        check(32768, |state| state.i16(..0));
        check(1000, |state| state.isize(isize::MIN..isize::MIN + 1000));
        check(1001, |state| state.u128(u128::MAX - 1000..=u128::MAX));
        check_with(16385, |state| state.f32(-1000.0..=-999.0), compare_f32);
        check_with(1430, |state| state.f32(-1e-42..=1e-42), compare_f32);
    }

    #[test]
    fn exhaustive_is_exhaustive() {
        fn check<T: Ord>(count: usize, generate: impl Fn(&mut State) -> T) {
            check_with(count, generate, T::cmp);
        }

        fn check_with<T>(
            count: usize,
            generate: impl Fn(&mut State) -> T,
            compare: impl Fn(&T, &T) -> Ordering,
        ) {
            let mut values = Iterator::map(0..count, |i| {
                generate(&mut State::exhaustive(i as _, count))
            })
            .collect::<Vec<_>>();
            values.sort_by(&compare);
            values.dedup_by(|left, right| compare(left, right) == Ordering::Equal);
            assert_eq!(values.len(), count);
        }

        check(2, |state| state.bool());
        check(26, |state| state.char('a'..='z'));
        check(8, |state| state.char('1'..'9'));
        check(256, |state| state.u8(..));
        check(256, |state| state.i8(..));
        check(65536, |state| state.u16(..));
        check(32768, |state| state.i16(..0));
        check(1000, |state| state.isize(isize::MIN..isize::MIN + 1000));
        check(1001, |state| state.u128(u128::MAX - 1000..=u128::MAX));
        check_with(16385, |state| state.f32(-1000.0..=-999.0), compare_f32);
        check_with(1430, |state| state.f32(-1e-42..=1e-42), compare_f32);
    }

    fn compare_f32(left: &f32, right: &f32) -> Ordering {
        let left = utility::f32::to_bits(*left);
        let right = utility::f32::to_bits(*right);
        u32::cmp(&left, &right)
    }

    #[test]
    fn exhaustive_integer_small_values_first() {
        fn collect(count: usize, generate: impl Fn(&mut State) -> i32) -> Vec<i32> {
            Iterator::map(0..count, |i| generate(&mut State::exhaustive(i, count))).collect()
        }

        // Non-negative range: ascending from start.
        let values = collect(5, |s| s.i32(0..=4));
        assert_eq!(values, [0, 1, 2, 3, 4]);

        // Non-positive range: descending from end (end is closest to 0).
        let values = collect(5, |s| s.i32(-4..=0));
        assert_eq!(values, [0, -1, -2, -3, -4]);

        // Symmetric range spanning 0: interleaved 0, 1, -1, 2, -2, ...
        let values = collect(5, |s| s.i32(-2..=2));
        assert_eq!(values, [0, 1, -1, 2, -2]);

        // Asymmetric range with more positives: interleave up to the smaller side,
        // then continue with the remaining positives.
        let values = collect(7, |s| s.i32(-2..=4));
        assert_eq!(values, [0, 1, -1, 2, -2, 3, 4]);

        // Asymmetric range with more negatives: interleave up to the smaller side,
        // then continue with the remaining negatives.
        let values = collect(7, |s| s.i32(-4..=2));
        assert_eq!(values, [0, 1, -1, 2, -2, -3, -4]);

        // First few exhaustive values for a large range should be near zero.
        let values = collect(5, |s| s.i32(-1000..=1000));
        assert_eq!(values, [0, 1, -1, 2, -2]);
    }

    #[test]
    fn exhaustive_float_small_values_first() {
        // Non-positive range: first value must be 0.0 (the end, closest to 0).
        let first = State::exhaustive(0, 100).f32(-1.0..=0.0);
        assert_eq!(first, 0.0);

        // Range spanning 0: first value is 0.0.
        let first = State::exhaustive(0, 1000).f32(-1.0..=1.0);
        assert_eq!(first, 0.0);

        // For a range spanning 0, the total-order magnitude should increase for
        // the first few samples.  (Use to_bits for total-order comparisons so
        // that -0.0 and 0.0 are treated as distinct adjacent values.)
        let zero_bits = utility::f32::to_bits(0.0);
        let values: Vec<u32> = Iterator::map(0..5, |i| {
            utility::f32::to_bits(State::exhaustive(i, 1000).f32(-1.0..=1.0))
        })
        .collect();
        // index 0 → 0.0, index 1 → small positive (> 0.0 in total order),
        // index 2 → small negative (< 0.0 in total order but closest to it),
        // index 3 → next positive (larger than index 1), index 4 → next negative.
        assert_eq!(values[0], zero_bits);
        assert!(values[1] > zero_bits && values[1] < values[3]);
        assert!(values[2] < zero_bits && values[2] > values[4]);
    }

    #[test]
    fn does_not_cycle_forever() {
        assert_eq!(State::any_exhaustive(&mut 100, []), None::<usize>);
        assert_eq!(State::any_exhaustive(&mut 100, [(Some(0), 1)]), None);
        assert_eq!(State::any_exhaustive(&mut 100, [(Some(0), 1); 10]), None);
        assert_eq!(
            State::any_exhaustive(&mut 100, [(Some(0), 1), (Some(1), 2), (Some(0), 3)]),
            Some(2)
        );
        assert_eq!(
            State::any_exhaustive(
                &mut 100,
                [
                    (Some(0), 1),
                    (Some(1), 2),
                    (Some(0), 3),
                    (Some(0), 4),
                    (Some(100), 5)
                ]
            ),
            Some(5)
        );
    }

    #[test]
    fn any_weighted_returns_none_for_empty_random() {
        let empty: Vec<Weight<u8>> = vec![];
        let mut state = State::random(0, 1, Sizes::DEFAULT, 42);
        let result = state.any_weighted(empty);
        assert_eq!(result, None);
    }

    #[test]
    fn any_weighted_returns_none_for_empty_exhaustive() {
        let empty: Vec<Weight<u8>> = vec![];
        let mut state = State::exhaustive(0, 1);
        let result = state.any_weighted(empty);
        assert_eq!(result, None);
    }

    #[test]
    fn any_uniform_returns_none_for_empty_random() {
        let empty: Vec<u8> = vec![];
        let mut state = State::random(0, 1, Sizes::DEFAULT, 42);
        let result = state.any_uniform(empty.iter());
        assert_eq!(result, None);
    }

    #[test]
    fn any_uniform_returns_none_for_empty_exhaustive() {
        let empty: Vec<u8> = vec![];
        let mut state = State::exhaustive(0, 1);
        let result = state.any_uniform(empty.iter());
        assert_eq!(result, None);
    }
}