random_constructible/
rand_construct_env.rs

1// ---------------- [ File: random-constructible/src/rand_construct_env.rs ]
2crate::ix!();
3
4pub trait RandConstructEnvironment {
5    fn create_random<R>() -> R
6    where
7        R: RandConstructEnumWithEnv,
8        Self: RandConstructProbabilityMapProvider<R> + Sized,
9    {
10        R::random_with_env::<Self>()
11    }
12
13    fn create_random_uniform<R>() -> R
14    where
15        R: RandConstructEnumWithEnv,
16        Self: RandConstructProbabilityMapProvider<R> + Sized,
17    {
18        R::random_uniform_with_env::<Self>()
19    }
20}
21
22#[macro_export]
23macro_rules! rand_construct_env {
24    ($provider:ident => $enum:ty { $($variant:ident => $weight:expr),* $(,)? }) => {
25        impl $crate::RandConstructProbabilityMapProvider<$enum> for $provider {
26            fn probability_map() -> std::sync::Arc<std::collections::HashMap<$enum, f64>> {
27                use once_cell::sync::Lazy;
28                static PROBABILITY_MAP: Lazy<std::sync::Arc<std::collections::HashMap<$enum, f64>>> = Lazy::new(|| {
29                    let mut map = std::collections::HashMap::new();
30                    $(
31                        map.insert(<$enum>::$variant, $weight);
32                    )*
33                    std::sync::Arc::new(map)
34                });
35                std::sync::Arc::clone(&PROBABILITY_MAP)
36            }
37
38            fn uniform_probability_map() -> std::sync::Arc<std::collections::HashMap<$enum, f64>> {
39                use once_cell::sync::Lazy;
40                static UNIFORM_PROBABILITY_MAP: Lazy<std::sync::Arc<std::collections::HashMap<$enum, f64>>> = Lazy::new(|| {
41                    let mut map = std::collections::HashMap::new();
42                    $(
43                        map.insert(<$enum>::$variant, 1.0);
44                    )*
45                    std::sync::Arc::new(map)
46                });
47                std::sync::Arc::clone(&UNIFORM_PROBABILITY_MAP)
48            }
49        }
50    };
51}