random_constructible/
rand_construct_env.rs

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
crate::ix!();

pub trait RandConstructEnvironment {
    fn create_random<R>() -> R
    where
        R: RandConstructEnumWithEnv,
        Self: RandConstructProbabilityMapProvider<R> + Sized,
    {
        R::random_with_env::<Self>()
    }

    fn create_random_uniform<R>() -> R
    where
        R: RandConstructEnumWithEnv,
        Self: RandConstructProbabilityMapProvider<R> + Sized,
    {
        R::random_uniform_with_env::<Self>()
    }
}

#[macro_export]
macro_rules! rand_construct_env {
    ($provider:ident => $enum:ty { $($variant:ident => $weight:expr),* $(,)? }) => {
        impl $crate::RandConstructProbabilityMapProvider<$enum> for $provider {
            fn probability_map() -> std::sync::Arc<std::collections::HashMap<$enum, f64>> {
                use once_cell::sync::Lazy;
                static PROBABILITY_MAP: Lazy<std::sync::Arc<std::collections::HashMap<$enum, f64>>> = Lazy::new(|| {
                    let mut map = std::collections::HashMap::new();
                    $(
                        map.insert(<$enum>::$variant, $weight);
                    )*
                    std::sync::Arc::new(map)
                });
                std::sync::Arc::clone(&PROBABILITY_MAP)
            }

            fn uniform_probability_map() -> std::sync::Arc<std::collections::HashMap<$enum, f64>> {
                use once_cell::sync::Lazy;
                static UNIFORM_PROBABILITY_MAP: Lazy<std::sync::Arc<std::collections::HashMap<$enum, f64>>> = Lazy::new(|| {
                    let mut map = std::collections::HashMap::new();
                    $(
                        map.insert(<$enum>::$variant, 1.0);
                    )*
                    std::sync::Arc::new(map)
                });
                std::sync::Arc::clone(&UNIFORM_PROBABILITY_MAP)
            }
        }
    };
}