Skip to main content

hpx_emulation/emulation/
rand.rs

1use strum::VariantArray;
2
3use super::{Emulation, EmulationOS, EmulationOption};
4
5impl Emulation {
6    /// Returns a random variant of the `Emulation` enum.
7    ///
8    /// This method uses the `rand` crate to select a random variant
9    /// from the `Emulation::VARIANTS` array.
10    ///
11    /// # Examples
12    ///
13    /// ```
14    /// use hpx_emulation::Emulation;
15    ///
16    /// let random_emulation = Emulation::random();
17    /// println!("{:?}", random_emulation);
18    /// ```
19    ///
20    /// # Panics
21    ///
22    /// This method will panic if the `Emulation::VARIANTS` array is empty.
23    #[inline]
24    pub fn random() -> EmulationOption {
25        let emulation = Emulation::VARIANTS;
26        let emulation_os = EmulationOS::VARIANTS;
27        let rand = rand::random::<u64>() as usize;
28        EmulationOption::builder()
29            .emulation(emulation[rand % emulation.len()])
30            .emulation_os(emulation_os[rand % emulation_os.len()])
31            .build()
32    }
33}
34
35#[cfg(test)]
36mod tests {
37    use std::{sync::Arc, thread};
38
39    use parking_lot::Mutex;
40
41    use super::*;
42
43    #[test]
44    fn test_concurrent_get_random_emulation() {
45        const THREAD_COUNT: usize = 10;
46        const ITERATIONS: usize = 100;
47
48        let results = Arc::new(Mutex::new(Vec::new()));
49
50        let mut handles = vec![];
51
52        for _ in 0..THREAD_COUNT {
53            let results = Arc::clone(&results);
54            let handle = thread::spawn(move || {
55                for _ in 0..ITERATIONS {
56                    let emulation = Emulation::random();
57                    let mut results = results.lock();
58                    results.push(emulation);
59                }
60            });
61            handles.push(handle);
62        }
63
64        for handle in handles {
65            handle.join().expect("worker thread panicked");
66        }
67
68        let results = results.lock();
69        println!("Total results: {}", results.len());
70    }
71}