Skip to content

Commit d68e3b9

Browse files
committed
Make uuid generator thread local for tests
1 parent d66992a commit d68e3b9

File tree

1 file changed

+21
-10
lines changed
  • editor/src/communication

1 file changed

+21
-10
lines changed

editor/src/communication/mod.rs

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@ use rand_chacha::{
66
rand_core::{RngCore, SeedableRng},
77
ChaCha20Rng,
88
};
9-
use spin::Mutex;
9+
use spin::{Mutex, MutexGuard};
1010

1111
pub use crate::input::InputPreprocessor;
1212
use std::{cell::Cell, collections::VecDeque};
1313

1414
pub type ActionList = Vec<Vec<MessageDiscriminant>>;
1515

16+
#[cfg(not(test))]
1617
static RNG: Mutex<Option<ChaCha20Rng>> = Mutex::new(None);
1718

1819
// TODO: Add Send + Sync requirement
@@ -31,19 +32,29 @@ where
3132

3233
thread_local! {
3334
pub static UUID_SEED: Cell<Option<u64>> = Cell::new(None);
35+
#[cfg(test)]
36+
static LOCAL_RNG: Mutex<Option<ChaCha20Rng>> = Mutex::new(None);
3437
}
3538

3639
pub fn set_uuid_seed(random_seed: u64) {
37-
UUID_SEED.with(|seed| seed.set(Some(random_seed)))
40+
UUID_SEED.with(|seed| seed.set(Some(random_seed)));
3841
}
3942

4043
pub fn generate_uuid() -> u64 {
41-
let mut lock = RNG.lock();
42-
if lock.is_none() {
43-
UUID_SEED.with(|seed| {
44-
let random_seed = seed.get().expect("random seed not set before editor was initialized");
45-
*lock = Some(ChaCha20Rng::seed_from_u64(random_seed));
46-
})
47-
}
48-
lock.as_mut().map(ChaCha20Rng::next_u64).unwrap()
44+
let init = |mut lock: MutexGuard<Option<ChaCha20Rng>>| {
45+
if lock.is_none() {
46+
UUID_SEED.with(|seed| {
47+
let random_seed = seed.get().expect("random seed not set before editor was initialized");
48+
*lock = Some(ChaCha20Rng::seed_from_u64(random_seed));
49+
})
50+
}
51+
lock.as_mut().map(ChaCha20Rng::next_u64).unwrap()
52+
};
53+
(
54+
#[cfg(test)]
55+
LOCAL_RNG.with(|rng| init(rng.lock())),
56+
#[cfg(not(test))]
57+
init(RNG.lock()),
58+
)
59+
.0
4960
}

0 commit comments

Comments
 (0)