Skip to main content

proptest_ext/
lib.rs

1// Copyright (c) The cargo-guppy Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4// Referenced so that Cargo's unused_dependencies lint sees the workspace-hack
5// dependency as used.
6use guppy_workspace_hack as _;
7
8use proptest::{
9    strategy::{Strategy, ValueTree},
10    test_runner::{Config, RngAlgorithm, TestRng, TestRunner},
11};
12use std::hash::{Hash, Hasher};
13use twox_hash::XxHash64;
14
15/// Context for generating single values out of strategies.
16///
17/// Proptest is designed to be built around "value trees", which represent a spectrum from complex
18/// values to simpler ones. But in some contexts, like benchmarking or generating corpuses, one just
19/// wants a single value. This is a convenience struct for that.
20#[derive(Debug, Default)]
21pub struct ValueGenerator {
22    runner: TestRunner,
23}
24
25impl ValueGenerator {
26    /// Creates a new value generator with the default RNG.
27    pub fn new() -> Self {
28        Self {
29            runner: TestRunner::new(Config::default()),
30        }
31    }
32
33    /// Creates a new value generator with a deterministic RNG.
34    ///
35    /// This generator has a hardcoded seed, so its results are predictable across test runs.
36    /// However, a new proptest version may change the seed.
37    pub fn deterministic() -> Self {
38        Self {
39            runner: TestRunner::deterministic(),
40        }
41    }
42
43    /// Creates a new value generator from the given seed.
44    ///
45    /// This generator is typically used with a hardcoded seed that is keyed on the input data
46    /// somehow. For example, for a test fixture it may be the name of the fixture.
47    pub fn from_seed(seed: impl Hash) -> Self {
48        // Convert the input seed into a 32-byte hash.
49        let mut rng_seed = [0u8; 32];
50        for hash_seed in 0usize..=3 {
51            let mut hasher = XxHash64::with_seed(hash_seed as u64);
52            seed.hash(&mut hasher);
53            rng_seed[hash_seed..(hash_seed + 8)].copy_from_slice(&hasher.finish().to_be_bytes());
54        }
55
56        Self {
57            runner: TestRunner::new_with_rng(
58                Config::default(),
59                TestRng::from_seed(RngAlgorithm::default(), &rng_seed),
60            ),
61        }
62    }
63
64    /// Does a "partial clone" of the `ValueGenerator`, creating a new independent but deterministic
65    /// RNG.
66    pub fn partial_clone(&mut self) -> Self {
67        Self {
68            runner: TestRunner::new_with_rng(Config::default(), self.runner.new_rng()),
69        }
70    }
71
72    /// Generates a single value for this strategy.
73    ///
74    /// Panics if generating the new value fails. The only situation in which this can happen is if
75    /// generating the value causes too many internal rejects.
76    pub fn generate<S: Strategy>(&mut self, strategy: S) -> S::Value {
77        strategy
78            .new_tree(&mut self.runner)
79            .expect("creating a new value should succeed")
80            .current()
81    }
82}