|
2 | 2 |
|
3 | 3 | use crate::fmt;
|
4 | 4 | use crate::marker::{PhantomData, Unpin};
|
| 5 | +use crate::ptr; |
5 | 6 |
|
6 | 7 | /// A `RawWaker` allows the implementor of a task executor to create a [`Waker`]
|
7 | 8 | /// which provides customized wakeup behavior.
|
@@ -322,6 +323,45 @@ impl Waker {
|
322 | 323 | Waker { waker }
|
323 | 324 | }
|
324 | 325 |
|
| 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 | + |
325 | 365 | /// Get a reference to the underlying [`RawWaker`].
|
326 | 366 | #[inline]
|
327 | 367 | #[must_use]
|
|
0 commit comments