Skip to content

Commit fb5d8fd

Browse files
authored
Make Parallel<T> more T: !Default accessible (#17943)
# Objective `ThreadLocal::<T>::default()` doesn't require `T: Default`, so `Parallel<T>` shouldn't require it either. ## Solution - Replaced the `Default` derive with a manually specified impl. - Added `Parallel::borrow_local_mut_or` as a non-`T: Default`-requiring alternative to `borrow_local_mut`. - Added `Parallel::scope_or` as a non-`T: Default`-requiring alternative to `scope`.
1 parent 2342e99 commit fb5d8fd

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

crates/bevy_utils/src/parallel_queue.rs

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ use thread_local::ThreadLocal;
55
/// A cohesive set of thread-local values of a given type.
66
///
77
/// Mutable references can be fetched if `T: Default` via [`Parallel::scope`].
8-
#[derive(Default)]
98
pub struct Parallel<T: Send> {
109
locals: ThreadLocal<RefCell<T>>,
1110
}
@@ -20,22 +19,40 @@ impl<T: Send> Parallel<T> {
2019
pub fn clear(&mut self) {
2120
self.locals.clear();
2221
}
22+
23+
/// Retrieves the thread-local value for the current thread and runs `f` on it.
24+
///
25+
/// If there is no thread-local value, it will be initialized to the result
26+
/// of `create`.
27+
pub fn scope_or<R>(&self, create: impl FnOnce() -> T, f: impl FnOnce(&mut T) -> R) -> R {
28+
f(&mut self.borrow_local_mut_or(create))
29+
}
30+
31+
/// Mutably borrows the thread-local value.
32+
///
33+
/// If there is no thread-local value, it will be initialized to the result
34+
/// of `create`.
35+
pub fn borrow_local_mut_or(
36+
&self,
37+
create: impl FnOnce() -> T,
38+
) -> impl DerefMut<Target = T> + '_ {
39+
self.locals.get_or(|| RefCell::new(create())).borrow_mut()
40+
}
2341
}
2442

2543
impl<T: Default + Send> Parallel<T> {
2644
/// Retrieves the thread-local value for the current thread and runs `f` on it.
2745
///
2846
/// If there is no thread-local value, it will be initialized to its default.
2947
pub fn scope<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
30-
let mut cell = self.locals.get_or_default().borrow_mut();
31-
f(cell.deref_mut())
48+
self.scope_or(Default::default, f)
3249
}
3350

3451
/// Mutably borrows the thread-local value.
3552
///
3653
/// If there is no thread-local value, it will be initialized to its default.
3754
pub fn borrow_local_mut(&self) -> impl DerefMut<Target = T> + '_ {
38-
self.locals.get_or_default().borrow_mut()
55+
self.borrow_local_mut_or(Default::default)
3956
}
4057
}
4158

@@ -72,3 +89,12 @@ impl<T: Send> Parallel<Vec<T>> {
7289
}
7390
}
7491
}
92+
93+
// `Default` is manually implemented to avoid the `T: Default` bound.
94+
impl<T: Send> Default for Parallel<T> {
95+
fn default() -> Self {
96+
Self {
97+
locals: ThreadLocal::default(),
98+
}
99+
}
100+
}

0 commit comments

Comments
 (0)