hegeltest 0.49.3

Property-based testing for Rust, built on Hypothesis
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
use super::{combine_labels, label_from_name};
use crate::pretty::PrettyPrinter;
use crate::test_case::{TestCase, invalid_argument};
use std::fmt::Debug;
use std::marker::PhantomData;
use std::sync::Arc;

const MAP_LABEL: u64 = label_from_name("hegel.map");
const FLAT_MAP_LABEL: u64 = label_from_name("hegel.flat_map");
const FILTER_LABEL: u64 = label_from_name("hegel.filter");
const FILTER_ATTEMPT_LABEL: u64 = label_from_name("hegel.filter.attempt");

/// The core trait for all generators.
///
/// Generators produce values of type `T` by drawing from the engine through
/// the [`TestCase`] passed to [`do_draw`](Self::do_draw).
pub trait Generator<T> {
    /// Produce a value.
    ///
    /// Called by the [`TestCase`] draw methods, which run it inside a span
    /// labelled with [`label`](Self::label). An implementation that draws
    /// from component generators should draw them through
    /// [`TestCase::draw_silent`] (or [`TestCase::draw_and_print`]) rather
    /// than calling their `do_draw` directly, so each component's choices
    /// get a span of their own; only a generator that merely forwards to a
    /// wrapped generator, without drawing anything else, should call the
    /// wrapped `do_draw` directly, so the forwarding layer doesn't register
    /// as a second span.
    #[doc(hidden)]
    fn do_draw(&self, tc: &TestCase) -> T;

    /// The label identifying this generator to the engine.
    ///
    /// Every draw from this generator runs inside a span carrying this
    /// label. A label is an opaque `u64` with no meaning beyond identity: the
    /// engine treats two spans with the same label as coming from the same
    /// generator, and so as candidates for swapping, duplicating and
    /// reordering when it shrinks and mutates test cases. Two generators that
    /// draw the same shape of value should share a label, and generators
    /// that draw different shapes should not.
    ///
    /// The default label is derived from the generator's type name, which is
    /// right for a generator with no component generators. A generator built
    /// from other generators should combine a label of its own with its
    /// components' labels, so that, say, a list of integers and a list of
    /// strings get different labels while every list of integers gets the
    /// same one; see [`combine_labels`](super::combine_labels) for how. A
    /// generator that merely wraps another without changing what it draws
    /// should return the wrapped generator's label.
    ///
    /// This is called on every draw, so compute the label once — at
    /// construction, stored in a field, or as a `const` from
    /// [`label_from_name`](super::label_from_name) for a generator with no
    /// components — rather than in this method. The default hashes the type
    /// name each time it is called.
    fn label(&self) -> u64 {
        label_from_name(std::any::type_name::<Self>())
    }

    /// Transform generated values using a function.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// // Generate even integers by doubling
    /// let evens = gs::integers::<i32>().map(|n| n * 2);
    /// ```
    fn map<U, F>(self, f: F) -> Mapped<T, U, F, Self>
    where
        Self: Sized,
        F: Fn(T) -> U + Send + Sync,
    {
        Mapped {
            label: combine_labels(&[MAP_LABEL, self.label()]),
            source: self,
            f: Arc::new(f),
            _phantom: PhantomData,
        }
    }

    /// Generate a value, then use it to choose or configure another generator.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// // Generate a length, then a vec of exactly that length
    /// let generator = gs::integers::<usize>()
    ///     .min_value(1)
    ///     .max_value(10)
    ///     .flat_map(|len| gs::vecs(gs::integers::<i32>())
    ///         .min_size(len)
    ///         .max_size(len));
    /// ```
    fn flat_map<U, G, F>(self, f: F) -> FlatMapped<T, U, G, F, Self>
    where
        Self: Sized,
        G: Generator<U>,
        F: Fn(T) -> G + Send + Sync,
    {
        FlatMapped {
            label: combine_labels(&[FLAT_MAP_LABEL, self.label()]),
            source: self,
            f,
            _phantom: PhantomData,
        }
    }

    /// Only keep generated values that satisfy the predicate.
    ///
    /// Retries up to 3 times, then calls `assume(false)` to reject the test case.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// // Generate integers, then filter out the even ones
    /// let odds = gs::integers::<i32>().filter(|n| n % 2 != 0);
    /// ```
    fn filter<F>(self, predicate: F) -> Filtered<T, F, Self>
    where
        Self: Sized,
        F: Fn(&T) -> bool + Send + Sync,
    {
        Filtered {
            label: combine_labels(&[FILTER_LABEL, self.label()]),
            source: self,
            predicate,
            _phantom: PhantomData,
        }
    }

    /// Convert this generator into a type-erased boxed generator.
    ///
    /// This is needed when you have generators of different concrete types
    /// but the same output type and need to store them together, e.g. in a
    /// `Vec` or when passing to [`one_of()`](super::one_of).
    ///
    /// A `BoxedGenerator<T>` is a [`PrintableGenerator`] whenever `T`
    /// implements `Debug`, printing each drawn value's `Debug`
    /// representation. For a `T` that is not `Debug`, or to keep a custom
    /// printing strategy (a [`print_with`](Generator::print_with), say)
    /// through the type erasure, box with
    /// [`boxed_printable`](PrintableGenerator::boxed_printable) instead.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// // Different generator types producing the same output type —
    /// // boxing lets them be stored in a vec and passed to one_of
    /// let generator = vec![
    ///     gs::integers::<i32>().min_value(0).max_value(10).boxed(),
    ///     gs::integers::<i32>().map(|n| n * 100).boxed(),
    ///     gs::sampled_from(vec![1, 2, 3]).boxed(),
    /// ];
    /// ```
    fn boxed<'a>(self) -> BoxedGenerator<'a, T>
    where
        Self: Sized + Send + Sync + 'a,
    {
        BoxedGenerator {
            inner: Arc::new(self),
        }
    }

    /// Make this generator printable by describing each drawn value with `print`.
    ///
    /// This is the fine-grained control point for printing: the resulting
    /// generator satisfies [`PrintableGenerator`] for any source generator,
    /// with the drawn value's representation produced by `print` — which
    /// receives the value and the [`PrettyPrinter`] to write it to — instead
    /// of the value's `Debug` output. Use it to mask a secret, to print a
    /// type without a useful `Debug` implementation, or to write a
    /// representation that isn't the value at all (the arguments that built
    /// it, say). [`PrettyPrinter::debug`] embeds a component's `Debug`
    /// representation in a larger layout.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// let masked = gs::text().print_with(|_, printer| printer.text("<secret>"));
    /// let pairs = gs::tuples!(gs::integers::<u8>(), gs::text())
    ///     .print_with(|(id, name), printer| {
    ///         printer.group(6, "Entry(", ")", |p| {
    ///             p.debug(id);
    ///             p.separator();
    ///             p.debug(name);
    ///         });
    ///     });
    /// ```
    fn print_with<F>(self, print: F) -> PrintedWith<Self, F>
    where
        Self: Sized,
        F: Fn(&T, &mut PrettyPrinter) + Send + Sync,
    {
        PrintedWith {
            source: self,
            print,
        }
    }

    /// Make this generator printable by printing each drawn value's `Debug`
    /// representation.
    ///
    /// Every value-producing generator in the library (`map`, `just`,
    /// `boxed`, composites) already prints this way, so this is for a
    /// hand-written [`Generator`] implementation that never implemented
    /// [`PrintableGenerator`]: the value is formatted with `{:?}` and laid
    /// out through [`PrettyPrinter::debug`], so large values wrap like
    /// natively printed ones.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    /// use hegel::TestCase;
    ///
    /// struct Evens;
    ///
    /// impl Generator<u32> for Evens {
    ///     fn do_draw(&self, tc: &TestCase) -> u32 {
    ///         tc.draw_silent(gs::integers::<u32>()) & !1
    ///     }
    /// }
    ///
    /// let evens = Evens.print_as_debug();
    /// ```
    fn print_as_debug(self) -> PrintedAsDebug<Self>
    where
        Self: Sized,
        T: std::fmt::Debug,
    {
        PrintedAsDebug { source: self }
    }
}

/// A [`Generator`] that can print each value's representation as it draws it.
///
/// Only printable generators can be passed to [`TestCase::draw`]; a plain
/// [`Generator`] can still be drawn with [`TestCase::draw_silent`]. Most
/// generators in the library are printable — leaves unconditionally,
/// structural combinators (collections, tuples, `optional`, `one_of!`,
/// `filter`, `flat_map`, `recursive`) whenever their component generators
/// are, and value-producing combinators (`map`, `just`, `sampled_from`,
/// `boxed`, composites) whenever the produced type implements `Debug`. For
/// everything else there are [`Generator::print_with`] and
/// [`Generator::print_as_debug`].
///
/// # Contract
///
/// `do_draw_and_print` must draw **exactly** the same choices as
/// [`Generator::do_draw`] — the engine explores with the silent path and
/// replays failures with the printing path, so any divergence makes failures
/// unreplayable. The reliable way to satisfy this is to write the drawing
/// logic once: implement `do_draw_and_print`, and implement
/// [`Generator::do_draw`] as
/// `self.do_draw_and_print(tc, &mut PrettyPrinter::noop())` — the no-op
/// printer discards all output, so both paths run the same body by
/// construction. Guard any work done purely for printing (formatting a
/// value, say) with [`PrettyPrinter::should_print`] to keep the silent path
/// cheap.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot print the values it draws",
    label = "`{Self}` does not implement `PrintableGenerator<{T}>`",
    note = "if `{T}` is your own type and does not implement `Debug`, adding `#[derive(Debug)]` fixes every generator of `{T}` at once",
    note = "otherwise, make this generator printable with `.print_with(|value, printer| ..)`, or with `.print_as_debug()` if `{T}` is `Debug` and the generator is hand-written",
    note = "a `map` whose input draw is printable can report the mapped expression instead with `.print_as_call(\"path::to::function\")`",
    note = "a `-> impl Generator<..>` return type or `.boxed()` erases printability: return `impl PrintableGenerator<..>` instead, and box a printing generator with `.boxed_printable()`",
    note = "or draw without reporting the value via `tc.draw_silent(..)`",
    note = "the `hegel::pretty` module docs walk through the whole printing system"
)]
pub trait PrintableGenerator<T>: Generator<T> {
    /// Produce a value, printing its representation to `printer` as it is
    /// drawn.
    ///
    /// A compositional implementation draws each inner generator with
    /// [`TestCase::draw_and_print`], the framework's one entry point for
    /// printed inner draws, which also opens the span grouping the inner
    /// generator's choices; a generator that merely forwards to an inner
    /// printable generator without printing or drawing anything itself calls
    /// the inner generator's `do_draw_and_print` directly instead, so the
    /// forwarding layer doesn't register as a second region or span.
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T;

    /// Convert this generator into a type-erased boxed printable generator,
    /// as accepted by [`one_of!`](crate::one_of).
    fn boxed_printable<'a>(self) -> BoxedPrintableGenerator<'a, T>
    where
        Self: Sized + Send + Sync + 'a,
    {
        BoxedPrintableGenerator {
            inner: Arc::new(self),
        }
    }
}

/// Draw from `generator` silently, then print the drawn value's `Debug`
/// representation. The shared implementation for every generator that
/// prints by value.
pub(crate) fn draw_and_print_value<T: Debug>(
    generator: &impl Generator<T>,
    tc: &TestCase,
    printer: &mut PrettyPrinter,
) -> T {
    let value = generator.do_draw(tc);
    printer.debug(&value);
    value
}

/// Result of [`Generator::print_with`].
pub struct PrintedWith<G, F> {
    source: G,
    print: F,
}

impl<T, G, F> Generator<T> for PrintedWith<G, F>
where
    G: Generator<T>,
    F: Fn(&T, &mut PrettyPrinter) + Send + Sync,
{
    fn label(&self) -> u64 {
        self.source.label()
    }

    fn do_draw(&self, tc: &TestCase) -> T {
        self.source.do_draw(tc)
    }
}

impl<T, G, F> PrintableGenerator<T> for PrintedWith<G, F>
where
    G: Generator<T>,
    F: Fn(&T, &mut PrettyPrinter) + Send + Sync,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        let value = self.source.do_draw(tc);
        (self.print)(&value, printer);
        value
    }
}

/// Result of [`Generator::print_as_debug`].
pub struct PrintedAsDebug<G> {
    source: G,
}

impl<T, G> Generator<T> for PrintedAsDebug<G>
where
    G: Generator<T>,
    T: Debug,
{
    fn label(&self) -> u64 {
        self.source.label()
    }

    fn do_draw(&self, tc: &TestCase) -> T {
        self.source.do_draw(tc)
    }
}

impl<T, G> PrintableGenerator<T> for PrintedAsDebug<G>
where
    G: Generator<T>,
    T: Debug,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        draw_and_print_value(&self.source, tc, printer)
    }
}

impl<T, G: Generator<T>> Generator<T> for &G {
    fn label(&self) -> u64 {
        (*self).label()
    }

    fn do_draw(&self, tc: &TestCase) -> T {
        (*self).do_draw(tc)
    }
}

impl<T, G: PrintableGenerator<T>> PrintableGenerator<T> for &G {
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        (*self).do_draw_and_print(tc, printer)
    }
}

/// Result of [`Generator::map`].
pub struct Mapped<T, U, F, G> {
    source: G,
    f: Arc<F>,
    label: u64,
    _phantom: PhantomData<fn(T) -> U>,
}

impl<T, U, F, G> Generator<U> for Mapped<T, U, F, G>
where
    G: Generator<T>,
    F: Fn(T) -> U + Send + Sync,
{
    fn label(&self) -> u64 {
        self.label
    }

    fn do_draw(&self, tc: &TestCase) -> U {
        (self.f)(tc.draw_silent(&self.source))
    }
}

impl<T, U, F, G> PrintableGenerator<U> for Mapped<T, U, F, G>
where
    G: Generator<T>,
    F: Fn(T) -> U + Send + Sync,
    U: Debug,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> U {
        draw_and_print_value(self, tc, printer)
    }
}

impl<T, U, F, G> Mapped<T, U, F, G>
where
    G: PrintableGenerator<T>,
    F: Fn(T) -> U + Send + Sync,
{
    /// Make this mapped generator printable by printing `function` applied
    /// to the drawn input: `function(input)`.
    ///
    /// A `map` prints the mapped value's `Debug` output, which for a type
    /// with an opaque or hand-written `Debug` implementation (`3v0` for a
    /// tagged pointer, say) may not say how the value came about. This
    /// prints the drawn input through the source generator instead, wrapped
    /// in a call of `function` — the mapping function's path, which cannot
    /// be recovered from the closure.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// struct KeyData(u64);
    ///
    /// impl KeyData {
    ///     fn from_ffi(value: u64) -> KeyData {
    ///         KeyData(value)
    ///     }
    /// }
    ///
    /// let keys = gs::integers::<u64>()
    ///     .map(KeyData::from_ffi)
    ///     .print_as_call("KeyData::from_ffi");
    /// ```
    ///
    /// A failing draw from `keys` reports `let key = KeyData::from_ffi(3);`
    /// rather than the `Debug` form `let key = 3v0;`.
    pub fn print_as_call(self, function: &str) -> PrintedAsCall<T, U, F, G> {
        if function.is_empty() {
            invalid_argument!("print_as_call requires a non-empty function name");
        }
        PrintedAsCall {
            source: self.source,
            f: self.f,
            open: format!("{function}("),
            label: self.label,
            _phantom: PhantomData,
        }
    }
}

/// Result of [`Mapped::print_as_call`].
pub struct PrintedAsCall<T, U, F, G> {
    source: G,
    f: Arc<F>,
    open: String,
    label: u64,
    _phantom: PhantomData<fn(T) -> U>,
}

impl<T, U, F, G> Generator<U> for PrintedAsCall<T, U, F, G>
where
    G: PrintableGenerator<T>,
    F: Fn(T) -> U + Send + Sync,
{
    fn label(&self) -> u64 {
        self.label
    }

    fn do_draw(&self, tc: &TestCase) -> U {
        self.do_draw_and_print(tc, &mut PrettyPrinter::noop())
    }
}

impl<T, U, F, G> PrintableGenerator<U> for PrintedAsCall<T, U, F, G>
where
    G: PrintableGenerator<T>,
    F: Fn(T) -> U + Send + Sync,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> U {
        printer.begin_group(self.open.chars().count(), &self.open);
        let input = tc.draw_and_print(&self.source, printer);
        printer.end_group(")");
        (self.f)(input)
    }
}

/// Result of [`Generator::flat_map`].
pub struct FlatMapped<T, U, G2, F, G1> {
    source: G1,
    f: F,
    label: u64,
    _phantom: PhantomData<fn(T) -> (U, G2)>,
}

impl<T, U, G2, F, G1> FlatMapped<T, U, G2, F, G1>
where
    G1: Generator<T>,
    F: Fn(T) -> G2 + Send + Sync,
{
    /// The one flat-map body both draw paths run; only how the derived
    /// generator is drawn (silently or printing) is injected.
    fn draw_flat_mapped(&self, tc: &TestCase, draw_next: impl FnOnce(G2, &TestCase) -> U) -> U {
        let intermediate = tc.draw_silent(&self.source);
        let next_gen = (self.f)(intermediate);
        draw_next(next_gen, tc)
    }
}

impl<T, U, G2, F, G1> Generator<U> for FlatMapped<T, U, G2, F, G1>
where
    G1: Generator<T>,
    G2: Generator<U>,
    F: Fn(T) -> G2 + Send + Sync,
{
    fn label(&self) -> u64 {
        self.label
    }

    fn do_draw(&self, tc: &TestCase) -> U {
        self.draw_flat_mapped(tc, |next_gen, tc| tc.draw_silent(next_gen))
    }
}

impl<T, U, G2, F, G1> PrintableGenerator<U> for FlatMapped<T, U, G2, F, G1>
where
    G1: Generator<T>,
    G2: PrintableGenerator<U>,
    F: Fn(T) -> G2 + Send + Sync,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> U {
        self.draw_flat_mapped(tc, |next_gen, tc| tc.draw_and_print(next_gen, printer))
    }
}

/// Result of [`Generator::filter`].
pub struct Filtered<T, F, G> {
    source: G,
    predicate: F,
    label: u64,
    _phantom: PhantomData<fn() -> T>,
}

impl<T, F, G> Filtered<T, F, G>
where
    F: Fn(&T) -> bool + Send + Sync,
{
    /// The one filtering loop both draw paths run: each attempt draws
    /// inside a speculative print region, so a rejected attempt discards
    /// whatever the injected `draw` printed — only the accepted value's
    /// representation survives — and inside a span of its own, closed as
    /// discarded when the attempt is rejected so the shrinker can remove
    /// it. The silent path passes the no-op printer and a print-free
    /// `draw`.
    fn draw_filtered(
        &self,
        tc: &TestCase,
        printer: &mut PrettyPrinter,
        draw: impl Fn(&G, &TestCase, &mut PrettyPrinter) -> T,
    ) -> T {
        for _ in 0..3 {
            tc.start_span(FILTER_ATTEMPT_LABEL);
            let mut speculation = printer.speculate();
            let value = draw(&self.source, tc, speculation.printer());
            if (self.predicate)(&value) {
                speculation.commit();
                tc.stop_span(false);
                return value;
            }
            speculation.abort();
            tc.stop_span(true);
        }
        tc.assume(false);
        unreachable!()
    }
}

impl<T, F, G> Generator<T> for Filtered<T, F, G>
where
    G: Generator<T>,
    F: Fn(&T) -> bool + Send + Sync,
{
    fn label(&self) -> u64 {
        self.label
    }

    fn do_draw(&self, tc: &TestCase) -> T {
        self.draw_filtered(tc, &mut PrettyPrinter::noop(), |source, tc, _| {
            tc.draw_silent(source)
        })
    }
}

impl<T, F, G> PrintableGenerator<T> for Filtered<T, F, G>
where
    G: PrintableGenerator<T>,
    F: Fn(&T) -> bool + Send + Sync,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        self.draw_filtered(tc, printer, |source, tc, printer| {
            tc.draw_and_print(source, printer)
        })
    }
}

/// A type-erased generator with a lifetime parameter.
pub struct BoxedGenerator<'a, T> {
    pub(super) inner: Arc<dyn Generator<T> + Send + Sync + 'a>,
}

impl<T> Clone for BoxedGenerator<'_, T> {
    fn clone(&self) -> Self {
        BoxedGenerator {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<T> Generator<T> for BoxedGenerator<'_, T> {
    fn label(&self) -> u64 {
        self.inner.label()
    }

    fn do_draw(&self, tc: &TestCase) -> T {
        self.inner.do_draw(tc)
    }

    fn boxed<'b>(self) -> BoxedGenerator<'b, T>
    where
        Self: Sized + Send + Sync + 'b,
    {
        BoxedGenerator { inner: self.inner }
    }
}

/// A boxed generator prints by value: the erased generator draws silently
/// and the drawn value's `Debug` representation is printed. A custom
/// printing strategy on the erased generator is not preserved — for that,
/// erase with [`PrintableGenerator::boxed_printable`].
impl<T: Debug> PrintableGenerator<T> for BoxedGenerator<'_, T> {
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        draw_and_print_value(self, tc, printer)
    }
}

/// A type-erased printable generator with a lifetime parameter, as produced
/// by [`PrintableGenerator::boxed_printable`] and consumed by
/// [`one_of!`](crate::one_of).
pub struct BoxedPrintableGenerator<'a, T> {
    inner: Arc<dyn PrintableGenerator<T> + Send + Sync + 'a>,
}

impl<T> Clone for BoxedPrintableGenerator<'_, T> {
    fn clone(&self) -> Self {
        BoxedPrintableGenerator {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<T> Generator<T> for BoxedPrintableGenerator<'_, T> {
    fn label(&self) -> u64 {
        self.inner.label()
    }

    fn do_draw(&self, tc: &TestCase) -> T {
        self.inner.do_draw(tc)
    }
}

impl<T> PrintableGenerator<T> for BoxedPrintableGenerator<'_, T> {
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        self.inner.do_draw_and_print(tc, printer)
    }

    fn boxed_printable<'b>(self) -> BoxedPrintableGenerator<'b, T>
    where
        Self: Sized + Send + Sync + 'b,
    {
        BoxedPrintableGenerator { inner: self.inner }
    }
}