mutatis 0.5.3

`mutatis` is a library for writing custom, structure-aware test-case mutators for fuzzers in Rust.
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
#![doc = include_str!("../README.md")]
#![no_std]
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "std")]
#[macro_use]
extern crate std;

pub mod _guide;
pub mod error;
mod log;
pub mod mutators;
mod rng;

use core::ops;

pub use error::{Error, Result};
pub use rng::Rng;

#[cfg(feature = "check")]
pub mod check;

#[cfg(feature = "derive")]
/// Automatically derive a mutator for a type.
///
/// See [the `#[derive(Mutate)]` section of the
/// guide][crate::_guide::derive_macro] for details.
pub use mutatis_derive::Mutate;

/// A mutation session and its configuration.
///
/// This type allows you to configure things like setting the RNG seed, or
/// whether to only perform shrinking mutations.
///
/// A session should be reused while a particular value, or set of values, are
/// being repeatedly mutated.
///
/// # Example
///
/// ```
/// # fn foo() -> mutatis::Result<()> {
/// use mutatis::Session;
///
/// // Create a new mutation session.
/// let mut session = Session::new()
///     // Configure the RNG seed, changing which random mutations are chosen.
///     .seed(0x12345678);
///
/// // Mutate a value a few times inside this session.
/// let mut x = 93;
/// for _ in 0..3 {
///     session.mutate(&mut x)?;
///     println!("mutated x is {x}");
/// }
///
/// // Example output:
/// //
/// //     mutated x is -906367562
/// //     mutated x is 766527557
/// //     mutated x is 132130383
/// # Ok(())
/// # }
/// # foo().unwrap();
/// ```
#[derive(Debug)]
pub struct Session {
    context: Context,
}

impl Default for Session {
    fn default() -> Self {
        Self::new()
    }
}

impl Session {
    /// Create a new, default `Session`.
    pub fn new() -> Self {
        Self {
            context: Context {
                rng: Rng::default(),
                shrink: false,
                generate_via_mutate_depth: 0,
            },
        }
    }

    /// Set the seed for the random number generator.
    pub fn seed(mut self, seed: u64) -> Self {
        self.context.rng = Rng::new(seed);
        self
    }

    /// Set whether to only perform shrinking mutations or not.
    ///
    /// Defaults to `false`.
    pub fn shrink(mut self, shrink: bool) -> Self {
        self.context.shrink = shrink;
        self
    }

    /// Mutate the given `value` with its default mutator and within the
    /// constraints of this `Session`'s configuration.
    ///
    /// The default mutator for a type is defined by the [`DefaultMutate`] trait
    /// implementation for that type.
    ///
    /// To use a custom mutator, rather than the default mutator, use the
    /// [`mutate_with`][Session::mutate_with] method instead.
    ///
    /// # Example
    ///
    /// ```
    /// # fn foo() -> mutatis::Result<()> {
    /// use mutatis::Session;
    ///
    /// let mut x = Some(1234i32);
    ///
    /// let mut session = Session::new().seed(0xaabbccdd);
    ///
    /// for _ in 0..5 {
    ///     session.mutate(&mut x)?;
    ///     println!("mutated x is {x:?}");
    /// }
    ///
    /// // Example output:
    /// //
    /// //     mutated x is None
    /// //     mutated x is Some(-688796504)
    /// //     mutated x is None
    /// //     mutated x is Some(-13390771)
    /// //     mutated x is Some(1208312368)
    /// # Ok(())
    /// # }
    /// # foo().unwrap();
    /// ```
    pub fn mutate<T>(&mut self, value: &mut T) -> Result<()>
    where
        T: DefaultMutate,
    {
        self.context.mutate(value)
    }

    /// Mutate the given `value` with the given `mutator` and within the
    /// constraints of this `Session`'s configuration.
    ///
    /// This is similar to the [`mutate`][Session::mutate] method, but allows
    /// you to specify a custom mutator to use instead of the default mutator
    /// for `value`'s type.
    ///
    /// # Example
    ///
    /// ```
    /// # fn foo() -> mutatis::Result<()> {
    /// use mutatis::{mutators as m, Session};
    ///
    /// let mut res = Ok(1234i32);
    ///
    /// // Create a custom mutator for `Result<i32, bool>` values.
    /// let mut mutator = m::result(m::mrange(-10..=10), m::just(true));
    ///
    /// let mut session = Session::new().seed(0x1984);
    ///
    /// for _ in 0..5 {
    ///     session.mutate_with(&mut mutator, &mut res)?;
    ///     println!("mutated res is {res:?}");
    /// }
    ///
    /// // Example output:
    /// //
    /// //     mutated res is Err(true)
    /// //     mutated res is Err(true)
    /// //     mutated res is Ok(9)
    /// //     mutated res is Err(true)
    /// //     mutated res is Ok(-6)
    /// # Ok(())
    /// # }
    /// # foo().unwrap();
    /// ```
    pub fn mutate_with<T>(
        &mut self,
        mutator: &mut (impl Mutate<T> + ?Sized),
        value: &mut T,
    ) -> Result<()> {
        self.context.mutate_with(mutator, value)
    }

    /// Generate a given `T` with its default mutator.
    ///
    /// The default mutator for a type is defined by the [`DefaultMutate`] trait
    /// implementation for that type.
    ///
    /// To use a custom mutator, rather than the default mutator, use the
    /// [`generate_with`][Session::generate_with] method instead.
    ///
    /// # Example
    ///
    /// ```
    /// # fn foo() -> mutatis::Result<()> {
    /// use mutatis::Session;
    ///
    /// let mut session = Session::new().seed(0xaabbccdd);
    ///
    /// for _ in 0..5 {
    ///     let x = session.generate::<u8>()?;
    ///     println!("generated x is {x:?}");
    /// }
    ///
    /// // Example output:
    /// //
    /// //     generated x is 127
    /// //     generated x is 247
    /// //     generated x is 211
    /// //     generated x is 245
    /// //     generated x is 86
    /// # Ok(())
    /// # }
    /// # foo().unwrap();
    /// ```
    pub fn generate<T>(&mut self) -> Result<T>
    where
        T: DefaultMutate,
        T::DefaultMutate: Generate<T>,
    {
        let mut generator = T::DefaultMutate::default();
        generator.generate(&mut self.context)
    }

    /// Generate a given `T` with its default mutator.
    ///
    /// The default mutator for a type is defined by the [`DefaultMutate`] trait
    /// implementation for that type.
    ///
    /// To use a custom mutator, rather than the default mutator, use the
    /// [`generate_with`][Session::generate_with] method instead.
    ///
    /// # Example
    ///
    /// ```
    /// # fn foo() -> mutatis::Result<()> {
    /// use mutatis::{mutators as m, Session};
    ///
    /// let mut session = Session::new().seed(0x12345678);
    ///
    /// // Create a mutator/generator for `Option<u32>` values, where the `u32`
    /// // is always in the range 10 to 20 inclusive.
    /// let mut mutator = m::option(m::mrange(10..=20));
    ///
    /// // Generate some values with that generation strategy.
    /// for _ in 0..5 {
    ///     let x = session.generate_with::<Option<u32>>(&mut mutator)?;
    ///     println!("generated x is {x:?}");
    /// }
    ///
    /// // Example output:
    /// //
    /// //     generated x is Some(15)
    /// //     generated x is Some(12)
    /// //     generated x is Some(18)
    /// //     generated x is Some(18)
    /// //     generated x is None
    /// # Ok(())
    /// # }
    /// # foo().unwrap();
    /// ```
    pub fn generate_with<T>(&mut self, generator: &mut impl Generate<T>) -> Result<T> {
        generator.generate(&mut self.context)
    }
}

/// The context for the current mutation.
///
/// This context includes things like configuration options (whether to only
/// perform "shrinking" mutations or not) as well as a random number generator.
///
/// Every candidate mutation, which is a closure that will perform its
/// associated changes when invoked, is given a context.
///
/// You do not create contexts directly. You create [`Session`s][crate::Session]
/// which internally manages contexts for you, passing them to the candidate
/// mutation closure that was chosen for execution as needed.
#[derive(Debug)]
pub struct Context {
    rng: Rng,
    shrink: bool,

    // Count of how many `generate_via_mutate` calls are active at a given
    // moment in time. Allows us to limit the depth of these calls for recursive
    // types so that we can avoid blowing the stack.
    generate_via_mutate_depth: u32,
}

impl Context {
    /// Get this context's random number generator.
    #[inline]
    #[must_use]
    pub fn rng(&mut self) -> &mut Rng {
        &mut self.rng
    }

    /// Whether only shrinking mutations should be performed or not.
    ///
    /// When this method returns `true`, then mutator implementations should
    /// avoid performing any mutation which increases the size or complexity of
    /// the value that they are mutating.
    #[inline]
    #[must_use]
    pub fn shrink(&self) -> bool {
        self.shrink
    }

    #[inline]
    pub(crate) fn mutate<T>(&mut self, value: &mut T) -> Result<()>
    where
        T: DefaultMutate,
    {
        let mut mutator = mutators::default::<T>();
        self.mutate_with(&mut mutator, value)
    }

    #[inline]
    pub(crate) fn mutate_with<T>(
        &mut self,
        mutator: &mut (impl Mutate<T> + ?Sized),
        value: &mut T,
    ) -> Result<()> {
        if let Some(count) = mutator.mutation_count(value, self.shrink) {
            self.apply_mutation(value, count, |c, value| mutator.mutate(c, value))
        } else {
            self.choose_and_apply_mutation(value, |c, value| mutator.mutate(c, value))
        }
    }

    fn apply_mutation<T>(
        &mut self,
        value: &mut T,
        count: u32,
        mut mutate_impl: impl FnMut(&mut Candidates, &mut T) -> Result<()>,
    ) -> Result<()> {
        log::trace!("=== applying mutation (fast path, count={count}) ===");

        let count_usize = usize::try_from(count).unwrap();

        if count_usize == 0 {
            log::trace!("mutator exhausted");
            return Err(Error::exhausted());
        }

        let target = self.rng().gen_index(count_usize).unwrap();
        log::trace!("targeting mutation {target}");
        debug_assert!(target < count_usize);

        let mut candidates = Candidates {
            context: self,
            phase: Phase::mutate(u32::try_from(target).unwrap()),
            applied_mutation: false,
        };

        match mutate_impl(&mut candidates, value) {
            Err(e) if e.is_early_exit() => {
                log::trace!("mutation applied successfully");
                Ok(())
            }

            Err(e) => {
                log::error!("failed to apply mutation: {e}");
                Err(e)
            }

            Ok(()) if candidates.applied_mutation => {
                panic!(
                    "We applied a mutation but did not receive an early-exit error \
                     from the mutator. This means that errors are not always being \
                     propagated, for example a `?` is missing from a call to the \
                     `Candidates::mutation` method.",
                )
            }
            Ok(()) => {
                let found = candidates.phase.current;
                panic!(
                    "Mutation count mismatch: expected {count} candidates but \
                     mutate only enumerated {found}. Ensure mutation_count and \
                     mutate agree, and that mutate is deterministic.",
                )
            }
        }
    }

    fn choose_and_apply_mutation<T>(
        &mut self,
        value: &mut T,
        mut mutate_impl: impl FnMut(&mut Candidates, &mut T) -> Result<()>,
    ) -> Result<()> {
        log::trace!("=== choosing and applying a mutation ===");

        let count = {
            let mut candidates = Candidates {
                context: self,
                phase: Phase::counting(),
                applied_mutation: false,
            };
            mutate_impl(&mut candidates, value)?;
            candidates.phase.current
        };
        log::trace!("counted {count} mutations");

        self.apply_mutation(value, count, mutate_impl)
    }

    #[inline]
    pub(crate) fn mutate_in_range_with<T>(
        &mut self,
        mutator: &mut impl MutateInRange<T>,
        value: &mut T,
        range: &ops::RangeInclusive<T>,
    ) -> Result<()> {
        self.choose_and_apply_mutation(value, |c, value| mutator.mutate_in_range(c, value, range))
    }

    const MAX_DEPTH: u32 = 8;

    pub(crate) fn with_generate_via_mutate_scope(
        &mut self,
        mut f: impl FnMut(&mut Self) -> Result<()>,
    ) -> Result<()> {
        self.generate_via_mutate_depth += 1;
        let result = if !self.shrink() && self.generate_via_mutate_depth < Self::MAX_DEPTH {
            f(self)
        } else {
            Ok(())
        };
        self.generate_via_mutate_depth -= 1;
        result
    }
}

// Logically this is
//
//     enum Phase {
//         Count(u32),
//         Mutate { current: u32, target: u32 },
//     }
//
// but we avoid the `enum` for performance.
#[derive(Clone)]
struct Phase {
    current: u32,

    // `u32::MAX` means we're in counting mode, and do not have target mutation
    // to apply.
    target: u32,
}

impl Phase {
    fn counting() -> Self {
        Phase {
            current: 0,
            target: u32::MAX,
        }
    }

    fn mutate(target: u32) -> Self {
        Phase { current: 0, target }
    }
}

/// The set of mutations that can be applied to a value.
///
/// This type is used by mutators to register the mutations that they can
/// perform on a value. It is passed to the [`Mutate::mutate`] trait method, and
/// provides a way to register candidate mutations, as well as to check if
/// shrinking is enabled.
pub struct Candidates<'a> {
    context: &'a mut Context,
    phase: Phase,
    applied_mutation: bool,
}

impl<'a> Candidates<'a> {
    /// Register a candidate mutation that can be applied to a value.
    ///
    /// This method is called by [`Mutate::mutate`] implementations to register
    /// the potential mutations that they can perform on a value.
    ///
    /// `f` should be a closure that performs the mutation on the value that was
    /// passed to `Mutate::mutate`, updating the value and the mutator itself as
    /// necessary.
    ///
    /// See the [`Mutate::mutate`] trait method documentation for more
    /// information on this method's use.
    #[inline]
    pub fn mutation(&mut self, mut f: impl FnMut(&mut Context) -> Result<()>) -> Result<()> {
        let idx = self.phase.current;
        self.phase.current = idx + 1;
        if idx == self.phase.target {
            self.applied_mutation = true;
            f(&mut self.context)?;
            Err(Error::early_exit())
        } else {
            Ok(())
        }
    }

    /// Register `count` candidate mutations as a group.
    ///
    /// During counting, this increments the candidate counter by `count` in a
    /// single step. During mutation, if the chosen target falls within this
    /// group, `f` is called with the offset within the group (`0..count`).
    ///
    /// This is useful when you have many related mutations (such as enum
    /// variant switches) that can be dispatched by index rather than
    /// registered one at a time via [`mutation`][Candidates::mutation].
    ///
    /// # Example
    ///
    /// ```
    /// # fn foo() -> mutatis::Result<()> {
    /// use mutatis::{Candidates, Mutate, Result, Session};
    ///
    /// #[derive(Clone, Copy, Debug, PartialEq)]
    /// enum Direction { North, South, East, West }
    ///
    /// struct DirectionMutator;
    ///
    /// impl Mutate<Direction> for DirectionMutator {
    ///     fn mutate(
    ///         &mut self,
    ///         mutations: &mut Candidates<'_>,
    ///         value: &mut Direction,
    ///     ) -> Result<()> {
    ///         // Register three variant-switch mutations (all directions
    ///         // other than the current one) in a single call.
    ///         let current = *value as u32;
    ///         mutations.mutation_group(3, |_ctx, which| {
    ///             let target = if which >= current { which + 1 } else { which };
    ///             *value = match target {
    ///                 0 => Direction::North,
    ///                 1 => Direction::South,
    ///                 2 => Direction::East,
    ///                 _ => Direction::West,
    ///             };
    ///             Ok(())
    ///         })?;
    ///         Ok(())
    ///     }
    /// }
    ///
    /// let mut direction = Direction::North;
    /// let mut session = Session::new();
    /// for _ in 0..5 {
    ///     session.mutate_with(&mut DirectionMutator, &mut direction)?;
    ///     println!("direction is now {direction:?}");
    /// }
    /// # Ok(())
    /// # }
    /// # foo().unwrap();
    /// ```
    #[inline]
    pub fn mutation_group(
        &mut self,
        count: u32,
        f: impl FnOnce(&mut Context, u32) -> Result<()>,
    ) -> Result<()> {
        let base = self.phase.current;
        self.phase.current = base + count;
        if self.phase.target.wrapping_sub(base) < count {
            self.applied_mutation = true;
            f(&mut self.context, self.phase.target - base)?;
            Err(Error::early_exit())
        } else {
            Ok(())
        }
    }

    /// Whether only shrinking mutations should be registered in this mutation
    /// set or not.
    ///
    /// When this method returns `true`, then you should not register any
    /// mutation which can grow the value being mutated.
    pub fn shrink(&self) -> bool {
        self.context.shrink()
    }
}

/// A trait for mutating values.
///
/// You can think of `Mutate<T>` as a streaming iterator of `T`s but instead of
/// internally containing and yielding access to the `T`s, it takes an `&mut T`
/// as an argument and mutates it in place.
///
/// The main method is the [`mutate`][Mutate::mutate] method, which applies one
/// of many potential mutations to the given value, or returns an error.
///
/// # Example: Using a Type's Default Mutator
///
/// Many types implement the `DefaultMutate` trait, which provides a default
/// mutator for that type. You can use this default mutator by calling
/// [`mutate`][Session::mutate] on a `Session` with a value of
/// that type.
///
/// ```
/// # fn foo() -> mutatis::Result<()> {
/// # #![cfg(feature = "std")]
/// use mutatis::{Context, Session};
///
/// let mut session = Session::new();
///
/// let mut x = 1234;
/// session.mutate(&mut x)?;
///
/// for _ in 0..5 {
///     session.mutate(&mut x)?;
///     println!("mutated x is {x}");
/// }
///
/// panic!();
/// // Example output:
/// //
/// //     mutated x is 1682887620
/// # Ok(())
/// # }
/// ```
///
/// # Example: Using Custom Mutators
///
/// ```
/// # fn foo() -> mutatis::Result<()> {
/// # #![cfg(feature = "std")]
/// use mutatis::{mutators as m, Mutate, Session};
///
/// // Define a mutator for `u32`s that only creates multiples-of-four
/// let mut mutator = m::u32()
///     .map(|_ctx, x| {
///         *x = *x & !3; // Clear the bottom two bits to make `x` a multiple of four.
///         Ok(())
///     });
///
/// // Mutate a value a bunch of times!
/// let mut x = 1234;
/// let mut session = Session::new();
/// for _ in 0..5 {
///     session.mutate_with(&mut mutator, &mut x)?;
///     println!("mutated x is {x}");
/// }
///
/// panic!();
/// // Example output:
/// //
/// //     mutated x is 2436583184
/// //     mutated x is 2032949584
/// //     mutated x is 2631247496
/// //     mutated x is 199875380
/// //     mutated x is 3751781284
/// # Ok(())
/// # }
/// ```
///
/// # Exhaustion
///
/// A mutator may become *exhausted*, meaning that it doesn't have any more
/// mutations it can perform for a given value. In this case, the mutator may
/// return an error of kind
/// [`ErrorKind::Exhausted`][crate::error::ErrorKind::Exhausted]. Many mutators
/// are effectively inexhaustible (or it would be prohibitively expensive to
/// precisely track whether they've already emitted every possible variant of a
/// value) and therefore it is valid for a mutator to never report exhaustion.
///
/// You may also ignore exhaustion errors via the
/// [`mutatis::error::ResultExt::ignore_exhausted`][crate::error::ResultExt::ignore_exhausted]
/// extension method.
///
/// Note that you should never return an `ErrorKind::Exhausted` error from your
/// own manual `Mutate` implementations. Instead, simply avoid registering any
/// candidate mutations and, if no other sibling or parent mutators have any
/// potential mutations either, then the library will return an exhaustion error
/// for you.
///
/// # Many-to-Many
///
/// Note that the relationship between mutator types and mutated types is not
/// one-to-one: a single mutator type can mutate many different types, and a
/// single type can be mutated by many different mutator types. This gives you
/// the flexibility to define new mutators for existing types (including those
/// that are not defined by your own crate).
///
/// ```
/// # fn foo () {
/// # #![cfg(feature = "derive")]
/// use mutatis::{
///     mutators as m, DefaultMutate, Mutate, Session, Candidates,
///     Result,
/// };
///
/// #[derive(Mutate)] // Derive a default mutator for `Foo`s.
/// pub struct Foo(u32);
///
/// // Also define and implement a second mutator type for `Foo` by hand!
///
/// pub struct AlignedFooMutator{
///     inner: <Foo as DefaultMutate>::DefaultMutate,
///     alignment: u32,
/// }
///
/// impl Mutate<Foo> for AlignedFooMutator {
///     fn mutate(&mut self, mutations: &mut Candidates, foo: &mut Foo) -> Result<()> {
///         self.inner
///             .by_ref()
///             .map(|_context, foo| {
///                 // Clear the bottom bits to keep the `Foo` "aligned".
///                 debug_assert!(self.alignment.is_power_of_two());
///                 let mask = !(self.alignment - 1);
///                 foo.0 = foo.0 & mask;
///                 Ok(())
///             })
///             .mutate(mutations, foo)
///     }
/// }
/// # }
/// ```
pub trait Mutate<T>
where
    T: ?Sized,
{
    // Required methods.

    /// Pseudo-randomly mutate the given value.
    ///
    /// # Calling the `mutate` Method
    ///
    /// If you just want to mutate a value, use [`Session::mutate`] or
    /// [`Session::mutate_with`] instead of invoking this trait method
    /// directly. See their documentation for more details.
    ///
    /// # Implementing the `mutate` Method
    ///
    /// Register every mutation that a mutator *could* perform by invoking the
    /// [`mutations.mutation(...)`][Candidates::mutation] function, passing in
    /// a closure that performs that mutation, updating `value` and `self` as
    /// necessary.
    ///
    /// `mutate` implementations must only mutate `self` and the given `value`
    /// from inside a registered mutation closure. It must not update `self` or
    /// modify `value` outside of one of those mutation closures.
    ///
    /// Furthermore, all `mutate` implementations must be deterministic: given
    /// the same inputs, the same set of mutations must be registered in the
    /// same order.
    ///
    /// These requirements exist because, under the hood, the `mutate` method is
    /// called twice for every mutation that is actually performed:
    ///
    /// 1. First, `mutate` is called to count all the possible mutations that
    ///    could be performed. In this phase, the mutation closures are ignored.
    ///
    /// 2. Next, a random index `i` between `0` and that count is chosen. This
    ///    is the index of the mutation that we will actually be applied.
    ///
    /// 3. Finally, `mutate` is called again. In this phase, the `i`th mutation
    ///    closure is invoked, applying the mutation, while all others are
    ///    ignored.
    ///
    /// Note that the registered mutations are roughly uniformly selected from,
    /// so if you wish to skew the distribution of mutations, making certain
    /// mutations more probable than others, you may register mutations multiple
    /// times or register overlapping mutations.
    ///
    /// ## Example
    ///
    /// ```
    /// # fn foo() -> mutatis::Result<()> {
    /// use mutatis::{
    ///     mutators as m, Generate, Mutate, Session, Candidates,
    ///     Result,
    /// };
    ///
    /// // A custom mutator that creates pairs where the first element is less
    /// // than or equal to the second.
    /// pub struct OrderedPairs;
    ///
    /// impl Mutate<(u64, u64)> for OrderedPairs {
    ///     fn mutate(
    ///         &mut self,
    ///         mutations: &mut Candidates<'_>,
    ///         pair: &mut (u64, u64),
    ///     ) -> Result<()> {
    ///         // We *cannot* mutate `self` or `pair` out here.
    ///
    ///         if *pair != (0, 0) {
    ///             // Note: we register this mutation -- even when not
    ///             // shrinking and even though the subsequent mutation
    ///             // subsumes this one -- to bias the distribution towards
    ///             // smaller values.
    ///             mutations.mutation(|ctx| {
    ///                 // We *can* mutate `self` and `pair` inside here.
    ///                 let a = m::mrange(0..=pair.0).generate(ctx)?;
    ///                 let b = m::mrange(0..=pair.1).generate(ctx)?;
    ///                 *pair = (a.min(b), a.max(b));
    ///                 Ok(())
    ///             })?;
    ///         }
    ///
    ///         if !mutations.shrink() {
    ///             // Only register this fully-general mutation when we are
    ///             // not shrinking, as this can grow the pair.
    ///             mutations.mutation(|ctx| {
    ///                 // We *can* mutate `self` and `pair` inside here.
    ///                 let a = m::u64().generate(ctx)?;
    ///                 let b = m::u64().generate(ctx)?;
    ///                 *pair = (a.min(b), a.max(b));
    ///                 Ok(())
    ///             })?;
    ///         }
    ///
    ///         Ok(())
    ///     }
    /// }
    ///
    /// // Create a pair.
    /// let mut pair = (1000, 2000);
    ///
    /// // And mutate it a bunch of times!
    /// let mut session = Session::new();
    /// for _ in 0..3 {
    ///     session.mutate_with(&mut OrderedPairs, &mut pair)?;
    ///     println!("mutated pair is {pair:?}");
    /// }
    ///
    /// // Example output:
    /// //
    /// //     mutated pair is (11, 861)
    /// //     mutated pair is (8, 818)
    /// //     mutated pair is (3305948426120559093, 16569598107406464568)
    /// # Ok(())
    /// # }
    /// # foo().unwrap();
    /// ```
    fn mutate(&mut self, mutations: &mut Candidates<'_>, value: &mut T) -> Result<()>;

    /// Return the number of mutations that [`mutate`][Mutate::mutate] would
    /// register for the given `value`.
    ///
    /// The default implementation returns `u32::MAX`, which signals that the
    /// count is unknown and the framework should fall back to a counting pass
    /// through [`mutate`][Mutate::mutate]. Implementations that can compute
    /// the count cheaply should override this method.
    #[inline]
    fn mutation_count(&self, value: &T, shrink: bool) -> Option<u32> {
        let _ = (value, shrink);
        None
    }

    // Provided methods.

    /// Generate a new value by mutating its default value `iters` times.
    ///
    /// The `iters` argument controls how many mutations are performed. More
    /// mutations will lead to generated values that are generally more
    /// different from the default value, but will take longer to generate. A
    /// small number, even just `1`, is usually sufficient, because the fuzzer
    /// will continue to mutate the input.
    ///
    /// This is a helper utility that allows you to implement `Generate<T>` "for
    /// free" if you already have `T: Default` and `Mutate<T>` implementations.
    ///
    /// This is especially useful when implementing `Generate<T>` with a uniform
    /// output distribution is otherwise difficult. For example, the natural way
    /// to write a generator is often a decision tree, but keeping decision
    /// trees balanced is difficult, which can easily bias the results
    /// (especially when the choices are abstracted away behind helper
    /// functions). Consider the following psuedocode:
    ///
    /// ```ignore
    /// if ctx.gen_bool() {
    ///     A
    /// } else if ctx.gen_bool() {
    ///     B
    /// } else if ctx.gen_bool() {
    ///     C
    /// } else {
    ///     D
    /// }
    /// ```
    ///
    /// We would ideally want to generate `A`, `B`, `C`, and `D` with equal
    /// probability, but we actually end up generating `A` 50% of the time, `B`
    /// 25% of the time, and `C` and `D` 12.5% of the time. Of course, this is
    /// fairly obvious when we look at this code directly, but it may be
    /// non-obvious in other cases due to code factoring.
    ///
    /// # Example
    ///
    /// Here we are generating random expressions, which contain factors, which
    /// contain terms. We don't want to bias towards generating more top-level
    /// expressions than top-level factors, for example.
    ///
    /// ```
    /// # #[cfg(feature = "derive")]
    /// # fn foo() -> mutatis::Result<()> {
    /// use mutatis::{
    ///     mutators as m, Candidates, Context, DefaultMutate, Generate, Mutate, MutateInRange,
    ///     Result, Session,
    /// };
    ///
    /// #[derive(Debug, Mutate)]
    /// #[mutatis(generate = false)]
    /// enum Expr {
    ///     Add(Factor, Factor),
    ///     Sub(Factor, Factor),
    ///     Factor(Factor),
    /// }
    ///
    /// impl Default for Expr {
    ///     fn default() -> Self {
    ///         Expr::Factor(Default::default())
    ///     }
    /// }
    ///
    /// impl Generate<Expr> for ExprMutator {
    ///     fn generate(&mut self, context: &mut Context) -> Result<Expr> {
    ///         self.generate_via_mutate(context, 2)
    ///     }
    /// }
    ///
    /// #[derive(Debug, Mutate)]
    /// #[mutatis(generate = false)]
    /// enum Factor {
    ///     Mul(Term, Term),
    ///     Div(Term, Term),
    ///     Term(Term),
    /// }
    ///
    /// impl Default for Factor {
    ///     fn default() -> Self {
    ///         Factor::Term(Default::default())
    ///     }
    /// }
    ///
    /// impl Generate<Factor> for FactorMutator {
    ///     fn generate(&mut self, context: &mut Context) -> Result<Factor> {
    ///         self.generate_via_mutate(context, 2)
    ///     }
    /// }
    ///
    /// #[derive(Debug, Mutate)]
    /// #[mutatis(generate = false)]
    /// enum Term {
    ///     Var(Var),
    ///     Num(u8),
    /// }
    ///
    /// impl Default for Term {
    ///     fn default() -> Self {
    ///         Term::Num(Default::default())
    ///     }
    /// }
    ///
    /// impl Generate<Term> for TermMutator {
    ///     fn generate(&mut self, context: &mut Context) -> Result<Term> {
    ///         self.generate_via_mutate(context, 1)
    ///     }
    /// }
    ///
    /// #[derive(Default, Debug)]
    /// struct Var(char);
    ///
    /// #[derive(Default)]
    /// struct VarMutator;
    ///
    /// impl Mutate<Var> for VarMutator {
    ///     fn mutate(&mut self, c: &mut Candidates<'_>, var: &mut Var) -> Result<()> {
    ///         let range = 'a'..='z';
    ///         m::char().mutate_in_range(c, &mut var.0, &range)
    ///     }
    /// }
    ///
    /// impl Generate<Var> for VarMutator {
    ///     fn generate(&mut self, context: &mut Context) -> Result<Var> {
    ///         self.generate_via_mutate(context, 1)
    ///     }
    /// }
    ///
    /// impl DefaultMutate for Var {
    ///     type DefaultMutate = VarMutator;
    /// }
    ///
    /// let mut session = Session::new();
    /// for _ in 0..5 {
    ///     let expr: Expr = session.generate()?;
    ///     println!("expr = {expr:?}");
    /// }
    /// // Example output:
    /// //
    /// //     expr = Factor(Mul(Num(12), Var(Var('z'))))
    /// //     expr = Sub(Div(Num(185), Var(Var('k'))), Div(Num(105), Var(Var('l'))))
    /// //     expr = Factor(Mul(Num(26), Var(Var('y'))))
    /// //     expr = Sub(Term(Num(121)), Mul(Var(Var('k')), Num(69)))
    /// //     expr = Factor(Term(Var(Var('p'))))
    /// # Ok(())
    /// # }
    /// # #[cfg(not(feature = "derive"))]
    /// # fn foo() -> mutatis::Result<()> { Ok(()) }
    /// # foo().unwrap()
    /// ```
    fn generate_via_mutate(&mut self, context: &mut Context, iters: usize) -> Result<T>
    where
        T: Sized + Default,
    {
        let mut value = T::default();
        context.with_generate_via_mutate_scope(|context| {
            for _ in 0..iters {
                context.mutate_with(self, &mut value)?;
            }
            Ok(())
        })?;
        Ok(value)
    }

    /// Create a new mutator that performs either this mutation or the `other`
    /// mutation.
    ///
    /// # Example
    ///
    /// ```
    /// # fn foo() -> mutatis::Result<()> {
    /// use mutatis::{mutators as m, Mutate, Session};
    ///
    /// let mut session = Session::new();
    ///
    /// // Either generate `-1`...
    /// let mut mutator = m::just(-1)
    ///     // ...or values in the range `0x40..=0x4f`...
    ///     .or(m::mrange(0x40..=0x4f))
    ///     // ...or values with just a single bit set.
    ///     .or(m::mrange(0..=31).map(|_ctx, x| {
    ///         *x = 1 << *x;
    ///         Ok(())
    ///     }));
    ///
    /// let mut value = 0;
    ///
    /// for _ in 0..5 {
    ///     session.mutate_with(&mut mutator, &mut value)?;
    ///     println!("mutated value is {value:#x}");
    /// }
    ///
    /// // Example output:
    /// //
    /// //     mutated value is 0x4a
    /// //     mutated value is 0xffffffff
    /// //     mutated value is 0x400000
    /// //     mutated value is 0x20000000
    /// //     mutated value is 0x4e
    /// # Ok(())
    /// # }
    /// # foo().unwrap()
    /// ```
    fn or<M>(self, other: M) -> mutators::Or<Self, M>
    where
        Self: Sized,
    {
        mutators::Or {
            left: self,
            right: other,
        }
    }

    /// Map a function over the mutations produced by this mutator.
    ///
    /// # Example
    ///
    /// ```
    /// # fn foo() -> mutatis::Result<()> {
    /// use mutatis::{mutators as m, Mutate, Session};
    ///
    /// let mut session = Session::new();
    ///
    /// let mut mutator = m::i32().map(|context, value| {
    ///     // Ensure that the value is always positive.
    ///     if *value <= 0 {
    ///         *value = i32::from(context.rng().gen_u16());
    ///     }
    ///     Ok(())
    /// });
    ///
    /// let mut value = -42;
    ///
    /// for _ in 0..10 {
    ///     session.mutate_with(&mut mutator, &mut value)?;
    ///     assert!(value > 0, "the mutated value is always positive");
    /// }
    /// # Ok(())
    /// # }
    /// # foo().unwrap()
    /// ```
    #[inline]
    #[must_use = "mutator combinators do nothing until you call their `mutate` method"]
    fn map<F>(self, f: F) -> mutators::Map<Self, F>
    where
        Self: Sized,
        F: FnMut(&mut Context, &mut T) -> Result<()>,
    {
        mutators::Map { mutator: self, f }
    }

    /// Given a projection function `F: FnMut(&mut U) -> &mut T`, turn this
    /// `Mutate<T>` into a `Mutate<U>`.
    ///
    /// # Example
    ///
    /// ```
    /// use mutatis::{mutators as m, Mutate, Session};
    /// # fn foo() -> mutatis::Result<()> {
    ///
    /// #[derive(Debug)]
    /// pub struct NewType(u32);
    ///
    /// let mut value = NewType(0);
    ///
    /// let mut mutator = m::u32().proj(|x: &mut NewType| &mut x.0);
    ///
    /// let mut session = Session::new();
    /// for _ in 0..3 {
    ///    session.mutate_with(&mut mutator, &mut value)?;
    ///    println!("mutated value is {value:?}");
    /// }
    ///
    /// // Example output:
    /// //
    /// //     mutated value is NewType(3729462868)
    /// //     mutated value is NewType(49968845)
    /// //     mutated value is NewType(2440803355)
    /// # Ok(())
    /// # }
    /// # foo().unwrap()
    /// ```
    #[inline]
    #[must_use = "mutator combinators do nothing until you call their `mutate` method"]
    fn proj<F, U>(self, f: F) -> mutators::Proj<Self, F>
    where
        Self: Sized,
        F: FnMut(&mut U) -> &mut T,
    {
        mutators::Proj { mutator: self, f }
    }

    /// Borrows a mutator, rather than consuming it.
    ///
    /// This is useful to allow applying mutator adapters while still retaining
    /// ownership of the original mutator.
    ///
    /// # Example
    ///
    /// ```
    /// use mutatis::{mutators as m, Mutate, Session};
    /// # fn foo() -> mutatis::Result<()> {
    ///
    /// let mut mutator = m::u32().map(|_context, x| {
    ///     *x = *x & !3;
    ///     Ok(())
    /// });
    ///
    ///
    /// let mut value = 1234;
    /// let mut session = Session::new();
    ///
    /// {
    ///     let mut borrowed_mutator = mutator.by_ref().map(|_context, x| {
    ///         *x = x.wrapping_add(1);
    ///         Ok(())
    ///     });
    ///     session.mutate_with(&mut borrowed_mutator, &mut value)?;
    ///     println!("first mutated value is {value}");
    /// }
    ///
    /// // In the outer scope, we can still use the original mutator.
    /// session.mutate_with(&mut mutator, &mut value)?;
    /// println!("second mutated value is {value}");
    ///
    /// // Example output:
    /// //
    /// //     first mutated value is 3729462869
    /// //     second mutated value is 49968844
    /// # Ok(())
    /// # }
    /// # foo().unwrap();
    #[inline]
    #[must_use = "mutator combinators do nothing until you call their `mutate` method"]
    fn by_ref(&mut self) -> &mut Self
    where
        Self: Sized,
    {
        self
    }
}

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

    // With a decision-tree approach like:
    //   if random() { A } else if random() { B } else if random() { C } else { D }
    // we'd get A=50%, B=25%, C=12.5%, D=12.5%.
    // Mutatis gathers all candidates first and picks uniformly, so each should be ~25%.
    //
    // Expected count per variant is ITERS/4 = 2500. Tolerance of 5% (500 counts)
    // is >11 standard deviations from the mean for a correct uniform distribution,
    // so false failures are essentially impossible.
    const ITERS: usize = 10_000;
    const EXPECTED: usize = ITERS / 4;
    const TOLERANCE: usize = ITERS / 20;

    fn assert_uniform(counts: &[usize; 4], label: &str) {
        for (i, &count) in counts.iter().enumerate() {
            assert!(
                count.abs_diff(EXPECTED) <= TOLERANCE,
                "{label} {i} was chosen {count} times (expected ~{EXPECTED}, \
                 tolerance ±{TOLERANCE}); mutation distribution is not uniform",
            );
        }
    }

    // ---- Flat enum ----

    #[derive(Clone, Copy)]
    enum FourVariants {
        A,
        B,
        C,
        D,
    }

    struct FourVariantsMutator;

    impl Mutate<FourVariants> for FourVariantsMutator {
        fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut FourVariants) -> Result<()> {
            c.mutation(|_| {
                *value = FourVariants::A;
                Ok(())
            })?;
            c.mutation(|_| {
                *value = FourVariants::B;
                Ok(())
            })?;
            c.mutation(|_| {
                *value = FourVariants::C;
                Ok(())
            })?;
            c.mutation(|_| {
                *value = FourVariants::D;
                Ok(())
            })?;
            Ok(())
        }
    }

    #[test]
    fn enum_mutation_is_uniform() {
        let mut session = Session::new();
        let mut value = FourVariants::A;
        let mut counts = [0usize; 4];
        let mut mutator = FourVariantsMutator;

        for _ in 0..ITERS {
            session.mutate_with(&mut mutator, &mut value).unwrap();
            counts[match value {
                FourVariants::A => 0,
                FourVariants::B => 1,
                FourVariants::C => 2,
                FourVariants::D => 3,
            }] += 1;
        }

        assert_uniform(&counts, "variant");
    }

    // ---- Flat struct with four bool fields ----

    struct FourFields {
        a: bool,
        b: bool,
        c: bool,
        d: bool,
    }

    #[derive(Default)]
    struct FourFieldsMutator {
        a: mutators::Bool,
        b: mutators::Bool,
        c: mutators::Bool,
        d: mutators::Bool,
    }

    impl Mutate<FourFields> for FourFieldsMutator {
        fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut FourFields) -> Result<()> {
            self.a.mutate(c, &mut value.a)?;
            self.b.mutate(c, &mut value.b)?;
            self.c.mutate(c, &mut value.c)?;
            self.d.mutate(c, &mut value.d)?;
            Ok(())
        }
    }

    #[test]
    fn struct_mutation_is_uniform() {
        let mut session = Session::new();
        let mut mutator = FourFieldsMutator::default();
        let mut counts = [0usize; 4];

        for _ in 0..ITERS {
            let mut value = FourFields {
                a: false,
                b: false,
                c: false,
                d: false,
            };
            session.mutate_with(&mut mutator, &mut value).unwrap();
            if value.a {
                counts[0] += 1;
            }
            if value.b {
                counts[1] += 1;
            }
            if value.c {
                counts[2] += 1;
            }
            if value.d {
                counts[3] += 1;
            }
        }

        assert_uniform(&counts, "field");
    }

    // ---- Nested structs: Abcd { a, bcd: Bcd { b, cd: Cd { c, d } } } ----

    struct NestedAbcd {
        a: bool,
        bcd: NestedBcd,
    }

    struct NestedBcd {
        b: bool,
        cd: NestedCd,
    }

    struct NestedCd {
        c: bool,
        d: bool,
    }

    #[derive(Default)]
    struct NestedCdMutator {
        c: mutators::Bool,
        d: mutators::Bool,
    }

    #[derive(Default)]
    struct NestedBcdMutator {
        b: mutators::Bool,
        cd: NestedCdMutator,
    }

    #[derive(Default)]
    struct NestedAbcdMutator {
        a: mutators::Bool,
        bcd: NestedBcdMutator,
    }

    impl Mutate<NestedCd> for NestedCdMutator {
        fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut NestedCd) -> Result<()> {
            self.c.mutate(c, &mut value.c)?;
            self.d.mutate(c, &mut value.d)?;
            Ok(())
        }
    }

    impl Mutate<NestedBcd> for NestedBcdMutator {
        fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut NestedBcd) -> Result<()> {
            self.b.mutate(c, &mut value.b)?;
            self.cd.mutate(c, &mut value.cd)?;
            Ok(())
        }
    }

    impl Mutate<NestedAbcd> for NestedAbcdMutator {
        fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut NestedAbcd) -> Result<()> {
            self.a.mutate(c, &mut value.a)?;
            self.bcd.mutate(c, &mut value.bcd)?;
            Ok(())
        }
    }

    #[test]
    fn nested_struct_mutation_is_uniform() {
        let mut session = Session::new();
        let mut mutator = NestedAbcdMutator::default();
        let mut counts = [0usize; 4];

        for _ in 0..ITERS {
            let mut value = NestedAbcd {
                a: false,
                bcd: NestedBcd {
                    b: false,
                    cd: NestedCd { c: false, d: false },
                },
            };
            session.mutate_with(&mut mutator, &mut value).unwrap();
            if value.a {
                counts[0] += 1;
            }
            if value.bcd.b {
                counts[1] += 1;
            }
            if value.bcd.cd.c {
                counts[2] += 1;
            }
            if value.bcd.cd.d {
                counts[3] += 1;
            }
        }

        assert_uniform(&counts, "field");
    }

    // ---- Nested enums: Abcd { A, Bcd(Bcd { B, Cd(Cd { C, D }) }) } ----

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum EnumAbcd {
        A,
        Bcd(EnumBcd),
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum EnumBcd {
        B,
        Cd(EnumCd),
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum EnumCd {
        C,
        D,
    }

    struct EnumCdMutator;

    impl Mutate<EnumCd> for EnumCdMutator {
        fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut EnumCd) -> Result<()> {
            c.mutation(|_| {
                *value = EnumCd::C;
                Ok(())
            })?;
            c.mutation(|_| {
                *value = EnumCd::D;
                Ok(())
            })?;
            Ok(())
        }
    }

    struct EnumBcdMutator {
        cd: EnumCdMutator,
    }

    impl Mutate<EnumBcd> for EnumBcdMutator {
        fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut EnumBcd) -> Result<()> {
            c.mutation(|_| {
                *value = EnumBcd::B;
                Ok(())
            })?;
            match value {
                EnumBcd::B => {
                    c.mutation(|_| {
                        *value = EnumBcd::Cd(EnumCd::C);
                        Ok(())
                    })?;
                    c.mutation(|_| {
                        *value = EnumBcd::Cd(EnumCd::D);
                        Ok(())
                    })?;
                }
                EnumBcd::Cd(cd) => {
                    self.cd.mutate(c, cd)?;
                }
            }
            Ok(())
        }
    }

    struct EnumAbcdMutator {
        bcd: EnumBcdMutator,
    }

    impl Mutate<EnumAbcd> for EnumAbcdMutator {
        fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut EnumAbcd) -> Result<()> {
            c.mutation(|_| {
                *value = EnumAbcd::A;
                Ok(())
            })?;
            match value {
                EnumAbcd::A => {
                    c.mutation(|_| {
                        *value = EnumAbcd::Bcd(EnumBcd::B);
                        Ok(())
                    })?;
                    c.mutation(|_| {
                        *value = EnumAbcd::Bcd(EnumBcd::Cd(EnumCd::C));
                        Ok(())
                    })?;
                    c.mutation(|_| {
                        *value = EnumAbcd::Bcd(EnumBcd::Cd(EnumCd::D));
                        Ok(())
                    })?;
                }
                EnumAbcd::Bcd(bcd) => {
                    self.bcd.mutate(c, bcd)?;
                }
            }
            Ok(())
        }
    }

    #[test]
    fn nested_enum_mutation_is_uniform() {
        let mut session = Session::new();
        let mut mutator = EnumAbcdMutator {
            bcd: EnumBcdMutator { cd: EnumCdMutator },
        };
        let mut counts = [0usize; 4];

        for _ in 0..ITERS {
            let mut value = EnumAbcd::Bcd(EnumBcd::Cd(EnumCd::D));
            session.mutate_with(&mut mutator, &mut value).unwrap();
            counts[match value {
                EnumAbcd::A => 0,
                EnumAbcd::Bcd(EnumBcd::B) => 1,
                EnumAbcd::Bcd(EnumBcd::Cd(EnumCd::C)) => 2,
                EnumAbcd::Bcd(EnumBcd::Cd(EnumCd::D)) => 3,
            }] += 1;
        }

        assert_uniform(&counts, "variant");
    }

    // ---- mutation_group with four alternatives ----

    #[derive(Clone, Copy)]
    enum FourGroupAlts {
        A,
        B,
        C,
        D,
    }

    struct FourGroupAltsMutator;

    impl Mutate<FourGroupAlts> for FourGroupAltsMutator {
        fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut FourGroupAlts) -> Result<()> {
            c.mutation_group(4, |_ctx, which| {
                *value = match which {
                    0 => FourGroupAlts::A,
                    1 => FourGroupAlts::B,
                    2 => FourGroupAlts::C,
                    _ => FourGroupAlts::D,
                };
                Ok(())
            })?;
            Ok(())
        }
    }

    #[test]
    fn mutation_group_is_uniform() {
        let mut session = Session::new();
        let mut value = FourGroupAlts::A;
        let mut counts = [0usize; 4];
        let mut mutator = FourGroupAltsMutator;

        for _ in 0..ITERS {
            session.mutate_with(&mut mutator, &mut value).unwrap();
            counts[match value {
                FourGroupAlts::A => 0,
                FourGroupAlts::B => 1,
                FourGroupAlts::C => 2,
                FourGroupAlts::D => 3,
            }] += 1;
        }

        assert_uniform(&counts, "mutation_group alt");
    }

    // ---- mutation_group mixed with individual mutations ----

    struct MixedGroupMutator;

    impl Mutate<FourGroupAlts> for MixedGroupMutator {
        fn mutate(&mut self, c: &mut Candidates<'_>, value: &mut FourGroupAlts) -> Result<()> {
            c.mutation_group(2, |_ctx, which| {
                *value = match which {
                    0 => FourGroupAlts::A,
                    _ => FourGroupAlts::B,
                };
                Ok(())
            })?;
            c.mutation(|_ctx| {
                *value = FourGroupAlts::C;
                Ok(())
            })?;
            c.mutation(|_ctx| {
                *value = FourGroupAlts::D;
                Ok(())
            })?;
            Ok(())
        }
    }

    #[test]
    fn mutation_group_mixed_with_individual_is_uniform() {
        let mut session = Session::new();
        let mut value = FourGroupAlts::A;
        let mut counts = [0usize; 4];
        let mut mutator = MixedGroupMutator;

        for _ in 0..ITERS {
            session.mutate_with(&mut mutator, &mut value).unwrap();
            counts[match value {
                FourGroupAlts::A => 0,
                FourGroupAlts::B => 1,
                FourGroupAlts::C => 2,
                FourGroupAlts::D => 3,
            }] += 1;
        }

        assert_uniform(&counts, "mixed group alt");
    }
}

fn _static_assert_object_safety(
    _: &dyn Mutate<u8>,
    _: &dyn Generate<u8>,
    _: &dyn MutateInRange<u8>,
) {
}

impl<M, T> Mutate<T> for &mut M
where
    M: Mutate<T>,
{
    fn mutate(&mut self, c: &mut Candidates, value: &mut T) -> Result<()> {
        (**self).mutate(c, value)
    }

    #[inline]
    fn mutation_count(&self, value: &T, shrink: bool) -> Option<u32> {
        (**self).mutation_count(value, shrink)
    }
}

impl<M, T> Generate<T> for &mut M
where
    M: Generate<T>,
{
    fn generate(&mut self, context: &mut Context) -> Result<T> {
        (**self).generate(context)
    }
}

/// A trait for types that have a default mutator.
pub trait DefaultMutate {
    /// The default mutator for this type.
    type DefaultMutate: Mutate<Self> + Default;
}

/// A mutator that can also generate a value from scratch.
pub trait Generate<T>: Mutate<T> {
    /// Generate a random `T` value from scratch.
    ///
    /// Implementations may use the `context`'s random number generator in the
    /// process of generating a `T`.
    fn generate(&mut self, context: &mut Context) -> Result<T>;
}

/// A mutator that supports clamping mutated values to within a given range.
///
/// To use `MutateInRange` implementations, use the
/// `[Session::mutate_in_range]` method,
/// `[Session::mutate_in_range_with]` method, or
/// [`mutators::range()`][crate::mutators::range] combinator.
pub trait MutateInRange<T>: Mutate<T> {
    /// Mutate a value, ensuring that the resulting mutation is within the given
    /// range.
    fn mutate_in_range(
        &mut self,
        mutations: &mut Candidates,
        value: &mut T,
        range: &ops::RangeInclusive<T>,
    ) -> Result<()>;
}