Make uuid generator thread local for tests

This commit is contained in:
Dennis
2022-01-04 10:24:02 +01:00
parent d66992ac94
commit d68e3b9c4e
+21 -10
View File
@@ -6,13 +6,14 @@ use rand_chacha::{
rand_core::{RngCore, SeedableRng}, rand_core::{RngCore, SeedableRng},
ChaCha20Rng, ChaCha20Rng,
}; };
use spin::Mutex; use spin::{Mutex, MutexGuard};
pub use crate::input::InputPreprocessor; pub use crate::input::InputPreprocessor;
use std::{cell::Cell, collections::VecDeque}; use std::{cell::Cell, collections::VecDeque};
pub type ActionList = Vec<Vec<MessageDiscriminant>>; pub type ActionList = Vec<Vec<MessageDiscriminant>>;
#[cfg(not(test))]
static RNG: Mutex<Option<ChaCha20Rng>> = Mutex::new(None); static RNG: Mutex<Option<ChaCha20Rng>> = Mutex::new(None);
// TODO: Add Send + Sync requirement // TODO: Add Send + Sync requirement
@@ -31,19 +32,29 @@ where
thread_local! { thread_local! {
pub static UUID_SEED: Cell<Option<u64>> = Cell::new(None); pub static UUID_SEED: Cell<Option<u64>> = Cell::new(None);
#[cfg(test)]
static LOCAL_RNG: Mutex<Option<ChaCha20Rng>> = Mutex::new(None);
} }
pub fn set_uuid_seed(random_seed: u64) { pub fn set_uuid_seed(random_seed: u64) {
UUID_SEED.with(|seed| seed.set(Some(random_seed))) UUID_SEED.with(|seed| seed.set(Some(random_seed)));
} }
pub fn generate_uuid() -> u64 { pub fn generate_uuid() -> u64 {
let mut lock = RNG.lock(); let init = |mut lock: MutexGuard<Option<ChaCha20Rng>>| {
if lock.is_none() { if lock.is_none() {
UUID_SEED.with(|seed| { UUID_SEED.with(|seed| {
let random_seed = seed.get().expect("random seed not set before editor was initialized"); let random_seed = seed.get().expect("random seed not set before editor was initialized");
*lock = Some(ChaCha20Rng::seed_from_u64(random_seed)); *lock = Some(ChaCha20Rng::seed_from_u64(random_seed));
}) })
} }
lock.as_mut().map(ChaCha20Rng::next_u64).unwrap() lock.as_mut().map(ChaCha20Rng::next_u64).unwrap()
};
(
#[cfg(test)]
LOCAL_RNG.with(|rng| init(rng.lock())),
#[cfg(not(test))]
init(RNG.lock()),
)
.0
} }