Make uuid generator thread local for tests

This commit is contained in:
Dennis
2022-01-04 10:23:27 +01:00
parent d66992ac94
commit d68e3b9c4e

View File

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