Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 10:29:08 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions

31
vendor/bevy_utils/src/default.rs vendored Normal file
View File

@@ -0,0 +1,31 @@
/// An ergonomic abbreviation for [`Default::default()`] to make initializing structs easier.
///
/// This is especially helpful when combined with ["struct update syntax"](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax).
/// ```
/// use bevy_utils::default;
///
/// #[derive(Default)]
/// struct Foo {
/// a: usize,
/// b: usize,
/// c: usize,
/// }
///
/// // Normally you would initialize a struct with defaults using "struct update syntax"
/// // combined with `Default::default()`. This example sets `Foo::bar` to 10 and the remaining
/// // values to their defaults.
/// let foo = Foo {
/// a: 10,
/// ..Default::default()
/// };
///
/// // But now you can do this, which is equivalent:
/// let foo = Foo {
/// a: 10,
/// ..default()
/// };
/// ```
#[inline]
pub fn default<T: Default>() -> T {
Default::default()
}

189
vendor/bevy_utils/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,189 @@
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![doc(
html_logo_url = "https://bevyengine.org/assets/icon.png",
html_favicon_url = "https://bevyengine.org/assets/icon.png"
)]
#![no_std]
//! General utilities for first-party [Bevy] engine crates.
//!
//! [Bevy]: https://bevyengine.org/
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "alloc")]
extern crate alloc;
/// The utilities prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
pub use crate::default;
}
pub mod synccell;
pub mod syncunsafecell;
mod default;
mod once;
#[cfg(feature = "std")]
mod parallel_queue;
#[doc(hidden)]
pub use once::OnceFlag;
pub use default::default;
#[cfg(feature = "std")]
pub use parallel_queue::*;
use core::mem::ManuallyDrop;
#[cfg(feature = "alloc")]
use {
bevy_platform::{
collections::HashMap,
hash::{Hashed, NoOpHash, PassHash},
},
core::{any::TypeId, hash::Hash},
};
/// A [`HashMap`] pre-configured to use [`Hashed`] keys and [`PassHash`] passthrough hashing.
/// Iteration order only depends on the order of insertions and deletions.
#[cfg(feature = "alloc")]
pub type PreHashMap<K, V> = HashMap<Hashed<K>, V, PassHash>;
/// Extension methods intended to add functionality to [`PreHashMap`].
#[cfg(feature = "alloc")]
pub trait PreHashMapExt<K, V> {
/// Tries to get or insert the value for the given `key` using the pre-computed hash first.
/// If the [`PreHashMap`] does not already contain the `key`, it will clone it and insert
/// the value returned by `func`.
fn get_or_insert_with<F: FnOnce() -> V>(&mut self, key: &Hashed<K>, func: F) -> &mut V;
}
#[cfg(feature = "alloc")]
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 {
use bevy_platform::collections::hash_map::RawEntryMut;
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
}
}
}
}
/// A specialized hashmap type with Key of [`TypeId`]
/// Iteration order only depends on the order of insertions and deletions.
#[cfg(feature = "alloc")]
pub type TypeIdMap<V> = HashMap<TypeId, V, NoOpHash>;
/// A type which calls a function when dropped.
/// This can be used to ensure that cleanup code is run even in case of a panic.
///
/// Note that this only works for panics that [unwind](https://doc.rust-lang.org/nomicon/unwinding.html)
/// -- any code within `OnDrop` will be skipped if a panic does not unwind.
/// In most cases, this will just work.
///
/// # Examples
///
/// ```
/// # use bevy_utils::OnDrop;
/// # fn test_panic(do_panic: bool, log: impl FnOnce(&str)) {
/// // This will print a message when the variable `_catch` gets dropped,
/// // even if a panic occurs before we reach the end of this scope.
/// // This is similar to a `try ... catch` block in languages such as C++.
/// let _catch = OnDrop::new(|| log("Oops, a panic occurred and this function didn't complete!"));
///
/// // Some code that may panic...
/// // ...
/// # if do_panic { panic!() }
///
/// // Make sure the message only gets printed if a panic occurs.
/// // If we remove this line, then the message will be printed regardless of whether a panic occurs
/// // -- similar to a `try ... finally` block.
/// core::mem::forget(_catch);
/// # }
/// #
/// # test_panic(false, |_| unreachable!());
/// # let mut did_log = false;
/// # std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
/// # test_panic(true, |_| did_log = true);
/// # }));
/// # assert!(did_log);
/// ```
pub struct OnDrop<F: FnOnce()> {
callback: ManuallyDrop<F>,
}
impl<F: FnOnce()> OnDrop<F> {
/// Returns an object that will invoke the specified callback when dropped.
pub fn new(callback: F) -> Self {
Self {
callback: ManuallyDrop::new(callback),
}
}
}
impl<F: FnOnce()> Drop for OnDrop<F> {
fn drop(&mut self) {
#![expect(
unsafe_code,
reason = "Taking from a ManuallyDrop requires unsafe code."
)]
// SAFETY: We may move out of `self`, since this instance can never be observed after it's dropped.
let callback = unsafe { ManuallyDrop::take(&mut self.callback) };
callback();
}
}
#[cfg(test)]
mod tests {
use super::*;
use static_assertions::assert_impl_all;
// Check that the HashMaps are Clone if the key/values are Clone
assert_impl_all!(PreHashMap::<u64, usize>: Clone);
#[test]
fn fast_typeid_hash() {
struct Hasher;
impl core::hash::Hasher for Hasher {
fn finish(&self) -> u64 {
0
}
fn write(&mut self, _: &[u8]) {
panic!("Hashing of core::any::TypeId changed");
}
fn write_u64(&mut self, _: u64) {}
}
Hash::hash(&TypeId::of::<()>(), &mut Hasher);
}
#[cfg(feature = "alloc")]
#[test]
fn stable_hash_within_same_program_execution() {
use alloc::vec::Vec;
let mut map_1 = <HashMap<_, _>>::default();
let mut map_2 = <HashMap<_, _>>::default();
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<_>>()
);
}
}

35
vendor/bevy_utils/src/once.rs vendored Normal file
View File

@@ -0,0 +1,35 @@
use bevy_platform::sync::atomic::{AtomicBool, Ordering};
/// Wrapper around an [`AtomicBool`], abstracting the backing implementation and
/// ordering considerations.
#[doc(hidden)]
pub struct OnceFlag(AtomicBool);
impl OnceFlag {
/// Create a new flag in the unset state.
pub const fn new() -> Self {
Self(AtomicBool::new(true))
}
/// Sets this flag. Will return `true` if this flag hasn't been set before.
pub fn set(&self) -> bool {
self.0.swap(false, Ordering::Relaxed)
}
}
impl Default for OnceFlag {
fn default() -> Self {
Self::new()
}
}
/// Call some expression only once per call site.
#[macro_export]
macro_rules! once {
($expression:expr) => {{
static SHOULD_FIRE: $crate::OnceFlag = $crate::OnceFlag::new();
if SHOULD_FIRE.set() {
$expression;
}
}};
}

77
vendor/bevy_utils/src/parallel_queue.rs vendored Normal file
View File

@@ -0,0 +1,77 @@
use alloc::vec::Vec;
use core::{cell::RefCell, ops::DerefMut};
use thread_local::ThreadLocal;
/// A cohesive set of thread-local values of a given type.
///
/// Mutable references can be fetched if `T: Default` via [`Parallel::scope`].
#[derive(Default)]
pub struct Parallel<T: Send> {
locals: ThreadLocal<RefCell<T>>,
}
/// A scope guard of a `Parallel`, when this struct is dropped ,the value will writeback to its `Parallel`
impl<T: Send> Parallel<T> {
/// Gets a mutable iterator over all of the per-thread queues.
pub fn iter_mut(&mut self) -> impl Iterator<Item = &'_ mut T> {
self.locals.iter_mut().map(RefCell::get_mut)
}
/// Clears all of the stored thread local values.
pub fn clear(&mut self) {
self.locals.clear();
}
}
impl<T: Default + Send> Parallel<T> {
/// Retrieves the thread-local value for the current thread and runs `f` on it.
///
/// If there is no thread-local value, it will be initialized to its default.
pub fn scope<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
let mut cell = self.locals.get_or_default().borrow_mut();
let ret = f(cell.deref_mut());
ret
}
/// Mutably borrows the thread-local value.
///
/// If there is no thread-local value, it will be initialized to it's default.
pub fn borrow_local_mut(&self) -> impl DerefMut<Target = T> + '_ {
self.locals.get_or_default().borrow_mut()
}
}
impl<T, I> Parallel<I>
where
I: IntoIterator<Item = T> + Default + Send + 'static,
{
/// Drains all enqueued items from all threads and returns an iterator over them.
///
/// Unlike [`Vec::drain`], this will piecemeal remove chunks of the data stored.
/// If iteration is terminated part way, the rest of the enqueued items in the same
/// chunk will be dropped, and the rest of the undrained elements will remain.
///
/// The ordering is not guaranteed.
pub fn drain(&mut self) -> impl Iterator<Item = T> + '_ {
self.locals.iter_mut().flat_map(|item| item.take())
}
}
#[cfg(feature = "alloc")]
impl<T: Send> Parallel<Vec<T>> {
/// Collect all enqueued items from all threads and appends them to the end of a
/// single Vec.
///
/// The ordering is not guaranteed.
pub fn drain_into(&mut self, out: &mut Vec<T>) {
let size = self
.locals
.iter_mut()
.map(|queue| queue.get_mut().len())
.sum();
out.reserve(size);
for queue in self.locals.iter_mut() {
out.append(queue.get_mut());
}
}
}

55
vendor/bevy_utils/src/synccell.rs vendored Normal file
View File

@@ -0,0 +1,55 @@
#![expect(unsafe_code, reason = "SyncCell requires unsafe code.")]
//! A reimplementation of the currently unstable [`std::sync::Exclusive`]
//!
//! [`std::sync::Exclusive`]: https://doc.rust-lang.org/nightly/std/sync/struct.Exclusive.html
use core::ptr;
/// See [`Exclusive`](https://github.com/rust-lang/rust/issues/98407) for stdlib's upcoming implementation,
/// which should replace this one entirely.
///
/// Provides a wrapper that allows making any type unconditionally [`Sync`] by only providing mutable access.
#[repr(transparent)]
pub struct SyncCell<T: ?Sized> {
inner: T,
}
impl<T: Sized> SyncCell<T> {
/// Construct a new instance of a `SyncCell` from the given value.
pub fn new(inner: T) -> Self {
Self { inner }
}
/// Deconstruct this `SyncCell` into its inner value.
pub fn to_inner(Self { inner }: Self) -> T {
inner
}
}
impl<T: ?Sized> SyncCell<T> {
/// Get a reference to this `SyncCell`'s inner value.
pub fn get(&mut self) -> &mut T {
&mut self.inner
}
/// For types that implement [`Sync`], get shared access to this `SyncCell`'s inner value.
pub fn read(&self) -> &T
where
T: Sync,
{
&self.inner
}
/// Build a mutable reference to a `SyncCell` from a mutable reference
/// to its inner value, to skip constructing with [`new()`](SyncCell::new()).
pub fn from_mut(r: &'_ mut T) -> &'_ mut SyncCell<T> {
// SAFETY: repr is transparent, so refs have the same layout; and `SyncCell` properties are `&mut`-agnostic
unsafe { &mut *(ptr::from_mut(r) as *mut SyncCell<T>) }
}
}
// SAFETY: `Sync` only allows multithreaded access via immutable reference.
// As `SyncCell` requires an exclusive reference to access the wrapped value for `!Sync` types,
// marking this type as `Sync` does not actually allow unsynchronized access to the inner value.
unsafe impl<T: ?Sized> Sync for SyncCell<T> {}

129
vendor/bevy_utils/src/syncunsafecell.rs vendored Normal file
View File

@@ -0,0 +1,129 @@
#![expect(unsafe_code, reason = "SyncUnsafeCell requires unsafe code.")]
//! A reimplementation of the currently unstable [`std::cell::SyncUnsafeCell`]
//!
//! [`std::cell::SyncUnsafeCell`]: https://doc.rust-lang.org/nightly/std/cell/struct.SyncUnsafeCell.html
pub use core::cell::UnsafeCell;
use core::ptr;
/// [`UnsafeCell`], but [`Sync`].
///
/// See [tracking issue](https://github.com/rust-lang/rust/issues/95439) for upcoming native impl,
/// which should replace this one entirely (except `from_mut`).
///
/// This is just an `UnsafeCell`, except it implements `Sync`
/// if `T` implements `Sync`.
///
/// `UnsafeCell` doesn't implement `Sync`, to prevent accidental misuse.
/// You can use `SyncUnsafeCell` instead of `UnsafeCell` to allow it to be
/// shared between threads, if that's intentional.
/// Providing proper synchronization is still the task of the user,
/// making this type just as unsafe to use.
///
/// See [`UnsafeCell`] for details.
#[repr(transparent)]
pub struct SyncUnsafeCell<T: ?Sized> {
value: UnsafeCell<T>,
}
// SAFETY: `T` is Sync, caller is responsible for upholding rust safety rules
unsafe impl<T: ?Sized + Sync> Sync for SyncUnsafeCell<T> {}
impl<T> SyncUnsafeCell<T> {
/// Constructs a new instance of `SyncUnsafeCell` which will wrap the specified value.
#[inline]
pub const fn new(value: T) -> Self {
Self {
value: UnsafeCell::new(value),
}
}
/// Unwraps the value.
#[inline]
pub fn into_inner(self) -> T {
self.value.into_inner()
}
}
impl<T: ?Sized> SyncUnsafeCell<T> {
/// Gets a mutable pointer to the wrapped value.
///
/// This can be cast to a pointer of any kind.
/// Ensure that the access is unique (no active references, mutable or not)
/// when casting to `&mut T`, and ensure that there are no mutations
/// or mutable aliases going on when casting to `&T`
#[inline]
pub const fn get(&self) -> *mut T {
self.value.get()
}
/// Returns a mutable reference to the underlying data.
///
/// This call borrows the `SyncUnsafeCell` mutably (at compile-time) which
/// guarantees that we possess the only reference.
#[inline]
pub fn get_mut(&mut self) -> &mut T {
self.value.get_mut()
}
/// Gets a mutable pointer to the wrapped value.
///
/// See [`UnsafeCell::get`] for details.
#[inline]
pub const fn raw_get(this: *const Self) -> *mut T {
// We can just cast the pointer from `SyncUnsafeCell<T>` to `T` because
// of #[repr(transparent)] on both SyncUnsafeCell and UnsafeCell.
// See UnsafeCell::raw_get.
(this as *const T).cast_mut()
}
#[inline]
/// Returns a `&mut SyncUnsafeCell<T>` from a `&mut T`.
pub fn from_mut(t: &mut T) -> &mut SyncUnsafeCell<T> {
let ptr = ptr::from_mut(t) as *mut SyncUnsafeCell<T>;
// SAFETY: `ptr` must be safe to mutably dereference, since it was originally
// obtained from a mutable reference. `SyncUnsafeCell` has the same representation
// as the original type `T`, since the former is annotated with #[repr(transparent)].
unsafe { &mut *ptr }
}
}
impl<T> SyncUnsafeCell<[T]> {
/// Returns a `&[SyncUnsafeCell<T>]` from a `&SyncUnsafeCell<[T]>`.
/// # Examples
///
/// ```
/// # use bevy_utils::syncunsafecell::SyncUnsafeCell;
///
/// let slice: &mut [i32] = &mut [1, 2, 3];
/// let cell_slice: &SyncUnsafeCell<[i32]> = SyncUnsafeCell::from_mut(slice);
/// let slice_cell: &[SyncUnsafeCell<i32>] = cell_slice.as_slice_of_cells();
///
/// assert_eq!(slice_cell.len(), 3);
/// ```
pub fn as_slice_of_cells(&self) -> &[SyncUnsafeCell<T>] {
let self_ptr: *const SyncUnsafeCell<[T]> = ptr::from_ref(self);
let slice_ptr = self_ptr as *const [SyncUnsafeCell<T>];
// SAFETY: `UnsafeCell<T>` and `SyncUnsafeCell<T>` have #[repr(transparent)]
// therefore:
// - `SyncUnsafeCell<T>` has the same layout as `T`
// - `SyncUnsafeCell<[T]>` has the same layout as `[T]`
// - `SyncUnsafeCell<[T]>` has the same layout as `[SyncUnsafeCell<T>]`
unsafe { &*slice_ptr }
}
}
impl<T: Default> Default for SyncUnsafeCell<T> {
/// Creates a new `SyncUnsafeCell` with the `Default` value for T.
fn default() -> SyncUnsafeCell<T> {
SyncUnsafeCell::new(Default::default())
}
}
impl<T> From<T> for SyncUnsafeCell<T> {
/// Creates a new `SyncUnsafeCell<T>` containing the given value.
fn from(t: T) -> SyncUnsafeCell<T> {
SyncUnsafeCell::new(t)
}
}