From b1f61ad74bb519bbe97aabfe9b2f04af9991d041 Mon Sep 17 00:00:00 2001 From: SabrinaJewson Date: Mon, 9 May 2022 17:01:35 +0100 Subject: [PATCH 1/2] Add `task::Waker::noop` --- library/core/src/task/wake.rs | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/library/core/src/task/wake.rs b/library/core/src/task/wake.rs index 27af227a1f27f..bf36d3ba2d674 100644 --- a/library/core/src/task/wake.rs +++ b/library/core/src/task/wake.rs @@ -2,6 +2,7 @@ use crate::fmt; use crate::marker::{PhantomData, Unpin}; +use crate::ptr; /// A `RawWaker` allows the implementor of a task executor to create a [`Waker`] /// which provides customized wakeup behavior. @@ -277,6 +278,45 @@ impl Waker { Waker { waker } } + /// Creates a new `Waker` that does nothing when `wake` is called. + /// + /// This is mostly useful for writing tests that need a [`Context`] to poll + /// some futures, but are not expecting those futures to wake the waker or + /// do not need to do anything specific if it happens. + /// + /// # Examples + /// + /// ``` + /// #![feature(noop_waker)] + /// + /// use std::future::Future; + /// use std::task; + /// + /// let waker = task::Waker::noop(); + /// let mut cx = task::Context::from_waker(&waker); + /// + /// let mut future = Box::pin(async { 10 }); + /// assert_eq!(future.as_mut().poll(&mut cx), task::Poll::Ready(10)); + /// ``` + #[inline] + #[must_use] + #[unstable(feature = "noop_waker", issue = "none")] + pub const fn noop() -> Waker { + const VTABLE: RawWakerVTable = RawWakerVTable::new( + // Cloning just returns a new no-op raw waker + |_| RAW, + // `wake` does nothing + |_| {}, + // `wake_by_ref` does nothing + |_| {}, + // Dropping does nothing as we don't allocate anything + |_| {}, + ); + const RAW: RawWaker = RawWaker::new(ptr::null(), &VTABLE); + + Waker { waker: RAW } + } + /// Get a reference to the underlying [`RawWaker`]. #[inline] #[must_use] From 1818ed7cfe8182c14cf05265d7af21ebd987b71e Mon Sep 17 00:00:00 2001 From: SabrinaJewson Date: Mon, 20 Jun 2022 11:58:10 +0100 Subject: [PATCH 2/2] Add tracking issue for `noop_waker` --- library/core/src/task/wake.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/task/wake.rs b/library/core/src/task/wake.rs index bf36d3ba2d674..3543e9655fade 100644 --- a/library/core/src/task/wake.rs +++ b/library/core/src/task/wake.rs @@ -300,7 +300,7 @@ impl Waker { /// ``` #[inline] #[must_use] - #[unstable(feature = "noop_waker", issue = "none")] + #[unstable(feature = "noop_waker", issue = "98286")] pub const fn noop() -> Waker { const VTABLE: RawWakerVTable = RawWakerVTable::new( // Cloning just returns a new no-op raw waker