Skip to content

Commit 10b7e46

Browse files
committed
Auto merge of rust-lang#96875 - SabrinaJewson:noop-waker, r=m-ou-se
Add `task::Waker::noop` I have found myself reimplementing this function many times when I need a `Context` but don't have a runtime or `futures` to hand. Prior art: [`futures::task::noop_waker`](https://docs.rs/futures/0.3/futures/task/fn.noop_waker.html) and [`futures::task::noop_waker_ref`](https://docs.rs/futures/0.3/futures/task/fn.noop_waker_ref.html) Tracking issue: rust-lang#98286 Unresolved questions: 1. Should we also add `RawWaker::noop()`? (I don't think so, I can't think of a use case for it) 2. Should we also add `Context::noop()`? Depending on the future direction `Context` goes a "noop context" might not even make sense in future. 3. Should it be an associated constant instead? That would allow for `let cx = &mut Context::from_waker(&Waker::NOOP);` to work on one line which is pretty nice. I don't really know what the guideline is here. r? rust-lang/libs-api `@rustbot` label +T-libs-api -T-libs
2 parents b3dd578 + 1818ed7 commit 10b7e46

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

library/core/src/task/wake.rs

+40
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
use crate::fmt;
44
use crate::marker::{PhantomData, Unpin};
5+
use crate::ptr;
56

67
/// A `RawWaker` allows the implementor of a task executor to create a [`Waker`]
78
/// which provides customized wakeup behavior.
@@ -322,6 +323,45 @@ impl Waker {
322323
Waker { waker }
323324
}
324325

326+
/// Creates a new `Waker` that does nothing when `wake` is called.
327+
///
328+
/// This is mostly useful for writing tests that need a [`Context`] to poll
329+
/// some futures, but are not expecting those futures to wake the waker or
330+
/// do not need to do anything specific if it happens.
331+
///
332+
/// # Examples
333+
///
334+
/// ```
335+
/// #![feature(noop_waker)]
336+
///
337+
/// use std::future::Future;
338+
/// use std::task;
339+
///
340+
/// let waker = task::Waker::noop();
341+
/// let mut cx = task::Context::from_waker(&waker);
342+
///
343+
/// let mut future = Box::pin(async { 10 });
344+
/// assert_eq!(future.as_mut().poll(&mut cx), task::Poll::Ready(10));
345+
/// ```
346+
#[inline]
347+
#[must_use]
348+
#[unstable(feature = "noop_waker", issue = "98286")]
349+
pub const fn noop() -> Waker {
350+
const VTABLE: RawWakerVTable = RawWakerVTable::new(
351+
// Cloning just returns a new no-op raw waker
352+
|_| RAW,
353+
// `wake` does nothing
354+
|_| {},
355+
// `wake_by_ref` does nothing
356+
|_| {},
357+
// Dropping does nothing as we don't allocate anything
358+
|_| {},
359+
);
360+
const RAW: RawWaker = RawWaker::new(ptr::null(), &VTABLE);
361+
362+
Waker { waker: RAW }
363+
}
364+
325365
/// Get a reference to the underlying [`RawWaker`].
326366
#[inline]
327367
#[must_use]

0 commit comments

Comments
 (0)