Skip to content

Commit b1f61ad

Browse files
committed
Add task::Waker::noop
1 parent e013f9e commit b1f61ad

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.
@@ -277,6 +278,45 @@ impl Waker {
277278
Waker { waker }
278279
}
279280

281+
/// Creates a new `Waker` that does nothing when `wake` is called.
282+
///
283+
/// This is mostly useful for writing tests that need a [`Context`] to poll
284+
/// some futures, but are not expecting those futures to wake the waker or
285+
/// do not need to do anything specific if it happens.
286+
///
287+
/// # Examples
288+
///
289+
/// ```
290+
/// #![feature(noop_waker)]
291+
///
292+
/// use std::future::Future;
293+
/// use std::task;
294+
///
295+
/// let waker = task::Waker::noop();
296+
/// let mut cx = task::Context::from_waker(&waker);
297+
///
298+
/// let mut future = Box::pin(async { 10 });
299+
/// assert_eq!(future.as_mut().poll(&mut cx), task::Poll::Ready(10));
300+
/// ```
301+
#[inline]
302+
#[must_use]
303+
#[unstable(feature = "noop_waker", issue = "none")]
304+
pub const fn noop() -> Waker {
305+
const VTABLE: RawWakerVTable = RawWakerVTable::new(
306+
// Cloning just returns a new no-op raw waker
307+
|_| RAW,
308+
// `wake` does nothing
309+
|_| {},
310+
// `wake_by_ref` does nothing
311+
|_| {},
312+
// Dropping does nothing as we don't allocate anything
313+
|_| {},
314+
);
315+
const RAW: RawWaker = RawWaker::new(ptr::null(), &VTABLE);
316+
317+
Waker { waker: RAW }
318+
}
319+
280320
/// Get a reference to the underlying [`RawWaker`].
281321
#[inline]
282322
#[must_use]

0 commit comments

Comments
 (0)