Skip to content

Commit fee5518

Browse files
committed
Auto merge of #96979 - SabrinaJewson:waker-update, r=workingjubilee
Override `Waker::clone_from` to avoid cloning `Waker`s unnecessarily This would be very useful for futures — I think it’s pretty much always what they want to do instead of `*waker = cx.waker().clone()`. Tracking issue: #98287 r? rust-lang/libs-api `@rustbot` label +T-libs-api -T-libs
2 parents c1ccc29 + 6cdb7df commit fee5518

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

Diff for: library/core/src/task/wake.rs

+14-1
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,10 @@ impl fmt::Debug for Context<'_> {
231231
/// this might be done to wake a future when a blocking function call completes on another
232232
/// thread.
233233
///
234+
/// Note that it is preferable to use `waker.clone_from(&new_waker)` instead
235+
/// of `*waker = new_waker.clone()`, as the former will avoid cloning the waker
236+
/// unnecessarily if the two wakers [wake the same task](Self::will_wake).
237+
///
234238
/// [`Future::poll()`]: core::future::Future::poll
235239
/// [`Poll::Pending`]: core::task::Poll::Pending
236240
#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/66401
@@ -302,7 +306,9 @@ impl Waker {
302306
/// when the `Waker`s would awaken the same task. However, if this function
303307
/// returns `true`, it is guaranteed that the `Waker`s will awaken the same task.
304308
///
305-
/// This function is primarily used for optimization purposes.
309+
/// This function is primarily used for optimization purposes — for example,
310+
/// this type's [`clone_from`](Self::clone_from) implementation uses it to
311+
/// avoid cloning the waker when they would wake the same task anyway.
306312
#[inline]
307313
#[must_use]
308314
#[stable(feature = "futures_api", since = "1.36.0")]
@@ -382,6 +388,13 @@ impl Clone for Waker {
382388
waker: unsafe { (self.waker.vtable.clone)(self.waker.data) },
383389
}
384390
}
391+
392+
#[inline]
393+
fn clone_from(&mut self, source: &Self) {
394+
if !self.will_wake(source) {
395+
*self = source.clone();
396+
}
397+
}
385398
}
386399

387400
#[stable(feature = "futures_api", since = "1.36.0")]

0 commit comments

Comments
 (0)