Skip to main content

bast3st_eval/spec/
random_generation.rs

1use serde::{Deserialize, Serialize};
2
3/// This specifies if e. g. a test is allowed to generate new random numbers
4/// in addition to (maybe) predefined ones.
5///
6/// _This is independent of predefined (fixed) random numbers and only influences
7/// if the test is stopped if it requests more random numbers then provided or
8/// if the request is satisfied._
9#[derive(Debug, PartialEq, Serialize, Deserialize, Default, Clone)]
10#[serde(from = "RandomGenerationRepr", into = "RandomGenerationRepr")]
11pub enum RandomGeneration {
12    /// (default) disable all random number generation capabilities.
13    #[default]
14    Disabled,
15    /// enable generation of new random numbers
16    Enabled,
17    /// enable generation of new random numbers and use the specified
18    /// seed for reproducible results (as long as the implementation doesn't change)
19    ///
20    /// See [`rand::SeedableRng::seed_from_u64`](https://docs.rs/rand/latest/rand/trait.SeedableRng.html#method.seed_from_u64)
21    /// for the function that will likely be used with this value
22    EnabledWithSeed(u64),
23}
24
25#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
26#[serde(untagged)]
27enum RandomGenerationRepr {
28    IsEnabled(bool),
29    Seed(u64),
30}
31impl From<RandomGeneration> for RandomGenerationRepr {
32    fn from(value: RandomGeneration) -> Self {
33        match value {
34            RandomGeneration::EnabledWithSeed(s) => Self::Seed(s),
35            RandomGeneration::Enabled => Self::IsEnabled(true),
36            RandomGeneration::Disabled => Self::IsEnabled(false),
37        }
38    }
39}
40impl From<RandomGenerationRepr> for RandomGeneration {
41    fn from(value: RandomGenerationRepr) -> Self {
42        match value {
43            RandomGenerationRepr::Seed(s) => Self::EnabledWithSeed(s),
44            RandomGenerationRepr::IsEnabled(true) => Self::Enabled,
45            RandomGenerationRepr::IsEnabled(false) => Self::Disabled,
46        }
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::RandomGeneration;
53    #[test]
54    fn test_random_generation_serde() {
55        let enabled: RandomGeneration = serde_json::from_str("true").unwrap();
56        let disabled: RandomGeneration = serde_json::from_str("false").unwrap();
57        let seed: RandomGeneration = serde_json::from_str("42").unwrap();
58        assert_eq!(RandomGeneration::Enabled, enabled);
59        assert_eq!(RandomGeneration::Disabled, disabled);
60        assert_eq!(RandomGeneration::EnabledWithSeed(42), seed);
61    }
62}