#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![allow(unsafe_code)]
#![doc(
html_logo_url = "https://bevyengine.org/assets/icon.png",
html_favicon_url = "https://bevyengine.org/assets/icon.png"
)]
#[allow(missing_docs)]
pub mod prelude {
pub use crate::default;
}
pub mod futures;
mod short_names;
pub use short_names::get_short_name;
pub mod synccell;
pub mod syncunsafecell;
mod cow_arc;
mod default;
mod once;
mod parallel_queue;
pub use ahash::{AHasher, RandomState};
pub use bevy_utils_proc_macros::*;
pub use cow_arc::*;
pub use default::default;
pub use hashbrown;
pub use parallel_queue::*;
pub use tracing;
pub use web_time::{Duration, Instant, SystemTime, SystemTimeError, TryFromFloatSecsError};
use hashbrown::hash_map::RawEntryMut;
use std::{
any::TypeId,
fmt::Debug,
hash::{BuildHasher, BuildHasherDefault, Hash, Hasher},
marker::PhantomData,
mem::ManuallyDrop,
ops::Deref,
};
#[cfg(not(target_arch = "wasm32"))]
mod conditional_send {
pub trait ConditionalSend: Send {}
impl<T: Send> ConditionalSend for T {}
}
#[cfg(target_arch = "wasm32")]
#[allow(missing_docs)]
mod conditional_send {
pub trait ConditionalSend {}
impl<T> ConditionalSend for T {}
}
pub use conditional_send::*;
pub trait ConditionalSendFuture: std::future::Future + ConditionalSend {}
impl<T: std::future::Future + ConditionalSend> ConditionalSendFuture for T {}
pub type BoxedFuture<'a, T> = std::pin::Pin<Box<dyn ConditionalSendFuture<Output = T> + 'a>>;
pub type Entry<'a, K, V, S = BuildHasherDefault<AHasher>> = hashbrown::hash_map::Entry<'a, K, V, S>;
#[derive(Debug, Clone, Default)]
pub struct FixedState;
impl BuildHasher for FixedState {
type Hasher = AHasher;
#[inline]
fn build_hasher(&self) -> AHasher {
RandomState::with_seeds(
0b10010101111011100000010011000100,
0b00000011001001101011001001111000,
0b11001111011010110111100010110101,
0b00000100001111100011010011010101,
)
.build_hasher()
}
}
pub type HashMap<K, V> = hashbrown::HashMap<K, V, BuildHasherDefault<AHasher>>;
#[deprecated(
note = "Will be required to use the hash library of your choice. Alias for: hashbrown::HashMap<K, V, FixedState>"
)]
pub type StableHashMap<K, V> = hashbrown::HashMap<K, V, FixedState>;
pub type HashSet<K> = hashbrown::HashSet<K, BuildHasherDefault<AHasher>>;
#[deprecated(
note = "Will be required to use the hash library of your choice. Alias for: hashbrown::HashSet<K, FixedState>"
)]
pub type StableHashSet<K> = hashbrown::HashSet<K, FixedState>;
pub struct Hashed<V, H = FixedState> {
hash: u64,
value: V,
marker: PhantomData<H>,
}
impl<V: Hash, H: BuildHasher + Default> Hashed<V, H> {
pub fn new(value: V) -> Self {
Self {
hash: H::default().hash_one(&value),
value,
marker: PhantomData,
}
}
#[inline]
pub fn hash(&self) -> u64 {
self.hash
}
}
impl<V, H> Hash for Hashed<V, H> {
#[inline]
fn hash<R: Hasher>(&self, state: &mut R) {
state.write_u64(self.hash);
}
}
impl<V, H> Deref for Hashed<V, H> {
type Target = V;
#[inline]
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<V: PartialEq, H> PartialEq for Hashed<V, H> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash && self.value.eq(&other.value)
}
}
impl<V: Debug, H> Debug for Hashed<V, H> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Hashed")
.field("hash", &self.hash)
.field("value", &self.value)
.finish()
}
}
impl<V: Clone, H> Clone for Hashed<V, H> {
#[inline]
fn clone(&self) -> Self {
Self {
hash: self.hash,
value: self.value.clone(),
marker: PhantomData,
}
}
}
impl<V: Eq, H> Eq for Hashed<V, H> {}
#[derive(Default, Clone)]
pub struct PassHash;
impl BuildHasher for PassHash {
type Hasher = PassHasher;
fn build_hasher(&self) -> Self::Hasher {
PassHasher::default()
}
}
#[derive(Debug, Default)]
pub struct PassHasher {
hash: u64,
}
impl Hasher for PassHasher {
#[inline]
fn finish(&self) -> u64 {
self.hash
}
fn write(&mut self, _bytes: &[u8]) {
panic!("can only hash u64 using PassHasher");
}
#[inline]
fn write_u64(&mut self, i: u64) {
self.hash = i;
}
}
pub type PreHashMap<K, V> = hashbrown::HashMap<Hashed<K>, V, PassHash>;
pub trait PreHashMapExt<K, V> {
fn get_or_insert_with<F: FnOnce() -> V>(&mut self, key: &Hashed<K>, func: F) -> &mut V;
}
impl<K: Hash + Eq + PartialEq + Clone, V> PreHashMapExt<K, V> for PreHashMap<K, V> {
#[inline]
fn get_or_insert_with<F: FnOnce() -> V>(&mut self, key: &Hashed<K>, func: F) -> &mut V {
let entry = self
.raw_entry_mut()
.from_key_hashed_nocheck(key.hash(), key);
match entry {
RawEntryMut::Occupied(entry) => entry.into_mut(),
RawEntryMut::Vacant(entry) => {
let (_, value) = entry.insert_hashed_nocheck(key.hash(), key.clone(), func());
value
}
}
}
}
#[derive(Default, Clone)]
pub struct EntityHash;
impl BuildHasher for EntityHash {
type Hasher = EntityHasher;
fn build_hasher(&self) -> Self::Hasher {
EntityHasher::default()
}
}
#[derive(Debug, Default)]
pub struct EntityHasher {
hash: u64,
}
impl Hasher for EntityHasher {
#[inline]
fn finish(&self) -> u64 {
self.hash
}
fn write(&mut self, _bytes: &[u8]) {
panic!("can only hash u64 using EntityHasher");
}
#[inline]
fn write_u64(&mut self, bits: u64) {
const UPPER_PHI: u64 = 0x9e37_79b9_0000_0001;
self.hash = bits.wrapping_mul(UPPER_PHI);
}
}
pub type EntityHashMap<K, V> = hashbrown::HashMap<K, V, EntityHash>;
pub type EntityHashSet<T> = hashbrown::HashSet<T, EntityHash>;
pub type TypeIdMap<V> = hashbrown::HashMap<TypeId, V, NoOpHash>;
#[derive(Clone, Default)]
pub struct NoOpHash;
impl BuildHasher for NoOpHash {
type Hasher = NoOpHasher;
fn build_hasher(&self) -> Self::Hasher {
NoOpHasher(0)
}
}
#[doc(hidden)]
pub struct NoOpHasher(u64);
impl std::hash::Hasher for NoOpHasher {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
self.0 = bytes.iter().fold(self.0, |hash, b| {
hash.rotate_left(8).wrapping_add(*b as u64)
});
}
#[inline]
fn write_u64(&mut self, i: u64) {
self.0 = i;
}
}
pub struct OnDrop<F: FnOnce()> {
callback: ManuallyDrop<F>,
}
impl<F: FnOnce()> OnDrop<F> {
pub fn new(callback: F) -> Self {
Self {
callback: ManuallyDrop::new(callback),
}
}
}
impl<F: FnOnce()> Drop for OnDrop<F> {
fn drop(&mut self) {
let callback = unsafe { ManuallyDrop::take(&mut self.callback) };
callback();
}
}
pub fn info<T: Debug>(data: T) {
tracing::info!("{:?}", data);
}
pub fn dbg<T: Debug>(data: T) {
tracing::debug!("{:?}", data);
}
pub fn warn<E: Debug>(result: Result<(), E>) {
if let Err(warn) = result {
tracing::warn!("{:?}", warn);
}
}
pub fn error<E: Debug>(result: Result<(), E>) {
if let Err(error) = result {
tracing::error!("{:?}", error);
}
}
#[macro_export]
macro_rules! detailed_trace {
($($tts:tt)*) => {
if cfg!(detailed_trace) {
bevy_utils::tracing::trace!($($tts)*);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use static_assertions::assert_impl_all;
assert_impl_all!(PreHashMap::<u64, usize>: Clone);
#[test]
fn fast_typeid_hash() {
struct Hasher;
impl std::hash::Hasher for Hasher {
fn finish(&self) -> u64 {
0
}
fn write(&mut self, _: &[u8]) {
panic!("Hashing of std::any::TypeId changed");
}
fn write_u64(&mut self, _: u64) {}
}
std::hash::Hash::hash(&TypeId::of::<()>(), &mut Hasher);
}
#[test]
fn stable_hash_within_same_program_execution() {
let mut map_1 = HashMap::new();
let mut map_2 = HashMap::new();
for i in 1..10 {
map_1.insert(i, i);
map_2.insert(i, i);
}
assert_eq!(
map_1.iter().collect::<Vec<_>>(),
map_2.iter().collect::<Vec<_>>()
);
}
}