random_constructible/
rand_construct_enum.rs

1crate::ix!();
2
3pub trait RandConstructProbabilityMapProvider<R: Eq + Hash + Sized> {
4    fn probability_map() -> Arc<HashMap<R, f64>>;
5    fn uniform_probability_map() -> Arc<HashMap<R, f64>>;
6}
7
8pub trait RandConstructEnumWithEnv: Sized + Clone + Eq + Hash {
9
10    fn random_with_env<P: RandConstructProbabilityMapProvider<Self>>() -> Self {
11        let mut rng = rand::thread_rng();
12        Self::sample_from_provider::<P,_>(&mut rng)
13    }
14
15    fn random_uniform_with_env<P: RandConstructProbabilityMapProvider<Self>>() -> Self {
16        let mut rng = rand::thread_rng();
17        Self::sample_uniformly_from_provider::<P,_>(&mut rng)
18    }
19
20    // Helper function to sample from a provider using the given RNG
21    fn sample_from_provider<P: RandConstructProbabilityMapProvider<Self>, RNG: Rng + ?Sized>(rng: &mut RNG) -> Self {
22        let probs = P::probability_map();
23        sample_variants_with_probabilities(rng,&probs)
24    }
25
26    fn sample_uniformly_from_provider<P: RandConstructProbabilityMapProvider<Self>, RNG: Rng + ?Sized>(rng: &mut RNG) -> Self {
27        let probs = P::uniform_probability_map();
28        sample_variants_with_probabilities(rng,&probs)
29    }
30}
31
32pub trait RandConstructEnum: Clone + Default + Eq + Hash + Sized {
33
34    //-----------------------------------------------------------------[provided by the proc macro crate]
35    fn default_weight(&self) -> f64;
36
37    fn all_variants() -> Vec<Self>;
38
39    // this is implemented in the proc macro so that we by default get once_cell behavior
40    fn create_default_probability_map() -> Arc<HashMap<Self,f64>>;
41
42    //-----------------------------------------------------------------[main user-interface]
43    fn random_variant() -> Self {
44        let map = Self::create_default_probability_map();
45        let mut rng = rand::thread_rng();
46        sample_variants_with_probabilities(&mut rng, &map)
47    }
48
49    fn uniform_variant() -> Self {
50        let variants = Self::all_variants();
51        let mut rng = rand::thread_rng();
52        variants.choose(&mut rng).unwrap().clone()
53    }
54
55    //-----------------------------------------------------------------[helper-methods]
56
57    fn random_enum_value_with_rng<RNG: Rng + ?Sized>(rng: &mut RNG) -> Self {
58        let map = Self::create_default_probability_map();
59        sample_variants_with_probabilities(rng, &map)
60    }
61}