-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
64 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
use std::sync::atomic::{AtomicUsize, Ordering}; | ||
|
||
#[derive(Copy, Clone, PartialEq, Eq, Debug)] | ||
// We use usize here because that is the largest `Atomic` we want to require | ||
/// A unique identifier for a [`super::World`]. | ||
pub struct WorldId(usize); | ||
|
||
/// The next [`WorldId`]. | ||
static MAX_WORLD_ID: AtomicUsize = AtomicUsize::new(0); | ||
|
||
impl WorldId { | ||
/// Create a new, unique [`WorldId`] | ||
/// | ||
/// # Panics | ||
/// If [`usize::MAX`] [`WorldId`]s have been created | ||
// This could be kept crate private, but external crates may wish to create some for their tests | ||
pub fn new() -> Self { | ||
let id = MAX_WORLD_ID | ||
// We use `Relaxed` here since this atomic only needs to be consistent with itself | ||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |val| { | ||
val.checked_add(1) | ||
}) | ||
.expect("More `bevy` `World`s have been created than is supported"); | ||
WorldId(id) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn world_ids_unique() { | ||
let ids = std::iter::repeat_with(WorldId::new) | ||
.take(50) | ||
.collect::<Vec<_>>(); | ||
for (i, &id1) in ids.iter().enumerate() { | ||
// For the first element, i is 0 - so skip 1 | ||
for &id2 in ids.iter().skip(i + 1) { | ||
assert_ne!(id1, id2, "WorldIds should not repeat"); | ||
} | ||
} | ||
} | ||
|
||
// We cannot use this test as-is, as it causes other tests to panic due to using the same atomic variable. | ||
// #[test] | ||
// #[should_panic] | ||
// fn panic_on_overflow() { | ||
// MAX_WORLD_ID.store(usize::MAX - 50, Ordering::Relaxed); | ||
// std::iter::repeat_with(WorldId::new) | ||
// .take(500) | ||
// .for_each(|_| ()); | ||
// } | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters