From 02ad0752922e71a162e8d6118c1599baa676a0af Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Fri, 15 Aug 2025 17:50:45 -0700 Subject: [PATCH 01/19] time: add `ignore-wasm` to failing wasm tests --- tokio/src/time/instant.rs | 6 +++--- tokio/src/time/interval.rs | 18 +++++++++--------- tokio/src/time/mod.rs | 4 ++-- tokio/src/time/sleep.rs | 8 ++++---- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/tokio/src/time/instant.rs b/tokio/src/time/instant.rs index 44955dc9878..c0d6f7f06c4 100644 --- a/tokio/src/time/instant.rs +++ b/tokio/src/time/instant.rs @@ -78,7 +78,7 @@ impl Instant { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::time::{Duration, Instant, sleep}; /// /// #[tokio::main] @@ -99,7 +99,7 @@ impl Instant { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::time::{Duration, Instant, sleep}; /// /// #[tokio::main] @@ -120,7 +120,7 @@ impl Instant { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::time::{Duration, Instant, sleep}; /// /// #[tokio::main] diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 0153a567f10..c209009cefb 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -23,7 +23,7 @@ use std::task::{ready, Context, Poll}; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::time::{self, Duration}; /// /// #[tokio::main] @@ -49,7 +49,7 @@ use std::task::{ready, Context, Poll}; /// would only be executed once every three seconds, and not every two /// seconds. /// -/// ``` +/// ```ignore-wasm /// use tokio::time; /// /// async fn task_that_takes_a_second() { @@ -89,7 +89,7 @@ pub fn interval(period: Duration) -> Interval { /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::time::{interval_at, Duration, Instant}; /// /// #[tokio::main] @@ -151,7 +151,7 @@ fn internal_interval_at( /// Sometimes, an [`Interval`]'s tick is missed. For example, consider the /// following: /// -/// ``` +/// ```ignore-wasm /// use tokio::time::{self, Duration}; /// # async fn task_that_takes_one_to_three_millis() {} /// @@ -413,7 +413,7 @@ impl Interval { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::time; /// /// use std::time::Duration; @@ -501,7 +501,7 @@ impl Interval { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::time; /// /// use std::time::Duration; @@ -533,7 +533,7 @@ impl Interval { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::time; /// /// use std::time::Duration; @@ -565,7 +565,7 @@ impl Interval { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::time; /// /// use std::time::Duration; @@ -601,7 +601,7 @@ impl Interval { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::time::{self, Instant}; /// /// use std::time::Duration; diff --git a/tokio/src/time/mod.rs b/tokio/src/time/mod.rs index c0cd7c62856..e314d0f29ca 100644 --- a/tokio/src/time/mod.rs +++ b/tokio/src/time/mod.rs @@ -23,7 +23,7 @@ //! //! Wait 100ms and print "100 ms have elapsed" //! -//! ``` +//! ```ignore-wasm //! use std::time::Duration; //! use tokio::time::sleep; //! @@ -63,7 +63,7 @@ //! would only be executed once every three seconds, and not every two //! seconds. //! -//! ``` +//! ```ignore-wasm //! use tokio::time; //! //! async fn task_that_takes_a_second() { diff --git a/tokio/src/time/sleep.rs b/tokio/src/time/sleep.rs index 1e3fe80d127..0cbf413dadc 100644 --- a/tokio/src/time/sleep.rs +++ b/tokio/src/time/sleep.rs @@ -25,7 +25,7 @@ use std::task::{self, ready, Poll}; /// /// Wait 100ms and print "100 ms have elapsed". /// -/// ``` +/// ```ignore-wasm /// use tokio::time::{sleep_until, Instant, Duration}; /// /// #[tokio::main] @@ -85,7 +85,7 @@ pub fn sleep_until(deadline: Instant) -> Sleep { /// /// Wait 100ms and print "100 ms have elapsed". /// -/// ``` +/// ```ignore-wasm /// use tokio::time::{sleep, Duration}; /// /// #[tokio::main] @@ -140,7 +140,7 @@ pin_project! { /// /// Wait 100ms and print "100 ms have elapsed". /// - /// ``` + /// ```ignore-wasm /// use tokio::time::{sleep, Duration}; /// /// #[tokio::main] @@ -152,7 +152,7 @@ pin_project! { /// /// Use with [`select!`]. Pinning the `Sleep` with [`tokio::pin!`] is /// necessary when the same `Sleep` is selected on multiple times. - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::time::{self, Duration, Instant}; /// /// #[tokio::main] From 12e45723732cab011d1d0cb1b4f7ea5b1a02e782 Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Sat, 16 Aug 2025 00:46:45 -0700 Subject: [PATCH 02/19] task: add `ignore-wasm` to failing wasm tests --- tokio/src/task/coop/mod.rs | 2 +- tokio/src/task/join_set.rs | 10 +++++----- tokio/src/task/local.rs | 16 ++++++++-------- tokio/src/task/mod.rs | 8 ++++---- tokio/src/task/spawn.rs | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/tokio/src/task/coop/mod.rs b/tokio/src/task/coop/mod.rs index 6c4588ccf92..dc8570531c4 100644 --- a/tokio/src/task/coop/mod.rs +++ b/tokio/src/task/coop/mod.rs @@ -36,7 +36,7 @@ //! scheduling. When a future is wrapped with `unconstrained`, it will never be forced to yield to //! Tokio. For example: //! -//! ``` +//! ```ignore-wasm //! # #[tokio::main] //! # async fn main() { //! use tokio::{task, sync::mpsc}; diff --git a/tokio/src/task/join_set.rs b/tokio/src/task/join_set.rs index 21367c989f5..029b082c612 100644 --- a/tokio/src/task/join_set.rs +++ b/tokio/src/task/join_set.rs @@ -28,7 +28,7 @@ use crate::util::IdleNotifiedSet; /// /// Spawn multiple tasks and wait for them. /// -/// ``` +/// ```ignore-wasm /// use tokio::task::JoinSet; /// /// #[tokio::main] @@ -208,7 +208,7 @@ impl JoinSet { /// /// Spawn multiple blocking tasks and wait for them. /// - /// ``` + /// ```ignore-wasm /// use tokio::task::JoinSet; /// /// #[tokio::main] @@ -382,7 +382,7 @@ impl JoinSet { /// /// Spawn multiple tasks and `join_all` them. /// - /// ``` + /// ```ignore-wasm /// use tokio::task::JoinSet; /// use std::time::Duration; /// @@ -404,7 +404,7 @@ impl JoinSet { /// /// Equivalent implementation of `join_all`, using [`join_next`] and loop. /// - /// ``` + /// ```ignore-wasm /// use tokio::task::JoinSet; /// use std::panic; /// @@ -600,7 +600,7 @@ impl Default for JoinSet { /// /// The main example from [`JoinSet`]'s documentation can also be written using [`collect`]: /// -/// ``` +/// ```ignore-wasm /// use tokio::task::JoinSet; /// /// #[tokio::main] diff --git a/tokio/src/task/local.rs b/tokio/src/task/local.rs index 22b1b9bb522..7d7b8e374be 100644 --- a/tokio/src/task/local.rs +++ b/tokio/src/task/local.rs @@ -60,7 +60,7 @@ cfg_rt! { /// local task set, we can use [`task::spawn_local`], which can spawn /// `!Send` futures. For example: /// - /// ```rust + /// ```rust,ignore-wasm /// use std::rc::Rc; /// use tokio::task; /// @@ -94,7 +94,7 @@ cfg_rt! { /// several futures on a `LocalSet` and drive the whole set until they /// complete. For example, /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::{task, time}; /// use std::rc::Rc; /// @@ -132,7 +132,7 @@ cfg_rt! { /// and communicate with it using an [`mpsc`] channel. /// /// The following example puts the `LocalSet` inside a new thread. - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Builder; /// use tokio::sync::{mpsc, oneshot}; /// use tokio::task::LocalSet; @@ -350,7 +350,7 @@ cfg_rt! { /// /// # Examples /// - /// ```rust + /// ```rust,ignore-wasm /// use std::rc::Rc; /// use tokio::task; /// @@ -540,7 +540,7 @@ impl LocalSet { /// /// # Examples /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::task; /// /// #[tokio::main] @@ -608,7 +608,7 @@ impl LocalSet { /// issued from a local task, the [`spawn_blocking`] API may be used instead. /// /// For example, this will panic: - /// ```should_panic + /// ```should_panic,ignore-wasm /// use tokio::runtime::Runtime; /// use tokio::task; /// @@ -625,7 +625,7 @@ impl LocalSet { /// }) /// ``` /// This, however, will not panic: - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// use tokio::task; /// @@ -672,7 +672,7 @@ impl LocalSet { /// /// # Examples /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::task; /// /// #[tokio::main] diff --git a/tokio/src/task/mod.rs b/tokio/src/task/mod.rs index f0c6f71c15a..fbe9a580802 100644 --- a/tokio/src/task/mod.rs +++ b/tokio/src/task/mod.rs @@ -67,7 +67,7 @@ //! A `JoinHandle` is itself a future which may be used to await the output of //! the spawned task. For example: //! -//! ``` +//! ```ignore-wasm //! use tokio::task; //! //! # #[tokio::main] async fn main() -> Result<(), Box> { @@ -89,7 +89,7 @@ //! task panics, awaiting its `JoinHandle` will return a [`JoinError`]. For //! example: //! -//! ``` +//! ```ignore-wasm //! use tokio::task; //! //! # #[tokio::main] async fn main() { @@ -220,7 +220,7 @@ //! //! For example: //! -//! ``` +//! ```ignore-wasm //! use tokio::task; //! //! # async fn docs() { @@ -242,7 +242,7 @@ //! scheduled. Eventually, the yielding task will be polled again, allowing it //! to execute. For example: //! -//! ```rust +//! ```rust,ignore-wasm //! use tokio::task; //! //! # #[tokio::main] async fn main() { diff --git a/tokio/src/task/spawn.rs b/tokio/src/task/spawn.rs index ab9bf5499b9..b275a1900d2 100644 --- a/tokio/src/task/spawn.rs +++ b/tokio/src/task/spawn.rs @@ -34,7 +34,7 @@ cfg_rt! { /// In this example, a server is started and `spawn` is used to start a new task /// that processes each received connection. /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::net::{TcpListener, TcpStream}; /// /// use std::io; @@ -102,7 +102,7 @@ cfg_rt! { /// /// For example, this will work: /// - /// ``` + /// ```ignore-wasm /// use tokio::task; /// /// use std::rc::Rc; From 3dfbeb391a97b7b60c76c96abfb08e1baed0aaa0 Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Sat, 16 Aug 2025 00:58:17 -0700 Subject: [PATCH 03/19] sync: add `ignore-wasm` to failing wasm tests --- tokio/src/sync/barrier.rs | 2 +- tokio/src/sync/broadcast.rs | 44 ++++++------- tokio/src/sync/mod.rs | 14 ++-- tokio/src/sync/mpsc/bounded.rs | 66 +++++++++---------- tokio/src/sync/mpsc/unbounded.rs | 22 +++---- tokio/src/sync/mutex.rs | 26 ++++---- tokio/src/sync/notify.rs | 10 +-- tokio/src/sync/once_cell.rs | 8 +-- tokio/src/sync/oneshot.rs | 52 +++++++-------- tokio/src/sync/rwlock.rs | 22 +++---- tokio/src/sync/rwlock/owned_read_guard.rs | 6 +- tokio/src/sync/rwlock/owned_write_guard.rs | 12 ++-- .../sync/rwlock/owned_write_guard_mapped.rs | 6 +- tokio/src/sync/rwlock/read_guard.rs | 4 +- tokio/src/sync/rwlock/write_guard.rs | 10 +-- tokio/src/sync/rwlock/write_guard_mapped.rs | 4 +- tokio/src/sync/semaphore.rs | 20 +++--- tokio/src/sync/set_once.rs | 8 +-- tokio/src/sync/watch.rs | 16 ++--- 19 files changed, 176 insertions(+), 176 deletions(-) diff --git a/tokio/src/sync/barrier.rs b/tokio/src/sync/barrier.rs index aa2f9e0cf75..5ad1b6f088b 100644 --- a/tokio/src/sync/barrier.rs +++ b/tokio/src/sync/barrier.rs @@ -5,7 +5,7 @@ use crate::util::trace; /// A barrier enables multiple tasks to synchronize the beginning of some computation. /// -/// ``` +/// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio::sync::Barrier; diff --git a/tokio/src/sync/broadcast.rs b/tokio/src/sync/broadcast.rs index 6cd0bfe9359..6d87fc3a63e 100644 --- a/tokio/src/sync/broadcast.rs +++ b/tokio/src/sync/broadcast.rs @@ -70,7 +70,7 @@ //! //! Basic usage //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::broadcast; //! //! #[tokio::main] @@ -95,7 +95,7 @@ //! //! Handling lag //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::broadcast; //! //! #[tokio::main] @@ -138,7 +138,7 @@ use std::task::{ready, Context, Poll, Waker}; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -180,7 +180,7 @@ pub struct Sender { /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::broadcast::channel; /// /// #[tokio::main] @@ -212,7 +212,7 @@ pub struct WeakSender { /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -475,7 +475,7 @@ const MAX_RECEIVERS: usize = usize::MAX >> 2; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -606,7 +606,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -671,7 +671,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -719,7 +719,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -766,7 +766,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -817,7 +817,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -842,7 +842,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -866,7 +866,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use futures::FutureExt; /// use tokio::sync::broadcast; /// @@ -1145,7 +1145,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -1174,7 +1174,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -1200,7 +1200,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -1345,7 +1345,7 @@ impl Receiver { /// [`Sender`]: crate::sync::broadcast::Sender /// /// # Examples - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -1373,7 +1373,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -1419,7 +1419,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -1444,7 +1444,7 @@ impl Receiver { /// /// Handling lag /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -1493,7 +1493,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::broadcast; /// /// #[tokio::main] @@ -1521,7 +1521,7 @@ impl Receiver { /// context. /// /// # Examples - /// ``` + /// ```ignore-wasm /// use std::thread; /// use tokio::sync::broadcast; /// diff --git a/tokio/src/sync/mod.rs b/tokio/src/sync/mod.rs index 20eef09f164..06a8a773a44 100644 --- a/tokio/src/sync/mod.rs +++ b/tokio/src/sync/mod.rs @@ -35,7 +35,7 @@ //! **Example:** using a [`oneshot` channel][oneshot] to receive the result of a //! computation. //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::oneshot; //! //! async fn some_computation() -> String { @@ -67,7 +67,7 @@ //! //! **Example:** //! -//! ``` +//! ```ignore-wasm //! async fn some_computation() -> String { //! "the result of the computation".to_string() //! } @@ -100,7 +100,7 @@ //! **Example:** using an mpsc to incrementally stream the results of a series //! of computations. //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::mpsc; //! //! async fn some_computation(input: u32) -> String { @@ -140,7 +140,7 @@ //! **Example:** sending data from many tasks over a single socket using message //! passing. //! -//! ```no_run +//! ```no_run,ignore-wasm //! use tokio::io::{self, AsyncWriteExt}; //! use tokio::net::TcpStream; //! use tokio::sync::mpsc; @@ -184,7 +184,7 @@ //! "fetch and increment" command. The counter value **before** the increment is //! sent over the provided `oneshot` channel. //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::{oneshot, mpsc}; //! use Command::Increment; //! @@ -251,7 +251,7 @@ //! //! Basic usage //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::broadcast; //! //! #[tokio::main] @@ -293,7 +293,7 @@ //! changes. In this example, a configuration file is checked periodically. When //! the file changes, the configuration changes are signalled to consumers. //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::watch; //! use tokio::time::{self, Duration, Instant}; //! diff --git a/tokio/src/sync/mpsc/bounded.rs b/tokio/src/sync/mpsc/bounded.rs index 06eeffc3f09..51dc8df8b1d 100644 --- a/tokio/src/sync/mpsc/bounded.rs +++ b/tokio/src/sync/mpsc/bounded.rs @@ -37,7 +37,7 @@ pub struct Sender { /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::mpsc::channel; /// /// #[tokio::main] @@ -131,7 +131,7 @@ pub struct Receiver { /// /// # Examples /// -/// ```rust +/// ```rust,ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -205,7 +205,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -223,7 +223,7 @@ impl Receiver { /// /// Values are buffered: /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -275,7 +275,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -337,7 +337,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// use tokio::sync::mpsc::error::TryRecvError; /// @@ -392,7 +392,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::thread; /// use tokio::runtime::Runtime; /// use tokio::sync::mpsc; @@ -445,7 +445,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -482,7 +482,7 @@ impl Receiver { /// [`Receiver::close`]: crate::sync::mpsc::Receiver::close /// /// # Examples - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -504,7 +504,7 @@ impl Receiver { /// This method returns `true` if the channel has no messages. /// /// # Examples - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -524,7 +524,7 @@ impl Receiver { /// Returns the number of messages in the channel. /// /// # Examples - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -549,7 +549,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -596,7 +596,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -667,7 +667,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::task::{Context, Poll}; /// use std::pin::Pin; /// use tokio::sync::mpsc; @@ -786,7 +786,7 @@ impl Sender { /// In the following example, each call to `send` will block until the /// previously sent value was received. /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -829,7 +829,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -880,7 +880,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -954,7 +954,7 @@ impl Sender { /// In the following example, each call to `send_timeout` will block until the /// previously sent value was received, unless the timeout has elapsed. /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::sync::mpsc; /// use tokio::time::{sleep, Duration}; /// @@ -1013,7 +1013,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::thread; /// use tokio::runtime::Runtime; /// use tokio::sync::mpsc; @@ -1083,7 +1083,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1139,7 +1139,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1202,7 +1202,7 @@ impl Sender { /// /// # Examples /// Sending a message using an [`OwnedPermit`]: - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1227,7 +1227,7 @@ impl Sender { /// When multiple [`OwnedPermit`]s are needed, or the sender cannot be moved /// by value, it can be inexpensively cloned before calling `reserve_owned`: /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1289,7 +1289,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1346,7 +1346,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1439,7 +1439,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1502,7 +1502,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1551,7 +1551,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1659,7 +1659,7 @@ impl Permit<'_, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1784,7 +1784,7 @@ impl OwnedPermit { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1818,7 +1818,7 @@ impl OwnedPermit { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1859,7 +1859,7 @@ impl OwnedPermit { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -1887,7 +1887,7 @@ impl OwnedPermit { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] diff --git a/tokio/src/sync/mpsc/unbounded.rs b/tokio/src/sync/mpsc/unbounded.rs index a9232dc934c..23503f0b2f6 100644 --- a/tokio/src/sync/mpsc/unbounded.rs +++ b/tokio/src/sync/mpsc/unbounded.rs @@ -26,7 +26,7 @@ pub struct UnboundedSender { /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::mpsc::unbounded_channel; /// /// #[tokio::main] @@ -132,7 +132,7 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -150,7 +150,7 @@ impl UnboundedReceiver { /// /// Values are buffered: /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -200,7 +200,7 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -262,7 +262,7 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// use tokio::sync::mpsc::error::TryRecvError; /// @@ -296,7 +296,7 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::thread; /// use tokio::sync::mpsc; /// @@ -349,7 +349,7 @@ impl UnboundedReceiver { /// [`UnboundedReceiver::close`]: crate::sync::mpsc::UnboundedReceiver::close /// /// # Examples - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -371,7 +371,7 @@ impl UnboundedReceiver { /// This method returns `true` if the channel has no messages. /// /// # Examples - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -391,7 +391,7 @@ impl UnboundedReceiver { /// Returns the number of messages in the channel. /// /// # Examples - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] @@ -454,7 +454,7 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::task::{Context, Poll}; /// use std::pin::Pin; /// use tokio::sync::mpsc; @@ -589,7 +589,7 @@ impl UnboundedSender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::mpsc; /// /// #[tokio::main] diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index 30f0bdecedb..b892f597d65 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -55,7 +55,7 @@ use std::{fmt, mem, ptr}; /// /// # Examples: /// -/// ```rust,no_run +/// ```rust,no_run,ignore-wasm /// use tokio::sync::Mutex; /// use std::sync::Arc; /// @@ -75,7 +75,7 @@ use std::{fmt, mem, ptr}; /// ``` /// /// -/// ```rust,no_run +/// ```rust,no_run,ignore-wasm /// use tokio::sync::Mutex; /// use std::sync::Arc; /// @@ -420,7 +420,7 @@ impl Mutex { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::Mutex; /// /// #[tokio::main] @@ -483,7 +483,7 @@ impl Mutex { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::Mutex; /// @@ -540,7 +540,7 @@ impl Mutex { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::Mutex; /// @@ -597,7 +597,7 @@ impl Mutex { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::Mutex; /// use std::sync::Arc; /// @@ -772,7 +772,7 @@ impl Mutex { /// Consumes the mutex, returning the underlying data. /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::Mutex; /// /// #[tokio::main] @@ -843,7 +843,7 @@ impl<'a, T: ?Sized> MutexGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{Mutex, MutexGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -891,7 +891,7 @@ impl<'a, T: ?Sized> MutexGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{Mutex, MutexGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -935,7 +935,7 @@ impl<'a, T: ?Sized> MutexGuard<'a, T> { /// Returns a reference to the original `Mutex`. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{Mutex, MutexGuard}; /// /// async fn unlock_and_relock<'l>(guard: MutexGuard<'l, u32>) -> MutexGuard<'l, u32> { @@ -1024,7 +1024,7 @@ impl OwnedMutexGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{Mutex, OwnedMutexGuard}; /// use std::sync::Arc; /// @@ -1072,7 +1072,7 @@ impl OwnedMutexGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{Mutex, OwnedMutexGuard}; /// use std::sync::Arc; /// @@ -1116,7 +1116,7 @@ impl OwnedMutexGuard { /// Returns a reference to the original `Arc`. /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{Mutex, OwnedMutexGuard}; /// diff --git a/tokio/src/sync/notify.rs b/tokio/src/sync/notify.rs index d460797936d..10120275140 100644 --- a/tokio/src/sync/notify.rs +++ b/tokio/src/sync/notify.rs @@ -52,7 +52,7 @@ type GuardedWaitList = GuardedLinkedList:: /// /// Basic usage. /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::Notify; /// use std::sync::Arc; /// @@ -544,7 +544,7 @@ impl Notify { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::Notify; /// use std::sync::Arc; /// @@ -590,7 +590,7 @@ impl Notify { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::Notify; /// @@ -637,7 +637,7 @@ impl Notify { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::Notify; /// use std::sync::Arc; /// @@ -718,7 +718,7 @@ impl Notify { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::Notify; /// use std::sync::Arc; /// diff --git a/tokio/src/sync/once_cell.rs b/tokio/src/sync/once_cell.rs index 1b723048dff..8d5f48ad83b 100644 --- a/tokio/src/sync/once_cell.rs +++ b/tokio/src/sync/once_cell.rs @@ -32,7 +32,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::OnceCell; /// /// async fn some_computation() -> u32 { @@ -50,7 +50,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// /// It is often useful to write a wrapper method for accessing the value. /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::OnceCell; /// /// static ONCE: OnceCell = OnceCell::const_new(); @@ -144,7 +144,7 @@ impl OnceCell { /// /// # Example /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::OnceCell; /// /// static ONCE: OnceCell = OnceCell::const_new(); @@ -199,7 +199,7 @@ impl OnceCell { /// visible in [`tokio-console`]. Instead, [`OnceCell::new_with`] should be /// used to create an instrumented object if that is needed. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::OnceCell; /// /// static ONCE: OnceCell = OnceCell::const_new_with(1); diff --git a/tokio/src/sync/oneshot.rs b/tokio/src/sync/oneshot.rs index 719745c75f5..f87a295fa8d 100644 --- a/tokio/src/sync/oneshot.rs +++ b/tokio/src/sync/oneshot.rs @@ -18,7 +18,7 @@ //! //! # Examples //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::oneshot; //! //! #[tokio::main] @@ -41,7 +41,7 @@ //! If the sender is dropped without sending, the receiver will fail with //! [`error::RecvError`]: //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::oneshot; //! //! #[tokio::main] @@ -62,7 +62,7 @@ //! To use a `oneshot` channel in a `tokio::select!` loop, add `&mut` in front of //! the channel. //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::oneshot; //! use tokio::time::{interval, sleep, Duration}; //! @@ -95,7 +95,7 @@ //! To use a `Sender` from a destructor, put it in an [`Option`] and call //! [`Option::take`]. //! -//! ``` +//! ```ignore-wasm //! use tokio::sync::oneshot; //! //! struct SendOnDrop { @@ -144,7 +144,7 @@ use std::task::{ready, Context, Poll, Waker}; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -167,7 +167,7 @@ use std::task::{ready, Context, Poll, Waker}; /// If the sender is dropped without sending, the receiver will fail with /// [`error::RecvError`]: /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -188,7 +188,7 @@ use std::task::{ready, Context, Poll, Waker}; /// To use a `Sender` from a destructor, put it in an [`Option`] and call /// [`Option::take`]. /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::oneshot; /// /// struct SendOnDrop { @@ -245,7 +245,7 @@ pub struct Sender { /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -268,7 +268,7 @@ pub struct Sender { /// If the sender is dropped without sending, the receiver will fail with /// [`error::RecvError`]: /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -289,7 +289,7 @@ pub struct Sender { /// To use a `Receiver` in a `tokio::select!` loop, add `&mut` in front of the /// channel. /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::oneshot; /// use tokio::time::{interval, sleep, Duration}; /// @@ -447,7 +447,7 @@ struct State(usize); /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -573,7 +573,7 @@ impl Sender { /// /// Send a value to another task /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -649,7 +649,7 @@ impl Sender { /// /// Basic usage /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -667,7 +667,7 @@ impl Sender { /// /// Paired with select /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// use tokio::time::{self, Duration}; /// @@ -728,7 +728,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -772,7 +772,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// /// use std::future::poll_fn; @@ -878,7 +878,7 @@ impl Receiver { /// /// Prevent a value from being sent /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// use tokio::sync::oneshot::error::TryRecvError; /// @@ -902,7 +902,7 @@ impl Receiver { /// /// Receive a value sent **before** calling `close` /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -940,7 +940,7 @@ impl Receiver { /// /// Sending a value and polling it. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// /// use std::task::Poll; @@ -969,7 +969,7 @@ impl Receiver { /// /// Dropping the sender. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -1001,7 +1001,7 @@ impl Receiver { /// /// Sending a value. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -1019,7 +1019,7 @@ impl Receiver { /// /// Dropping the sender. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -1038,7 +1038,7 @@ impl Receiver { /// /// Terminated channels are empty. /// - /// ```should_panic + /// ```should_panic,ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -1098,7 +1098,7 @@ impl Receiver { /// /// `try_recv` before a value is sent, then after. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// use tokio::sync::oneshot::error::TryRecvError; /// @@ -1124,7 +1124,7 @@ impl Receiver { /// /// `try_recv` when the sender dropped before sending a value /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// use tokio::sync::oneshot::error::TryRecvError; /// @@ -1188,7 +1188,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::thread; /// use tokio::sync::oneshot; /// diff --git a/tokio/src/sync/rwlock.rs b/tokio/src/sync/rwlock.rs index d94b6514306..7cf765e5f67 100644 --- a/tokio/src/sync/rwlock.rs +++ b/tokio/src/sync/rwlock.rs @@ -55,7 +55,7 @@ const MAX_READS: u32 = 10; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::RwLock; /// /// #[tokio::main] @@ -406,7 +406,7 @@ impl RwLock { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::RwLock; /// @@ -488,7 +488,7 @@ impl RwLock { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::RwLock; /// @@ -551,7 +551,7 @@ impl RwLock { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::RwLock; /// @@ -627,7 +627,7 @@ impl RwLock { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::RwLock; /// @@ -692,7 +692,7 @@ impl RwLock { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::RwLock; /// @@ -758,7 +758,7 @@ impl RwLock { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::RwLock; /// /// #[tokio::main] @@ -830,7 +830,7 @@ impl RwLock { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::{sync::RwLock}; /// @@ -889,7 +889,7 @@ impl RwLock { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::RwLock; /// @@ -956,7 +956,7 @@ impl RwLock { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::RwLock; /// /// #[tokio::main] @@ -1013,7 +1013,7 @@ impl RwLock { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::RwLock; /// diff --git a/tokio/src/sync/rwlock/owned_read_guard.rs b/tokio/src/sync/rwlock/owned_read_guard.rs index f50b2abcaf5..7be97908dfe 100644 --- a/tokio/src/sync/rwlock/owned_read_guard.rs +++ b/tokio/src/sync/rwlock/owned_read_guard.rs @@ -55,7 +55,7 @@ impl OwnedRwLockReadGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockReadGuard}; /// @@ -102,7 +102,7 @@ impl OwnedRwLockReadGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockReadGuard}; /// @@ -143,7 +143,7 @@ impl OwnedRwLockReadGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockReadGuard}; /// diff --git a/tokio/src/sync/rwlock/owned_write_guard.rs b/tokio/src/sync/rwlock/owned_write_guard.rs index 11be26a9bad..34e20eff62c 100644 --- a/tokio/src/sync/rwlock/owned_write_guard.rs +++ b/tokio/src/sync/rwlock/owned_write_guard.rs @@ -62,7 +62,7 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// @@ -114,7 +114,7 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// @@ -186,7 +186,7 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// @@ -248,7 +248,7 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// @@ -333,7 +333,7 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use tokio::sync::RwLock; /// # use std::sync::Arc; /// # @@ -395,7 +395,7 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// diff --git a/tokio/src/sync/rwlock/owned_write_guard_mapped.rs b/tokio/src/sync/rwlock/owned_write_guard_mapped.rs index e0699d09794..bcdbfee7f6e 100644 --- a/tokio/src/sync/rwlock/owned_write_guard_mapped.rs +++ b/tokio/src/sync/rwlock/owned_write_guard_mapped.rs @@ -61,7 +61,7 @@ impl OwnedRwLockMappedWriteGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// @@ -112,7 +112,7 @@ impl OwnedRwLockMappedWriteGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// @@ -160,7 +160,7 @@ impl OwnedRwLockMappedWriteGuard { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::{ /// RwLock, diff --git a/tokio/src/sync/rwlock/read_guard.rs b/tokio/src/sync/rwlock/read_guard.rs index a04b59588d5..fa4b17858f1 100644 --- a/tokio/src/sync/rwlock/read_guard.rs +++ b/tokio/src/sync/rwlock/read_guard.rs @@ -60,7 +60,7 @@ impl<'a, T: ?Sized> RwLockReadGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{RwLock, RwLockReadGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -112,7 +112,7 @@ impl<'a, T: ?Sized> RwLockReadGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{RwLock, RwLockReadGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/tokio/src/sync/rwlock/write_guard.rs b/tokio/src/sync/rwlock/write_guard.rs index d405fc2b39f..1af2a6f507b 100644 --- a/tokio/src/sync/rwlock/write_guard.rs +++ b/tokio/src/sync/rwlock/write_guard.rs @@ -66,7 +66,7 @@ impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -124,7 +124,7 @@ impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -199,7 +199,7 @@ impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -268,7 +268,7 @@ impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -348,7 +348,7 @@ impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use tokio::sync::RwLock; /// # use std::sync::Arc; /// # diff --git a/tokio/src/sync/rwlock/write_guard_mapped.rs b/tokio/src/sync/rwlock/write_guard_mapped.rs index 7705189e70f..96c35aa447b 100644 --- a/tokio/src/sync/rwlock/write_guard_mapped.rs +++ b/tokio/src/sync/rwlock/write_guard_mapped.rs @@ -63,7 +63,7 @@ impl<'a, T: ?Sized> RwLockMappedWriteGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -118,7 +118,7 @@ impl<'a, T: ?Sized> RwLockMappedWriteGuard<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/tokio/src/sync/semaphore.rs b/tokio/src/sync/semaphore.rs index 97963afddc2..7b8e9d681df 100644 --- a/tokio/src/sync/semaphore.rs +++ b/tokio/src/sync/semaphore.rs @@ -30,7 +30,7 @@ use std::sync::Arc; /// /// Basic usage: /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::{Semaphore, TryAcquireError}; /// /// #[tokio::main] @@ -60,7 +60,7 @@ use std::sync::Arc; /// no more than 100 files at a time. When trying to open the 101st /// file, the program will wait until a permit becomes available before /// proceeding to open another file. -/// ``` +/// ```ignore-wasm /// use std::io::Result; /// use tokio::fs::File; /// use tokio::sync::Semaphore; @@ -89,7 +89,7 @@ use std::sync::Arc; /// sent in parallel at any given time. After a task has sent a request, it /// drops the permit to allow other tasks to send requests. /// -/// ``` +/// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::Semaphore; /// @@ -143,7 +143,7 @@ use std::sync::Arc; /// [`Semaphore::acquire_owned`] to be movable across the task boundary. /// (Since our semaphore is not a global variable — if it was, then `acquire` would be enough.) /// -/// ```no_run +/// ```no_run,ignore-wasm /// use std::sync::Arc; /// use tokio::sync::Semaphore; /// use tokio::net::TcpListener; @@ -318,7 +318,7 @@ use std::sync::Arc; /// [token bucket]: https://en.wikipedia.org/wiki/Token_bucket /// [`add_permits`]: crate::sync::Semaphore::add_permits /// [`SemaphorePermit::forget`]: crate::sync::SemaphorePermit::forget -/// ``` +/// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::Semaphore; /// use tokio::time::{interval, Duration}; @@ -556,7 +556,7 @@ impl Semaphore { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::Semaphore; /// /// #[tokio::main] @@ -609,7 +609,7 @@ impl Semaphore { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::Semaphore; /// /// #[tokio::main] @@ -731,7 +731,7 @@ impl Semaphore { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::Semaphore; /// @@ -792,7 +792,7 @@ impl Semaphore { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::Semaphore; /// @@ -931,7 +931,7 @@ impl Semaphore { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::Semaphore; /// use std::sync::Arc; /// use tokio::sync::TryAcquireError; diff --git a/tokio/src/sync/set_once.rs b/tokio/src/sync/set_once.rs index e4adbf59398..682fbab38e3 100644 --- a/tokio/src/sync/set_once.rs +++ b/tokio/src/sync/set_once.rs @@ -28,7 +28,7 @@ use std::sync::atomic::Ordering; /// /// # Example /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::{SetOnce, SetOnceError}; /// /// static ONCE: SetOnce = SetOnce::const_new(); @@ -55,7 +55,7 @@ use std::sync::atomic::Ordering; /// /// # Example /// -/// ``` +/// ```ignore-wasm /// use tokio::sync::{SetOnce, SetOnceError}; /// use std::sync::Arc; /// @@ -168,7 +168,7 @@ impl SetOnce { /// /// # Example /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::{SetOnce, SetOnceError}; /// /// static ONCE: SetOnce = SetOnce::const_new(); @@ -221,7 +221,7 @@ impl SetOnce { /// visible in [`tokio-console`]. Instead, [`SetOnce::new_with`] should be /// used to create an instrumented object if that is needed. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::SetOnce; /// /// static ONCE: SetOnce = SetOnce::const_new_with(1); diff --git a/tokio/src/sync/watch.rs b/tokio/src/sync/watch.rs index 884efffa30c..65effc01b21 100644 --- a/tokio/src/sync/watch.rs +++ b/tokio/src/sync/watch.rs @@ -204,7 +204,7 @@ impl<'a, T> Ref<'a, T> { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::watch; /// /// #[tokio::main] @@ -646,7 +646,7 @@ impl Receiver { /// Returns an error if the channel has been closed. /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::watch; /// /// #[tokio::main] @@ -725,7 +725,7 @@ impl Receiver { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::watch; /// /// #[tokio::main] @@ -1221,7 +1221,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::watch; /// /// #[tokio::main] @@ -1269,7 +1269,7 @@ impl Sender { /// /// The new channel will receive messages sent on this `Sender`. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::watch; /// /// #[tokio::main] @@ -1289,7 +1289,7 @@ impl Sender { /// The most recent message is considered seen by the channel, so this test /// is guaranteed to pass. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::watch; /// use tokio::time::Duration; /// @@ -1325,7 +1325,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::watch; /// /// #[tokio::main] @@ -1347,7 +1347,7 @@ impl Sender { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::watch; /// /// #[tokio::main] From 94c0796c8137847f4a95437e1dbf0ef4088148d1 Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Sat, 16 Aug 2025 01:05:08 -0700 Subject: [PATCH 04/19] runtime: add `ignore-wasm` to failing wasm tests --- tokio/src/runtime/builder.rs | 30 ++++++++++++++-------------- tokio/src/runtime/handle.rs | 16 +++++++-------- tokio/src/runtime/metrics/runtime.rs | 12 +++++------ tokio/src/runtime/mod.rs | 6 +++--- tokio/src/runtime/runtime.rs | 14 ++++++------- tokio/src/runtime/task/error.rs | 6 +++--- tokio/src/runtime/task/join.rs | 6 +++--- 7 files changed, 45 insertions(+), 45 deletions(-) diff --git a/tokio/src/runtime/builder.rs b/tokio/src/runtime/builder.rs index 76800296a27..774e485e285 100644 --- a/tokio/src/runtime/builder.rs +++ b/tokio/src/runtime/builder.rs @@ -30,7 +30,7 @@ use std::time::Duration; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::runtime::Builder; /// /// fn main() { @@ -323,7 +323,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime; /// /// let rt = runtime::Builder::new_multi_thread() @@ -365,7 +365,7 @@ impl Builder { /// /// ## Multi threaded runtime with 4 threads /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime; /// /// // This will spawn a work-stealing runtime with 4 worker threads. @@ -459,7 +459,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use tokio::runtime; /// /// # pub fn main() { @@ -480,7 +480,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use tokio::runtime; /// # use std::sync::atomic::{AtomicUsize, Ordering}; /// # pub fn main() { @@ -511,7 +511,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use tokio::runtime; /// /// # pub fn main() { @@ -532,7 +532,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use tokio::runtime; /// # pub fn main() { /// let runtime = runtime::Builder::new_multi_thread() @@ -557,7 +557,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use tokio::runtime; /// # pub fn main() { /// let runtime = runtime::Builder::new_multi_thread() @@ -589,7 +589,7 @@ impl Builder { /// # Examples /// /// ## Multithreaded executor - /// ``` + /// ```ignore-wasm /// # use std::sync::Arc; /// # use std::sync::atomic::{AtomicBool, Ordering}; /// # use tokio::runtime; @@ -665,7 +665,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use tokio::runtime; /// # pub fn main() { /// let runtime = runtime::Builder::new_multi_thread() @@ -882,7 +882,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Builder; /// /// let rt = Builder::new_multi_thread().build().unwrap(); @@ -954,7 +954,7 @@ impl Builder { /// /// # Example /// - /// ``` + /// ```ignore-wasm /// # use tokio::runtime; /// # use std::time::Duration; /// # pub fn main() { @@ -991,7 +991,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use tokio::runtime; /// # pub fn main() { /// let rt = runtime::Builder::new_multi_thread() @@ -1025,7 +1025,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use tokio::runtime; /// # pub fn main() { /// let rt = runtime::Builder::new_multi_thread() @@ -1567,7 +1567,7 @@ cfg_time! { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime; /// /// let rt = runtime::Builder::new_multi_thread() diff --git a/tokio/src/runtime/handle.rs b/tokio/src/runtime/handle.rs index 8f9d95090b9..a26252a19fb 100644 --- a/tokio/src/runtime/handle.rs +++ b/tokio/src/runtime/handle.rs @@ -51,7 +51,7 @@ impl Handle { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// /// let rt = Runtime::new().unwrap(); @@ -65,7 +65,7 @@ impl Handle { /// Do **not** do the following, this shows a scenario that will result in a /// panic and possible memory leak. /// - /// ```should_panic + /// ```should_panic,ignore-wasm /// use tokio::runtime::Runtime; /// /// let rt1 = Runtime::new().unwrap(); @@ -105,7 +105,7 @@ impl Handle { /// This can be used to obtain the handle of the surrounding runtime from an async /// block or function running on that runtime. /// - /// ``` + /// ```ignore-wasm /// # use std::thread; /// # use tokio::runtime::Runtime; /// # fn dox() { @@ -169,7 +169,7 @@ impl Handle { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// /// # fn dox() { @@ -203,7 +203,7 @@ impl Handle { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// /// # fn dox() { @@ -255,7 +255,7 @@ impl Handle { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// /// // Create the runtime @@ -272,7 +272,7 @@ impl Handle { /// /// Or using `Handle::current`: /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -386,7 +386,7 @@ impl Handle { /// } /// ``` /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::{Handle, RuntimeFlavor}; /// /// #[tokio::main(flavor = "multi_thread", worker_threads = 4)] diff --git a/tokio/src/runtime/metrics/runtime.rs b/tokio/src/runtime/metrics/runtime.rs index 6302457b8d5..a67ff09b371 100644 --- a/tokio/src/runtime/metrics/runtime.rs +++ b/tokio/src/runtime/metrics/runtime.rs @@ -34,7 +34,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -56,7 +56,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -82,7 +82,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -123,7 +123,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -168,7 +168,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -216,7 +216,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] diff --git a/tokio/src/runtime/mod.rs b/tokio/src/runtime/mod.rs index 031fde5d0b0..872b6171950 100644 --- a/tokio/src/runtime/mod.rs +++ b/tokio/src/runtime/mod.rs @@ -18,7 +18,7 @@ //! When no fine tuning is required, the [`tokio::main`] attribute macro can be //! used. //! -//! ```no_run +//! ```no_run,ignore-wasm //! use tokio::net::TcpListener; //! use tokio::io::{AsyncReadExt, AsyncWriteExt}; //! @@ -61,7 +61,7 @@ //! //! A [`Runtime`] instance can also be used directly. //! -//! ```no_run +//! ```no_run,ignore-wasm //! use tokio::net::TcpListener; //! use tokio::io::{AsyncReadExt, AsyncWriteExt}; //! use tokio::runtime::Runtime; @@ -117,7 +117,7 @@ //! CPU core available on the system. This tends to be the ideal configuration //! for most applications. The multi-thread scheduler requires the `rt-multi-thread` //! feature flag, and is selected by default: -//! ``` +//! ```ignore-wasm //! use tokio::runtime; //! //! # fn main() -> Result<(), Box> { diff --git a/tokio/src/runtime/runtime.rs b/tokio/src/runtime/runtime.rs index 1bbb0205bff..adee31ee43e 100644 --- a/tokio/src/runtime/runtime.rs +++ b/tokio/src/runtime/runtime.rs @@ -183,7 +183,7 @@ impl Runtime { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// /// let rt = Runtime::new() @@ -213,7 +213,7 @@ impl Runtime { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// /// # fn dox() { @@ -246,7 +246,7 @@ impl Runtime { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// /// # fn dox() { @@ -308,7 +308,7 @@ impl Runtime { /// /// # Examples /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::runtime::Runtime; /// /// // Create the runtime @@ -371,7 +371,7 @@ impl Runtime { /// /// # Example /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// use tokio::task::JoinHandle; /// @@ -406,7 +406,7 @@ impl Runtime { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// use tokio::task; /// @@ -447,7 +447,7 @@ impl Runtime { /// /// This function is equivalent to calling `shutdown_timeout(Duration::from_nanos(0))`. /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Runtime; /// /// fn main() { diff --git a/tokio/src/runtime/task/error.rs b/tokio/src/runtime/task/error.rs index b3bd819511e..8a6d5f89789 100644 --- a/tokio/src/runtime/task/error.rs +++ b/tokio/src/runtime/task/error.rs @@ -45,7 +45,7 @@ impl JoinError { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::panic; /// /// #[tokio::main] @@ -71,7 +71,7 @@ impl JoinError { /// /// # Examples /// - /// ```should_panic + /// ```should_panic,ignore-wasm /// use std::panic; /// /// #[tokio::main] @@ -98,7 +98,7 @@ impl JoinError { /// /// # Examples /// - /// ```should_panic + /// ```should_panic,ignore-wasm /// use std::panic; /// /// #[tokio::main] diff --git a/tokio/src/runtime/task/join.rs b/tokio/src/runtime/task/join.rs index db1df2eb6cb..ac2e77e4fe4 100644 --- a/tokio/src/runtime/task/join.rs +++ b/tokio/src/runtime/task/join.rs @@ -87,7 +87,7 @@ cfg_rt! { /// `Result` because panics in the spawned task are caught by Tokio. The `?` operator has /// to be double chained to extract the returned value: /// - /// ``` + /// ```ignore-wasm /// use tokio::task; /// use std::io; /// @@ -105,7 +105,7 @@ cfg_rt! { /// /// If the task panics, the error is a [`JoinError`] that contains the panic: /// - /// ``` + /// ```ignore-wasm /// use tokio::task; /// use std::io; /// use std::panic; @@ -124,7 +124,7 @@ cfg_rt! { /// ``` /// Child being detached and outliving its parent: /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::task; /// use tokio::time; /// use std::time::Duration; From 92cb650f8767e6f5e6c2009354bf9fb7a4dba3eb Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Sat, 16 Aug 2025 01:19:44 -0700 Subject: [PATCH 05/19] tokio|io|macros: add remaining `ignore-wasm` to failing doctests --- tokio/src/io/mod.rs | 6 +++--- tokio/src/lib.rs | 4 ++-- tokio/src/macros/join.rs | 4 ++-- tokio/src/macros/pin.rs | 6 +++--- tokio/src/macros/select.rs | 22 +++++++++++----------- tokio/src/macros/try_join.rs | 6 +++--- 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/tokio/src/io/mod.rs b/tokio/src/io/mod.rs index 763a3fabbf4..e053e23754c 100644 --- a/tokio/src/io/mod.rs +++ b/tokio/src/io/mod.rs @@ -35,7 +35,7 @@ //! [demonstrating][std_example] reading some bytes from a [`std::fs::File`]. We //! can do the same with [`tokio::fs::File`][`File`]: //! -//! ```no_run +//! ```no_run,ignore-wasm //! use tokio::io::{self, AsyncReadExt}; //! use tokio::fs::File; //! @@ -72,7 +72,7 @@ //! For example, [`BufReader`] works with the [`AsyncBufRead`] trait to add //! extra methods to any async reader: //! -//! ```no_run +//! ```no_run,ignore-wasm //! use tokio::io::{self, BufReader, AsyncBufReadExt}; //! use tokio::fs::File; //! @@ -94,7 +94,7 @@ //! to [`write`](crate::io::AsyncWriteExt::write). However, you **must** flush //! [`BufWriter`] to ensure that any buffered data is written. //! -//! ```no_run +//! ```no_run,ignore-wasm //! use tokio::io::{self, BufWriter, AsyncWriteExt}; //! use tokio::fs::File; //! diff --git a/tokio/src/lib.rs b/tokio/src/lib.rs index 366ea04a0df..cc7ee992ce3 100644 --- a/tokio/src/lib.rs +++ b/tokio/src/lib.rs @@ -193,7 +193,7 @@ //! [`spawn_blocking`]: crate::task::spawn_blocking() //! [`thread_keep_alive`]: crate::runtime::Builder::thread_keep_alive() //! -//! ``` +//! ```ignore-wasm //! #[tokio::main] //! async fn main() { //! // This is running on a core thread. @@ -265,7 +265,7 @@ //! //! A simple TCP echo server: //! -//! ```no_run +//! ```no_run,ignore-wasm //! use tokio::net::TcpListener; //! use tokio::io::{AsyncReadExt, AsyncWriteExt}; //! diff --git a/tokio/src/macros/join.rs b/tokio/src/macros/join.rs index cd89da1cc02..3f00d87638f 100644 --- a/tokio/src/macros/join.rs +++ b/tokio/src/macros/join.rs @@ -55,7 +55,7 @@ macro_rules! doc { /// /// Basic join with two branches /// - /// ``` + /// ```ignore-wasm /// async fn do_stuff_async() { /// // async work /// } @@ -76,7 +76,7 @@ macro_rules! doc { /// /// Using the `biased;` mode to control polling order. /// - /// ``` + /// ```ignore-wasm /// async fn do_stuff_async() { /// // async work /// } diff --git a/tokio/src/macros/pin.rs b/tokio/src/macros/pin.rs index 7af9ce7d1f0..710b3c30469 100644 --- a/tokio/src/macros/pin.rs +++ b/tokio/src/macros/pin.rs @@ -24,7 +24,7 @@ /// /// To make this work requires pinning: /// -/// ``` +/// ```ignore-wasm /// use tokio::pin; /// /// async fn my_async_fn() { @@ -69,7 +69,7 @@ /// /// Using with select: /// -/// ``` +/// ```ignore-wasm /// use tokio::{pin, select}; /// use tokio_stream::{self as stream, StreamExt}; /// @@ -101,7 +101,7 @@ /// Because assigning to a variable followed by pinning is common, there is also /// a variant of the macro that supports doing both in one go. /// -/// ``` +/// ```ignore-wasm /// use tokio::{pin, select}; /// /// async fn my_async_fn() { diff --git a/tokio/src/macros/select.rs b/tokio/src/macros/select.rs index 18cc44b988a..1408966ecc7 100644 --- a/tokio/src/macros/select.rs +++ b/tokio/src/macros/select.rs @@ -149,7 +149,7 @@ macro_rules! doc { /// /// Basic select with two branches. /// - /// ``` + /// ```ignore-wasm /// async fn do_stuff_async() { /// // async work /// } @@ -173,7 +173,7 @@ macro_rules! doc { /// /// Basic stream selecting. /// - /// ``` + /// ```ignore-wasm /// use tokio_stream::{self as stream, StreamExt}; /// /// #[tokio::main] @@ -194,7 +194,7 @@ macro_rules! doc { /// matching and the fact that `stream::iter` is "fused", i.e. once the stream /// is complete, all calls to `next()` return `None`. /// - /// ``` + /// ```ignore-wasm /// use tokio_stream::{self as stream, StreamExt}; /// /// #[tokio::main] @@ -226,7 +226,7 @@ macro_rules! doc { /// /// Here, a stream is consumed for at most 1 second. /// - /// ``` + /// ```ignore-wasm /// use tokio_stream::{self as stream, StreamExt}; /// use tokio::time::{self, Duration}; /// @@ -256,7 +256,7 @@ macro_rules! doc { /// /// Joining two values using `select!`. /// - /// ``` + /// ```ignore-wasm /// use tokio::sync::oneshot; /// /// #[tokio::main] @@ -291,7 +291,7 @@ macro_rules! doc { /// /// Using the `biased;` mode to control polling order. /// - /// ``` + /// ```ignore-wasm /// #[tokio::main] /// async fn main() { /// let mut count = 0u8; @@ -337,7 +337,7 @@ macro_rules! doc { /// is to repeatedly run an asynchronous task for up to 50 milliseconds. /// However, there is a potential for the `sleep` completion to be missed. /// - /// ```no_run,should_panic + /// ```no_run,should_panic,ignore-wasm /// use tokio::time::{self, Duration}; /// /// async fn some_async_work() { @@ -372,7 +372,7 @@ macro_rules! doc { /// /// One way to write the above example without the race would be: /// - /// ``` + /// ```ignore-wasm /// use tokio::time::{self, Duration}; /// /// async fn some_async_work() { @@ -422,7 +422,7 @@ macro_rules! doc { /// /// ### Example with `select!` /// - /// ``` + /// ```ignore-wasm /// struct File; /// struct Channel; /// struct Socket; @@ -461,7 +461,7 @@ macro_rules! doc { /// eliminating the need to manage tasks manually and reducing the risk of /// unintended behavior like data loss. /// - /// ``` + /// ```ignore-wasm /// use std::pin::pin; /// /// use futures::stream::unfold; @@ -530,7 +530,7 @@ macro_rules! doc { /// - [`futures_lite::future::or`](https://docs.rs/futures-lite/latest/futures_lite/future/fn.or.html) /// - [`futures_lite::future::race`](https://docs.rs/futures-lite/latest/futures_lite/future/fn.race.html) /// - /// ``` + /// ```ignore-wasm /// use futures_concurrency::future::Race; /// /// #[tokio::main] diff --git a/tokio/src/macros/try_join.rs b/tokio/src/macros/try_join.rs index 471b5ebb42d..3c0ecdc8ae5 100644 --- a/tokio/src/macros/try_join.rs +++ b/tokio/src/macros/try_join.rs @@ -53,7 +53,7 @@ macro_rules! doc { /// /// Basic `try_join` with two branches. /// - /// ``` + /// ```ignore-wasm /// async fn do_stuff_async() -> Result<(), &'static str> { /// // async work /// # Ok(()) @@ -83,7 +83,7 @@ macro_rules! doc { /// /// Using `try_join!` with spawned tasks. /// - /// ``` + /// ```ignore-wasm /// use tokio::task::JoinHandle; /// /// async fn do_stuff_async() -> Result<(), &'static str> { @@ -121,7 +121,7 @@ macro_rules! doc { /// ``` /// Using the `biased;` mode to control polling order. /// - /// ``` + /// ```ignore-wasm /// async fn do_stuff_async() -> Result<(), &'static str> { /// // async work /// # Ok(()) From 5a37a0be9002b313b2b18330cddf401fcfaaddce Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Sat, 16 Aug 2025 01:27:26 -0700 Subject: [PATCH 06/19] ci: unpin rust version for wasm tests --- .github/workflows/ci.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6ca746bfb19..3b8d0620859 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1055,10 +1055,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - - name: Install Rust 1.88.0 + - name: Install Rust ${{ env.rust_stable }} uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.88.0 + toolchain: ${{ env.rust_stable }} - name: Install wasm-pack uses: taiki-e/install-action@wasm-pack @@ -1078,10 +1078,10 @@ jobs: - wasm32-wasip1-threads steps: - uses: actions/checkout@v4 - - name: Install Rust 1.88.0 + - name: Install Rust ${{ env.rust_stable }} uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.88.0 + toolchain: ${{ env.rust_stable }} targets: ${{ matrix.target }} # Install dependencies From 9a1484e068df7fa3f1ca49b3e4fad20fd7a7a4db Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Fri, 22 Aug 2025 19:56:11 -0700 Subject: [PATCH 07/19] ci: update cfgs for WASI test tokio --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b8d0620859..1346741ac21 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1092,7 +1092,7 @@ jobs: - uses: Swatinem/rust-cache@v2 - name: WASI test tokio full - run: cargo test -p tokio --target ${{ matrix.target }} --features full + run: cargo test -p tokio --target ${{ matrix.target }} --features "sync,macros,io-util,rt,time" env: CARGO_TARGET_WASM32_WASIP1_RUNNER: "wasmtime run --" CARGO_TARGET_WASM32_WASIP1_THREADS_RUNNER: "wasmtime run -W bulk-memory=y -W threads=y -S threads=y --" From ab2a5f50bfde381a6fecf3bf6d3b2d4e12bacff4 Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Sat, 23 Aug 2025 00:21:04 -0700 Subject: [PATCH 08/19] tokio|tokio-stream|tokio-util - ignore failing wasm tests --- .../tests/fail/macros_type_mismatch.stderr | 4 ++ tokio-stream/src/empty.rs | 2 +- tokio-stream/src/lib.rs | 2 +- tokio-stream/src/once.rs | 2 +- tokio-stream/src/stream_close.rs | 2 +- tokio-stream/src/stream_ext.rs | 44 +++++++------- tokio-stream/src/stream_map.rs | 4 +- tokio-stream/src/wrappers/tcp_listener.rs | 2 +- tokio-stream/src/wrappers/watch.rs | 6 +- tokio-util/src/codec/length_delimited.rs | 14 ++--- tokio-util/src/codec/mod.rs | 4 +- tokio-util/src/compat.rs | 4 +- tokio-util/src/context.rs | 6 +- tokio-util/src/either.rs | 2 +- tokio-util/src/io/read_arc.rs | 2 +- tokio-util/src/io/read_buf.rs | 2 +- tokio-util/src/io/reader_stream.rs | 2 +- tokio-util/src/io/sync_bridge.rs | 6 +- tokio-util/src/task/join_map.rs | 12 ++-- tokio-util/src/task/spawn_pinned.rs | 6 +- tokio-util/src/task/task_tracker.rs | 2 +- tokio-util/src/time/delay_queue.rs | 26 ++++---- tokio-util/src/util/poll_buf.rs | 2 +- tokio/src/io/util/async_buf_read_ext.rs | 6 +- tokio/src/io/util/async_read_ext.rs | 60 +++++++++---------- tokio/src/io/util/async_seek_ext.rs | 4 +- tokio/src/io/util/async_write_ext.rs | 60 +++++++++---------- tokio/src/io/util/empty.rs | 4 +- tokio/src/io/util/repeat.rs | 2 +- tokio/src/io/util/sink.rs | 2 +- tokio/src/loom/std/barrier.rs | 4 +- 31 files changed, 152 insertions(+), 148 deletions(-) diff --git a/tests-build/tests/fail/macros_type_mismatch.stderr b/tests-build/tests/fail/macros_type_mismatch.stderr index f9c32f00578..201df9cdd05 100644 --- a/tests-build/tests/fail/macros_type_mismatch.stderr +++ b/tests-build/tests/fail/macros_type_mismatch.stderr @@ -57,6 +57,8 @@ error[E0277]: the `?` operator can only be used in an async block that returns ` 39 | async fn question_mark_operator_with_invalid_option() -> Option<()> { 40 | None?; | ^ cannot use the `?` operator in an async block that returns `()` + | + = help: the trait `FromResidual>` is not implemented for `()` error[E0308]: mismatched types --> tests/fail/macros_type_mismatch.rs:40:5 @@ -85,6 +87,8 @@ error[E0277]: the `?` operator can only be used in an async block that returns ` 56 | async fn question_mark_operator_with_invalid_result() -> Result<(), ()> { 57 | Ok(())?; | ^ cannot use the `?` operator in an async block that returns `()` + | + = help: the trait `FromResidual>` is not implemented for `()` error[E0308]: mismatched types --> tests/fail/macros_type_mismatch.rs:57:5 diff --git a/tokio-stream/src/empty.rs b/tokio-stream/src/empty.rs index 965dcf5da7a..39dd6040019 100644 --- a/tokio-stream/src/empty.rs +++ b/tokio-stream/src/empty.rs @@ -23,7 +23,7 @@ unsafe impl Sync for Empty {} /// /// Basic usage: /// -/// ``` +/// ```ignore-wasm /// use tokio_stream::{self as stream, StreamExt}; /// /// #[tokio::main] diff --git a/tokio-stream/src/lib.rs b/tokio-stream/src/lib.rs index 28fa22a2ff6..bbeaf66749b 100644 --- a/tokio-stream/src/lib.rs +++ b/tokio-stream/src/lib.rs @@ -31,7 +31,7 @@ //! `Stream`, but this is unfortunately not possible. Instead, you can use a //! `while let` loop as follows: //! -//! ```rust +//! ```rust,ignore-wasm //! use tokio_stream::{self as stream, StreamExt}; //! //! #[tokio::main] diff --git a/tokio-stream/src/once.rs b/tokio-stream/src/once.rs index c5b19bccd79..6f12b3413cd 100644 --- a/tokio-stream/src/once.rs +++ b/tokio-stream/src/once.rs @@ -19,7 +19,7 @@ impl Unpin for Once {} /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio_stream::{self as stream, StreamExt}; /// /// #[tokio::main] diff --git a/tokio-stream/src/stream_close.rs b/tokio-stream/src/stream_close.rs index 735acf091f9..36e2f27bec4 100644 --- a/tokio-stream/src/stream_close.rs +++ b/tokio-stream/src/stream_close.rs @@ -14,7 +14,7 @@ pin_project! { /// /// Using `StreamNotifyClose` to handle closed streams with `StreamMap`. /// - /// ``` + /// ```ignore-wasm /// use tokio_stream::{StreamExt, StreamMap, StreamNotifyClose}; /// /// #[tokio::main] diff --git a/tokio-stream/src/stream_ext.rs b/tokio-stream/src/stream_ext.rs index cdbada30bc5..2812b858ae6 100644 --- a/tokio-stream/src/stream_ext.rs +++ b/tokio-stream/src/stream_ext.rs @@ -128,7 +128,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -170,7 +170,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -202,7 +202,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -238,7 +238,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -282,7 +282,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -417,7 +417,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -453,7 +453,7 @@ pub trait StreamExt: Stream { /// standard library. /// /// # Examples - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -487,7 +487,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio_stream::{Stream, StreamExt}; /// /// use std::pin::Pin; @@ -550,7 +550,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -579,7 +579,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -605,7 +605,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -636,7 +636,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -679,7 +679,7 @@ pub trait StreamExt: Stream { /// /// Basic usage: /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -694,7 +694,7 @@ pub trait StreamExt: Stream { /// /// Stopping at the first `false`: /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -738,7 +738,7 @@ pub trait StreamExt: Stream { /// /// Basic usage: /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -753,7 +753,7 @@ pub trait StreamExt: Stream { /// /// Stopping at the first `true`: /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -784,7 +784,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio_stream::{self as stream, StreamExt}; /// /// #[tokio::main] @@ -822,7 +822,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// Basic usage: - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, *}; @@ -871,7 +871,7 @@ pub trait StreamExt: Stream { /// /// Basic usage: /// - /// ``` + /// ```ignore-wasm /// use tokio_stream::{self as stream, StreamExt}; /// /// #[tokio::main] @@ -888,7 +888,7 @@ pub trait StreamExt: Stream { /// /// Collecting a stream of `Result` values /// - /// ``` + /// ```ignore-wasm /// use tokio_stream::{self as stream, StreamExt}; /// /// #[tokio::main] @@ -944,7 +944,7 @@ pub trait StreamExt: Stream { /// /// Suppose we have a stream `int_stream` that yields 3 numbers (1, 2, 3): /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; @@ -1030,7 +1030,7 @@ pub trait StreamExt: Stream { /// /// Suppose we have a stream `int_stream` that yields 3 numbers (1, 2, 3): /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; diff --git a/tokio-stream/src/stream_map.rs b/tokio-stream/src/stream_map.rs index f276f99210e..eedc95da49b 100644 --- a/tokio-stream/src/stream_map.rs +++ b/tokio-stream/src/stream_map.rs @@ -60,7 +60,7 @@ use std::task::{ready, Context, Poll}; /// /// Merging two streams, then remove them after receiving the first value /// -/// ``` +/// ```ignore-wasm /// use tokio_stream::{StreamExt, StreamMap, Stream}; /// use tokio::sync::mpsc; /// use std::pin::Pin; @@ -182,7 +182,7 @@ use std::task::{ready, Context, Poll}; /// /// Using `StreamNotifyClose` to handle closed streams with `StreamMap`. /// -/// ``` +/// ```ignore-wasm /// use tokio_stream::{StreamExt, StreamMap, StreamNotifyClose}; /// /// #[tokio::main] diff --git a/tokio-stream/src/wrappers/tcp_listener.rs b/tokio-stream/src/wrappers/tcp_listener.rs index c463ef1426c..c6302c4faa6 100644 --- a/tokio-stream/src/wrappers/tcp_listener.rs +++ b/tokio-stream/src/wrappers/tcp_listener.rs @@ -10,7 +10,7 @@ use tokio::net::{TcpListener, TcpStream}; /// /// Accept connections from both IPv4 and IPv6 listeners in the same loop: /// -/// ```no_run +/// ```no_run,ignore-wasm /// use std::net::{Ipv4Addr, Ipv6Addr}; /// /// use tokio::net::TcpListener; diff --git a/tokio-stream/src/wrappers/watch.rs b/tokio-stream/src/wrappers/watch.rs index a1e4fbfa03a..a30dd32904a 100644 --- a/tokio-stream/src/wrappers/watch.rs +++ b/tokio-stream/src/wrappers/watch.rs @@ -16,7 +16,7 @@ use tokio::sync::watch::error::RecvError; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{StreamExt, wrappers::WatchStream}; @@ -32,7 +32,7 @@ use tokio::sync::watch::error::RecvError; /// # } /// ``` /// -/// ``` +/// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_stream::{StreamExt, wrappers::WatchStream}; @@ -50,7 +50,7 @@ use tokio::sync::watch::error::RecvError; /// /// Example with [`WatchStream::from_changes`]: /// -/// ``` +/// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use futures::future::FutureExt; diff --git a/tokio-util/src/codec/length_delimited.rs b/tokio-util/src/codec/length_delimited.rs index fed49ca8a79..138e81d4b80 100644 --- a/tokio-util/src/codec/length_delimited.rs +++ b/tokio-util/src/codec/length_delimited.rs @@ -78,7 +78,7 @@ //! The following will parse a `u16` length field at offset 0, omitting the //! frame head in the yielded `BytesMut`. //! -//! ``` +//! ```ignore-wasm //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; //! # #[tokio::main] @@ -114,7 +114,7 @@ //! The following will parse a `u16` length field at offset 0, including the //! frame head in the yielded `BytesMut`. //! -//! ``` +//! ```ignore-wasm //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; //! # #[tokio::main] @@ -151,7 +151,7 @@ //! frame head in the yielded `BytesMut`. In this case, the length field //! **includes** the frame head length. //! -//! ``` +//! ```ignore-wasm //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; //! # #[tokio::main] @@ -187,7 +187,7 @@ //! The following will parse a 3 byte length field at offset 0 in a 5 byte //! frame head, including the frame head in the yielded `BytesMut`. //! -//! ``` +//! ```ignore-wasm //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; //! # #[tokio::main] @@ -234,7 +234,7 @@ //! yielded `BytesMut`, but the trailing 2 bytes of the frame head will be //! included. //! -//! ``` +//! ```ignore-wasm //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; //! # #[tokio::main] @@ -283,7 +283,7 @@ //! included. In this case, the length field **includes** the frame head //! length. //! -//! ``` +//! ```ignore-wasm //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; //! # #[tokio::main] @@ -326,7 +326,7 @@ //! The following will parse a 3 byte length field at offset 0 in a 4 byte //! frame head, excluding the 4th byte from the yielded `BytesMut`. //! -//! ``` +//! ```ignore-wasm //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; //! # #[tokio::main] diff --git a/tokio-util/src/codec/mod.rs b/tokio-util/src/codec/mod.rs index 11f44133e69..4bc3a0b7a52 100644 --- a/tokio-util/src/codec/mod.rs +++ b/tokio-util/src/codec/mod.rs @@ -14,7 +14,7 @@ //! [`FramedWrite`] are first framed according to a specific codec, and then sent to //! an implementor of [`AsyncWrite`]. //! -//! ``` +//! ```ignore-wasm //! use futures::sink::SinkExt; //! use tokio_util::codec::LinesCodec; //! use tokio_util::codec::FramedWrite; @@ -46,7 +46,7 @@ //! will keep reading from an [`AsyncRead`] implementor until a whole frame, according to a codec, //! can be parsed. //! -//!``` +//!```ignore-wasm //! use tokio_stream::StreamExt; //! use tokio_util::codec::LinesCodec; //! use tokio_util::codec::FramedRead; diff --git a/tokio-util/src/compat.rs b/tokio-util/src/compat.rs index 9e3f26bdc3e..7d9707492e2 100644 --- a/tokio-util/src/compat.rs +++ b/tokio-util/src/compat.rs @@ -33,7 +33,7 @@ //! [`futures::io::AsyncReadExt::read`] from the `futures` crate to read it after adapting the //! stream via [`compat()`]. //! -//! ```no_run +//! ```no_run,ignore-wasm //! use tokio::net::{TcpListener, TcpStream}; //! use tokio::io::AsyncWriteExt; //! use tokio_util::compat::TokioAsyncReadCompatExt; @@ -65,7 +65,7 @@ //! The reverse is also possible: you can take a [`futures::io::AsyncRead`] (e.g. a cursor) and //! adapt it to be used with [`tokio::io::AsyncReadExt::read_to_end`] //! -//! ``` +//! ```ignore-wasm //! use futures::io::Cursor; //! use tokio_util::compat::FuturesAsyncReadCompatExt; //! use tokio::io::AsyncReadExt; diff --git a/tokio-util/src/context.rs b/tokio-util/src/context.rs index a7a5e029490..88d4dc0bb82 100644 --- a/tokio-util/src/context.rs +++ b/tokio-util/src/context.rs @@ -36,7 +36,7 @@ pin_project! { /// This example creates two runtimes, but only [enables time] on one of /// them. It then uses the context of the runtime with the timer enabled to /// execute a [`sleep`] future on the runtime with timing disabled. - /// ``` + /// ```ignore-wasm /// use tokio::time::{sleep, Duration}; /// use tokio_util::context::RuntimeExt; /// @@ -87,7 +87,7 @@ impl TokioContext { /// /// [`RuntimeExt::wrap`]: fn@RuntimeExt::wrap /// - /// ``` + /// ```ignore-wasm /// use tokio::time::{sleep, Duration}; /// use tokio_util::context::TokioContext; /// @@ -152,7 +152,7 @@ pub trait RuntimeExt { /// them. It then uses the context of the runtime with the timer enabled to /// execute a [`sleep`] future on the runtime with timing disabled. /// - /// ``` + /// ```ignore-wasm /// use tokio::time::{sleep, Duration}; /// use tokio_util::context::RuntimeExt; /// diff --git a/tokio-util/src/either.rs b/tokio-util/src/either.rs index f661bb9e11d..e2d58098655 100644 --- a/tokio-util/src/either.rs +++ b/tokio-util/src/either.rs @@ -40,7 +40,7 @@ use tokio::io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, ReadBuf, Result} /// When the output type is the same, we can wrap each future in `Either` to avoid the /// issue: /// -/// ``` +/// ```ignore-wasm /// use tokio_util::either::Either; /// # fn some_condition() -> bool { true } /// # async fn some_async_function() -> u32 { 10 } diff --git a/tokio-util/src/io/read_arc.rs b/tokio-util/src/io/read_arc.rs index 30b87023f55..51955a80527 100644 --- a/tokio-util/src/io/read_arc.rs +++ b/tokio-util/src/io/read_arc.rs @@ -9,7 +9,7 @@ use tokio::io::{AsyncRead, AsyncReadExt}; /// /// # Example /// -/// ``` +/// ```ignore-wasm /// # #[tokio::main] /// # async fn main() -> std::io::Result<()> { /// use tokio_util::io::read_exact_arc; diff --git a/tokio-util/src/io/read_buf.rs b/tokio-util/src/io/read_buf.rs index d7938a3bc16..ffebb335215 100644 --- a/tokio-util/src/io/read_buf.rs +++ b/tokio-util/src/io/read_buf.rs @@ -11,7 +11,7 @@ use tokio::io::AsyncRead; /// /// # Example /// -/// ``` +/// ```ignore-wasm /// use bytes::{Bytes, BytesMut}; /// use tokio_stream as stream; /// use tokio::io::Result; diff --git a/tokio-util/src/io/reader_stream.rs b/tokio-util/src/io/reader_stream.rs index 866c11408d5..6c07526e707 100644 --- a/tokio-util/src/io/reader_stream.rs +++ b/tokio-util/src/io/reader_stream.rs @@ -15,7 +15,7 @@ pin_project! { /// /// # Example /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() -> std::io::Result<()> { /// use tokio_stream::StreamExt; diff --git a/tokio-util/src/io/sync_bridge.rs b/tokio-util/src/io/sync_bridge.rs index 6821c7ede71..b768bf288c2 100644 --- a/tokio-util/src/io/sync_bridge.rs +++ b/tokio-util/src/io/sync_bridge.rs @@ -42,7 +42,7 @@ use tokio::io::{ /// Explanation: This example demonstrates how to asynchronously read data from a /// reader into memory and hash it using a synchronous hashing function. The /// `SyncIoBridge` is avoided, ensuring that the async runtime is not blocked. -/// ```rust +/// ```rust,ignore-wasm /// use tokio::io::AsyncReadExt; /// use tokio::io::AsyncRead; /// use std::io::Cursor; @@ -77,7 +77,7 @@ use tokio::io::{ /// incrementally. This avoids blocking and improves performance over using /// `SyncIoBridge`. /// -/// ```rust +/// ```rust,ignore-wasm /// use tokio::io::AsyncReadExt; /// use tokio::io::AsyncRead; /// use std::io::Cursor; @@ -217,7 +217,7 @@ use tokio::io::{ /// `spawn_blocking` ensures that the synchronous code is offloaded to a dedicated /// thread pool, preventing it from interfering with the async tasks. /// -/// ```rust +/// ```rust,ignore-wasm /// use tokio::task::spawn_blocking; /// use tokio_util::io::SyncIoBridge; /// use tokio::io::AsyncRead; diff --git a/tokio-util/src/task/join_map.rs b/tokio-util/src/task/join_map.rs index e7e898fcb2a..5f4d4d5d6a6 100644 --- a/tokio-util/src/task/join_map.rs +++ b/tokio-util/src/task/join_map.rs @@ -33,7 +33,7 @@ use tokio::task::{AbortHandle, Id, JoinError, JoinSet, LocalSet}; /// /// Spawn multiple tasks and wait for them: /// -/// ``` +/// ```ignore-wasm /// use tokio_util::task::JoinMap; /// /// #[tokio::main] @@ -62,7 +62,7 @@ use tokio::task::{AbortHandle, Id, JoinError, JoinSet, LocalSet}; /// /// Cancel tasks based on their keys: /// -/// ``` +/// ```ignore-wasm /// use tokio_util::task::JoinMap; /// /// #[tokio::main] @@ -185,7 +185,7 @@ impl JoinMap { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_util::task::JoinMap; @@ -518,7 +518,7 @@ where /// ``` /// /// `abort` returns `true` if a task was aborted: - /// ``` + /// ```ignore-wasm /// use tokio_util::task::JoinMap; /// /// # #[tokio::main] @@ -685,7 +685,7 @@ where /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_util::task::JoinMap; @@ -714,7 +714,7 @@ where /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # #[tokio::main] /// # async fn main() { /// use tokio_util::task::JoinMap; diff --git a/tokio-util/src/task/spawn_pinned.rs b/tokio-util/src/task/spawn_pinned.rs index 177ea028df3..f6ba5b68327 100644 --- a/tokio-util/src/task/spawn_pinned.rs +++ b/tokio-util/src/task/spawn_pinned.rs @@ -21,7 +21,7 @@ use tokio::task::{spawn_local, JoinHandle, LocalSet}; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use std::rc::Rc; /// use tokio::task; /// use tokio_util::task::LocalPoolHandle; @@ -93,7 +93,7 @@ impl LocalPoolHandle { /// [`FnOnce`] which creates it is. /// /// # Examples - /// ``` + /// ```ignore-wasm /// use std::rc::Rc; /// use tokio_util::task::LocalPoolHandle; /// @@ -143,7 +143,7 @@ impl LocalPoolHandle { /// /// This method can be used to spawn a task on all worker threads of the pool: /// - /// ``` + /// ```ignore-wasm /// use tokio_util::task::LocalPoolHandle; /// /// #[tokio::main] diff --git a/tokio-util/src/task/task_tracker.rs b/tokio-util/src/task/task_tracker.rs index 682ebf35fd9..ebb57e29ffd 100644 --- a/tokio-util/src/task/task_tracker.rs +++ b/tokio-util/src/task/task_tracker.rs @@ -63,7 +63,7 @@ use tokio::{ /// /// This is a simple example. For this case, [`JoinSet`] should probably be used instead. /// -/// ``` +/// ```ignore-wasm /// use tokio_util::task::TaskTracker; /// /// #[tokio::main] diff --git a/tokio-util/src/time/delay_queue.rs b/tokio-util/src/time/delay_queue.rs index a65101d163a..6365b06ae7e 100644 --- a/tokio-util/src/time/delay_queue.rs +++ b/tokio-util/src/time/delay_queue.rs @@ -452,7 +452,7 @@ impl DelayQueue { /// /// # Examples /// - /// ```rust + /// ```rust,ignore-wasm /// # use tokio_util::time::DelayQueue; /// # use std::time::Duration; /// @@ -508,7 +508,7 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::time::{Duration, Instant}; /// use tokio_util::time::DelayQueue; /// @@ -628,7 +628,7 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// @@ -683,7 +683,7 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// @@ -734,7 +734,7 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// @@ -832,7 +832,7 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::time::{Duration, Instant}; /// use tokio_util::time::DelayQueue; /// @@ -889,7 +889,7 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// @@ -922,7 +922,7 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// @@ -974,7 +974,7 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// @@ -1005,7 +1005,7 @@ impl DelayQueue { /// /// # Examples /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// @@ -1047,7 +1047,7 @@ impl DelayQueue { /// /// # Examples /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// @@ -1082,7 +1082,7 @@ impl DelayQueue { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// @@ -1112,7 +1112,7 @@ impl DelayQueue { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// diff --git a/tokio-util/src/util/poll_buf.rs b/tokio-util/src/util/poll_buf.rs index 452cc3c836b..19a6684fcaa 100644 --- a/tokio-util/src/util/poll_buf.rs +++ b/tokio-util/src/util/poll_buf.rs @@ -11,7 +11,7 @@ use std::task::{ready, Context, Poll}; /// /// # Example /// -/// ``` +/// ```ignore-wasm /// use bytes::{Bytes, BytesMut}; /// use tokio_stream as stream; /// use tokio::io::Result; diff --git a/tokio/src/io/util/async_buf_read_ext.rs b/tokio/src/io/util/async_buf_read_ext.rs index 1e9da4c8c4d..2ddbd42af50 100644 --- a/tokio/src/io/util/async_buf_read_ext.rs +++ b/tokio/src/io/util/async_buf_read_ext.rs @@ -57,7 +57,7 @@ cfg_io_util! { /// /// [`Cursor`]: std::io::Cursor /// - /// ``` + /// ```ignore-wasm /// use tokio::io::AsyncBufReadExt; /// /// use std::io::Cursor; @@ -159,7 +159,7 @@ cfg_io_util! { /// /// [`Cursor`]: std::io::Cursor /// - /// ``` + /// ```ignore-wasm /// use tokio::io::AsyncBufReadExt; /// /// use std::io::Cursor; @@ -326,7 +326,7 @@ cfg_io_util! { /// /// [`Cursor`]: std::io::Cursor /// - /// ``` + /// ```ignore-wasm /// use tokio::io::AsyncBufReadExt; /// /// use std::io::Cursor; diff --git a/tokio/src/io/util/async_read_ext.rs b/tokio/src/io/util/async_read_ext.rs index 8c80385128f..124a0e97e59 100644 --- a/tokio/src/io/util/async_read_ext.rs +++ b/tokio/src/io/util/async_read_ext.rs @@ -40,7 +40,7 @@ cfg_io_util! { /// [`AsyncRead`] types. Callers will tend to import this trait instead of /// [`AsyncRead`]. /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::fs::File; /// use tokio::io::{self, AsyncReadExt}; /// @@ -71,7 +71,7 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `AsyncRead`: /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::fs::File; /// use tokio::io::{self, AsyncReadExt}; /// @@ -149,7 +149,7 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `Read`: /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::fs::File; /// use tokio::io::{self, AsyncReadExt}; /// @@ -218,7 +218,7 @@ cfg_io_util! { /// [`BytesMut`]: bytes::BytesMut /// [`BufMut`]: bytes::BufMut /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::fs::File; /// use tokio::io::{self, AsyncReadExt}; /// @@ -288,7 +288,7 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `Read`: /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::fs::File; /// use tokio::io::{self, AsyncReadExt}; /// @@ -340,7 +340,7 @@ cfg_io_util! { /// /// Read unsigned 8 bit integers from an `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -384,7 +384,7 @@ cfg_io_util! { /// /// Read unsigned 8 bit integers from an `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -429,7 +429,7 @@ cfg_io_util! { /// /// Read unsigned 16 bit big-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -473,7 +473,7 @@ cfg_io_util! { /// /// Read signed 16 bit big-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -517,7 +517,7 @@ cfg_io_util! { /// /// Read unsigned 32-bit big-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -561,7 +561,7 @@ cfg_io_util! { /// /// Read signed 32-bit big-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -604,7 +604,7 @@ cfg_io_util! { /// /// Read unsigned 64-bit big-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -649,7 +649,7 @@ cfg_io_util! { /// /// Read signed 64-bit big-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -692,7 +692,7 @@ cfg_io_util! { /// /// Read unsigned 128-bit big-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -738,7 +738,7 @@ cfg_io_util! { /// /// Read signed 128-bit big-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -784,7 +784,7 @@ cfg_io_util! { /// /// Read 32-bit floating point type from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -827,7 +827,7 @@ cfg_io_util! { /// /// Read 64-bit floating point type from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -872,7 +872,7 @@ cfg_io_util! { /// /// Read unsigned 16 bit little-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -916,7 +916,7 @@ cfg_io_util! { /// /// Read signed 16 bit little-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -960,7 +960,7 @@ cfg_io_util! { /// /// Read unsigned 32-bit little-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -1004,7 +1004,7 @@ cfg_io_util! { /// /// Read signed 32-bit little-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -1047,7 +1047,7 @@ cfg_io_util! { /// /// Read unsigned 64-bit little-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -1092,7 +1092,7 @@ cfg_io_util! { /// /// Read signed 64-bit little-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -1135,7 +1135,7 @@ cfg_io_util! { /// /// Read unsigned 128-bit little-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -1181,7 +1181,7 @@ cfg_io_util! { /// /// Read signed 128-bit little-endian integers from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -1227,7 +1227,7 @@ cfg_io_util! { /// /// Read 32-bit floating point type from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -1270,7 +1270,7 @@ cfg_io_util! { /// /// Read 64-bit floating point type from a `AsyncRead`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; @@ -1314,7 +1314,7 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `Read`: /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// use tokio::fs::File; /// @@ -1362,7 +1362,7 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `Read`: /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// use tokio::fs::File; /// @@ -1402,7 +1402,7 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `Read`: /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// use tokio::fs::File; /// diff --git a/tokio/src/io/util/async_seek_ext.rs b/tokio/src/io/util/async_seek_ext.rs index aadf3a76a96..a776a9350ec 100644 --- a/tokio/src/io/util/async_seek_ext.rs +++ b/tokio/src/io/util/async_seek_ext.rs @@ -7,7 +7,7 @@ cfg_io_util! { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::io::{self, Cursor, SeekFrom}; /// use tokio::io::{AsyncSeekExt, AsyncReadExt}; /// @@ -45,7 +45,7 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::fs::File; /// use tokio::io::{AsyncSeekExt, AsyncReadExt}; /// diff --git a/tokio/src/io/util/async_write_ext.rs b/tokio/src/io/util/async_write_ext.rs index cd42d4f0fb7..1628b2bba14 100644 --- a/tokio/src/io/util/async_write_ext.rs +++ b/tokio/src/io/util/async_write_ext.rs @@ -43,7 +43,7 @@ cfg_io_util! { /// [`AsyncWrite`] types. Callers will tend to import this trait instead of /// [`AsyncWrite`]. /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -107,7 +107,7 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -147,7 +147,7 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// use std::io::IoSlice; @@ -227,7 +227,7 @@ cfg_io_util! { /// [`Buf`]: bytes::Buf /// [`Cursor`]: std::io::Cursor /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -298,7 +298,7 @@ cfg_io_util! { /// [`Cursor`]: std::io::Cursor /// [advanced]: bytes::Buf::advance /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -351,7 +351,7 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -395,7 +395,7 @@ cfg_io_util! { /// /// Write unsigned 8 bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -432,7 +432,7 @@ cfg_io_util! { /// /// Write signed 8 bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -470,7 +470,7 @@ cfg_io_util! { /// /// Write unsigned 16-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -508,7 +508,7 @@ cfg_io_util! { /// /// Write signed 16-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -546,7 +546,7 @@ cfg_io_util! { /// /// Write unsigned 32-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -584,7 +584,7 @@ cfg_io_util! { /// /// Write signed 32-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -622,7 +622,7 @@ cfg_io_util! { /// /// Write unsigned 64-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -660,7 +660,7 @@ cfg_io_util! { /// /// Write signed 64-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -698,7 +698,7 @@ cfg_io_util! { /// /// Write unsigned 128-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -738,7 +738,7 @@ cfg_io_util! { /// /// Write signed 128-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -778,7 +778,7 @@ cfg_io_util! { /// /// Write 32-bit floating point type to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -815,7 +815,7 @@ cfg_io_util! { /// /// Write 64-bit floating point type to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -854,7 +854,7 @@ cfg_io_util! { /// /// Write unsigned 16-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -892,7 +892,7 @@ cfg_io_util! { /// /// Write signed 16-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -930,7 +930,7 @@ cfg_io_util! { /// /// Write unsigned 32-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -968,7 +968,7 @@ cfg_io_util! { /// /// Write signed 32-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -1006,7 +1006,7 @@ cfg_io_util! { /// /// Write unsigned 64-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -1044,7 +1044,7 @@ cfg_io_util! { /// /// Write signed 64-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -1082,7 +1082,7 @@ cfg_io_util! { /// /// Write unsigned 128-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -1122,7 +1122,7 @@ cfg_io_util! { /// /// Write signed 128-bit integers to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -1162,7 +1162,7 @@ cfg_io_util! { /// /// Write 32-bit floating point type to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -1199,7 +1199,7 @@ cfg_io_util! { /// /// Write 64-bit floating point type to a `AsyncWrite`: /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] @@ -1243,7 +1243,7 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, BufWriter, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -1282,7 +1282,7 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run + /// ```no_run,ignore-wasm /// use tokio::io::{self, BufWriter, AsyncWriteExt}; /// use tokio::fs::File; /// diff --git a/tokio/src/io/util/empty.rs b/tokio/src/io/util/empty.rs index 8821f4f2e35..163b35f8914 100644 --- a/tokio/src/io/util/empty.rs +++ b/tokio/src/io/util/empty.rs @@ -36,7 +36,7 @@ cfg_io_util! { /// /// A slightly sad example of not reading anything into a buffer: /// - /// ``` + /// ```ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// #[tokio::main] @@ -49,7 +49,7 @@ cfg_io_util! { /// /// A convoluted way of getting the length of a buffer: /// - /// ``` + /// ```ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] diff --git a/tokio/src/io/util/repeat.rs b/tokio/src/io/util/repeat.rs index 33a8fd9862b..b1e63d93bda 100644 --- a/tokio/src/io/util/repeat.rs +++ b/tokio/src/io/util/repeat.rs @@ -34,7 +34,7 @@ cfg_io_util! { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::io::{self, AsyncReadExt}; /// /// #[tokio::main] diff --git a/tokio/src/io/util/sink.rs b/tokio/src/io/util/sink.rs index 01a4b111cc0..5142ed96dd6 100644 --- a/tokio/src/io/util/sink.rs +++ b/tokio/src/io/util/sink.rs @@ -34,7 +34,7 @@ cfg_io_util! { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::io::{self, AsyncWriteExt}; /// /// #[tokio::main] diff --git a/tokio/src/loom/std/barrier.rs b/tokio/src/loom/std/barrier.rs index a3f0ca0ab6d..468395d8e16 100644 --- a/tokio/src/loom/std/barrier.rs +++ b/tokio/src/loom/std/barrier.rs @@ -11,7 +11,7 @@ use std::time::{Duration, Instant}; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use std::sync::{Arc, Barrier}; /// use std::thread; /// @@ -102,7 +102,7 @@ impl Barrier { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use std::sync::{Arc, Barrier}; /// use std::thread; /// From 6dc771d6136530dabfa3781387d9f6ff55777991 Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Sat, 23 Aug 2025 14:25:02 -0700 Subject: [PATCH 09/19] test: revert changes to `macros_type_mismatch.stderr` --- tests-build/tests/fail/macros_type_mismatch.stderr | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests-build/tests/fail/macros_type_mismatch.stderr b/tests-build/tests/fail/macros_type_mismatch.stderr index 201df9cdd05..f9c32f00578 100644 --- a/tests-build/tests/fail/macros_type_mismatch.stderr +++ b/tests-build/tests/fail/macros_type_mismatch.stderr @@ -57,8 +57,6 @@ error[E0277]: the `?` operator can only be used in an async block that returns ` 39 | async fn question_mark_operator_with_invalid_option() -> Option<()> { 40 | None?; | ^ cannot use the `?` operator in an async block that returns `()` - | - = help: the trait `FromResidual>` is not implemented for `()` error[E0308]: mismatched types --> tests/fail/macros_type_mismatch.rs:40:5 @@ -87,8 +85,6 @@ error[E0277]: the `?` operator can only be used in an async block that returns ` 56 | async fn question_mark_operator_with_invalid_result() -> Result<(), ()> { 57 | Ok(())?; | ^ cannot use the `?` operator in an async block that returns `()` - | - = help: the trait `FromResidual>` is not implemented for `()` error[E0308]: mismatched types --> tests/fail/macros_type_mismatch.rs:57:5 From 5bf9656351c458a246849f73b75f538d3b62f7ab Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Tue, 2 Sep 2025 16:03:57 -0700 Subject: [PATCH 10/19] stream: revert annotations and utilize `futures::executor::block_on` --- tokio-stream/Cargo.toml | 2 +- tokio-stream/src/empty.rs | 9 +- tokio-stream/src/lib.rs | 9 +- tokio-stream/src/once.rs | 9 +- tokio-stream/src/stream_close.rs | 9 +- tokio-stream/src/stream_ext.rs | 168 ++++++++++++++++------------- tokio-stream/src/stream_map.rs | 14 ++- tokio-stream/src/wrappers/watch.rs | 24 ++--- 8 files changed, 153 insertions(+), 91 deletions(-) diff --git a/tokio-stream/Cargo.toml b/tokio-stream/Cargo.toml index 547d7f5deaf..87e8f14f79a 100644 --- a/tokio-stream/Cargo.toml +++ b/tokio-stream/Cargo.toml @@ -46,7 +46,7 @@ tokio = { version = "1.2.0", path = "../tokio", features = ["full", "test-util"] async-stream = "0.3" parking_lot = "0.12.0" tokio-test = { version = "0.4", path = "../tokio-test" } -futures = { version = "0.3", default-features = false } +futures = { version = "0.3", default-features = false, features = ["executor"] } [package.metadata.docs.rs] all-features = true diff --git a/tokio-stream/src/empty.rs b/tokio-stream/src/empty.rs index 39dd6040019..f6c67c5c344 100644 --- a/tokio-stream/src/empty.rs +++ b/tokio-stream/src/empty.rs @@ -23,15 +23,22 @@ unsafe impl Sync for Empty {} /// /// Basic usage: /// -/// ```ignore-wasm +/// ``` +/// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// +/// # /* /// #[tokio::main] /// async fn main() { +/// # */ +/// # block_on(async { /// let mut none = stream::empty::(); /// /// assert_eq!(None, none.next().await); +/// # }) +/// # /* /// } +/// # */ /// ``` pub const fn empty() -> Empty { Empty(PhantomData) diff --git a/tokio-stream/src/lib.rs b/tokio-stream/src/lib.rs index bbeaf66749b..735ab005ac4 100644 --- a/tokio-stream/src/lib.rs +++ b/tokio-stream/src/lib.rs @@ -31,17 +31,24 @@ //! `Stream`, but this is unfortunately not possible. Instead, you can use a //! `while let` loop as follows: //! -//! ```rust,ignore-wasm +//! ```rust +//! # use futures::executor::block_on; //! use tokio_stream::{self as stream, StreamExt}; //! +//! # /* //! #[tokio::main] //! async fn main() { +//! # */ +//! # block_on(async { //! let mut stream = stream::iter(vec![0, 1, 2]); //! //! while let Some(value) = stream.next().await { //! println!("Got {}", value); //! } +//! # }) +//! # /* //! } +//! # */ //! ``` //! //! # Returning a Stream from a function diff --git a/tokio-stream/src/once.rs b/tokio-stream/src/once.rs index 6f12b3413cd..2d4f22ff606 100644 --- a/tokio-stream/src/once.rs +++ b/tokio-stream/src/once.rs @@ -19,11 +19,15 @@ impl Unpin for Once {} /// /// # Examples /// -/// ```ignore-wasm +/// ``` +/// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// +/// # /* /// #[tokio::main] /// async fn main() { +/// # */ +/// # block_on(async { /// // one is the loneliest number /// let mut one = stream::once(1); /// @@ -31,7 +35,10 @@ impl Unpin for Once {} /// /// // just one, that's all we get /// assert_eq!(None, one.next().await); +/// # }) +/// # /* /// } +/// # */ /// ``` pub fn once(value: T) -> Once { Once { diff --git a/tokio-stream/src/stream_close.rs b/tokio-stream/src/stream_close.rs index 36e2f27bec4..cae470f3ff8 100644 --- a/tokio-stream/src/stream_close.rs +++ b/tokio-stream/src/stream_close.rs @@ -14,11 +14,15 @@ pin_project! { /// /// Using `StreamNotifyClose` to handle closed streams with `StreamMap`. /// - /// ```ignore-wasm + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{StreamExt, StreamMap, StreamNotifyClose}; /// + /// # /* /// #[tokio::main] /// async fn main() { + /// # */ + /// # block_on(async { /// let mut map = StreamMap::new(); /// let stream = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); /// let stream2 = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); @@ -30,7 +34,10 @@ pin_project! { /// None => println!("stream {key:?} closed"), /// } /// } + /// # }) + /// # /* /// } + /// # */ /// ``` #[must_use = "streams do nothing unless polled"] pub struct StreamNotifyClose { diff --git a/tokio-stream/src/stream_ext.rs b/tokio-stream/src/stream_ext.rs index 2812b858ae6..44b28dcd6ec 100644 --- a/tokio-stream/src/stream_ext.rs +++ b/tokio-stream/src/stream_ext.rs @@ -128,18 +128,18 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// + /// # block_on(async { /// let mut stream = stream::iter(1..=3); /// /// assert_eq!(stream.next().await, Some(1)); /// assert_eq!(stream.next().await, Some(2)); /// assert_eq!(stream.next().await, Some(3)); /// assert_eq!(stream.next().await, None); - /// # } + /// # }) /// ``` fn next(&mut self) -> Next<'_, Self> where @@ -170,17 +170,17 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// + /// # block_on(async { /// let mut stream = stream::iter(vec![Ok(1), Ok(2), Err("nope")]); /// /// assert_eq!(stream.try_next().await, Ok(Some(1))); /// assert_eq!(stream.try_next().await, Ok(Some(2))); /// assert_eq!(stream.try_next().await, Err("nope")); - /// # } + /// # }) /// ``` fn try_next(&mut self) -> TryNext<'_, Self> where @@ -202,18 +202,18 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// + /// # block_on(async { /// let stream = stream::iter(1..=3); /// let mut stream = stream.map(|x| x + 3); /// /// assert_eq!(stream.next().await, Some(4)); /// assert_eq!(stream.next().await, Some(5)); /// assert_eq!(stream.next().await, Some(6)); - /// # } + /// # }) /// ``` fn map(self, f: F) -> Map where @@ -238,11 +238,11 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// + /// # block_on(async { /// let stream = stream::iter(1..=10); /// let mut stream = stream.map_while(|x| { /// if x < 4 { @@ -255,7 +255,7 @@ pub trait StreamExt: Stream { /// assert_eq!(stream.next().await, Some(5)); /// assert_eq!(stream.next().await, Some(6)); /// assert_eq!(stream.next().await, None); - /// # } + /// # }) /// ``` fn map_while(self, f: F) -> MapWhile where @@ -282,11 +282,11 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// + /// # block_on(async { /// async fn do_async_work(value: i32) -> i32 { /// value + 3 /// } @@ -299,7 +299,7 @@ pub trait StreamExt: Stream { /// assert_eq!(stream.next().await, Some(4)); /// assert_eq!(stream.next().await, Some(5)); /// assert_eq!(stream.next().await, Some(6)); - /// # } + /// # }) /// ``` fn then(self, f: F) -> Then where @@ -417,11 +417,11 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// + /// # block_on(async { /// let stream = stream::iter(1..=8); /// let mut evens = stream.filter(|x| x % 2 == 0); /// @@ -430,7 +430,7 @@ pub trait StreamExt: Stream { /// assert_eq!(Some(6), evens.next().await); /// assert_eq!(Some(8), evens.next().await); /// assert_eq!(None, evens.next().await); - /// # } + /// # }) /// ``` fn filter(self, f: F) -> Filter where @@ -453,11 +453,11 @@ pub trait StreamExt: Stream { /// standard library. /// /// # Examples - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// + /// # block_on(async { /// let stream = stream::iter(1..=8); /// let mut evens = stream.filter_map(|x| { /// if x % 2 == 0 { Some(x + 1) } else { None } @@ -468,7 +468,7 @@ pub trait StreamExt: Stream { /// assert_eq!(Some(7), evens.next().await); /// assert_eq!(Some(9), evens.next().await); /// assert_eq!(None, evens.next().await); - /// # } + /// # }) /// ``` fn filter_map(self, f: F) -> FilterMap where @@ -487,7 +487,7 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio_stream::{Stream, StreamExt}; /// /// use std::pin::Pin; @@ -514,7 +514,10 @@ pub trait StreamExt: Stream { /// } /// } /// + /// # /* /// #[tokio::main] + /// # */ + /// # #[tokio::main(flavor = "current_thread")] /// async fn main() { /// let mut stream = Alternate { state: 0 }; /// @@ -550,10 +553,10 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; + /// # block_on(async { /// /// let mut stream = stream::iter(1..=10).take(3); /// @@ -561,7 +564,7 @@ pub trait StreamExt: Stream { /// assert_eq!(Some(2), stream.next().await); /// assert_eq!(Some(3), stream.next().await); /// assert_eq!(None, stream.next().await); - /// # } + /// # }) /// ``` fn take(self, n: usize) -> Take where @@ -579,10 +582,10 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; + /// # block_on(async { /// /// let mut stream = stream::iter(1..=10).take_while(|x| *x <= 3); /// @@ -590,7 +593,7 @@ pub trait StreamExt: Stream { /// assert_eq!(Some(2), stream.next().await); /// assert_eq!(Some(3), stream.next().await); /// assert_eq!(None, stream.next().await); - /// # } + /// # }) /// ``` fn take_while(self, f: F) -> TakeWhile where @@ -605,10 +608,10 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; + /// # block_on(async { /// /// let mut stream = stream::iter(1..=10).skip(7); /// @@ -616,7 +619,7 @@ pub trait StreamExt: Stream { /// assert_eq!(Some(9), stream.next().await); /// assert_eq!(Some(10), stream.next().await); /// assert_eq!(None, stream.next().await); - /// # } + /// # }) /// ``` fn skip(self, n: usize) -> Skip where @@ -636,17 +639,17 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; + /// # block_on(async { /// let mut stream = stream::iter(vec![1,2,3,4,1]).skip_while(|x| *x < 3); /// /// assert_eq!(Some(3), stream.next().await); /// assert_eq!(Some(4), stream.next().await); /// assert_eq!(Some(1), stream.next().await); /// assert_eq!(None, stream.next().await); - /// # } + /// # }) /// ``` fn skip_while(self, f: F) -> SkipWhile where @@ -679,25 +682,25 @@ pub trait StreamExt: Stream { /// /// Basic usage: /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; + /// # block_on(async { /// /// let a = [1, 2, 3]; /// /// assert!(stream::iter(&a).all(|&x| x > 0).await); /// /// assert!(!stream::iter(&a).all(|&x| x > 2).await); - /// # } + /// # }) /// ``` /// /// Stopping at the first `false`: /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; + /// # block_on(async { /// /// let a = [1, 2, 3]; /// @@ -707,7 +710,7 @@ pub trait StreamExt: Stream { /// /// // we can still use `iter`, as there are more elements. /// assert_eq!(iter.next().await, Some(&3)); - /// # } + /// # }) /// ``` fn all(&mut self, f: F) -> AllFuture<'_, Self, F> where @@ -738,25 +741,25 @@ pub trait StreamExt: Stream { /// /// Basic usage: /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; + /// # block_on(async { /// /// let a = [1, 2, 3]; /// /// assert!(stream::iter(&a).any(|&x| x > 0).await); /// /// assert!(!stream::iter(&a).any(|&x| x > 5).await); - /// # } + /// # }) /// ``` /// /// Stopping at the first `true`: /// - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; + /// # block_on(async { /// /// let a = [1, 2, 3]; /// @@ -766,7 +769,7 @@ pub trait StreamExt: Stream { /// /// // we can still use `iter`, as there are more elements. /// assert_eq!(iter.next().await, Some(&2)); - /// # } + /// # }) /// ``` fn any(&mut self, f: F) -> AnyFuture<'_, Self, F> where @@ -784,11 +787,15 @@ pub trait StreamExt: Stream { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// + /// # /* /// #[tokio::main] /// async fn main() { + /// # */ + /// # block_on(async { /// let one = stream::iter(vec![1, 2, 3]); /// let two = stream::iter(vec![4, 5, 6]); /// @@ -801,7 +808,10 @@ pub trait StreamExt: Stream { /// assert_eq!(stream.next().await, Some(5)); /// assert_eq!(stream.next().await, Some(6)); /// assert_eq!(stream.next().await, None); + /// # }) + /// # /* /// } + /// # */ /// ``` fn chain(self, other: U) -> Chain where @@ -822,16 +832,16 @@ pub trait StreamExt: Stream { /// /// # Examples /// Basic usage: - /// ```ignore-wasm - /// # #[tokio::main] - /// # async fn main() { + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, *}; + /// # block_on(async { /// /// let s = stream::iter(vec![1u8, 2, 3]); /// let sum = s.fold(0, |acc, x| acc + x).await; /// /// assert_eq!(sum, 6); - /// # } + /// # }) /// ``` fn fold(self, init: B, f: F) -> FoldFuture where @@ -871,11 +881,15 @@ pub trait StreamExt: Stream { /// /// Basic usage: /// - /// ```ignore-wasm + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// + /// # /* /// #[tokio::main] /// async fn main() { + /// # */ + /// # block_on(async { /// let doubled: Vec = /// stream::iter(vec![1, 2, 3]) /// .map(|x| x * 2) @@ -883,16 +897,23 @@ pub trait StreamExt: Stream { /// .await; /// /// assert_eq!(vec![2, 4, 6], doubled); + /// # }) + /// # /* /// } + /// # */ /// ``` /// /// Collecting a stream of `Result` values /// - /// ```ignore-wasm + /// ``` + /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// + /// # /* /// #[tokio::main] /// async fn main() { + /// # */ + /// # block_on(async { /// // A stream containing only `Ok` values will be collected /// let values: Result, &str> = /// stream::iter(vec![Ok(1), Ok(2), Ok(3)]) @@ -910,7 +931,10 @@ pub trait StreamExt: Stream { /// .await; /// /// assert_eq!(Err("no"), values); + /// # }) + /// # /* /// } + /// # */ /// ``` fn collect(self) -> Collect where @@ -944,8 +968,8 @@ pub trait StreamExt: Stream { /// /// Suppose we have a stream `int_stream` that yields 3 numbers (1, 2, 3): /// - /// ```ignore-wasm - /// # #[tokio::main] + /// ``` + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; /// use std::time::Duration; @@ -1030,8 +1054,8 @@ pub trait StreamExt: Stream { /// /// Suppose we have a stream `int_stream` that yields 3 numbers (1, 2, 3): /// - /// ```ignore-wasm - /// # #[tokio::main] + /// ``` + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; /// use std::time::Duration; diff --git a/tokio-stream/src/stream_map.rs b/tokio-stream/src/stream_map.rs index eedc95da49b..05f662702bb 100644 --- a/tokio-stream/src/stream_map.rs +++ b/tokio-stream/src/stream_map.rs @@ -60,12 +60,15 @@ use std::task::{ready, Context, Poll}; /// /// Merging two streams, then remove them after receiving the first value /// -/// ```ignore-wasm +/// ``` /// use tokio_stream::{StreamExt, StreamMap, Stream}; /// use tokio::sync::mpsc; /// use std::pin::Pin; /// +/// # /* /// #[tokio::main] +/// # */ +/// # #[tokio::main(flavor = "current_thread")] /// async fn main() { /// let (tx1, mut rx1) = mpsc::channel::(10); /// let (tx2, mut rx2) = mpsc::channel::(10); @@ -182,11 +185,15 @@ use std::task::{ready, Context, Poll}; /// /// Using `StreamNotifyClose` to handle closed streams with `StreamMap`. /// -/// ```ignore-wasm +/// ``` +/// # use futures::executor::block_on; /// use tokio_stream::{StreamExt, StreamMap, StreamNotifyClose}; /// +/// # /* /// #[tokio::main] /// async fn main() { +/// # */ +/// # block_on(async { /// let mut map = StreamMap::new(); /// let stream = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); /// let stream2 = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); @@ -198,7 +205,10 @@ use std::task::{ready, Context, Poll}; /// None => println!("stream {key:?} closed"), /// } /// } +/// # }) +/// # /* /// } +/// # */ /// ``` #[derive(Debug)] diff --git a/tokio-stream/src/wrappers/watch.rs b/tokio-stream/src/wrappers/watch.rs index a30dd32904a..76117d0720b 100644 --- a/tokio-stream/src/wrappers/watch.rs +++ b/tokio-stream/src/wrappers/watch.rs @@ -16,9 +16,9 @@ use tokio::sync::watch::error::RecvError; /// /// # Examples /// -/// ```ignore-wasm -/// # #[tokio::main] -/// # async fn main() { +/// ``` +/// # use futures::executor::block_on; +/// # block_on(async { /// use tokio_stream::{StreamExt, wrappers::WatchStream}; /// use tokio::sync::watch; /// @@ -29,12 +29,12 @@ use tokio::sync::watch::error::RecvError; /// /// tx.send("goodbye").unwrap(); /// assert_eq!(rx.next().await, Some("goodbye")); -/// # } +/// # }) /// ``` /// -/// ```ignore-wasm -/// # #[tokio::main] -/// # async fn main() { +/// ``` +/// # use futures::executor::block_on; +/// # block_on(async { /// use tokio_stream::{StreamExt, wrappers::WatchStream}; /// use tokio::sync::watch; /// @@ -45,14 +45,14 @@ use tokio::sync::watch::error::RecvError; /// /// tx.send("goodbye").unwrap(); /// assert_eq!(rx.next().await, Some("goodbye")); -/// # } +/// # }) /// ``` /// /// Example with [`WatchStream::from_changes`]: /// -/// ```ignore-wasm -/// # #[tokio::main] -/// # async fn main() { +/// ``` +/// # use futures::executor::block_on; +/// # block_on(async { /// use futures::future::FutureExt; /// use tokio::sync::watch; /// use tokio_stream::{StreamExt, wrappers::WatchStream}; @@ -65,7 +65,7 @@ use tokio::sync::watch::error::RecvError; /// /// tx.send("goodbye").unwrap(); /// assert_eq!(rx.next().await, Some("goodbye")); -/// # } +/// # }) /// ``` /// /// [`tokio::sync::watch::Receiver`]: struct@tokio::sync::watch::Receiver From e0762b679d1807b95654de2972ce6cb78cf2a90e Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Tue, 2 Sep 2025 17:06:51 -0700 Subject: [PATCH 11/19] ci|tokio: add `RUSTDOCFLAGS` and ignore subsequently failed tests --- .github/workflows/ci.yml | 3 +++ tokio/src/runtime/builder.rs | 22 ++++++++--------- tokio/src/runtime/id.rs | 2 +- tokio/src/runtime/local_runtime/runtime.rs | 2 +- tokio/src/runtime/metrics/runtime.rs | 28 +++++++++++----------- tokio/src/task/local.rs | 4 ++-- 6 files changed, 32 insertions(+), 29 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1346741ac21..0439ee90b81 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1097,6 +1097,9 @@ jobs: CARGO_TARGET_WASM32_WASIP1_RUNNER: "wasmtime run --" CARGO_TARGET_WASM32_WASIP1_THREADS_RUNNER: "wasmtime run -W bulk-memory=y -W threads=y -S threads=y --" RUSTFLAGS: --cfg tokio_unstable -Dwarnings -C target-feature=+atomics,+bulk-memory -C link-args=--max-memory=67108864 + # in order to run doctests for unstable features, we must also pass + # the unstable cfg to RustDoc + RUSTDOCFLAGS: --cfg tokio_unstable - name: WASI test tokio-util full run: cargo test -p tokio-util --target ${{ matrix.target }} --features full diff --git a/tokio/src/runtime/builder.rs b/tokio/src/runtime/builder.rs index 774e485e285..d8ebfc77207 100644 --- a/tokio/src/runtime/builder.rs +++ b/tokio/src/runtime/builder.rs @@ -151,7 +151,7 @@ cfg_unstable! { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::{self, UnhandledPanic}; /// /// # pub fn main() { @@ -753,7 +753,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use std::sync::{atomic::AtomicUsize, Arc}; /// # use tokio::task::yield_now; /// # pub fn main() { @@ -797,7 +797,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// # use std::sync::{atomic::AtomicUsize, Arc}; /// # use tokio::task::yield_now; /// # pub fn main() { @@ -1135,7 +1135,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime; /// /// let rt = runtime::Builder::new_multi_thread() @@ -1205,7 +1205,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime; /// /// let rt = runtime::Builder::new_multi_thread() @@ -1251,7 +1251,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::{self, HistogramScale}; /// /// # #[allow(deprecated)] @@ -1275,7 +1275,7 @@ impl Builder { /// /// # Examples /// Configure a [`LogHistogram`] with [default configuration]: - /// ``` + /// ```ignore-wasm /// use tokio::runtime; /// use tokio::runtime::{HistogramConfiguration, LogHistogram}; /// @@ -1289,7 +1289,7 @@ impl Builder { /// ``` /// /// Configure a linear histogram with 100 buckets, each 10μs wide - /// ``` + /// ```ignore-wasm /// use tokio::runtime; /// use std::time::Duration; /// use tokio::runtime::HistogramConfiguration; @@ -1307,7 +1307,7 @@ impl Builder { /// - Measure times from 100ns to 120s /// - Max error of 0.1 /// - No more than 1024 buckets - /// ``` + /// ```ignore-wasm /// use std::time::Duration; /// use tokio::runtime; /// use tokio::runtime::{HistogramConfiguration, LogHistogram}; @@ -1373,7 +1373,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime; /// use std::time::Duration; /// @@ -1408,7 +1408,7 @@ impl Builder { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime; /// /// # #[allow(deprecated)] diff --git a/tokio/src/runtime/id.rs b/tokio/src/runtime/id.rs index 8c6df7fcefb..14c724f7bd7 100644 --- a/tokio/src/runtime/id.rs +++ b/tokio/src/runtime/id.rs @@ -15,7 +15,7 @@ use std::num::{NonZeroU32, NonZeroU64}; /// /// # Examples /// -/// ``` +/// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main(flavor = "multi_thread", worker_threads = 4)] diff --git a/tokio/src/runtime/local_runtime/runtime.rs b/tokio/src/runtime/local_runtime/runtime.rs index 2e9d14e13b4..e72ea1fa4e6 100644 --- a/tokio/src/runtime/local_runtime/runtime.rs +++ b/tokio/src/runtime/local_runtime/runtime.rs @@ -312,7 +312,7 @@ impl LocalRuntime { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::LocalRuntime; /// use tokio::task; /// diff --git a/tokio/src/runtime/metrics/runtime.rs b/tokio/src/runtime/metrics/runtime.rs index a67ff09b371..65f99a07d73 100644 --- a/tokio/src/runtime/metrics/runtime.rs +++ b/tokio/src/runtime/metrics/runtime.rs @@ -251,7 +251,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -281,7 +281,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -325,7 +325,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -373,7 +373,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -547,7 +547,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -577,7 +577,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -605,7 +605,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -663,7 +663,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -709,7 +709,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -755,7 +755,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -796,7 +796,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -841,7 +841,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -887,7 +887,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -996,7 +996,7 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ``` + /// ```ignore-wasm /// use tokio::runtime::Handle; /// /// #[tokio::main] diff --git a/tokio/src/task/local.rs b/tokio/src/task/local.rs index 7d7b8e374be..e90a125a469 100644 --- a/tokio/src/task/local.rs +++ b/tokio/src/task/local.rs @@ -860,7 +860,7 @@ cfg_unstable! { /// execute. The call to `run_until` will panic due to the runtime being /// forcibly shutdown. /// - /// ```should_panic + /// ```should_panic,ignore-wasm /// use tokio::runtime::UnhandledPanic; /// /// # #[tokio::main] @@ -894,7 +894,7 @@ cfg_unstable! { /// /// # Examples /// - /// ```rust + /// ```rust,ignore-wasm /// use tokio::task; /// /// #[tokio::main] From 2ea35295f96ff7295c34c5a59f7051cb947d8c1d Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Wed, 3 Sep 2025 08:29:14 -0700 Subject: [PATCH 12/19] stream: use `current_thread` flavor instead of `futures::executor::block_on` --- tokio-stream/Cargo.toml | 2 +- tokio-stream/src/empty.rs | 8 +- tokio-stream/src/lib.rs | 8 +- tokio-stream/src/once.rs | 8 +- tokio-stream/src/stream_close.rs | 8 +- tokio-stream/src/stream_ext.rs | 121 +++++++++++++---------------- tokio-stream/src/stream_map.rs | 8 +- tokio-stream/src/wrappers/watch.rs | 18 ++--- 8 files changed, 75 insertions(+), 106 deletions(-) diff --git a/tokio-stream/Cargo.toml b/tokio-stream/Cargo.toml index 87e8f14f79a..547d7f5deaf 100644 --- a/tokio-stream/Cargo.toml +++ b/tokio-stream/Cargo.toml @@ -46,7 +46,7 @@ tokio = { version = "1.2.0", path = "../tokio", features = ["full", "test-util"] async-stream = "0.3" parking_lot = "0.12.0" tokio-test = { version = "0.4", path = "../tokio-test" } -futures = { version = "0.3", default-features = false, features = ["executor"] } +futures = { version = "0.3", default-features = false } [package.metadata.docs.rs] all-features = true diff --git a/tokio-stream/src/empty.rs b/tokio-stream/src/empty.rs index f6c67c5c344..7f5385f7b71 100644 --- a/tokio-stream/src/empty.rs +++ b/tokio-stream/src/empty.rs @@ -24,21 +24,17 @@ unsafe impl Sync for Empty {} /// Basic usage: /// /// ``` -/// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// /// # /* /// #[tokio::main] -/// async fn main() { /// # */ -/// # block_on(async { +/// # #[tokio::main(flavor = "current_thread")] +/// async fn main() { /// let mut none = stream::empty::(); /// /// assert_eq!(None, none.next().await); -/// # }) -/// # /* /// } -/// # */ /// ``` pub const fn empty() -> Empty { Empty(PhantomData) diff --git a/tokio-stream/src/lib.rs b/tokio-stream/src/lib.rs index 735ab005ac4..024b738af19 100644 --- a/tokio-stream/src/lib.rs +++ b/tokio-stream/src/lib.rs @@ -32,23 +32,19 @@ //! `while let` loop as follows: //! //! ```rust -//! # use futures::executor::block_on; //! use tokio_stream::{self as stream, StreamExt}; //! //! # /* //! #[tokio::main] -//! async fn main() { //! # */ -//! # block_on(async { +//! # #[tokio::main(flavor = "current_thread")] +//! async fn main() { //! let mut stream = stream::iter(vec![0, 1, 2]); //! //! while let Some(value) = stream.next().await { //! println!("Got {}", value); //! } -//! # }) -//! # /* //! } -//! # */ //! ``` //! //! # Returning a Stream from a function diff --git a/tokio-stream/src/once.rs b/tokio-stream/src/once.rs index 2d4f22ff606..5e3c56447bd 100644 --- a/tokio-stream/src/once.rs +++ b/tokio-stream/src/once.rs @@ -20,14 +20,13 @@ impl Unpin for Once {} /// # Examples /// /// ``` -/// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// /// # /* /// #[tokio::main] -/// async fn main() { /// # */ -/// # block_on(async { +/// # #[tokio::main(flavor = "current_thread")] +/// async fn main() { /// // one is the loneliest number /// let mut one = stream::once(1); /// @@ -35,10 +34,7 @@ impl Unpin for Once {} /// /// // just one, that's all we get /// assert_eq!(None, one.next().await); -/// # }) -/// # /* /// } -/// # */ /// ``` pub fn once(value: T) -> Once { Once { diff --git a/tokio-stream/src/stream_close.rs b/tokio-stream/src/stream_close.rs index cae470f3ff8..a17ce3e9225 100644 --- a/tokio-stream/src/stream_close.rs +++ b/tokio-stream/src/stream_close.rs @@ -15,14 +15,13 @@ pin_project! { /// Using `StreamNotifyClose` to handle closed streams with `StreamMap`. /// /// ``` - /// # use futures::executor::block_on; /// use tokio_stream::{StreamExt, StreamMap, StreamNotifyClose}; /// /// # /* /// #[tokio::main] - /// async fn main() { /// # */ - /// # block_on(async { + /// # #[tokio::main(flavor = "current_thread")] + /// async fn main() { /// let mut map = StreamMap::new(); /// let stream = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); /// let stream2 = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); @@ -34,10 +33,7 @@ pin_project! { /// None => println!("stream {key:?} closed"), /// } /// } - /// # }) - /// # /* /// } - /// # */ /// ``` #[must_use = "streams do nothing unless polled"] pub struct StreamNotifyClose { diff --git a/tokio-stream/src/stream_ext.rs b/tokio-stream/src/stream_ext.rs index 44b28dcd6ec..66f8228685a 100644 --- a/tokio-stream/src/stream_ext.rs +++ b/tokio-stream/src/stream_ext.rs @@ -129,17 +129,17 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; /// - /// # block_on(async { /// let mut stream = stream::iter(1..=3); /// /// assert_eq!(stream.next().await, Some(1)); /// assert_eq!(stream.next().await, Some(2)); /// assert_eq!(stream.next().await, Some(3)); /// assert_eq!(stream.next().await, None); - /// # }) + /// # } /// ``` fn next(&mut self) -> Next<'_, Self> where @@ -171,16 +171,17 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// /// use tokio_stream::{self as stream, StreamExt}; /// - /// # block_on(async { /// let mut stream = stream::iter(vec![Ok(1), Ok(2), Err("nope")]); /// /// assert_eq!(stream.try_next().await, Ok(Some(1))); /// assert_eq!(stream.try_next().await, Ok(Some(2))); /// assert_eq!(stream.try_next().await, Err("nope")); - /// # }) + /// # } /// ``` fn try_next(&mut self) -> TryNext<'_, Self> where @@ -203,17 +204,17 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; /// - /// # block_on(async { /// let stream = stream::iter(1..=3); /// let mut stream = stream.map(|x| x + 3); /// /// assert_eq!(stream.next().await, Some(4)); /// assert_eq!(stream.next().await, Some(5)); /// assert_eq!(stream.next().await, Some(6)); - /// # }) + /// # } /// ``` fn map(self, f: F) -> Map where @@ -239,10 +240,10 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; /// - /// # block_on(async { /// let stream = stream::iter(1..=10); /// let mut stream = stream.map_while(|x| { /// if x < 4 { @@ -255,7 +256,7 @@ pub trait StreamExt: Stream { /// assert_eq!(stream.next().await, Some(5)); /// assert_eq!(stream.next().await, Some(6)); /// assert_eq!(stream.next().await, None); - /// # }) + /// # } /// ``` fn map_while(self, f: F) -> MapWhile where @@ -283,10 +284,10 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; /// - /// # block_on(async { /// async fn do_async_work(value: i32) -> i32 { /// value + 3 /// } @@ -299,7 +300,7 @@ pub trait StreamExt: Stream { /// assert_eq!(stream.next().await, Some(4)); /// assert_eq!(stream.next().await, Some(5)); /// assert_eq!(stream.next().await, Some(6)); - /// # }) + /// # } /// ``` fn then(self, f: F) -> Then where @@ -418,10 +419,10 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; /// - /// # block_on(async { /// let stream = stream::iter(1..=8); /// let mut evens = stream.filter(|x| x % 2 == 0); /// @@ -430,7 +431,7 @@ pub trait StreamExt: Stream { /// assert_eq!(Some(6), evens.next().await); /// assert_eq!(Some(8), evens.next().await); /// assert_eq!(None, evens.next().await); - /// # }) + /// # } /// ``` fn filter(self, f: F) -> Filter where @@ -454,10 +455,10 @@ pub trait StreamExt: Stream { /// /// # Examples /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; /// - /// # block_on(async { /// let stream = stream::iter(1..=8); /// let mut evens = stream.filter_map(|x| { /// if x % 2 == 0 { Some(x + 1) } else { None } @@ -468,7 +469,7 @@ pub trait StreamExt: Stream { /// assert_eq!(Some(7), evens.next().await); /// assert_eq!(Some(9), evens.next().await); /// assert_eq!(None, evens.next().await); - /// # }) + /// # } /// ``` fn filter_map(self, f: F) -> FilterMap where @@ -554,9 +555,9 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; - /// # block_on(async { /// /// let mut stream = stream::iter(1..=10).take(3); /// @@ -564,7 +565,7 @@ pub trait StreamExt: Stream { /// assert_eq!(Some(2), stream.next().await); /// assert_eq!(Some(3), stream.next().await); /// assert_eq!(None, stream.next().await); - /// # }) + /// # } /// ``` fn take(self, n: usize) -> Take where @@ -583,9 +584,9 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; - /// # block_on(async { /// /// let mut stream = stream::iter(1..=10).take_while(|x| *x <= 3); /// @@ -593,7 +594,7 @@ pub trait StreamExt: Stream { /// assert_eq!(Some(2), stream.next().await); /// assert_eq!(Some(3), stream.next().await); /// assert_eq!(None, stream.next().await); - /// # }) + /// # } /// ``` fn take_while(self, f: F) -> TakeWhile where @@ -609,9 +610,9 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; - /// # block_on(async { /// /// let mut stream = stream::iter(1..=10).skip(7); /// @@ -619,7 +620,7 @@ pub trait StreamExt: Stream { /// assert_eq!(Some(9), stream.next().await); /// assert_eq!(Some(10), stream.next().await); /// assert_eq!(None, stream.next().await); - /// # }) + /// # } /// ``` fn skip(self, n: usize) -> Skip where @@ -640,16 +641,16 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; - /// # block_on(async { /// let mut stream = stream::iter(vec![1,2,3,4,1]).skip_while(|x| *x < 3); /// /// assert_eq!(Some(3), stream.next().await); /// assert_eq!(Some(4), stream.next().await); /// assert_eq!(Some(1), stream.next().await); /// assert_eq!(None, stream.next().await); - /// # }) + /// # } /// ``` fn skip_while(self, f: F) -> SkipWhile where @@ -683,24 +684,24 @@ pub trait StreamExt: Stream { /// Basic usage: /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; - /// # block_on(async { /// /// let a = [1, 2, 3]; /// /// assert!(stream::iter(&a).all(|&x| x > 0).await); /// /// assert!(!stream::iter(&a).all(|&x| x > 2).await); - /// # }) + /// # } /// ``` /// /// Stopping at the first `false`: /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; - /// # block_on(async { /// /// let a = [1, 2, 3]; /// @@ -710,7 +711,7 @@ pub trait StreamExt: Stream { /// /// // we can still use `iter`, as there are more elements. /// assert_eq!(iter.next().await, Some(&3)); - /// # }) + /// # } /// ``` fn all(&mut self, f: F) -> AllFuture<'_, Self, F> where @@ -742,24 +743,24 @@ pub trait StreamExt: Stream { /// Basic usage: /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; - /// # block_on(async { /// /// let a = [1, 2, 3]; /// /// assert!(stream::iter(&a).any(|&x| x > 0).await); /// /// assert!(!stream::iter(&a).any(|&x| x > 5).await); - /// # }) + /// # } /// ``` /// /// Stopping at the first `true`: /// /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, StreamExt}; - /// # block_on(async { /// /// let a = [1, 2, 3]; /// @@ -769,7 +770,7 @@ pub trait StreamExt: Stream { /// /// // we can still use `iter`, as there are more elements. /// assert_eq!(iter.next().await, Some(&2)); - /// # }) + /// # } /// ``` fn any(&mut self, f: F) -> AnyFuture<'_, Self, F> where @@ -788,14 +789,13 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// /// # /* /// #[tokio::main] - /// async fn main() { /// # */ - /// # block_on(async { + /// # #[tokio::main(flavor = "current_thread")] + /// async fn main() { /// let one = stream::iter(vec![1, 2, 3]); /// let two = stream::iter(vec![4, 5, 6]); /// @@ -808,10 +808,7 @@ pub trait StreamExt: Stream { /// assert_eq!(stream.next().await, Some(5)); /// assert_eq!(stream.next().await, Some(6)); /// assert_eq!(stream.next().await, None); - /// # }) - /// # /* /// } - /// # */ /// ``` fn chain(self, other: U) -> Chain where @@ -833,15 +830,15 @@ pub trait StreamExt: Stream { /// # Examples /// Basic usage: /// ``` - /// # use futures::executor::block_on; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// use tokio_stream::{self as stream, *}; - /// # block_on(async { /// /// let s = stream::iter(vec![1u8, 2, 3]); /// let sum = s.fold(0, |acc, x| acc + x).await; /// /// assert_eq!(sum, 6); - /// # }) + /// # } /// ``` fn fold(self, init: B, f: F) -> FoldFuture where @@ -882,14 +879,13 @@ pub trait StreamExt: Stream { /// Basic usage: /// /// ``` - /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// /// # /* /// #[tokio::main] - /// async fn main() { /// # */ - /// # block_on(async { + /// # #[tokio::main(flavor = "current_thread")] + /// async fn main() { /// let doubled: Vec = /// stream::iter(vec![1, 2, 3]) /// .map(|x| x * 2) @@ -897,23 +893,19 @@ pub trait StreamExt: Stream { /// .await; /// /// assert_eq!(vec![2, 4, 6], doubled); - /// # }) - /// # /* /// } - /// # */ /// ``` /// /// Collecting a stream of `Result` values /// /// ``` - /// # use futures::executor::block_on; /// use tokio_stream::{self as stream, StreamExt}; /// /// # /* /// #[tokio::main] - /// async fn main() { /// # */ - /// # block_on(async { + /// # #[tokio::main(flavor = "current_thread")] + /// async fn main() { /// // A stream containing only `Ok` values will be collected /// let values: Result, &str> = /// stream::iter(vec![Ok(1), Ok(2), Ok(3)]) @@ -931,10 +923,7 @@ pub trait StreamExt: Stream { /// .await; /// /// assert_eq!(Err("no"), values); - /// # }) - /// # /* /// } - /// # */ /// ``` fn collect(self) -> Collect where diff --git a/tokio-stream/src/stream_map.rs b/tokio-stream/src/stream_map.rs index 05f662702bb..0548c92cb9a 100644 --- a/tokio-stream/src/stream_map.rs +++ b/tokio-stream/src/stream_map.rs @@ -186,14 +186,13 @@ use std::task::{ready, Context, Poll}; /// Using `StreamNotifyClose` to handle closed streams with `StreamMap`. /// /// ``` -/// # use futures::executor::block_on; /// use tokio_stream::{StreamExt, StreamMap, StreamNotifyClose}; /// /// # /* /// #[tokio::main] -/// async fn main() { /// # */ -/// # block_on(async { +/// # #[tokio::main(flavor = "current_thread")] +/// async fn main() { /// let mut map = StreamMap::new(); /// let stream = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); /// let stream2 = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); @@ -205,10 +204,7 @@ use std::task::{ready, Context, Poll}; /// None => println!("stream {key:?} closed"), /// } /// } -/// # }) -/// # /* /// } -/// # */ /// ``` #[derive(Debug)] diff --git a/tokio-stream/src/wrappers/watch.rs b/tokio-stream/src/wrappers/watch.rs index 76117d0720b..e5eb47ef3c6 100644 --- a/tokio-stream/src/wrappers/watch.rs +++ b/tokio-stream/src/wrappers/watch.rs @@ -17,8 +17,8 @@ use tokio::sync::watch::error::RecvError; /// # Examples /// /// ``` -/// # use futures::executor::block_on; -/// # block_on(async { +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { /// use tokio_stream::{StreamExt, wrappers::WatchStream}; /// use tokio::sync::watch; /// @@ -29,12 +29,12 @@ use tokio::sync::watch::error::RecvError; /// /// tx.send("goodbye").unwrap(); /// assert_eq!(rx.next().await, Some("goodbye")); -/// # }) +/// # } /// ``` /// /// ``` -/// # use futures::executor::block_on; -/// # block_on(async { +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { /// use tokio_stream::{StreamExt, wrappers::WatchStream}; /// use tokio::sync::watch; /// @@ -45,14 +45,14 @@ use tokio::sync::watch::error::RecvError; /// /// tx.send("goodbye").unwrap(); /// assert_eq!(rx.next().await, Some("goodbye")); -/// # }) +/// # } /// ``` /// /// Example with [`WatchStream::from_changes`]: /// /// ``` -/// # use futures::executor::block_on; -/// # block_on(async { +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { /// use futures::future::FutureExt; /// use tokio::sync::watch; /// use tokio_stream::{StreamExt, wrappers::WatchStream}; @@ -65,7 +65,7 @@ use tokio::sync::watch::error::RecvError; /// /// tx.send("goodbye").unwrap(); /// assert_eq!(rx.next().await, Some("goodbye")); -/// # }) +/// # } /// ``` /// /// [`tokio::sync::watch::Receiver`]: struct@tokio::sync::watch::Receiver From f0df0a150eb30dc380a5b637cada83d872ecbd2f Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Fri, 5 Sep 2025 10:25:12 -0700 Subject: [PATCH 13/19] stream|util: revert and update `util` and `stream` annotations --- tokio-stream/src/empty.rs | 11 +- tokio-stream/src/lib.rs | 13 +- tokio-stream/src/once.rs | 17 +-- tokio-stream/src/stream_close.rs | 25 ++-- tokio-stream/src/stream_ext.rs | 160 +++++++++++------------ tokio-stream/src/stream_map.rs | 124 +++++++++--------- tokio-util/src/codec/length_delimited.rs | 4 +- tokio-util/src/codec/mod.rs | 32 ++--- tokio-util/src/either.rs | 24 ++-- tokio-util/src/io/read_arc.rs | 4 +- tokio-util/src/io/read_buf.rs | 4 +- tokio-util/src/io/reader_stream.rs | 4 +- tokio-util/src/io/sync_bridge.rs | 5 +- 13 files changed, 200 insertions(+), 227 deletions(-) diff --git a/tokio-stream/src/empty.rs b/tokio-stream/src/empty.rs index 7f5385f7b71..85d70079a17 100644 --- a/tokio-stream/src/empty.rs +++ b/tokio-stream/src/empty.rs @@ -26,15 +26,12 @@ unsafe impl Sync for Empty {} /// ``` /// use tokio_stream::{self as stream, StreamExt}; /// -/// # /* -/// #[tokio::main] -/// # */ /// # #[tokio::main(flavor = "current_thread")] -/// async fn main() { -/// let mut none = stream::empty::(); +/// # async fn main() { +/// let mut none = stream::empty::(); /// -/// assert_eq!(None, none.next().await); -/// } +/// assert_eq!(None, none.next().await); +/// # } /// ``` pub const fn empty() -> Empty { Empty(PhantomData) diff --git a/tokio-stream/src/lib.rs b/tokio-stream/src/lib.rs index 024b738af19..a5b3a05e03a 100644 --- a/tokio-stream/src/lib.rs +++ b/tokio-stream/src/lib.rs @@ -34,17 +34,14 @@ //! ```rust //! use tokio_stream::{self as stream, StreamExt}; //! -//! # /* -//! #[tokio::main] -//! # */ //! # #[tokio::main(flavor = "current_thread")] -//! async fn main() { -//! let mut stream = stream::iter(vec![0, 1, 2]); +//! # async fn main() { +//! let mut stream = stream::iter(vec![0, 1, 2]); //! -//! while let Some(value) = stream.next().await { -//! println!("Got {}", value); -//! } +//! while let Some(value) = stream.next().await { +//! println!("Got {}", value); //! } +//! # } //! ``` //! //! # Returning a Stream from a function diff --git a/tokio-stream/src/once.rs b/tokio-stream/src/once.rs index 5e3c56447bd..ccde6281999 100644 --- a/tokio-stream/src/once.rs +++ b/tokio-stream/src/once.rs @@ -22,19 +22,16 @@ impl Unpin for Once {} /// ``` /// use tokio_stream::{self as stream, StreamExt}; /// -/// # /* -/// #[tokio::main] -/// # */ /// # #[tokio::main(flavor = "current_thread")] -/// async fn main() { -/// // one is the loneliest number -/// let mut one = stream::once(1); +/// # async fn main() { +/// // one is the loneliest number +/// let mut one = stream::once(1); /// -/// assert_eq!(Some(1), one.next().await); +/// assert_eq!(Some(1), one.next().await); /// -/// // just one, that's all we get -/// assert_eq!(None, one.next().await); -/// } +/// // just one, that's all we get +/// assert_eq!(None, one.next().await); +/// # } /// ``` pub fn once(value: T) -> Once { Once { diff --git a/tokio-stream/src/stream_close.rs b/tokio-stream/src/stream_close.rs index a17ce3e9225..f9b2f1ada08 100644 --- a/tokio-stream/src/stream_close.rs +++ b/tokio-stream/src/stream_close.rs @@ -17,23 +17,20 @@ pin_project! { /// ``` /// use tokio_stream::{StreamExt, StreamMap, StreamNotifyClose}; /// - /// # /* - /// #[tokio::main] - /// # */ /// # #[tokio::main(flavor = "current_thread")] - /// async fn main() { - /// let mut map = StreamMap::new(); - /// let stream = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); - /// let stream2 = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); - /// map.insert(0, stream); - /// map.insert(1, stream2); - /// while let Some((key, val)) = map.next().await { - /// match val { - /// Some(val) => println!("got {val:?} from stream {key:?}"), - /// None => println!("stream {key:?} closed"), - /// } + /// # async fn main() { + /// let mut map = StreamMap::new(); + /// let stream = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); + /// let stream2 = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); + /// map.insert(0, stream); + /// map.insert(1, stream2); + /// while let Some((key, val)) = map.next().await { + /// match val { + /// Some(val) => println!("got {val:?} from stream {key:?}"), + /// None => println!("stream {key:?} closed"), /// } /// } + /// # } /// ``` #[must_use = "streams do nothing unless polled"] pub struct StreamNotifyClose { diff --git a/tokio-stream/src/stream_ext.rs b/tokio-stream/src/stream_ext.rs index 66f8228685a..ec8fb1b252a 100644 --- a/tokio-stream/src/stream_ext.rs +++ b/tokio-stream/src/stream_ext.rs @@ -338,62 +338,59 @@ pub trait StreamExt: Stream { /// use std::time::Duration; /// use std::pin::Pin; /// - /// # /* - /// #[tokio::main] - /// # */ /// # #[tokio::main(flavor = "current_thread")] - /// async fn main() { + /// # async fn main() { /// # time::pause(); - /// let (tx1, mut rx1) = mpsc::channel::(10); - /// let (tx2, mut rx2) = mpsc::channel::(10); + /// let (tx1, mut rx1) = mpsc::channel::(10); + /// let (tx2, mut rx2) = mpsc::channel::(10); /// - /// // Convert the channels to a `Stream`. - /// let rx1 = Box::pin(async_stream::stream! { - /// while let Some(item) = rx1.recv().await { - /// yield item; - /// } - /// }) as Pin + Send>>; + /// // Convert the channels to a `Stream`. + /// let rx1 = Box::pin(async_stream::stream! { + /// while let Some(item) = rx1.recv().await { + /// yield item; + /// } + /// }) as Pin + Send>>; /// - /// let rx2 = Box::pin(async_stream::stream! { - /// while let Some(item) = rx2.recv().await { - /// yield item; - /// } - /// }) as Pin + Send>>; + /// let rx2 = Box::pin(async_stream::stream! { + /// while let Some(item) = rx2.recv().await { + /// yield item; + /// } + /// }) as Pin + Send>>; /// - /// let mut rx = rx1.merge(rx2); + /// let mut rx = rx1.merge(rx2); /// - /// tokio::spawn(async move { - /// // Send some values immediately - /// tx1.send(1).await.unwrap(); - /// tx1.send(2).await.unwrap(); + /// tokio::spawn(async move { + /// // Send some values immediately + /// tx1.send(1).await.unwrap(); + /// tx1.send(2).await.unwrap(); /// - /// // Let the other task send values - /// time::sleep(Duration::from_millis(20)).await; + /// // Let the other task send values + /// time::sleep(Duration::from_millis(20)).await; /// - /// tx1.send(4).await.unwrap(); - /// }); + /// tx1.send(4).await.unwrap(); + /// }); /// - /// tokio::spawn(async move { - /// // Wait for the first task to send values - /// time::sleep(Duration::from_millis(5)).await; + /// tokio::spawn(async move { + /// // Wait for the first task to send values + /// time::sleep(Duration::from_millis(5)).await; /// - /// tx2.send(3).await.unwrap(); + /// tx2.send(3).await.unwrap(); /// - /// time::sleep(Duration::from_millis(25)).await; + /// time::sleep(Duration::from_millis(25)).await; /// - /// // Send the final value - /// tx2.send(5).await.unwrap(); - /// }); + /// // Send the final value + /// tx2.send(5).await.unwrap(); + /// }); /// - /// assert_eq!(1, rx.next().await.unwrap()); - /// assert_eq!(2, rx.next().await.unwrap()); - /// assert_eq!(3, rx.next().await.unwrap()); - /// assert_eq!(4, rx.next().await.unwrap()); - /// assert_eq!(5, rx.next().await.unwrap()); + /// assert_eq!(1, rx.next().await.unwrap()); + /// assert_eq!(2, rx.next().await.unwrap()); + /// assert_eq!(3, rx.next().await.unwrap()); + /// assert_eq!(4, rx.next().await.unwrap()); + /// assert_eq!(5, rx.next().await.unwrap()); /// - /// // The merged stream is consumed - /// assert!(rx.next().await.is_none()); - /// } + /// // The merged stream is consumed + /// assert!(rx.next().await.is_none()); + /// # } /// ``` fn merge(self, other: U) -> Merge where @@ -791,24 +788,21 @@ pub trait StreamExt: Stream { /// ``` /// use tokio_stream::{self as stream, StreamExt}; /// - /// # /* - /// #[tokio::main] - /// # */ /// # #[tokio::main(flavor = "current_thread")] - /// async fn main() { - /// let one = stream::iter(vec![1, 2, 3]); - /// let two = stream::iter(vec![4, 5, 6]); + /// # async fn main() { + /// let one = stream::iter(vec![1, 2, 3]); + /// let two = stream::iter(vec![4, 5, 6]); /// - /// let mut stream = one.chain(two); + /// let mut stream = one.chain(two); /// - /// assert_eq!(stream.next().await, Some(1)); - /// assert_eq!(stream.next().await, Some(2)); - /// assert_eq!(stream.next().await, Some(3)); - /// assert_eq!(stream.next().await, Some(4)); - /// assert_eq!(stream.next().await, Some(5)); - /// assert_eq!(stream.next().await, Some(6)); - /// assert_eq!(stream.next().await, None); - /// } + /// assert_eq!(stream.next().await, Some(1)); + /// assert_eq!(stream.next().await, Some(2)); + /// assert_eq!(stream.next().await, Some(3)); + /// assert_eq!(stream.next().await, Some(4)); + /// assert_eq!(stream.next().await, Some(5)); + /// assert_eq!(stream.next().await, Some(6)); + /// assert_eq!(stream.next().await, None); + /// # } /// ``` fn chain(self, other: U) -> Chain where @@ -881,19 +875,16 @@ pub trait StreamExt: Stream { /// ``` /// use tokio_stream::{self as stream, StreamExt}; /// - /// # /* - /// #[tokio::main] - /// # */ /// # #[tokio::main(flavor = "current_thread")] - /// async fn main() { - /// let doubled: Vec = - /// stream::iter(vec![1, 2, 3]) - /// .map(|x| x * 2) - /// .collect() - /// .await; + /// # async fn main() { + /// let doubled: Vec = + /// stream::iter(vec![1, 2, 3]) + /// .map(|x| x * 2) + /// .collect() + /// .await; /// - /// assert_eq!(vec![2, 4, 6], doubled); - /// } + /// assert_eq!(vec![2, 4, 6], doubled); + /// # } /// ``` /// /// Collecting a stream of `Result` values @@ -901,29 +892,26 @@ pub trait StreamExt: Stream { /// ``` /// use tokio_stream::{self as stream, StreamExt}; /// - /// # /* - /// #[tokio::main] - /// # */ /// # #[tokio::main(flavor = "current_thread")] - /// async fn main() { - /// // A stream containing only `Ok` values will be collected - /// let values: Result, &str> = - /// stream::iter(vec![Ok(1), Ok(2), Ok(3)]) - /// .collect() - /// .await; + /// # async fn main() { + /// // A stream containing only `Ok` values will be collected + /// let values: Result, &str> = + /// stream::iter(vec![Ok(1), Ok(2), Ok(3)]) + /// .collect() + /// .await; /// - /// assert_eq!(Ok(vec![1, 2, 3]), values); + /// assert_eq!(Ok(vec![1, 2, 3]), values); /// - /// // A stream containing `Err` values will return the first error. - /// let results = vec![Ok(1), Err("no"), Ok(2), Ok(3), Err("nein")]; + /// // A stream containing `Err` values will return the first error. + /// let results = vec![Ok(1), Err("no"), Ok(2), Ok(3), Err("nein")]; /// - /// let values: Result, &str> = - /// stream::iter(results) - /// .collect() - /// .await; + /// let values: Result, &str> = + /// stream::iter(results) + /// .collect() + /// .await; /// - /// assert_eq!(Err("no"), values); - /// } + /// assert_eq!(Err("no"), values); + /// # } /// ``` fn collect(self) -> Collect where diff --git a/tokio-stream/src/stream_map.rs b/tokio-stream/src/stream_map.rs index 0548c92cb9a..b015c053f33 100644 --- a/tokio-stream/src/stream_map.rs +++ b/tokio-stream/src/stream_map.rs @@ -65,60 +65,57 @@ use std::task::{ready, Context, Poll}; /// use tokio::sync::mpsc; /// use std::pin::Pin; /// -/// # /* -/// #[tokio::main] -/// # */ /// # #[tokio::main(flavor = "current_thread")] -/// async fn main() { -/// let (tx1, mut rx1) = mpsc::channel::(10); -/// let (tx2, mut rx2) = mpsc::channel::(10); -/// -/// // Convert the channels to a `Stream`. -/// let rx1 = Box::pin(async_stream::stream! { -/// while let Some(item) = rx1.recv().await { -/// yield item; -/// } -/// }) as Pin + Send>>; -/// -/// let rx2 = Box::pin(async_stream::stream! { -/// while let Some(item) = rx2.recv().await { -/// yield item; -/// } -/// }) as Pin + Send>>; -/// -/// tokio::spawn(async move { -/// tx1.send(1).await.unwrap(); -/// -/// // This value will never be received. The send may or may not return -/// // `Err` depending on if the remote end closed first or not. -/// let _ = tx1.send(2).await; -/// }); -/// -/// tokio::spawn(async move { -/// tx2.send(3).await.unwrap(); -/// let _ = tx2.send(4).await; -/// }); -/// -/// let mut map = StreamMap::new(); -/// -/// // Insert both streams -/// map.insert("one", rx1); -/// map.insert("two", rx2); -/// -/// // Read twice -/// for _ in 0..2 { -/// let (key, val) = map.next().await.unwrap(); -/// -/// if key == "one" { -/// assert_eq!(val, 1); -/// } else { -/// assert_eq!(val, 3); -/// } -/// -/// // Remove the stream to prevent reading the next value -/// map.remove(key); +/// # async fn main() { +/// let (tx1, mut rx1) = mpsc::channel::(10); +/// let (tx2, mut rx2) = mpsc::channel::(10); +/// +/// // Convert the channels to a `Stream`. +/// let rx1 = Box::pin(async_stream::stream! { +/// while let Some(item) = rx1.recv().await { +/// yield item; +/// } +/// }) as Pin + Send>>; +/// +/// let rx2 = Box::pin(async_stream::stream! { +/// while let Some(item) = rx2.recv().await { +/// yield item; +/// } +/// }) as Pin + Send>>; +/// +/// tokio::spawn(async move { +/// tx1.send(1).await.unwrap(); +/// +/// // This value will never be received. The send may or may not return +/// // `Err` depending on if the remote end closed first or not. +/// let _ = tx1.send(2).await; +/// }); +/// +/// tokio::spawn(async move { +/// tx2.send(3).await.unwrap(); +/// let _ = tx2.send(4).await; +/// }); +/// +/// let mut map = StreamMap::new(); +/// +/// // Insert both streams +/// map.insert("one", rx1); +/// map.insert("two", rx2); +/// +/// // Read twice +/// for _ in 0..2 { +/// let (key, val) = map.next().await.unwrap(); +/// +/// if key == "one" { +/// assert_eq!(val, 1); +/// } else { +/// assert_eq!(val, 3); /// } +/// +/// // Remove the stream to prevent reading the next value +/// map.remove(key); /// } +/// # } /// ``` /// /// This example models a read-only client to a chat system with channels. The @@ -188,23 +185,20 @@ use std::task::{ready, Context, Poll}; /// ``` /// use tokio_stream::{StreamExt, StreamMap, StreamNotifyClose}; /// -/// # /* -/// #[tokio::main] -/// # */ /// # #[tokio::main(flavor = "current_thread")] -/// async fn main() { -/// let mut map = StreamMap::new(); -/// let stream = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); -/// let stream2 = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); -/// map.insert(0, stream); -/// map.insert(1, stream2); -/// while let Some((key, val)) = map.next().await { -/// match val { -/// Some(val) => println!("got {val:?} from stream {key:?}"), -/// None => println!("stream {key:?} closed"), -/// } +/// # async fn main() { +/// let mut map = StreamMap::new(); +/// let stream = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); +/// let stream2 = StreamNotifyClose::new(tokio_stream::iter(vec![0, 1])); +/// map.insert(0, stream); +/// map.insert(1, stream2); +/// while let Some((key, val)) = map.next().await { +/// match val { +/// Some(val) => println!("got {val:?} from stream {key:?}"), +/// None => println!("stream {key:?} closed"), /// } /// } +/// # } /// ``` #[derive(Debug)] diff --git a/tokio-util/src/codec/length_delimited.rs b/tokio-util/src/codec/length_delimited.rs index 138e81d4b80..add40eb2f94 100644 --- a/tokio-util/src/codec/length_delimited.rs +++ b/tokio-util/src/codec/length_delimited.rs @@ -78,10 +78,10 @@ //! The following will parse a `u16` length field at offset 0, omitting the //! frame head in the yielded `BytesMut`. //! -//! ```ignore-wasm +//! ``` //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; -//! # #[tokio::main] +//! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! # let io: &[u8] = b"\x00\x0BHello world"; //! let mut reader = LengthDelimitedCodec::builder() diff --git a/tokio-util/src/codec/mod.rs b/tokio-util/src/codec/mod.rs index 4bc3a0b7a52..ad6e4434fc5 100644 --- a/tokio-util/src/codec/mod.rs +++ b/tokio-util/src/codec/mod.rs @@ -14,30 +14,30 @@ //! [`FramedWrite`] are first framed according to a specific codec, and then sent to //! an implementor of [`AsyncWrite`]. //! -//! ```ignore-wasm +//! ``` //! use futures::sink::SinkExt; //! use tokio_util::codec::LinesCodec; //! use tokio_util::codec::FramedWrite; //! -//! #[tokio::main] -//! async fn main() { -//! let buffer = Vec::new(); -//! let messages = vec!["Hello", "World"]; -//! let encoder = LinesCodec::new(); +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let buffer = Vec::new(); +//! let messages = vec!["Hello", "World"]; +//! let encoder = LinesCodec::new(); //! -//! // FramedWrite is a sink which means you can send values into it -//! // asynchronously. -//! let mut writer = FramedWrite::new(buffer, encoder); +//! // FramedWrite is a sink which means you can send values into it +//! // asynchronously. +//! let mut writer = FramedWrite::new(buffer, encoder); //! -//! // To be able to send values into a FramedWrite, you need to bring the -//! // `SinkExt` trait into scope. -//! writer.send(messages[0]).await.unwrap(); -//! writer.send(messages[1]).await.unwrap(); +//! // To be able to send values into a FramedWrite, you need to bring the +//! // `SinkExt` trait into scope. +//! writer.send(messages[0]).await.unwrap(); +//! writer.send(messages[1]).await.unwrap(); //! -//! let buffer = writer.get_ref(); +//! let buffer = writer.get_ref(); //! -//! assert_eq!(buffer.as_slice(), "Hello\nWorld\n".as_bytes()); -//! } +//! assert_eq!(buffer.as_slice(), "Hello\nWorld\n".as_bytes()); +//! # } //!``` //! //! # Example decoding using `LinesCodec` diff --git a/tokio-util/src/either.rs b/tokio-util/src/either.rs index e2d58098655..9e4c34fa3ef 100644 --- a/tokio-util/src/either.rs +++ b/tokio-util/src/either.rs @@ -40,24 +40,24 @@ use tokio::io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, ReadBuf, Result} /// When the output type is the same, we can wrap each future in `Either` to avoid the /// issue: /// -/// ```ignore-wasm +/// ``` /// use tokio_util::either::Either; /// # fn some_condition() -> bool { true } /// # async fn some_async_function() -> u32 { 10 } /// # async fn other_async_function() -> u32 { 20 } /// -/// #[tokio::main] -/// async fn main() { -/// let result = if some_condition() { -/// Either::Left(some_async_function()) -/// } else { -/// Either::Right(other_async_function()) -/// }; +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let result = if some_condition() { +/// Either::Left(some_async_function()) +/// } else { +/// Either::Right(other_async_function()) +/// }; /// -/// let value = result.await; -/// println!("Result is {}", value); -/// # assert_eq!(value, 10); -/// } +/// let value = result.await; +/// println!("Result is {}", value); +/// # assert_eq!(value, 10); +/// # } /// ``` #[allow(missing_docs)] // Doc-comments for variants in this particular case don't make much sense. #[derive(Debug, Clone)] diff --git a/tokio-util/src/io/read_arc.rs b/tokio-util/src/io/read_arc.rs index 51955a80527..393b7f4fbec 100644 --- a/tokio-util/src/io/read_arc.rs +++ b/tokio-util/src/io/read_arc.rs @@ -9,8 +9,8 @@ use tokio::io::{AsyncRead, AsyncReadExt}; /// /// # Example /// -/// ```ignore-wasm -/// # #[tokio::main] +/// ``` +/// # #[tokio::main(flavor = "current_thread")] /// # async fn main() -> std::io::Result<()> { /// use tokio_util::io::read_exact_arc; /// diff --git a/tokio-util/src/io/read_buf.rs b/tokio-util/src/io/read_buf.rs index ffebb335215..ddc974bfa8a 100644 --- a/tokio-util/src/io/read_buf.rs +++ b/tokio-util/src/io/read_buf.rs @@ -11,12 +11,12 @@ use tokio::io::AsyncRead; /// /// # Example /// -/// ```ignore-wasm +/// ``` /// use bytes::{Bytes, BytesMut}; /// use tokio_stream as stream; /// use tokio::io::Result; /// use tokio_util::io::{StreamReader, read_buf}; -/// # #[tokio::main] +/// # #[tokio::main(flavor = "current_thread")] /// # async fn main() -> std::io::Result<()> { /// /// // Create a reader from an iterator. This particular reader will always be diff --git a/tokio-util/src/io/reader_stream.rs b/tokio-util/src/io/reader_stream.rs index 6c07526e707..93bc594f22f 100644 --- a/tokio-util/src/io/reader_stream.rs +++ b/tokio-util/src/io/reader_stream.rs @@ -15,8 +15,8 @@ pin_project! { /// /// # Example /// - /// ```ignore-wasm - /// # #[tokio::main] + /// ``` + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() -> std::io::Result<()> { /// use tokio_stream::StreamExt; /// use tokio_util::io::ReaderStream; diff --git a/tokio-util/src/io/sync_bridge.rs b/tokio-util/src/io/sync_bridge.rs index b768bf288c2..f01de6f724d 100644 --- a/tokio-util/src/io/sync_bridge.rs +++ b/tokio-util/src/io/sync_bridge.rs @@ -77,7 +77,7 @@ use tokio::io::{ /// incrementally. This avoids blocking and improves performance over using /// `SyncIoBridge`. /// -/// ```rust,ignore-wasm +/// ```rust /// use tokio::io::AsyncReadExt; /// use tokio::io::AsyncRead; /// use std::io::Cursor; @@ -104,7 +104,10 @@ use tokio::io::{ /// Ok(hash) ///} /// +/// # /* /// #[tokio::main] +/// # */ +/// # #[tokio::main(flavor = "current_thread")] /// async fn main() -> Result<(), std::io::Error> { /// // Example: In-memory data. /// let data = b"Hello, world!"; // A byte slice. From 58f199e42c520aa15b5a53838b4fc3093b4319ba Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Fri, 5 Sep 2025 10:48:27 -0700 Subject: [PATCH 14/19] util: lower memory allocated for `sync_bridge.rs` doctest --- tokio-util/src/io/sync_bridge.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tokio-util/src/io/sync_bridge.rs b/tokio-util/src/io/sync_bridge.rs index f01de6f724d..669e6372d13 100644 --- a/tokio-util/src/io/sync_bridge.rs +++ b/tokio-util/src/io/sync_bridge.rs @@ -88,7 +88,7 @@ use tokio::io::{ /// /// and hashes the data incrementally. /// async fn hash_stream(mut reader: impl AsyncRead + Unpin, mut hasher: Hasher) -> Result<(), std::io::Error> { /// // Create a buffer to read data into, sized for performance. -/// let mut data = vec![0; 64 * 1024]; +/// let mut data = vec![0; 16 * 1024]; /// loop { /// // Read data from the reader into the buffer. /// let len = reader.read(&mut data).await?; From 8e453ba09dda43337c58d5e03897e69666cb4e94 Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Tue, 9 Sep 2025 05:00:16 -0700 Subject: [PATCH 15/19] revert most annotations and re-enable tests, overhaul formatting --- tokio-stream/src/stream_ext.rs | 81 +- tokio-util/src/codec/length_delimited.rs | 24 +- tokio-util/src/codec/mod.rs | 40 +- tokio-util/src/io/sync_bridge.rs | 37 +- tokio-util/src/task/join_map.rs | 90 +- tokio-util/src/task/task_tracker.rs | 30 +- tokio-util/src/time/delay_queue.rs | 52 +- tokio-util/src/util/poll_buf.rs | 4 +- tokio/src/io/util/async_buf_read_ext.rs | 134 +-- tokio/src/io/util/async_read_ext.rs | 358 +++---- tokio/src/io/util/async_seek_ext.rs | 24 +- tokio/src/io/util/async_write_ext.rs | 412 ++++---- tokio/src/io/util/empty.rs | 22 +- tokio/src/io/util/repeat.rs | 14 +- tokio/src/io/util/sink.rs | 16 +- tokio/src/macros/join.rs | 34 +- tokio/src/macros/pin.rs | 70 +- tokio/src/macros/select.rs | 379 ++++--- tokio/src/macros/try_join.rs | 86 +- tokio/src/runtime/builder.rs | 2 +- tokio/src/runtime/metrics/runtime.rs | 282 ++--- tokio/src/runtime/task/error.rs | 16 +- tokio/src/runtime/task/join.rs | 45 +- tokio/src/sync/barrier.rs | 4 +- tokio/src/sync/broadcast.rs | 548 +++++----- tokio/src/sync/mod.rs | 320 +++--- tokio/src/sync/mpsc/bounded.rs | 978 +++++++++--------- tokio/src/sync/mpsc/unbounded.rs | 298 +++--- tokio/src/sync/mutex.rs | 128 +-- tokio/src/sync/notify.rs | 134 +-- tokio/src/sync/once_cell.rs | 48 +- tokio/src/sync/oneshot.rs | 626 +++++------ tokio/src/sync/rwlock.rs | 312 +++--- tokio/src/sync/rwlock/owned_read_guard.rs | 12 +- tokio/src/sync/rwlock/owned_write_guard.rs | 24 +- .../sync/rwlock/owned_write_guard_mapped.rs | 12 +- tokio/src/sync/rwlock/read_guard.rs | 8 +- tokio/src/sync/rwlock/write_guard.rs | 20 +- tokio/src/sync/rwlock/write_guard_mapped.rs | 8 +- tokio/src/sync/semaphore.rs | 240 ++--- tokio/src/sync/set_once.rs | 86 +- tokio/src/sync/watch.rs | 224 ++-- tokio/src/task/coop/mod.rs | 4 +- tokio/src/task/join_set.rs | 140 +-- tokio/src/task/local.rs | 174 ++-- tokio/src/task/mod.rs | 15 +- tokio/src/task/spawn.rs | 24 +- tokio/src/time/instant.rs | 50 +- tokio/src/time/interval.rs | 186 ++-- tokio/src/time/mod.rs | 24 +- tokio/src/time/sleep.rs | 60 +- 51 files changed, 3481 insertions(+), 3478 deletions(-) diff --git a/tokio-stream/src/stream_ext.rs b/tokio-stream/src/stream_ext.rs index ec8fb1b252a..7e915d9909e 100644 --- a/tokio-stream/src/stream_ext.rs +++ b/tokio-stream/src/stream_ext.rs @@ -338,59 +338,62 @@ pub trait StreamExt: Stream { /// use std::time::Duration; /// use std::pin::Pin; /// + /// # /* + /// #[tokio::main] + /// # */ /// # #[tokio::main(flavor = "current_thread")] - /// # async fn main() { + /// async fn main() { /// # time::pause(); - /// let (tx1, mut rx1) = mpsc::channel::(10); - /// let (tx2, mut rx2) = mpsc::channel::(10); + /// let (tx1, mut rx1) = mpsc::channel::(10); + /// let (tx2, mut rx2) = mpsc::channel::(10); /// - /// // Convert the channels to a `Stream`. - /// let rx1 = Box::pin(async_stream::stream! { - /// while let Some(item) = rx1.recv().await { - /// yield item; - /// } - /// }) as Pin + Send>>; + /// // Convert the channels to a `Stream`. + /// let rx1 = Box::pin(async_stream::stream! { + /// while let Some(item) = rx1.recv().await { + /// yield item; + /// } + /// }) as Pin + Send>>; /// - /// let rx2 = Box::pin(async_stream::stream! { - /// while let Some(item) = rx2.recv().await { - /// yield item; - /// } - /// }) as Pin + Send>>; + /// let rx2 = Box::pin(async_stream::stream! { + /// while let Some(item) = rx2.recv().await { + /// yield item; + /// } + /// }) as Pin + Send>>; /// - /// let mut rx = rx1.merge(rx2); + /// let mut rx = rx1.merge(rx2); /// - /// tokio::spawn(async move { - /// // Send some values immediately - /// tx1.send(1).await.unwrap(); - /// tx1.send(2).await.unwrap(); + /// tokio::spawn(async move { + /// // Send some values immediately + /// tx1.send(1).await.unwrap(); + /// tx1.send(2).await.unwrap(); /// - /// // Let the other task send values - /// time::sleep(Duration::from_millis(20)).await; + /// // Let the other task send values + /// time::sleep(Duration::from_millis(20)).await; /// - /// tx1.send(4).await.unwrap(); - /// }); + /// tx1.send(4).await.unwrap(); + /// }); /// - /// tokio::spawn(async move { - /// // Wait for the first task to send values - /// time::sleep(Duration::from_millis(5)).await; + /// tokio::spawn(async move { + /// // Wait for the first task to send values + /// time::sleep(Duration::from_millis(5)).await; /// - /// tx2.send(3).await.unwrap(); + /// tx2.send(3).await.unwrap(); /// - /// time::sleep(Duration::from_millis(25)).await; + /// time::sleep(Duration::from_millis(25)).await; /// - /// // Send the final value - /// tx2.send(5).await.unwrap(); - /// }); + /// // Send the final value + /// tx2.send(5).await.unwrap(); + /// }); /// - /// assert_eq!(1, rx.next().await.unwrap()); - /// assert_eq!(2, rx.next().await.unwrap()); - /// assert_eq!(3, rx.next().await.unwrap()); - /// assert_eq!(4, rx.next().await.unwrap()); - /// assert_eq!(5, rx.next().await.unwrap()); + /// assert_eq!(1, rx.next().await.unwrap()); + /// assert_eq!(2, rx.next().await.unwrap()); + /// assert_eq!(3, rx.next().await.unwrap()); + /// assert_eq!(4, rx.next().await.unwrap()); + /// assert_eq!(5, rx.next().await.unwrap()); /// - /// // The merged stream is consumed - /// assert!(rx.next().await.is_none()); - /// # } + /// // The merged stream is consumed + /// assert!(rx.next().await.is_none()); + /// } /// ``` fn merge(self, other: U) -> Merge where diff --git a/tokio-util/src/codec/length_delimited.rs b/tokio-util/src/codec/length_delimited.rs index add40eb2f94..ff40fe497c9 100644 --- a/tokio-util/src/codec/length_delimited.rs +++ b/tokio-util/src/codec/length_delimited.rs @@ -114,10 +114,10 @@ //! The following will parse a `u16` length field at offset 0, including the //! frame head in the yielded `BytesMut`. //! -//! ```ignore-wasm +//! ``` //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; -//! # #[tokio::main] +//! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! # let io: &[u8] = b"\x00\x0BHello world"; //! let mut reader = LengthDelimitedCodec::builder() @@ -151,10 +151,10 @@ //! frame head in the yielded `BytesMut`. In this case, the length field //! **includes** the frame head length. //! -//! ```ignore-wasm +//! ``` //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; -//! # #[tokio::main] +//! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! # let io: &[u8] = b"\x00\x0DHello world"; //! let mut reader = LengthDelimitedCodec::builder() @@ -187,10 +187,10 @@ //! The following will parse a 3 byte length field at offset 0 in a 5 byte //! frame head, including the frame head in the yielded `BytesMut`. //! -//! ```ignore-wasm +//! ``` //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; -//! # #[tokio::main] +//! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! # let io: &[u8] = b"\x00\x00\x0B\xCA\xFEHello world"; //! let mut reader = LengthDelimitedCodec::builder() @@ -234,10 +234,10 @@ //! yielded `BytesMut`, but the trailing 2 bytes of the frame head will be //! included. //! -//! ```ignore-wasm +//! ``` //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; -//! # #[tokio::main] +//! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! # let io: &[u8] = b"\xCA\x00\x0B\xFEHello world"; //! let mut reader = LengthDelimitedCodec::builder() @@ -283,10 +283,10 @@ //! included. In this case, the length field **includes** the frame head //! length. //! -//! ```ignore-wasm +//! ``` //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; -//! # #[tokio::main] +//! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! # let io: &[u8] = b"\xCA\x00\x0F\xFEHello world"; //! let mut reader = LengthDelimitedCodec::builder() @@ -326,10 +326,10 @@ //! The following will parse a 3 byte length field at offset 0 in a 4 byte //! frame head, excluding the 4th byte from the yielded `BytesMut`. //! -//! ```ignore-wasm +//! ``` //! # use tokio_stream::StreamExt; //! # use tokio_util::codec::LengthDelimitedCodec; -//! # #[tokio::main] +//! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! # let io: &[u8] = b"\x00\x00\x0B\xFFHello world"; //! let mut reader = LengthDelimitedCodec::builder() diff --git a/tokio-util/src/codec/mod.rs b/tokio-util/src/codec/mod.rs index ad6e4434fc5..a03c0b943d4 100644 --- a/tokio-util/src/codec/mod.rs +++ b/tokio-util/src/codec/mod.rs @@ -46,30 +46,30 @@ //! will keep reading from an [`AsyncRead`] implementor until a whole frame, according to a codec, //! can be parsed. //! -//!```ignore-wasm +//!``` //! use tokio_stream::StreamExt; //! use tokio_util::codec::LinesCodec; //! use tokio_util::codec::FramedRead; //! -//! #[tokio::main] -//! async fn main() { -//! let message = "Hello\nWorld".as_bytes(); -//! let decoder = LinesCodec::new(); -//! -//! // FramedRead can be used to read a stream of values that are framed according to -//! // a codec. FramedRead will read from its input (here `buffer`) until a whole frame -//! // can be parsed. -//! let mut reader = FramedRead::new(message, decoder); -//! -//! // To read values from a FramedRead, you need to bring the -//! // `StreamExt` trait into scope. -//! let frame1 = reader.next().await.unwrap().unwrap(); -//! let frame2 = reader.next().await.unwrap().unwrap(); -//! -//! assert!(reader.next().await.is_none()); -//! assert_eq!(frame1, "Hello"); -//! assert_eq!(frame2, "World"); -//! } +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let message = "Hello\nWorld".as_bytes(); +//! let decoder = LinesCodec::new(); +//! +//! // FramedRead can be used to read a stream of values that are framed according to +//! // a codec. FramedRead will read from its input (here `buffer`) until a whole frame +//! // can be parsed. +//! let mut reader = FramedRead::new(message, decoder); +//! +//! // To read values from a FramedRead, you need to bring the +//! // `StreamExt` trait into scope. +//! let frame1 = reader.next().await.unwrap().unwrap(); +//! let frame2 = reader.next().await.unwrap().unwrap(); +//! +//! assert!(reader.next().await.is_none()); +//! assert_eq!(frame1, "Hello"); +//! assert_eq!(frame2, "World"); +//! # } //! ``` //! //! # The Decoder trait diff --git a/tokio-util/src/io/sync_bridge.rs b/tokio-util/src/io/sync_bridge.rs index 669e6372d13..c42ff577992 100644 --- a/tokio-util/src/io/sync_bridge.rs +++ b/tokio-util/src/io/sync_bridge.rs @@ -42,7 +42,7 @@ use tokio::io::{ /// Explanation: This example demonstrates how to asynchronously read data from a /// reader into memory and hash it using a synchronous hashing function. The /// `SyncIoBridge` is avoided, ensuring that the async runtime is not blocked. -/// ```rust,ignore-wasm +/// ```rust /// use tokio::io::AsyncReadExt; /// use tokio::io::AsyncRead; /// use std::io::Cursor; @@ -57,15 +57,15 @@ use tokio::io::{ /// let hash = blake3::hash(&data); /// /// Ok(hash) -///} -/// -/// #[tokio::main] -/// async fn main() -> Result<(), std::io::Error> { -/// // Example: In-memory data. -/// let data = b"Hello, world!"; // A byte slice. -/// let reader = Cursor::new(data); // Create an in-memory AsyncRead. -/// hash_contents(reader).await /// } +/// +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() -> Result<(), std::io::Error> { +/// // Example: In-memory data. +/// let data = b"Hello, world!"; // A byte slice. +/// let reader = Cursor::new(data); // Create an in-memory AsyncRead. +/// hash_contents(reader).await +/// # } /// ``` /// /// When the data doesn't fit into memory, the hashing library will usually @@ -102,19 +102,16 @@ use tokio::io::{ /// let hash = hasher.finalize(); /// /// Ok(hash) -///} +/// } /// -/// # /* -/// #[tokio::main] -/// # */ /// # #[tokio::main(flavor = "current_thread")] -/// async fn main() -> Result<(), std::io::Error> { -/// // Example: In-memory data. -/// let data = b"Hello, world!"; // A byte slice. -/// let reader = Cursor::new(data); // Create an in-memory AsyncRead. -/// let hasher = Hasher; -/// hash_stream(reader, hasher).await -/// } +/// # async fn main() -> Result<(), std::io::Error> { +/// // Example: In-memory data. +/// let data = b"Hello, world!"; // A byte slice. +/// let reader = Cursor::new(data); // Create an in-memory AsyncRead. +/// let hasher = Hasher; +/// hash_stream(reader, hasher).await +/// # } /// ``` /// /// diff --git a/tokio-util/src/task/join_map.rs b/tokio-util/src/task/join_map.rs index 5f4d4d5d6a6..7740e91161f 100644 --- a/tokio-util/src/task/join_map.rs +++ b/tokio-util/src/task/join_map.rs @@ -33,62 +33,62 @@ use tokio::task::{AbortHandle, Id, JoinError, JoinSet, LocalSet}; /// /// Spawn multiple tasks and wait for them: /// -/// ```ignore-wasm +/// ``` /// use tokio_util::task::JoinMap; /// -/// #[tokio::main] -/// async fn main() { -/// let mut map = JoinMap::new(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let mut map = JoinMap::new(); /// -/// for i in 0..10 { -/// // Spawn a task on the `JoinMap` with `i` as its key. -/// map.spawn(i, async move { /* ... */ }); -/// } +/// for i in 0..10 { +/// // Spawn a task on the `JoinMap` with `i` as its key. +/// map.spawn(i, async move { /* ... */ }); +/// } /// -/// let mut seen = [false; 10]; +/// let mut seen = [false; 10]; /// -/// // When a task completes, `join_next` returns the task's key along -/// // with its output. -/// while let Some((key, res)) = map.join_next().await { -/// seen[key] = true; -/// assert!(res.is_ok(), "task {} completed successfully!", key); -/// } +/// // When a task completes, `join_next` returns the task's key along +/// // with its output. +/// while let Some((key, res)) = map.join_next().await { +/// seen[key] = true; +/// assert!(res.is_ok(), "task {} completed successfully!", key); +/// } /// -/// for i in 0..10 { -/// assert!(seen[i]); -/// } +/// for i in 0..10 { +/// assert!(seen[i]); /// } +/// # } /// ``` /// /// Cancel tasks based on their keys: /// -/// ```ignore-wasm +/// ``` /// use tokio_util::task::JoinMap; /// -/// #[tokio::main] -/// async fn main() { -/// let mut map = JoinMap::new(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let mut map = JoinMap::new(); /// -/// map.spawn("hello world", std::future::ready(1)); -/// map.spawn("goodbye world", std::future::pending()); +/// map.spawn("hello world", std::future::ready(1)); +/// map.spawn("goodbye world", std::future::pending()); /// -/// // Look up the "goodbye world" task in the map and abort it. -/// let aborted = map.abort("goodbye world"); +/// // Look up the "goodbye world" task in the map and abort it. +/// let aborted = map.abort("goodbye world"); /// -/// // `JoinMap::abort` returns `true` if a task existed for the -/// // provided key. -/// assert!(aborted); +/// // `JoinMap::abort` returns `true` if a task existed for the +/// // provided key. +/// assert!(aborted); /// -/// while let Some((key, res)) = map.join_next().await { -/// if key == "goodbye world" { -/// // The aborted task should complete with a cancelled `JoinError`. -/// assert!(res.unwrap_err().is_cancelled()); -/// } else { -/// // Other tasks should complete normally. -/// assert_eq!(res.unwrap(), 1); -/// } +/// while let Some((key, res)) = map.join_next().await { +/// if key == "goodbye world" { +/// // The aborted task should complete with a cancelled `JoinError`. +/// assert!(res.unwrap_err().is_cancelled()); +/// } else { +/// // Other tasks should complete normally. +/// assert_eq!(res.unwrap(), 1); /// } /// } +/// # } /// ``` /// /// [`JoinSet`]: tokio::task::JoinSet @@ -185,8 +185,8 @@ impl JoinMap { /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] + /// ``` + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// use tokio_util::task::JoinMap; /// use std::collections::hash_map::RandomState; @@ -518,10 +518,10 @@ where /// ``` /// /// `abort` returns `true` if a task was aborted: - /// ```ignore-wasm + /// ``` /// use tokio_util::task::JoinMap; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut map = JoinMap::new(); /// @@ -685,8 +685,8 @@ where /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] + /// ``` + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// use tokio_util::task::JoinMap; /// @@ -714,8 +714,8 @@ where /// /// # Examples /// - /// ```ignore-wasm - /// # #[tokio::main] + /// ``` + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// use tokio_util::task::JoinMap; /// diff --git a/tokio-util/src/task/task_tracker.rs b/tokio-util/src/task/task_tracker.rs index ebb57e29ffd..e168baa4238 100644 --- a/tokio-util/src/task/task_tracker.rs +++ b/tokio-util/src/task/task_tracker.rs @@ -63,26 +63,26 @@ use tokio::{ /// /// This is a simple example. For this case, [`JoinSet`] should probably be used instead. /// -/// ```ignore-wasm +/// ``` /// use tokio_util::task::TaskTracker; /// -/// #[tokio::main] -/// async fn main() { -/// let tracker = TaskTracker::new(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let tracker = TaskTracker::new(); /// -/// for i in 0..10 { -/// tracker.spawn(async move { -/// println!("Task {} is running!", i); -/// }); -/// } -/// // Once we spawned everything, we close the tracker. -/// tracker.close(); +/// for i in 0..10 { +/// tracker.spawn(async move { +/// println!("Task {} is running!", i); +/// }); +/// } +/// // Once we spawned everything, we close the tracker. +/// tracker.close(); /// -/// // Wait for everything to finish. -/// tracker.wait().await; +/// // Wait for everything to finish. +/// tracker.wait().await; /// -/// println!("This is printed after all of the tasks."); -/// } +/// println!("This is printed after all of the tasks."); +/// # } /// ``` /// /// ## Wait for tasks to exit diff --git a/tokio-util/src/time/delay_queue.rs b/tokio-util/src/time/delay_queue.rs index 6365b06ae7e..e48948a9f7c 100644 --- a/tokio-util/src/time/delay_queue.rs +++ b/tokio-util/src/time/delay_queue.rs @@ -452,11 +452,11 @@ impl DelayQueue { /// /// # Examples /// - /// ```rust,ignore-wasm + /// ```rust /// # use tokio_util::time::DelayQueue; /// # use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::with_capacity(10); /// @@ -508,11 +508,11 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::time::{Duration, Instant}; /// use tokio_util::time::DelayQueue; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::new(); /// let key = delay_queue.insert_at( @@ -628,11 +628,11 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::new(); /// let key = delay_queue.insert("foo", Duration::from_secs(5)); @@ -683,11 +683,11 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::new(); /// @@ -734,11 +734,11 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::new(); /// let key = delay_queue.insert("foo", Duration::from_secs(5)); @@ -832,11 +832,11 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::time::{Duration, Instant}; /// use tokio_util::time::DelayQueue; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::new(); /// let key = delay_queue.insert("foo", Duration::from_secs(5)); @@ -889,11 +889,11 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::with_capacity(10); /// @@ -922,11 +922,11 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::new(); /// @@ -974,11 +974,11 @@ impl DelayQueue { /// /// Basic usage /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::new(); /// let key = delay_queue.insert("foo", Duration::from_secs(5)); @@ -1005,11 +1005,11 @@ impl DelayQueue { /// /// # Examples /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::new(); /// @@ -1047,11 +1047,11 @@ impl DelayQueue { /// /// # Examples /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue: DelayQueue = DelayQueue::with_capacity(10); /// assert_eq!(delay_queue.len(), 0); @@ -1082,11 +1082,11 @@ impl DelayQueue { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::new(); /// @@ -1112,11 +1112,11 @@ impl DelayQueue { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio_util::time::DelayQueue; /// use std::time::Duration; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut delay_queue = DelayQueue::new(); /// assert!(delay_queue.is_empty()); diff --git a/tokio-util/src/util/poll_buf.rs b/tokio-util/src/util/poll_buf.rs index 19a6684fcaa..4894d164cb1 100644 --- a/tokio-util/src/util/poll_buf.rs +++ b/tokio-util/src/util/poll_buf.rs @@ -11,14 +11,14 @@ use std::task::{ready, Context, Poll}; /// /// # Example /// -/// ```ignore-wasm +/// ``` /// use bytes::{Bytes, BytesMut}; /// use tokio_stream as stream; /// use tokio::io::Result; /// use tokio_util::io::{StreamReader, poll_read_buf}; /// use std::future::poll_fn; /// use std::pin::Pin; -/// # #[tokio::main] +/// # #[tokio::main(flavor = "current_thread")] /// # async fn main() -> std::io::Result<()> { /// /// // Create a reader from an iterator. This particular reader will always be diff --git a/tokio/src/io/util/async_buf_read_ext.rs b/tokio/src/io/util/async_buf_read_ext.rs index 2ddbd42af50..f6ef7419528 100644 --- a/tokio/src/io/util/async_buf_read_ext.rs +++ b/tokio/src/io/util/async_buf_read_ext.rs @@ -57,41 +57,41 @@ cfg_io_util! { /// /// [`Cursor`]: std::io::Cursor /// - /// ```ignore-wasm + /// ``` /// use tokio::io::AsyncBufReadExt; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() { - /// let mut cursor = Cursor::new(b"lorem-ipsum"); - /// let mut buf = vec![]; - /// - /// // cursor is at 'l' - /// let num_bytes = cursor.read_until(b'-', &mut buf) - /// .await - /// .expect("reading from cursor won't fail"); - /// - /// assert_eq!(num_bytes, 6); - /// assert_eq!(buf, b"lorem-"); - /// buf.clear(); - /// - /// // cursor is at 'i' - /// let num_bytes = cursor.read_until(b'-', &mut buf) - /// .await - /// .expect("reading from cursor won't fail"); - /// - /// assert_eq!(num_bytes, 5); - /// assert_eq!(buf, b"ipsum"); - /// buf.clear(); - /// - /// // cursor is at EOF - /// let num_bytes = cursor.read_until(b'-', &mut buf) - /// .await - /// .expect("reading from cursor won't fail"); - /// assert_eq!(num_bytes, 0); - /// assert_eq!(buf, b""); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut cursor = Cursor::new(b"lorem-ipsum"); + /// let mut buf = vec![]; + /// + /// // cursor is at 'l' + /// let num_bytes = cursor.read_until(b'-', &mut buf) + /// .await + /// .expect("reading from cursor won't fail"); + /// + /// assert_eq!(num_bytes, 6); + /// assert_eq!(buf, b"lorem-"); + /// buf.clear(); + /// + /// // cursor is at 'i' + /// let num_bytes = cursor.read_until(b'-', &mut buf) + /// .await + /// .expect("reading from cursor won't fail"); + /// + /// assert_eq!(num_bytes, 5); + /// assert_eq!(buf, b"ipsum"); + /// buf.clear(); + /// + /// // cursor is at EOF + /// let num_bytes = cursor.read_until(b'-', &mut buf) + /// .await + /// .expect("reading from cursor won't fail"); + /// assert_eq!(num_bytes, 0); + /// assert_eq!(buf, b""); + /// # } /// ``` fn read_until<'a>(&'a mut self, byte: u8, buf: &'a mut Vec) -> ReadUntil<'a, Self> where @@ -159,42 +159,42 @@ cfg_io_util! { /// /// [`Cursor`]: std::io::Cursor /// - /// ```ignore-wasm + /// ``` /// use tokio::io::AsyncBufReadExt; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() { - /// let mut cursor = Cursor::new(b"foo\nbar"); - /// let mut buf = String::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut cursor = Cursor::new(b"foo\nbar"); + /// let mut buf = String::new(); /// - /// // cursor is at 'f' - /// let num_bytes = cursor.read_line(&mut buf) - /// .await - /// .expect("reading from cursor won't fail"); + /// // cursor is at 'f' + /// let num_bytes = cursor.read_line(&mut buf) + /// .await + /// .expect("reading from cursor won't fail"); /// - /// assert_eq!(num_bytes, 4); - /// assert_eq!(buf, "foo\n"); - /// buf.clear(); + /// assert_eq!(num_bytes, 4); + /// assert_eq!(buf, "foo\n"); + /// buf.clear(); /// - /// // cursor is at 'b' - /// let num_bytes = cursor.read_line(&mut buf) - /// .await - /// .expect("reading from cursor won't fail"); + /// // cursor is at 'b' + /// let num_bytes = cursor.read_line(&mut buf) + /// .await + /// .expect("reading from cursor won't fail"); /// - /// assert_eq!(num_bytes, 3); - /// assert_eq!(buf, "bar"); - /// buf.clear(); + /// assert_eq!(num_bytes, 3); + /// assert_eq!(buf, "bar"); + /// buf.clear(); /// - /// // cursor is at EOF - /// let num_bytes = cursor.read_line(&mut buf) - /// .await - /// .expect("reading from cursor won't fail"); + /// // cursor is at EOF + /// let num_bytes = cursor.read_line(&mut buf) + /// .await + /// .expect("reading from cursor won't fail"); /// - /// assert_eq!(num_bytes, 0); - /// assert_eq!(buf, ""); - /// } + /// assert_eq!(num_bytes, 0); + /// assert_eq!(buf, ""); + /// # } /// ``` fn read_line<'a>(&'a mut self, buf: &'a mut String) -> ReadLine<'a, Self> where @@ -326,22 +326,22 @@ cfg_io_util! { /// /// [`Cursor`]: std::io::Cursor /// - /// ```ignore-wasm + /// ``` /// use tokio::io::AsyncBufReadExt; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() { - /// let cursor = Cursor::new(b"lorem\nipsum\r\ndolor"); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let cursor = Cursor::new(b"lorem\nipsum\r\ndolor"); /// - /// let mut lines = cursor.lines(); + /// let mut lines = cursor.lines(); /// - /// assert_eq!(lines.next_line().await.unwrap(), Some(String::from("lorem"))); - /// assert_eq!(lines.next_line().await.unwrap(), Some(String::from("ipsum"))); - /// assert_eq!(lines.next_line().await.unwrap(), Some(String::from("dolor"))); - /// assert_eq!(lines.next_line().await.unwrap(), None); - /// } + /// assert_eq!(lines.next_line().await.unwrap(), Some(String::from("lorem"))); + /// assert_eq!(lines.next_line().await.unwrap(), Some(String::from("ipsum"))); + /// assert_eq!(lines.next_line().await.unwrap(), Some(String::from("dolor"))); + /// assert_eq!(lines.next_line().await.unwrap(), None); + /// # } /// ``` /// /// [`AsyncBufReadExt::read_line`]: AsyncBufReadExt::read_line diff --git a/tokio/src/io/util/async_read_ext.rs b/tokio/src/io/util/async_read_ext.rs index 124a0e97e59..d6befce1e62 100644 --- a/tokio/src/io/util/async_read_ext.rs +++ b/tokio/src/io/util/async_read_ext.rs @@ -340,20 +340,20 @@ cfg_io_util! { /// /// Read unsigned 8 bit integers from an `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![2, 5]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![2, 5]); /// - /// assert_eq!(2, reader.read_u8().await?); - /// assert_eq!(5, reader.read_u8().await?); + /// assert_eq!(2, reader.read_u8().await?); + /// assert_eq!(5, reader.read_u8().await?); /// - /// Ok(()) - /// } + /// Ok(()) + /// # } /// ``` fn read_u8(&mut self) -> ReadU8; @@ -384,20 +384,20 @@ cfg_io_util! { /// /// Read unsigned 8 bit integers from an `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0x02, 0xfb]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0x02, 0xfb]); /// - /// assert_eq!(2, reader.read_i8().await?); - /// assert_eq!(-5, reader.read_i8().await?); + /// assert_eq!(2, reader.read_i8().await?); + /// assert_eq!(-5, reader.read_i8().await?); /// - /// Ok(()) - /// } + /// Ok(()) + /// # } /// ``` fn read_i8(&mut self) -> ReadI8; @@ -429,19 +429,19 @@ cfg_io_util! { /// /// Read unsigned 16 bit big-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![2, 5, 3, 0]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![2, 5, 3, 0]); /// - /// assert_eq!(517, reader.read_u16().await?); - /// assert_eq!(768, reader.read_u16().await?); - /// Ok(()) - /// } + /// assert_eq!(517, reader.read_u16().await?); + /// assert_eq!(768, reader.read_u16().await?); + /// Ok(()) + /// # } /// ``` fn read_u16(&mut self) -> ReadU16; @@ -473,19 +473,19 @@ cfg_io_util! { /// /// Read signed 16 bit big-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0x00, 0xc1, 0xff, 0x7c]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0x00, 0xc1, 0xff, 0x7c]); /// - /// assert_eq!(193, reader.read_i16().await?); - /// assert_eq!(-132, reader.read_i16().await?); - /// Ok(()) - /// } + /// assert_eq!(193, reader.read_i16().await?); + /// assert_eq!(-132, reader.read_i16().await?); + /// Ok(()) + /// # } /// ``` fn read_i16(&mut self) -> ReadI16; @@ -517,18 +517,18 @@ cfg_io_util! { /// /// Read unsigned 32-bit big-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0x00, 0x00, 0x01, 0x0b]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0x00, 0x00, 0x01, 0x0b]); /// - /// assert_eq!(267, reader.read_u32().await?); - /// Ok(()) - /// } + /// assert_eq!(267, reader.read_u32().await?); + /// Ok(()) + /// # } /// ``` fn read_u32(&mut self) -> ReadU32; @@ -561,18 +561,18 @@ cfg_io_util! { /// /// Read signed 32-bit big-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0xff, 0xff, 0x7a, 0x33]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0xff, 0xff, 0x7a, 0x33]); /// - /// assert_eq!(-34253, reader.read_i32().await?); - /// Ok(()) - /// } + /// assert_eq!(-34253, reader.read_i32().await?); + /// Ok(()) + /// # } /// ``` fn read_i32(&mut self) -> ReadI32; @@ -604,20 +604,20 @@ cfg_io_util! { /// /// Read unsigned 64-bit big-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![ - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 - /// ]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![ + /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 + /// ]); /// - /// assert_eq!(918733457491587, reader.read_u64().await?); - /// Ok(()) - /// } + /// assert_eq!(918733457491587, reader.read_u64().await?); + /// Ok(()) + /// # } /// ``` fn read_u64(&mut self) -> ReadU64; @@ -649,18 +649,18 @@ cfg_io_util! { /// /// Read signed 64-bit big-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0]); /// - /// assert_eq!(i64::MIN, reader.read_i64().await?); - /// Ok(()) - /// } + /// assert_eq!(i64::MIN, reader.read_i64().await?); + /// Ok(()) + /// # } /// ``` fn read_i64(&mut self) -> ReadI64; @@ -692,21 +692,21 @@ cfg_io_util! { /// /// Read unsigned 128-bit big-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![ + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![ /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83, - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 - /// ]); + /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 + /// ]); /// - /// assert_eq!(16947640962301618749969007319746179, reader.read_u128().await?); - /// Ok(()) - /// } + /// assert_eq!(16947640962301618749969007319746179, reader.read_u128().await?); + /// Ok(()) + /// # } /// ``` fn read_u128(&mut self) -> ReadU128; @@ -738,21 +738,21 @@ cfg_io_util! { /// /// Read signed 128-bit big-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![ - /// 0x80, 0, 0, 0, 0, 0, 0, 0, - /// 0, 0, 0, 0, 0, 0, 0, 0 - /// ]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![ + /// 0x80, 0, 0, 0, 0, 0, 0, 0, + /// 0, 0, 0, 0, 0, 0, 0, 0 + /// ]); /// - /// assert_eq!(i128::MIN, reader.read_i128().await?); - /// Ok(()) - /// } + /// assert_eq!(i128::MIN, reader.read_i128().await?); + /// Ok(()) + /// # } /// ``` fn read_i128(&mut self) -> ReadI128; @@ -784,18 +784,18 @@ cfg_io_util! { /// /// Read 32-bit floating point type from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0xff, 0x7f, 0xff, 0xff]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0xff, 0x7f, 0xff, 0xff]); /// - /// assert_eq!(f32::MIN, reader.read_f32().await?); - /// Ok(()) - /// } + /// assert_eq!(f32::MIN, reader.read_f32().await?); + /// Ok(()) + /// # } /// ``` fn read_f32(&mut self) -> ReadF32; @@ -827,20 +827,20 @@ cfg_io_util! { /// /// Read 64-bit floating point type from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![ - /// 0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff - /// ]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![ + /// 0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff + /// ]); /// - /// assert_eq!(f64::MIN, reader.read_f64().await?); - /// Ok(()) - /// } + /// assert_eq!(f64::MIN, reader.read_f64().await?); + /// Ok(()) + /// # } /// ``` fn read_f64(&mut self) -> ReadF64; @@ -872,19 +872,19 @@ cfg_io_util! { /// /// Read unsigned 16 bit little-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![2, 5, 3, 0]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![2, 5, 3, 0]); /// - /// assert_eq!(1282, reader.read_u16_le().await?); - /// assert_eq!(3, reader.read_u16_le().await?); - /// Ok(()) - /// } + /// assert_eq!(1282, reader.read_u16_le().await?); + /// assert_eq!(3, reader.read_u16_le().await?); + /// Ok(()) + /// # } /// ``` fn read_u16_le(&mut self) -> ReadU16Le; @@ -916,19 +916,19 @@ cfg_io_util! { /// /// Read signed 16 bit little-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0x00, 0xc1, 0xff, 0x7c]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0x00, 0xc1, 0xff, 0x7c]); /// - /// assert_eq!(-16128, reader.read_i16_le().await?); - /// assert_eq!(31999, reader.read_i16_le().await?); - /// Ok(()) - /// } + /// assert_eq!(-16128, reader.read_i16_le().await?); + /// assert_eq!(31999, reader.read_i16_le().await?); + /// Ok(()) + /// # } /// ``` fn read_i16_le(&mut self) -> ReadI16Le; @@ -960,18 +960,18 @@ cfg_io_util! { /// /// Read unsigned 32-bit little-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0x00, 0x00, 0x01, 0x0b]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0x00, 0x00, 0x01, 0x0b]); /// - /// assert_eq!(184614912, reader.read_u32_le().await?); - /// Ok(()) - /// } + /// assert_eq!(184614912, reader.read_u32_le().await?); + /// Ok(()) + /// # } /// ``` fn read_u32_le(&mut self) -> ReadU32Le; @@ -1004,18 +1004,18 @@ cfg_io_util! { /// /// Read signed 32-bit little-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0xff, 0xff, 0x7a, 0x33]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0xff, 0xff, 0x7a, 0x33]); /// - /// assert_eq!(863698943, reader.read_i32_le().await?); - /// Ok(()) - /// } + /// assert_eq!(863698943, reader.read_i32_le().await?); + /// Ok(()) + /// # } /// ``` fn read_i32_le(&mut self) -> ReadI32Le; @@ -1047,20 +1047,20 @@ cfg_io_util! { /// /// Read unsigned 64-bit little-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![ - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 - /// ]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![ + /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 + /// ]); /// - /// assert_eq!(9477368352180732672, reader.read_u64_le().await?); - /// Ok(()) - /// } + /// assert_eq!(9477368352180732672, reader.read_u64_le().await?); + /// Ok(()) + /// # } /// ``` fn read_u64_le(&mut self) -> ReadU64Le; @@ -1092,18 +1092,18 @@ cfg_io_util! { /// /// Read signed 64-bit little-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0]); /// - /// assert_eq!(128, reader.read_i64_le().await?); - /// Ok(()) - /// } + /// assert_eq!(128, reader.read_i64_le().await?); + /// Ok(()) + /// # } /// ``` fn read_i64_le(&mut self) -> ReadI64Le; @@ -1135,21 +1135,21 @@ cfg_io_util! { /// /// Read unsigned 128-bit little-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![ - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83, - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 - /// ]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![ + /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83, + /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 + /// ]); /// - /// assert_eq!(174826588484952389081207917399662330624, reader.read_u128_le().await?); - /// Ok(()) - /// } + /// assert_eq!(174826588484952389081207917399662330624, reader.read_u128_le().await?); + /// Ok(()) + /// # } /// ``` fn read_u128_le(&mut self) -> ReadU128Le; @@ -1181,21 +1181,21 @@ cfg_io_util! { /// /// Read signed 128-bit little-endian integers from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![ - /// 0x80, 0, 0, 0, 0, 0, 0, 0, - /// 0, 0, 0, 0, 0, 0, 0, 0 - /// ]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![ + /// 0x80, 0, 0, 0, 0, 0, 0, 0, + /// 0, 0, 0, 0, 0, 0, 0, 0 + /// ]); /// - /// assert_eq!(128, reader.read_i128_le().await?); - /// Ok(()) - /// } + /// assert_eq!(128, reader.read_i128_le().await?); + /// Ok(()) + /// # } /// ``` fn read_i128_le(&mut self) -> ReadI128Le; @@ -1227,18 +1227,18 @@ cfg_io_util! { /// /// Read 32-bit floating point type from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![0xff, 0xff, 0x7f, 0xff]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![0xff, 0xff, 0x7f, 0xff]); /// - /// assert_eq!(f32::MIN, reader.read_f32_le().await?); - /// Ok(()) - /// } + /// assert_eq!(f32::MIN, reader.read_f32_le().await?); + /// Ok(()) + /// # } /// ``` fn read_f32_le(&mut self) -> ReadF32Le; @@ -1270,20 +1270,20 @@ cfg_io_util! { /// /// Read 64-bit floating point type from a `AsyncRead`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncReadExt}; /// /// use std::io::Cursor; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut reader = Cursor::new(vec![ - /// 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff - /// ]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut reader = Cursor::new(vec![ + /// 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff + /// ]); /// - /// assert_eq!(f64::MIN, reader.read_f64_le().await?); - /// Ok(()) - /// } + /// assert_eq!(f64::MIN, reader.read_f64_le().await?); + /// Ok(()) + /// # } /// ``` fn read_f64_le(&mut self) -> ReadF64Le; } diff --git a/tokio/src/io/util/async_seek_ext.rs b/tokio/src/io/util/async_seek_ext.rs index a776a9350ec..0dc4b0552e0 100644 --- a/tokio/src/io/util/async_seek_ext.rs +++ b/tokio/src/io/util/async_seek_ext.rs @@ -7,24 +7,24 @@ cfg_io_util! { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::io::{self, Cursor, SeekFrom}; /// use tokio::io::{AsyncSeekExt, AsyncReadExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut cursor = Cursor::new(b"abcdefg"); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut cursor = Cursor::new(b"abcdefg"); /// - /// // the `seek` method is defined by this trait - /// cursor.seek(SeekFrom::Start(3)).await?; + /// // the `seek` method is defined by this trait + /// cursor.seek(SeekFrom::Start(3)).await?; /// - /// let mut buf = [0; 1]; - /// let n = cursor.read(&mut buf).await?; - /// assert_eq!(n, 1); - /// assert_eq!(buf, [b'd']); + /// let mut buf = [0; 1]; + /// let n = cursor.read(&mut buf).await?; + /// assert_eq!(n, 1); + /// assert_eq!(buf, [b'd']); /// - /// Ok(()) - /// } + /// Ok(()) + /// # } /// ``` /// /// See [module][crate::io] documentation for more details. diff --git a/tokio/src/io/util/async_write_ext.rs b/tokio/src/io/util/async_write_ext.rs index 1628b2bba14..3e56c38c32d 100644 --- a/tokio/src/io/util/async_write_ext.rs +++ b/tokio/src/io/util/async_write_ext.rs @@ -395,19 +395,19 @@ cfg_io_util! { /// /// Write unsigned 8 bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_u8(2).await?; - /// writer.write_u8(5).await?; + /// writer.write_u8(2).await?; + /// writer.write_u8(5).await?; /// - /// assert_eq!(writer, b"\x02\x05"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x02\x05"); + /// Ok(()) + /// # } /// ``` fn write_u8(&mut self, n: u8) -> WriteU8; @@ -432,19 +432,19 @@ cfg_io_util! { /// /// Write signed 8 bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_i8(-2).await?; - /// writer.write_i8(126).await?; + /// writer.write_i8(-2).await?; + /// writer.write_i8(126).await?; /// - /// assert_eq!(writer, b"\xFE\x7E"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\xFE\x7E"); + /// Ok(()) + /// # } /// ``` fn write_i8(&mut self, n: i8) -> WriteI8; @@ -470,19 +470,19 @@ cfg_io_util! { /// /// Write unsigned 16-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_u16(517).await?; - /// writer.write_u16(768).await?; + /// writer.write_u16(517).await?; + /// writer.write_u16(768).await?; /// - /// assert_eq!(writer, b"\x02\x05\x03\x00"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x02\x05\x03\x00"); + /// Ok(()) + /// # } /// ``` fn write_u16(&mut self, n: u16) -> WriteU16; @@ -508,19 +508,19 @@ cfg_io_util! { /// /// Write signed 16-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_i16(193).await?; - /// writer.write_i16(-132).await?; + /// writer.write_i16(193).await?; + /// writer.write_i16(-132).await?; /// - /// assert_eq!(writer, b"\x00\xc1\xff\x7c"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x00\xc1\xff\x7c"); + /// Ok(()) + /// # } /// ``` fn write_i16(&mut self, n: i16) -> WriteI16; @@ -546,19 +546,19 @@ cfg_io_util! { /// /// Write unsigned 32-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_u32(267).await?; - /// writer.write_u32(1205419366).await?; + /// writer.write_u32(267).await?; + /// writer.write_u32(1205419366).await?; /// - /// assert_eq!(writer, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66"); + /// Ok(()) + /// # } /// ``` fn write_u32(&mut self, n: u32) -> WriteU32; @@ -584,19 +584,19 @@ cfg_io_util! { /// /// Write signed 32-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_i32(267).await?; - /// writer.write_i32(1205419366).await?; + /// writer.write_i32(267).await?; + /// writer.write_i32(1205419366).await?; /// - /// assert_eq!(writer, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66"); + /// Ok(()) + /// # } /// ``` fn write_i32(&mut self, n: i32) -> WriteI32; @@ -622,19 +622,19 @@ cfg_io_util! { /// /// Write unsigned 64-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_u64(918733457491587).await?; - /// writer.write_u64(143).await?; + /// writer.write_u64(918733457491587).await?; + /// writer.write_u64(143).await?; /// - /// assert_eq!(writer, b"\x00\x03\x43\x95\x4d\x60\x86\x83\x00\x00\x00\x00\x00\x00\x00\x8f"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x00\x03\x43\x95\x4d\x60\x86\x83\x00\x00\x00\x00\x00\x00\x00\x8f"); + /// Ok(()) + /// # } /// ``` fn write_u64(&mut self, n: u64) -> WriteU64; @@ -660,19 +660,19 @@ cfg_io_util! { /// /// Write signed 64-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_i64(i64::MIN).await?; - /// writer.write_i64(i64::MAX).await?; + /// writer.write_i64(i64::MIN).await?; + /// writer.write_i64(i64::MAX).await?; /// - /// assert_eq!(writer, b"\x80\x00\x00\x00\x00\x00\x00\x00\x7f\xff\xff\xff\xff\xff\xff\xff"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x80\x00\x00\x00\x00\x00\x00\x00\x7f\xff\xff\xff\xff\xff\xff\xff"); + /// Ok(()) + /// # } /// ``` fn write_i64(&mut self, n: i64) -> WriteI64; @@ -698,21 +698,21 @@ cfg_io_util! { /// /// Write unsigned 128-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_u128(16947640962301618749969007319746179).await?; + /// writer.write_u128(16947640962301618749969007319746179).await?; /// - /// assert_eq!(writer, vec![ - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83, - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 - /// ]); - /// Ok(()) - /// } + /// assert_eq!(writer, vec![ + /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83, + /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 + /// ]); + /// Ok(()) + /// # } /// ``` fn write_u128(&mut self, n: u128) -> WriteU128; @@ -738,21 +738,21 @@ cfg_io_util! { /// /// Write signed 128-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_i128(i128::MIN).await?; + /// writer.write_i128(i128::MIN).await?; /// - /// assert_eq!(writer, vec![ - /// 0x80, 0, 0, 0, 0, 0, 0, 0, - /// 0, 0, 0, 0, 0, 0, 0, 0 - /// ]); - /// Ok(()) - /// } + /// assert_eq!(writer, vec![ + /// 0x80, 0, 0, 0, 0, 0, 0, 0, + /// 0, 0, 0, 0, 0, 0, 0, 0 + /// ]); + /// Ok(()) + /// # } /// ``` fn write_i128(&mut self, n: i128) -> WriteI128; @@ -778,18 +778,18 @@ cfg_io_util! { /// /// Write 32-bit floating point type to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_f32(f32::MIN).await?; + /// writer.write_f32(f32::MIN).await?; /// - /// assert_eq!(writer, vec![0xff, 0x7f, 0xff, 0xff]); - /// Ok(()) - /// } + /// assert_eq!(writer, vec![0xff, 0x7f, 0xff, 0xff]); + /// Ok(()) + /// # } /// ``` fn write_f32(&mut self, n: f32) -> WriteF32; @@ -815,20 +815,20 @@ cfg_io_util! { /// /// Write 64-bit floating point type to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_f64(f64::MIN).await?; + /// writer.write_f64(f64::MIN).await?; /// - /// assert_eq!(writer, vec![ - /// 0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff - /// ]); - /// Ok(()) - /// } + /// assert_eq!(writer, vec![ + /// 0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff + /// ]); + /// Ok(()) + /// # } /// ``` fn write_f64(&mut self, n: f64) -> WriteF64; @@ -854,19 +854,19 @@ cfg_io_util! { /// /// Write unsigned 16-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_u16_le(517).await?; - /// writer.write_u16_le(768).await?; + /// writer.write_u16_le(517).await?; + /// writer.write_u16_le(768).await?; /// - /// assert_eq!(writer, b"\x05\x02\x00\x03"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x05\x02\x00\x03"); + /// Ok(()) + /// # } /// ``` fn write_u16_le(&mut self, n: u16) -> WriteU16Le; @@ -892,19 +892,19 @@ cfg_io_util! { /// /// Write signed 16-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_i16_le(193).await?; - /// writer.write_i16_le(-132).await?; + /// writer.write_i16_le(193).await?; + /// writer.write_i16_le(-132).await?; /// - /// assert_eq!(writer, b"\xc1\x00\x7c\xff"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\xc1\x00\x7c\xff"); + /// Ok(()) + /// # } /// ``` fn write_i16_le(&mut self, n: i16) -> WriteI16Le; @@ -930,19 +930,19 @@ cfg_io_util! { /// /// Write unsigned 32-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_u32_le(267).await?; - /// writer.write_u32_le(1205419366).await?; + /// writer.write_u32_le(267).await?; + /// writer.write_u32_le(1205419366).await?; /// - /// assert_eq!(writer, b"\x0b\x01\x00\x00\x66\x3d\xd9\x47"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x0b\x01\x00\x00\x66\x3d\xd9\x47"); + /// Ok(()) + /// # } /// ``` fn write_u32_le(&mut self, n: u32) -> WriteU32Le; @@ -968,19 +968,19 @@ cfg_io_util! { /// /// Write signed 32-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_i32_le(267).await?; - /// writer.write_i32_le(1205419366).await?; + /// writer.write_i32_le(267).await?; + /// writer.write_i32_le(1205419366).await?; /// - /// assert_eq!(writer, b"\x0b\x01\x00\x00\x66\x3d\xd9\x47"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x0b\x01\x00\x00\x66\x3d\xd9\x47"); + /// Ok(()) + /// # } /// ``` fn write_i32_le(&mut self, n: i32) -> WriteI32Le; @@ -1006,19 +1006,19 @@ cfg_io_util! { /// /// Write unsigned 64-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_u64_le(918733457491587).await?; - /// writer.write_u64_le(143).await?; + /// writer.write_u64_le(918733457491587).await?; + /// writer.write_u64_le(143).await?; /// - /// assert_eq!(writer, b"\x83\x86\x60\x4d\x95\x43\x03\x00\x8f\x00\x00\x00\x00\x00\x00\x00"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x83\x86\x60\x4d\x95\x43\x03\x00\x8f\x00\x00\x00\x00\x00\x00\x00"); + /// Ok(()) + /// # } /// ``` fn write_u64_le(&mut self, n: u64) -> WriteU64Le; @@ -1044,19 +1044,19 @@ cfg_io_util! { /// /// Write signed 64-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_i64_le(i64::MIN).await?; - /// writer.write_i64_le(i64::MAX).await?; + /// writer.write_i64_le(i64::MIN).await?; + /// writer.write_i64_le(i64::MAX).await?; /// - /// assert_eq!(writer, b"\x00\x00\x00\x00\x00\x00\x00\x80\xff\xff\xff\xff\xff\xff\xff\x7f"); - /// Ok(()) - /// } + /// assert_eq!(writer, b"\x00\x00\x00\x00\x00\x00\x00\x80\xff\xff\xff\xff\xff\xff\xff\x7f"); + /// Ok(()) + /// # } /// ``` fn write_i64_le(&mut self, n: i64) -> WriteI64Le; @@ -1082,21 +1082,21 @@ cfg_io_util! { /// /// Write unsigned 128-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_u128_le(16947640962301618749969007319746179).await?; + /// writer.write_u128_le(16947640962301618749969007319746179).await?; /// - /// assert_eq!(writer, vec![ - /// 0x83, 0x86, 0x60, 0x4d, 0x95, 0x43, 0x03, 0x00, - /// 0x83, 0x86, 0x60, 0x4d, 0x95, 0x43, 0x03, 0x00, - /// ]); - /// Ok(()) - /// } + /// assert_eq!(writer, vec![ + /// 0x83, 0x86, 0x60, 0x4d, 0x95, 0x43, 0x03, 0x00, + /// 0x83, 0x86, 0x60, 0x4d, 0x95, 0x43, 0x03, 0x00, + /// ]); + /// Ok(()) + /// # } /// ``` fn write_u128_le(&mut self, n: u128) -> WriteU128Le; @@ -1122,21 +1122,21 @@ cfg_io_util! { /// /// Write signed 128-bit integers to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_i128_le(i128::MIN).await?; + /// writer.write_i128_le(i128::MIN).await?; /// - /// assert_eq!(writer, vec![ - /// 0, 0, 0, 0, 0, 0, 0, - /// 0, 0, 0, 0, 0, 0, 0, 0, 0x80 - /// ]); - /// Ok(()) - /// } + /// assert_eq!(writer, vec![ + /// 0, 0, 0, 0, 0, 0, 0, + /// 0, 0, 0, 0, 0, 0, 0, 0, 0x80 + /// ]); + /// Ok(()) + /// # } /// ``` fn write_i128_le(&mut self, n: i128) -> WriteI128Le; @@ -1162,18 +1162,18 @@ cfg_io_util! { /// /// Write 32-bit floating point type to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_f32_le(f32::MIN).await?; + /// writer.write_f32_le(f32::MIN).await?; /// - /// assert_eq!(writer, vec![0xff, 0xff, 0x7f, 0xff]); - /// Ok(()) - /// } + /// assert_eq!(writer, vec![0xff, 0xff, 0x7f, 0xff]); + /// Ok(()) + /// # } /// ``` fn write_f32_le(&mut self, n: f32) -> WriteF32Le; @@ -1199,20 +1199,20 @@ cfg_io_util! { /// /// Write 64-bit floating point type to a `AsyncWrite`: /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let mut writer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let mut writer = Vec::new(); /// - /// writer.write_f64_le(f64::MIN).await?; + /// writer.write_f64_le(f64::MIN).await?; /// - /// assert_eq!(writer, vec![ - /// 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff - /// ]); - /// Ok(()) - /// } + /// assert_eq!(writer, vec![ + /// 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff + /// ]); + /// Ok(()) + /// # } /// ``` fn write_f64_le(&mut self, n: f64) -> WriteF64Le; } diff --git a/tokio/src/io/util/empty.rs b/tokio/src/io/util/empty.rs index 163b35f8914..0cc6211cb63 100644 --- a/tokio/src/io/util/empty.rs +++ b/tokio/src/io/util/empty.rs @@ -36,28 +36,28 @@ cfg_io_util! { /// /// A slightly sad example of not reading anything into a buffer: /// - /// ```ignore-wasm + /// ``` /// use tokio::io::{self, AsyncReadExt}; /// - /// #[tokio::main] - /// async fn main() { + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// let mut buffer = String::new(); /// io::empty().read_to_string(&mut buffer).await.unwrap(); /// assert!(buffer.is_empty()); - /// } + /// # } /// ``` /// /// A convoluted way of getting the length of a buffer: /// - /// ```ignore-wasm + /// ``` /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() { - /// let buffer = vec![1, 2, 3, 5, 8]; - /// let num_bytes = io::empty().write(&buffer).await.unwrap(); - /// assert_eq!(num_bytes, 5); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let buffer = vec![1, 2, 3, 5, 8]; + /// let num_bytes = io::empty().write(&buffer).await.unwrap(); + /// assert_eq!(num_bytes, 5); + /// # } /// ``` pub fn empty() -> Empty { Empty { _p: () } diff --git a/tokio/src/io/util/repeat.rs b/tokio/src/io/util/repeat.rs index b1e63d93bda..e5bce46abc4 100644 --- a/tokio/src/io/util/repeat.rs +++ b/tokio/src/io/util/repeat.rs @@ -34,15 +34,15 @@ cfg_io_util! { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::io::{self, AsyncReadExt}; /// - /// #[tokio::main] - /// async fn main() { - /// let mut buffer = [0; 3]; - /// io::repeat(0b101).read_exact(&mut buffer).await.unwrap(); - /// assert_eq!(buffer, [0b101, 0b101, 0b101]); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut buffer = [0; 3]; + /// io::repeat(0b101).read_exact(&mut buffer).await.unwrap(); + /// assert_eq!(buffer, [0b101, 0b101, 0b101]); + /// # } /// ``` pub fn repeat(byte: u8) -> Repeat { Repeat { byte } diff --git a/tokio/src/io/util/sink.rs b/tokio/src/io/util/sink.rs index 5142ed96dd6..28adc540866 100644 --- a/tokio/src/io/util/sink.rs +++ b/tokio/src/io/util/sink.rs @@ -34,16 +34,16 @@ cfg_io_util! { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::io::{self, AsyncWriteExt}; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let buffer = vec![1, 2, 3, 5, 8]; - /// let num_bytes = io::sink().write(&buffer).await?; - /// assert_eq!(num_bytes, 5); - /// Ok(()) - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let buffer = vec![1, 2, 3, 5, 8]; + /// let num_bytes = io::sink().write(&buffer).await?; + /// assert_eq!(num_bytes, 5); + /// Ok(()) + /// # } /// ``` pub fn sink() -> Sink { Sink { _p: () } diff --git a/tokio/src/macros/join.rs b/tokio/src/macros/join.rs index 3f00d87638f..37482dad02d 100644 --- a/tokio/src/macros/join.rs +++ b/tokio/src/macros/join.rs @@ -55,7 +55,7 @@ macro_rules! doc { /// /// Basic join with two branches /// - /// ```ignore-wasm + /// ``` /// async fn do_stuff_async() { /// // async work /// } @@ -64,14 +64,14 @@ macro_rules! doc { /// // more here /// } /// - /// #[tokio::main] - /// async fn main() { - /// let (first, second) = tokio::join!( - /// do_stuff_async(), - /// more_async_work()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (first, second) = tokio::join!( + /// do_stuff_async(), + /// more_async_work()); /// - /// // do something with the values - /// } + /// // do something with the values + /// # } /// ``` /// /// Using the `biased;` mode to control polling order. @@ -85,16 +85,16 @@ macro_rules! doc { /// // more here /// } /// - /// #[tokio::main] - /// async fn main() { - /// let (first, second) = tokio::join!( - /// biased; - /// do_stuff_async(), - /// more_async_work() - /// ); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (first, second) = tokio::join!( + /// biased; + /// do_stuff_async(), + /// more_async_work() + /// ); /// - /// // do something with the values - /// } + /// // do something with the values + /// # } /// ``` #[macro_export] diff --git a/tokio/src/macros/pin.rs b/tokio/src/macros/pin.rs index 710b3c30469..d40220b0cbf 100644 --- a/tokio/src/macros/pin.rs +++ b/tokio/src/macros/pin.rs @@ -24,20 +24,20 @@ /// /// To make this work requires pinning: /// -/// ```ignore-wasm +/// ``` /// use tokio::pin; /// /// async fn my_async_fn() { /// // async logic here /// } /// -/// #[tokio::main] -/// async fn main() { -/// let future = my_async_fn(); -/// pin!(future); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let future = my_async_fn(); +/// pin!(future); /// -/// (&mut future).await; -/// } +/// (&mut future).await; +/// # } /// ``` /// /// Pinning is useful when using `select!` and stream operators that require `T: @@ -69,7 +69,7 @@ /// /// Using with select: /// -/// ```ignore-wasm +/// ``` /// use tokio::{pin, select}; /// use tokio_stream::{self as stream, StreamExt}; /// @@ -77,49 +77,49 @@ /// // async logic here /// } /// -/// #[tokio::main] -/// async fn main() { -/// let mut stream = stream::iter(vec![1, 2, 3, 4]); -/// -/// let future = my_async_fn(); -/// pin!(future); -/// -/// loop { -/// select! { -/// _ = &mut future => { -/// // Stop looping `future` will be polled after completion -/// break; -/// } -/// Some(val) = stream.next() => { -/// println!("got value = {}", val); -/// } +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let mut stream = stream::iter(vec![1, 2, 3, 4]); +/// +/// let future = my_async_fn(); +/// pin!(future); +/// +/// loop { +/// select! { +/// _ = &mut future => { +/// // Stop looping `future` will be polled after completion +/// break; +/// } +/// Some(val) = stream.next() => { +/// println!("got value = {}", val); /// } /// } /// } +/// # } /// ``` /// /// Because assigning to a variable followed by pinning is common, there is also /// a variant of the macro that supports doing both in one go. /// -/// ```ignore-wasm +/// ``` /// use tokio::{pin, select}; /// /// async fn my_async_fn() { /// // async logic here /// } /// -/// #[tokio::main] -/// async fn main() { -/// pin! { -/// let future1 = my_async_fn(); -/// let future2 = my_async_fn(); -/// } +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// pin! { +/// let future1 = my_async_fn(); +/// let future2 = my_async_fn(); +/// } /// -/// select! { -/// _ = &mut future1 => {} -/// _ = &mut future2 => {} -/// } +/// select! { +/// _ = &mut future1 => {} +/// _ = &mut future2 => {} /// } +/// # } /// ``` #[macro_export] macro_rules! pin { diff --git a/tokio/src/macros/select.rs b/tokio/src/macros/select.rs index 1408966ecc7..351ca24ee80 100644 --- a/tokio/src/macros/select.rs +++ b/tokio/src/macros/select.rs @@ -149,7 +149,7 @@ macro_rules! doc { /// /// Basic select with two branches. /// - /// ```ignore-wasm + /// ``` /// async fn do_stuff_async() { /// // async work /// } @@ -158,63 +158,63 @@ macro_rules! doc { /// // more here /// } /// - /// #[tokio::main] - /// async fn main() { - /// tokio::select! { - /// _ = do_stuff_async() => { - /// println!("do_stuff_async() completed first") - /// } - /// _ = more_async_work() => { - /// println!("more_async_work() completed first") - /// } - /// }; - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// tokio::select! { + /// _ = do_stuff_async() => { + /// println!("do_stuff_async() completed first") + /// } + /// _ = more_async_work() => { + /// println!("more_async_work() completed first") + /// } + /// }; + /// # } /// ``` /// /// Basic stream selecting. /// - /// ```ignore-wasm + /// ``` /// use tokio_stream::{self as stream, StreamExt}; /// - /// #[tokio::main] - /// async fn main() { - /// let mut stream1 = stream::iter(vec![1, 2, 3]); - /// let mut stream2 = stream::iter(vec![4, 5, 6]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut stream1 = stream::iter(vec![1, 2, 3]); + /// let mut stream2 = stream::iter(vec![4, 5, 6]); /// - /// let next = tokio::select! { - /// v = stream1.next() => v.unwrap(), - /// v = stream2.next() => v.unwrap(), - /// }; + /// let next = tokio::select! { + /// v = stream1.next() => v.unwrap(), + /// v = stream2.next() => v.unwrap(), + /// }; /// - /// assert!(next == 1 || next == 4); - /// } + /// assert!(next == 1 || next == 4); + /// # } /// ``` /// /// Collect the contents of two streams. In this example, we rely on pattern /// matching and the fact that `stream::iter` is "fused", i.e. once the stream /// is complete, all calls to `next()` return `None`. /// - /// ```ignore-wasm + /// ``` /// use tokio_stream::{self as stream, StreamExt}; /// - /// #[tokio::main] - /// async fn main() { - /// let mut stream1 = stream::iter(vec![1, 2, 3]); - /// let mut stream2 = stream::iter(vec![4, 5, 6]); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut stream1 = stream::iter(vec![1, 2, 3]); + /// let mut stream2 = stream::iter(vec![4, 5, 6]); /// - /// let mut values = vec![]; + /// let mut values = vec![]; /// - /// loop { - /// tokio::select! { - /// Some(v) = stream1.next() => values.push(v), - /// Some(v) = stream2.next() => values.push(v), - /// else => break, - /// } + /// loop { + /// tokio::select! { + /// Some(v) = stream1.next() => values.push(v), + /// Some(v) = stream2.next() => values.push(v), + /// else => break, /// } - /// - /// values.sort(); - /// assert_eq!(&[1, 2, 3, 4, 5, 6], &values[..]); /// } + /// + /// values.sort(); + /// assert_eq!(&[1, 2, 3, 4, 5, 6], &values[..]); + /// # } /// ``` /// /// Using the same future in multiple `select!` expressions can be done by passing @@ -226,106 +226,106 @@ macro_rules! doc { /// /// Here, a stream is consumed for at most 1 second. /// - /// ```ignore-wasm + /// ``` /// use tokio_stream::{self as stream, StreamExt}; /// use tokio::time::{self, Duration}; /// - /// #[tokio::main] - /// async fn main() { - /// let mut stream = stream::iter(vec![1, 2, 3]); - /// let sleep = time::sleep(Duration::from_secs(1)); - /// tokio::pin!(sleep); - /// - /// loop { - /// tokio::select! { - /// maybe_v = stream.next() => { - /// if let Some(v) = maybe_v { - /// println!("got = {}", v); - /// } else { - /// break; - /// } - /// } - /// _ = &mut sleep => { - /// println!("timeout"); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut stream = stream::iter(vec![1, 2, 3]); + /// let sleep = time::sleep(Duration::from_secs(1)); + /// tokio::pin!(sleep); + /// + /// loop { + /// tokio::select! { + /// maybe_v = stream.next() => { + /// if let Some(v) = maybe_v { + /// println!("got = {}", v); + /// } else { /// break; /// } /// } + /// _ = &mut sleep => { + /// println!("timeout"); + /// break; + /// } /// } /// } + /// # } /// ``` /// /// Joining two values using `select!`. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx1, mut rx1) = oneshot::channel(); - /// let (tx2, mut rx2) = oneshot::channel(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx1, mut rx1) = oneshot::channel(); + /// let (tx2, mut rx2) = oneshot::channel(); /// - /// tokio::spawn(async move { - /// tx1.send("first").unwrap(); - /// }); + /// tokio::spawn(async move { + /// tx1.send("first").unwrap(); + /// }); /// - /// tokio::spawn(async move { - /// tx2.send("second").unwrap(); - /// }); + /// tokio::spawn(async move { + /// tx2.send("second").unwrap(); + /// }); /// - /// let mut a = None; - /// let mut b = None; + /// let mut a = None; + /// let mut b = None; /// - /// while a.is_none() || b.is_none() { - /// tokio::select! { - /// v1 = (&mut rx1), if a.is_none() => a = Some(v1.unwrap()), - /// v2 = (&mut rx2), if b.is_none() => b = Some(v2.unwrap()), - /// } + /// while a.is_none() || b.is_none() { + /// tokio::select! { + /// v1 = (&mut rx1), if a.is_none() => a = Some(v1.unwrap()), + /// v2 = (&mut rx2), if b.is_none() => b = Some(v2.unwrap()), /// } + /// } /// - /// let res = (a.unwrap(), b.unwrap()); + /// let res = (a.unwrap(), b.unwrap()); /// - /// assert_eq!(res.0, "first"); - /// assert_eq!(res.1, "second"); - /// } + /// assert_eq!(res.0, "first"); + /// assert_eq!(res.1, "second"); + /// # } /// ``` /// /// Using the `biased;` mode to control polling order. /// - /// ```ignore-wasm - /// #[tokio::main] - /// async fn main() { - /// let mut count = 0u8; - /// - /// loop { - /// tokio::select! { - /// // If you run this example without `biased;`, the polling order is - /// // pseudo-random, and the assertions on the value of count will - /// // (probably) fail. - /// biased; - /// - /// _ = async {}, if count < 1 => { - /// count += 1; - /// assert_eq!(count, 1); - /// } - /// _ = async {}, if count < 2 => { - /// count += 1; - /// assert_eq!(count, 2); - /// } - /// _ = async {}, if count < 3 => { - /// count += 1; - /// assert_eq!(count, 3); - /// } - /// _ = async {}, if count < 4 => { - /// count += 1; - /// assert_eq!(count, 4); - /// } + /// ``` + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut count = 0u8; /// - /// else => { - /// break; - /// } - /// }; - /// } + /// loop { + /// tokio::select! { + /// // If you run this example without `biased;`, the polling order is + /// // pseudo-random, and the assertions on the value of count will + /// // (probably) fail. + /// biased; + /// + /// _ = async {}, if count < 1 => { + /// count += 1; + /// assert_eq!(count, 1); + /// } + /// _ = async {}, if count < 2 => { + /// count += 1; + /// assert_eq!(count, 2); + /// } + /// _ = async {}, if count < 3 => { + /// count += 1; + /// assert_eq!(count, 3); + /// } + /// _ = async {}, if count < 4 => { + /// count += 1; + /// assert_eq!(count, 4); + /// } + /// + /// else => { + /// break; + /// } + /// }; /// } + /// # } /// ``` /// /// ## Avoid racy `if` preconditions @@ -337,31 +337,31 @@ macro_rules! doc { /// is to repeatedly run an asynchronous task for up to 50 milliseconds. /// However, there is a potential for the `sleep` completion to be missed. /// - /// ```no_run,should_panic,ignore-wasm + /// ```no_run,should_panic /// use tokio::time::{self, Duration}; /// /// async fn some_async_work() { /// // do work /// } /// - /// #[tokio::main] - /// async fn main() { - /// let sleep = time::sleep(Duration::from_millis(50)); - /// tokio::pin!(sleep); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let sleep = time::sleep(Duration::from_millis(50)); + /// tokio::pin!(sleep); /// - /// while !sleep.is_elapsed() { - /// tokio::select! { - /// _ = &mut sleep, if !sleep.is_elapsed() => { - /// println!("operation timed out"); - /// } - /// _ = some_async_work() => { - /// println!("operation completed"); - /// } + /// while !sleep.is_elapsed() { + /// tokio::select! { + /// _ = &mut sleep, if !sleep.is_elapsed() => { + /// println!("operation timed out"); + /// } + /// _ = some_async_work() => { + /// println!("operation completed"); /// } /// } - /// - /// panic!("This example shows how not to do it!"); /// } + /// + /// panic!("This example shows how not to do it!"); + /// # } /// ``` /// /// In the above example, `sleep.is_elapsed()` may return `true` even if @@ -372,7 +372,7 @@ macro_rules! doc { /// /// One way to write the above example without the race would be: /// - /// ```ignore-wasm + /// ``` /// use tokio::time::{self, Duration}; /// /// async fn some_async_work() { @@ -380,23 +380,23 @@ macro_rules! doc { /// // do work /// } /// - /// #[tokio::main] - /// async fn main() { - /// let sleep = time::sleep(Duration::from_millis(50)); - /// tokio::pin!(sleep); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let sleep = time::sleep(Duration::from_millis(50)); + /// tokio::pin!(sleep); /// - /// loop { - /// tokio::select! { - /// _ = &mut sleep => { - /// println!("operation timed out"); - /// break; - /// } - /// _ = some_async_work() => { - /// println!("operation completed"); - /// } + /// loop { + /// tokio::select! { + /// _ = &mut sleep => { + /// println!("operation timed out"); + /// break; + /// } + /// _ = some_async_work() => { + /// println!("operation completed"); /// } /// } /// } + /// # } /// ``` /// # Alternatives from the Ecosystem /// @@ -422,7 +422,7 @@ macro_rules! doc { /// /// ### Example with `select!` /// - /// ```ignore-wasm + /// ``` /// struct File; /// struct Channel; /// struct Socket; @@ -437,22 +437,21 @@ macro_rules! doc { /// // do work that is not cancel safe /// } /// - /// #[tokio::main] - /// async fn main() { - /// // open our IO types - /// let mut file = File; - /// let mut channel = Channel; - /// let mut socket = Socket; - /// - /// loop { - /// tokio::select! { - /// _ = read_send(&mut file, &mut channel) => { /* ... */ }, - /// _data = socket.read_packet() => { /* ... */ } - /// _ = futures::future::ready(()) => break - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// // open our IO types + /// let mut file = File; + /// let mut channel = Channel; + /// let mut socket = Socket; + /// + /// loop { + /// tokio::select! { + /// _ = read_send(&mut file, &mut channel) => { /* ... */ }, + /// _data = socket.read_packet() => { /* ... */ } + /// _ = futures::future::ready(()) => break /// } /// } - /// + /// # } /// ``` /// /// ### Moving to `merge` @@ -461,7 +460,7 @@ macro_rules! doc { /// eliminating the need to manage tasks manually and reducing the risk of /// unintended behavior like data loss. /// - /// ```ignore-wasm + /// ``` /// use std::pin::pin; /// /// use futures::stream::unfold; @@ -487,32 +486,32 @@ macro_rules! doc { /// Data(Vec), /// } /// - /// #[tokio::main] - /// async fn main() { - /// // open our IO types - /// let file = File; - /// let channel = Channel; - /// let socket = Socket; - /// - /// let a = unfold((file, channel), |(mut file, mut channel)| async { - /// read_send(&mut file, &mut channel).await; - /// Some((Message::Sent, (file, channel))) - /// }); - /// let b = unfold(socket, |mut socket| async { - /// let data = socket.read_packet().await; - /// Some((Message::Data(data), socket)) - /// }); - /// let c = tokio_stream::iter([Message::Stop]); - /// - /// let mut s = pin!(a.merge(b).merge(c)); - /// while let Some(msg) = s.next().await { - /// match msg { - /// Message::Data(_data) => { /* ... */ } - /// Message::Sent => continue, - /// Message::Stop => break, - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// // open our IO types + /// let file = File; + /// let channel = Channel; + /// let socket = Socket; + /// + /// let a = unfold((file, channel), |(mut file, mut channel)| async { + /// read_send(&mut file, &mut channel).await; + /// Some((Message::Sent, (file, channel))) + /// }); + /// let b = unfold(socket, |mut socket| async { + /// let data = socket.read_packet().await; + /// Some((Message::Data(data), socket)) + /// }); + /// let c = tokio_stream::iter([Message::Stop]); + /// + /// let mut s = pin!(a.merge(b).merge(c)); + /// while let Some(msg) = s.next().await { + /// match msg { + /// Message::Data(_data) => { /* ... */ } + /// Message::Sent => continue, + /// Message::Stop => break, /// } /// } + /// # } /// ``` /// /// ## Racing Futures @@ -530,20 +529,20 @@ macro_rules! doc { /// - [`futures_lite::future::or`](https://docs.rs/futures-lite/latest/futures_lite/future/fn.or.html) /// - [`futures_lite::future::race`](https://docs.rs/futures-lite/latest/futures_lite/future/fn.race.html) /// - /// ```ignore-wasm + /// ``` /// use futures_concurrency::future::Race; /// - /// #[tokio::main] - /// async fn main() { - /// let task_a = async { Ok("ok") }; - /// let task_b = async { Err("error") }; - /// let result = (task_a, task_b).race().await; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let task_a = async { Ok("ok") }; + /// let task_b = async { Err("error") }; + /// let result = (task_a, task_b).race().await; /// - /// match result { - /// Ok(output) => println!("First task completed with: {output}"), - /// Err(err) => eprintln!("Error occurred: {err}"), - /// } + /// match result { + /// Ok(output) => println!("First task completed with: {output}"), + /// Err(err) => eprintln!("Error occurred: {err}"), /// } + /// # } /// ``` #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "macros")))] diff --git a/tokio/src/macros/try_join.rs b/tokio/src/macros/try_join.rs index 3c0ecdc8ae5..fda5f08fa4a 100644 --- a/tokio/src/macros/try_join.rs +++ b/tokio/src/macros/try_join.rs @@ -53,7 +53,7 @@ macro_rules! doc { /// /// Basic `try_join` with two branches. /// - /// ```ignore-wasm + /// ``` /// async fn do_stuff_async() -> Result<(), &'static str> { /// // async work /// # Ok(()) @@ -64,26 +64,26 @@ macro_rules! doc { /// # Ok(()) /// } /// - /// #[tokio::main] - /// async fn main() { - /// let res = tokio::try_join!( - /// do_stuff_async(), - /// more_async_work()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let res = tokio::try_join!( + /// do_stuff_async(), + /// more_async_work()); /// - /// match res { - /// Ok((first, second)) => { - /// // do something with the values - /// } - /// Err(err) => { - /// println!("processing failed; error = {}", err); - /// } - /// } + /// match res { + /// Ok((first, second)) => { + /// // do something with the values + /// } + /// Err(err) => { + /// println!("processing failed; error = {}", err); + /// } /// } + /// # } /// ``` /// /// Using `try_join!` with spawned tasks. /// - /// ```ignore-wasm + /// ``` /// use tokio::task::JoinHandle; /// /// async fn do_stuff_async() -> Result<(), &'static str> { @@ -104,24 +104,24 @@ macro_rules! doc { /// } /// } /// - /// #[tokio::main] - /// async fn main() { - /// let handle1 = tokio::spawn(do_stuff_async()); - /// let handle2 = tokio::spawn(more_async_work()); - /// match tokio::try_join!(flatten(handle1), flatten(handle2)) { - /// Ok(val) => { - /// // do something with the values - /// } - /// Err(err) => { - /// println!("Failed with {}.", err); - /// # assert_eq!(err, "failed"); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let handle1 = tokio::spawn(do_stuff_async()); + /// let handle2 = tokio::spawn(more_async_work()); + /// match tokio::try_join!(flatten(handle1), flatten(handle2)) { + /// Ok(val) => { + /// // do something with the values + /// } + /// Err(err) => { + /// println!("Failed with {}.", err); + /// # assert_eq!(err, "failed"); /// } /// } + /// # } /// ``` /// Using the `biased;` mode to control polling order. /// - /// ```ignore-wasm + /// ``` /// async fn do_stuff_async() -> Result<(), &'static str> { /// // async work /// # Ok(()) @@ -132,23 +132,23 @@ macro_rules! doc { /// # Ok(()) /// } /// - /// #[tokio::main] - /// async fn main() { - /// let res = tokio::try_join!( - /// biased; - /// do_stuff_async(), - /// more_async_work() - /// ); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let res = tokio::try_join!( + /// biased; + /// do_stuff_async(), + /// more_async_work() + /// ); /// - /// match res { - /// Ok((first, second)) => { - /// // do something with the values - /// } - /// Err(err) => { - /// println!("processing failed; error = {}", err); - /// } - /// } + /// match res { + /// Ok((first, second)) => { + /// // do something with the values + /// } + /// Err(err) => { + /// println!("processing failed; error = {}", err); + /// } /// } + /// # } /// ``` #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "macros")))] diff --git a/tokio/src/runtime/builder.rs b/tokio/src/runtime/builder.rs index d8ebfc77207..a3ffc04c355 100644 --- a/tokio/src/runtime/builder.rs +++ b/tokio/src/runtime/builder.rs @@ -151,7 +151,7 @@ cfg_unstable! { /// /// # Examples /// - /// ```ignore-wasm + /// ```should_panic /// use tokio::runtime::{self, UnhandledPanic}; /// /// # pub fn main() { diff --git a/tokio/src/runtime/metrics/runtime.rs b/tokio/src/runtime/metrics/runtime.rs index 65f99a07d73..9ca3b88967d 100644 --- a/tokio/src/runtime/metrics/runtime.rs +++ b/tokio/src/runtime/metrics/runtime.rs @@ -34,16 +34,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.num_workers(); - /// println!("Runtime is using {} workers", n); - /// } + /// let n = metrics.num_workers(); + /// println!("Runtime is using {} workers", n); + /// # } /// ``` pub fn num_workers(&self) -> usize { self.handle.inner.num_workers() @@ -56,16 +56,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.num_alive_tasks(); - /// println!("Runtime has {} alive tasks", n); - /// } + /// let n = metrics.num_alive_tasks(); + /// println!("Runtime has {} alive tasks", n); + /// # } /// ``` pub fn num_alive_tasks(&self) -> usize { self.handle.inner.num_alive_tasks() @@ -82,16 +82,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.global_queue_depth(); - /// println!("{} tasks currently pending in the runtime's global queue", n); - /// } + /// let n = metrics.global_queue_depth(); + /// println!("{} tasks currently pending in the runtime's global queue", n); + /// # } /// ``` pub fn global_queue_depth(&self) -> usize { self.handle.inner.injection_queue_depth() @@ -123,16 +123,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.worker_total_busy_duration(0); - /// println!("worker 0 was busy for a total of {:?}", n); - /// } + /// let n = metrics.worker_total_busy_duration(0); + /// println!("worker 0 was busy for a total of {:?}", n); + /// # } /// ``` pub fn worker_total_busy_duration(&self, worker: usize) -> Duration { let nanos = self @@ -168,16 +168,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.worker_park_count(0); - /// println!("worker 0 parked {} times", n); - /// } + /// let n = metrics.worker_park_count(0); + /// println!("worker 0 parked {} times", n); + /// # } /// ``` pub fn worker_park_count(&self, worker: usize) -> u64 { self.handle @@ -216,22 +216,22 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); - /// let n = metrics.worker_park_unpark_count(0); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); + /// let n = metrics.worker_park_unpark_count(0); /// - /// println!("worker 0 parked and unparked {} times", n); + /// println!("worker 0 parked and unparked {} times", n); /// - /// if n % 2 == 0 { - /// println!("worker 0 is active"); - /// } else { - /// println!("worker 0 is parked"); - /// } + /// if n % 2 == 0 { + /// println!("worker 0 is active"); + /// } else { + /// println!("worker 0 is parked"); /// } + /// # } /// ``` pub fn worker_park_unpark_count(&self, worker: usize) -> u64 { self.handle @@ -254,17 +254,17 @@ impl RuntimeMetrics { /// ```ignore-wasm /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let _ = tokio::task::spawn_blocking(move || { - /// // Stand-in for compute-heavy work or using synchronous APIs - /// 1 + 1 - /// }).await; - /// let metrics = Handle::current().metrics(); - /// - /// let n = metrics.num_blocking_threads(); - /// println!("Runtime has created {} threads", n); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let _ = tokio::task::spawn_blocking(move || { + /// // Stand-in for compute-heavy work or using synchronous APIs + /// 1 + 1 + /// }).await; + /// let metrics = Handle::current().metrics(); + /// + /// let n = metrics.num_blocking_threads(); + /// println!("Runtime has created {} threads", n); + /// # } /// ``` pub fn num_blocking_threads(&self) -> usize { self.handle.inner.num_blocking_threads() @@ -325,16 +325,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let id = metrics.worker_thread_id(0); - /// println!("worker 0 has id {:?}", id); - /// } + /// let id = metrics.worker_thread_id(0); + /// println!("worker 0 has id {:?}", id); + /// # } /// ``` pub fn worker_thread_id(&self, worker: usize) -> Option { self.handle @@ -373,16 +373,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.worker_local_queue_depth(0); - /// println!("{} tasks currently pending in worker 0's local queue", n); - /// } + /// let n = metrics.worker_local_queue_depth(0); + /// println!("{} tasks currently pending in worker 0's local queue", n); + /// # } /// ``` pub fn worker_local_queue_depth(&self, worker: usize) -> usize { self.handle.inner.worker_local_queue_depth(worker) @@ -547,16 +547,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.blocking_queue_depth(); - /// println!("{} tasks currently pending in the blocking thread pool", n); - /// } + /// let n = metrics.blocking_queue_depth(); + /// println!("{} tasks currently pending in the blocking thread pool", n); + /// # } /// ``` pub fn blocking_queue_depth(&self) -> usize { self.handle.inner.blocking_queue_depth() @@ -577,16 +577,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.spawned_tasks_count(); - /// println!("Runtime has had {} tasks spawned", n); - /// } + /// let n = metrics.spawned_tasks_count(); + /// println!("Runtime has had {} tasks spawned", n); + /// # } /// ``` pub fn spawned_tasks_count(&self) -> u64 { self.handle.inner.spawned_tasks_count() @@ -605,16 +605,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.remote_schedule_count(); - /// println!("{} tasks were scheduled from outside the runtime", n); - /// } + /// let n = metrics.remote_schedule_count(); + /// println!("{} tasks were scheduled from outside the runtime", n); + /// # } /// ``` pub fn remote_schedule_count(&self) -> u64 { self.handle @@ -663,16 +663,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.worker_noop_count(0); - /// println!("worker 0 had {} no-op unparks", n); - /// } + /// let n = metrics.worker_noop_count(0); + /// println!("worker 0 had {} no-op unparks", n); + /// # } /// ``` pub fn worker_noop_count(&self, worker: usize) -> u64 { self.handle @@ -709,16 +709,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.worker_steal_count(0); - /// println!("worker 0 has stolen {} tasks", n); - /// } + /// let n = metrics.worker_steal_count(0); + /// println!("worker 0 has stolen {} tasks", n); + /// # } /// ``` pub fn worker_steal_count(&self, worker: usize) -> u64 { self.handle @@ -755,16 +755,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.worker_steal_operations(0); - /// println!("worker 0 has stolen tasks {} times", n); - /// } + /// let n = metrics.worker_steal_operations(0); + /// println!("worker 0 has stolen tasks {} times", n); + /// # } /// ``` pub fn worker_steal_operations(&self, worker: usize) -> u64 { self.handle @@ -796,16 +796,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.worker_poll_count(0); - /// println!("worker 0 has polled {} tasks", n); - /// } + /// let n = metrics.worker_poll_count(0); + /// println!("worker 0 has polled {} tasks", n); + /// # } /// ``` pub fn worker_poll_count(&self, worker: usize) -> u64 { self.handle @@ -841,16 +841,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.worker_local_schedule_count(0); - /// println!("{} tasks were scheduled on the worker's local queue", n); - /// } + /// let n = metrics.worker_local_schedule_count(0); + /// println!("{} tasks were scheduled on the worker's local queue", n); + /// # } /// ``` pub fn worker_local_schedule_count(&self, worker: usize) -> u64 { self.handle @@ -887,16 +887,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.worker_overflow_count(0); - /// println!("worker 0 has overflowed its queue {} times", n); - /// } + /// let n = metrics.worker_overflow_count(0); + /// println!("worker 0 has overflowed its queue {} times", n); + /// # } /// ``` pub fn worker_overflow_count(&self, worker: usize) -> u64 { self.handle @@ -996,16 +996,16 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::runtime::Handle; /// - /// #[tokio::main] - /// async fn main() { - /// let metrics = Handle::current().metrics(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let metrics = Handle::current().metrics(); /// - /// let n = metrics.worker_mean_poll_time(0); - /// println!("worker 0 has a mean poll time of {:?}", n); - /// } + /// let n = metrics.worker_mean_poll_time(0); + /// println!("worker 0 has a mean poll time of {:?}", n); + /// # } /// ``` #[track_caller] pub fn worker_mean_poll_time(&self, worker: usize) -> Duration { diff --git a/tokio/src/runtime/task/error.rs b/tokio/src/runtime/task/error.rs index 8a6d5f89789..0971ba6c1d6 100644 --- a/tokio/src/runtime/task/error.rs +++ b/tokio/src/runtime/task/error.rs @@ -45,17 +45,17 @@ impl JoinError { /// /// # Examples /// - /// ```ignore-wasm + /// ```should_panic /// use std::panic; /// - /// #[tokio::main] - /// async fn main() { - /// let err = tokio::spawn(async { - /// panic!("boom"); - /// }).await.unwrap_err(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let err = tokio::spawn(async { + /// panic!("boom"); + /// }).await.unwrap_err(); /// - /// assert!(err.is_panic()); - /// } + /// assert!(err.is_panic()); + /// # } /// ``` pub fn is_panic(&self) -> bool { matches!(&self.repr, Repr::Panic(_)) diff --git a/tokio/src/runtime/task/join.rs b/tokio/src/runtime/task/join.rs index ac2e77e4fe4..d101f5f875f 100644 --- a/tokio/src/runtime/task/join.rs +++ b/tokio/src/runtime/task/join.rs @@ -87,49 +87,50 @@ cfg_rt! { /// `Result` because panics in the spawned task are caught by Tokio. The `?` operator has /// to be double chained to extract the returned value: /// - /// ```ignore-wasm + /// ``` /// use tokio::task; /// use std::io; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let join_handle: task::JoinHandle> = tokio::spawn(async { - /// Ok(5 + 3) - /// }); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let join_handle: task::JoinHandle> = tokio::spawn(async { + /// Ok(5 + 3) + /// }); /// - /// let result = join_handle.await??; - /// assert_eq!(result, 8); - /// Ok(()) - /// } + /// let result = join_handle.await??; + /// assert_eq!(result, 8); + /// Ok(()) + /// # } /// ``` /// /// If the task panics, the error is a [`JoinError`] that contains the panic: /// - /// ```ignore-wasm + /// ```should_panic /// use tokio::task; /// use std::io; /// use std::panic; /// - /// #[tokio::main] - /// async fn main() -> io::Result<()> { - /// let join_handle: task::JoinHandle> = tokio::spawn(async { - /// panic!("boom"); - /// }); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> io::Result<()> { + /// let join_handle: task::JoinHandle> = tokio::spawn(async { + /// panic!("boom"); + /// }); /// - /// let err = join_handle.await.unwrap_err(); - /// assert!(err.is_panic()); - /// Ok(()) - /// } + /// let err = join_handle.await.unwrap_err(); + /// assert!(err.is_panic()); + /// Ok(()) + /// # } /// /// ``` /// Child being detached and outliving its parent: /// - /// ```no_run,ignore-wasm + /// ```no_run /// use tokio::task; /// use tokio::time; /// use std::time::Duration; /// - /// # #[tokio::main] async fn main() { + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { /// let original_task = task::spawn(async { /// let _detached_task = task::spawn(async { /// // Here we sleep to make sure that the first task returns before. diff --git a/tokio/src/sync/barrier.rs b/tokio/src/sync/barrier.rs index 5ad1b6f088b..00fc212d987 100644 --- a/tokio/src/sync/barrier.rs +++ b/tokio/src/sync/barrier.rs @@ -5,8 +5,8 @@ use crate::util::trace; /// A barrier enables multiple tasks to synchronize the beginning of some computation. /// -/// ```ignore-wasm -/// # #[tokio::main] +/// ``` +/// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// use tokio::sync::Barrier; /// use std::sync::Arc; diff --git a/tokio/src/sync/broadcast.rs b/tokio/src/sync/broadcast.rs index 6d87fc3a63e..2094a7f398d 100644 --- a/tokio/src/sync/broadcast.rs +++ b/tokio/src/sync/broadcast.rs @@ -70,50 +70,50 @@ //! //! Basic usage //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::broadcast; //! -//! #[tokio::main] -//! async fn main() { -//! let (tx, mut rx1) = broadcast::channel(16); -//! let mut rx2 = tx.subscribe(); +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let (tx, mut rx1) = broadcast::channel(16); +//! let mut rx2 = tx.subscribe(); //! -//! tokio::spawn(async move { -//! assert_eq!(rx1.recv().await.unwrap(), 10); -//! assert_eq!(rx1.recv().await.unwrap(), 20); -//! }); +//! tokio::spawn(async move { +//! assert_eq!(rx1.recv().await.unwrap(), 10); +//! assert_eq!(rx1.recv().await.unwrap(), 20); +//! }); //! -//! tokio::spawn(async move { -//! assert_eq!(rx2.recv().await.unwrap(), 10); -//! assert_eq!(rx2.recv().await.unwrap(), 20); -//! }); +//! tokio::spawn(async move { +//! assert_eq!(rx2.recv().await.unwrap(), 10); +//! assert_eq!(rx2.recv().await.unwrap(), 20); +//! }); //! -//! tx.send(10).unwrap(); -//! tx.send(20).unwrap(); -//! } +//! tx.send(10).unwrap(); +//! tx.send(20).unwrap(); +//! # } //! ``` //! //! Handling lag //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::broadcast; //! -//! #[tokio::main] -//! async fn main() { -//! let (tx, mut rx) = broadcast::channel(2); +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let (tx, mut rx) = broadcast::channel(2); //! -//! tx.send(10).unwrap(); -//! tx.send(20).unwrap(); -//! tx.send(30).unwrap(); +//! tx.send(10).unwrap(); +//! tx.send(20).unwrap(); +//! tx.send(30).unwrap(); //! -//! // The receiver lagged behind -//! assert!(rx.recv().await.is_err()); +//! // The receiver lagged behind +//! assert!(rx.recv().await.is_err()); //! -//! // At this point, we can abort or continue with lost messages +//! // At this point, we can abort or continue with lost messages //! -//! assert_eq!(20, rx.recv().await.unwrap()); -//! assert_eq!(30, rx.recv().await.unwrap()); -//! } +//! assert_eq!(20, rx.recv().await.unwrap()); +//! assert_eq!(30, rx.recv().await.unwrap()); +//! # } //! ``` use crate::loom::cell::UnsafeCell; @@ -138,27 +138,27 @@ use std::task::{ready, Context, Poll, Waker}; /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::broadcast; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, mut rx1) = broadcast::channel(16); -/// let mut rx2 = tx.subscribe(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, mut rx1) = broadcast::channel(16); +/// let mut rx2 = tx.subscribe(); /// -/// tokio::spawn(async move { -/// assert_eq!(rx1.recv().await.unwrap(), 10); -/// assert_eq!(rx1.recv().await.unwrap(), 20); -/// }); +/// tokio::spawn(async move { +/// assert_eq!(rx1.recv().await.unwrap(), 10); +/// assert_eq!(rx1.recv().await.unwrap(), 20); +/// }); /// -/// tokio::spawn(async move { -/// assert_eq!(rx2.recv().await.unwrap(), 10); -/// assert_eq!(rx2.recv().await.unwrap(), 20); -/// }); +/// tokio::spawn(async move { +/// assert_eq!(rx2.recv().await.unwrap(), 10); +/// assert_eq!(rx2.recv().await.unwrap(), 20); +/// }); /// -/// tx.send(10).unwrap(); -/// tx.send(20).unwrap(); -/// } +/// tx.send(10).unwrap(); +/// tx.send(20).unwrap(); +/// # } /// ``` /// /// [`broadcast`]: crate::sync::broadcast @@ -180,21 +180,21 @@ pub struct Sender { /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::broadcast::channel; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, _rx) = channel::(15); -/// let tx_weak = tx.downgrade(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, _rx) = channel::(15); +/// let tx_weak = tx.downgrade(); /// -/// // Upgrading will succeed because `tx` still exists. -/// assert!(tx_weak.upgrade().is_some()); +/// // Upgrading will succeed because `tx` still exists. +/// assert!(tx_weak.upgrade().is_some()); /// -/// // If we drop `tx`, then it will fail. -/// drop(tx); -/// assert!(tx_weak.clone().upgrade().is_none()); -/// } +/// // If we drop `tx`, then it will fail. +/// drop(tx); +/// assert!(tx_weak.clone().upgrade().is_none()); +/// # } /// ``` pub struct WeakSender { shared: Arc>, @@ -212,27 +212,27 @@ pub struct WeakSender { /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::broadcast; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, mut rx1) = broadcast::channel(16); -/// let mut rx2 = tx.subscribe(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, mut rx1) = broadcast::channel(16); +/// let mut rx2 = tx.subscribe(); /// -/// tokio::spawn(async move { -/// assert_eq!(rx1.recv().await.unwrap(), 10); -/// assert_eq!(rx1.recv().await.unwrap(), 20); -/// }); +/// tokio::spawn(async move { +/// assert_eq!(rx1.recv().await.unwrap(), 10); +/// assert_eq!(rx1.recv().await.unwrap(), 20); +/// }); /// -/// tokio::spawn(async move { -/// assert_eq!(rx2.recv().await.unwrap(), 10); -/// assert_eq!(rx2.recv().await.unwrap(), 20); -/// }); +/// tokio::spawn(async move { +/// assert_eq!(rx2.recv().await.unwrap(), 10); +/// assert_eq!(rx2.recv().await.unwrap(), 20); +/// }); /// -/// tx.send(10).unwrap(); -/// tx.send(20).unwrap(); -/// } +/// tx.send(10).unwrap(); +/// tx.send(20).unwrap(); +/// # } /// ``` /// /// [`broadcast`]: crate::sync::broadcast @@ -475,27 +475,27 @@ const MAX_RECEIVERS: usize = usize::MAX >> 2; /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::broadcast; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, mut rx1) = broadcast::channel(16); -/// let mut rx2 = tx.subscribe(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, mut rx1) = broadcast::channel(16); +/// let mut rx2 = tx.subscribe(); /// -/// tokio::spawn(async move { -/// assert_eq!(rx1.recv().await.unwrap(), 10); -/// assert_eq!(rx1.recv().await.unwrap(), 20); -/// }); +/// tokio::spawn(async move { +/// assert_eq!(rx1.recv().await.unwrap(), 10); +/// assert_eq!(rx1.recv().await.unwrap(), 20); +/// }); /// -/// tokio::spawn(async move { -/// assert_eq!(rx2.recv().await.unwrap(), 10); -/// assert_eq!(rx2.recv().await.unwrap(), 20); -/// }); +/// tokio::spawn(async move { +/// assert_eq!(rx2.recv().await.unwrap(), 10); +/// assert_eq!(rx2.recv().await.unwrap(), 20); +/// }); /// -/// tx.send(10).unwrap(); -/// tx.send(20).unwrap(); -/// } +/// tx.send(10).unwrap(); +/// tx.send(20).unwrap(); +/// # } /// ``` /// /// # Panics @@ -606,27 +606,27 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx1) = broadcast::channel(16); - /// let mut rx2 = tx.subscribe(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx1) = broadcast::channel(16); + /// let mut rx2 = tx.subscribe(); /// - /// tokio::spawn(async move { - /// assert_eq!(rx1.recv().await.unwrap(), 10); - /// assert_eq!(rx1.recv().await.unwrap(), 20); - /// }); + /// tokio::spawn(async move { + /// assert_eq!(rx1.recv().await.unwrap(), 10); + /// assert_eq!(rx1.recv().await.unwrap(), 20); + /// }); /// - /// tokio::spawn(async move { - /// assert_eq!(rx2.recv().await.unwrap(), 10); - /// assert_eq!(rx2.recv().await.unwrap(), 20); - /// }); + /// tokio::spawn(async move { + /// assert_eq!(rx2.recv().await.unwrap(), 10); + /// assert_eq!(rx2.recv().await.unwrap(), 20); + /// }); /// - /// tx.send(10).unwrap(); - /// tx.send(20).unwrap(); - /// } + /// tx.send(10).unwrap(); + /// tx.send(20).unwrap(); + /// # } /// ``` pub fn send(&self, value: T) -> Result> { let mut tail = self.shared.tail.lock(); @@ -671,23 +671,23 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, _rx) = broadcast::channel(16); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, _rx) = broadcast::channel(16); /// - /// // Will not be seen - /// tx.send(10).unwrap(); + /// // Will not be seen + /// tx.send(10).unwrap(); /// - /// let mut rx = tx.subscribe(); + /// let mut rx = tx.subscribe(); /// - /// tx.send(20).unwrap(); + /// tx.send(20).unwrap(); /// - /// let value = rx.recv().await.unwrap(); - /// assert_eq!(20, value); - /// } + /// let value = rx.recv().await.unwrap(); + /// assert_eq!(20, value); + /// # } /// ``` pub fn subscribe(&self) -> Receiver { let shared = self.shared.clone(); @@ -719,29 +719,29 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx1) = broadcast::channel(16); - /// let mut rx2 = tx.subscribe(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx1) = broadcast::channel(16); + /// let mut rx2 = tx.subscribe(); /// - /// tx.send(10).unwrap(); - /// tx.send(20).unwrap(); - /// tx.send(30).unwrap(); + /// tx.send(10).unwrap(); + /// tx.send(20).unwrap(); + /// tx.send(30).unwrap(); /// - /// assert_eq!(tx.len(), 3); + /// assert_eq!(tx.len(), 3); /// - /// rx1.recv().await.unwrap(); + /// rx1.recv().await.unwrap(); /// - /// // The len is still 3 since rx2 hasn't seen the first value yet. - /// assert_eq!(tx.len(), 3); + /// // The len is still 3 since rx2 hasn't seen the first value yet. + /// assert_eq!(tx.len(), 3); /// - /// rx2.recv().await.unwrap(); + /// rx2.recv().await.unwrap(); /// - /// assert_eq!(tx.len(), 2); - /// } + /// assert_eq!(tx.len(), 2); + /// # } /// ``` pub fn len(&self) -> usize { let tail = self.shared.tail.lock(); @@ -766,29 +766,29 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx1) = broadcast::channel(16); - /// let mut rx2 = tx.subscribe(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx1) = broadcast::channel(16); + /// let mut rx2 = tx.subscribe(); /// - /// assert!(tx.is_empty()); + /// assert!(tx.is_empty()); /// - /// tx.send(10).unwrap(); + /// tx.send(10).unwrap(); /// - /// assert!(!tx.is_empty()); + /// assert!(!tx.is_empty()); /// - /// rx1.recv().await.unwrap(); + /// rx1.recv().await.unwrap(); /// - /// // The queue is still not empty since rx2 hasn't seen the value. - /// assert!(!tx.is_empty()); + /// // The queue is still not empty since rx2 hasn't seen the value. + /// assert!(!tx.is_empty()); /// - /// rx2.recv().await.unwrap(); + /// rx2.recv().await.unwrap(); /// - /// assert!(tx.is_empty()); - /// } + /// assert!(tx.is_empty()); + /// # } /// ``` pub fn is_empty(&self) -> bool { let tail = self.shared.tail.lock(); @@ -817,21 +817,21 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, _rx1) = broadcast::channel(16); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, _rx1) = broadcast::channel(16); /// - /// assert_eq!(1, tx.receiver_count()); + /// assert_eq!(1, tx.receiver_count()); /// - /// let mut _rx2 = tx.subscribe(); + /// let mut _rx2 = tx.subscribe(); /// - /// assert_eq!(2, tx.receiver_count()); + /// assert_eq!(2, tx.receiver_count()); /// - /// tx.send(10).unwrap(); - /// } + /// tx.send(10).unwrap(); + /// # } /// ``` pub fn receiver_count(&self) -> usize { let tail = self.shared.tail.lock(); @@ -842,20 +842,20 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, _rx) = broadcast::channel::<()>(16); - /// let tx2 = tx.clone(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, _rx) = broadcast::channel::<()>(16); + /// let tx2 = tx.clone(); /// - /// assert!(tx.same_channel(&tx2)); + /// assert!(tx.same_channel(&tx2)); /// - /// let (tx3, _rx3) = broadcast::channel::<()>(16); + /// let (tx3, _rx3) = broadcast::channel::<()>(16); /// - /// assert!(!tx3.same_channel(&tx2)); - /// } + /// assert!(!tx3.same_channel(&tx2)); + /// # } /// ``` pub fn same_channel(&self, other: &Self) -> bool { Arc::ptr_eq(&self.shared, &other.shared) @@ -866,25 +866,25 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use futures::FutureExt; /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx1) = broadcast::channel::(16); - /// let mut rx2 = tx.subscribe(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx1) = broadcast::channel::(16); + /// let mut rx2 = tx.subscribe(); /// - /// let _ = tx.send(10); + /// let _ = tx.send(10); /// - /// assert_eq!(rx1.recv().await.unwrap(), 10); - /// drop(rx1); - /// assert!(tx.closed().now_or_never().is_none()); + /// assert_eq!(rx1.recv().await.unwrap(), 10); + /// drop(rx1); + /// assert!(tx.closed().now_or_never().is_none()); /// - /// assert_eq!(rx2.recv().await.unwrap(), 10); - /// drop(rx2); - /// assert!(tx.closed().now_or_never().is_some()); - /// } + /// assert_eq!(rx2.recv().await.unwrap(), 10); + /// drop(rx2); + /// assert!(tx.closed().now_or_never().is_some()); + /// # } /// ``` pub async fn closed(&self) { loop { @@ -1145,22 +1145,22 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx1) = broadcast::channel(16); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx1) = broadcast::channel(16); /// - /// tx.send(10).unwrap(); - /// tx.send(20).unwrap(); + /// tx.send(10).unwrap(); + /// tx.send(20).unwrap(); /// - /// assert_eq!(rx1.len(), 2); - /// assert_eq!(rx1.recv().await.unwrap(), 10); - /// assert_eq!(rx1.len(), 1); - /// assert_eq!(rx1.recv().await.unwrap(), 20); - /// assert_eq!(rx1.len(), 0); - /// } + /// assert_eq!(rx1.len(), 2); + /// assert_eq!(rx1.recv().await.unwrap(), 10); + /// assert_eq!(rx1.len(), 1); + /// assert_eq!(rx1.recv().await.unwrap(), 20); + /// assert_eq!(rx1.len(), 0); + /// # } /// ``` pub fn len(&self) -> usize { let next_send_pos = self.shared.tail.lock().pos; @@ -1174,23 +1174,23 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx1) = broadcast::channel(16); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx1) = broadcast::channel(16); /// - /// assert!(rx1.is_empty()); + /// assert!(rx1.is_empty()); /// - /// tx.send(10).unwrap(); - /// tx.send(20).unwrap(); + /// tx.send(10).unwrap(); + /// tx.send(20).unwrap(); /// - /// assert!(!rx1.is_empty()); - /// assert_eq!(rx1.recv().await.unwrap(), 10); - /// assert_eq!(rx1.recv().await.unwrap(), 20); - /// assert!(rx1.is_empty()); - /// } + /// assert!(!rx1.is_empty()); + /// assert_eq!(rx1.recv().await.unwrap(), 10); + /// assert_eq!(rx1.recv().await.unwrap(), 20); + /// assert!(rx1.is_empty()); + /// # } /// ``` pub fn is_empty(&self) -> bool { self.len() == 0 @@ -1200,20 +1200,20 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = broadcast::channel::<()>(16); - /// let rx2 = tx.subscribe(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = broadcast::channel::<()>(16); + /// let rx2 = tx.subscribe(); /// - /// assert!(rx.same_channel(&rx2)); + /// assert!(rx.same_channel(&rx2)); /// - /// let (_tx3, rx3) = broadcast::channel::<()>(16); + /// let (_tx3, rx3) = broadcast::channel::<()>(16); /// - /// assert!(!rx3.same_channel(&rx2)); - /// } + /// assert!(!rx3.same_channel(&rx2)); + /// # } /// ``` pub fn same_channel(&self, other: &Self) -> bool { Arc::ptr_eq(&self.shared, &other.shared) @@ -1345,18 +1345,18 @@ impl Receiver { /// [`Sender`]: crate::sync::broadcast::Sender /// /// # Examples - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = broadcast::channel::<()>(10); - /// assert!(!rx.is_closed()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = broadcast::channel::<()>(10); + /// assert!(!rx.is_closed()); /// - /// drop(tx); + /// drop(tx); /// - /// assert!(rx.is_closed()); - /// } + /// assert!(rx.is_closed()); + /// # } /// ``` pub fn is_closed(&self) -> bool { // Channel is closed when there are no strong senders left active @@ -1373,20 +1373,20 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = broadcast::channel(2); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = broadcast::channel(2); /// - /// tx.send(1).unwrap(); - /// let mut rx2 = rx.resubscribe(); - /// tx.send(2).unwrap(); + /// tx.send(1).unwrap(); + /// let mut rx2 = rx.resubscribe(); + /// tx.send(2).unwrap(); /// - /// assert_eq!(rx2.recv().await.unwrap(), 2); - /// assert_eq!(rx.recv().await.unwrap(), 1); - /// } + /// assert_eq!(rx2.recv().await.unwrap(), 2); + /// assert_eq!(rx.recv().await.unwrap(), 1); + /// # } /// ``` pub fn resubscribe(&self) -> Self { let shared = self.shared.clone(); @@ -1419,50 +1419,50 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx1) = broadcast::channel(16); - /// let mut rx2 = tx.subscribe(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx1) = broadcast::channel(16); + /// let mut rx2 = tx.subscribe(); /// - /// tokio::spawn(async move { - /// assert_eq!(rx1.recv().await.unwrap(), 10); - /// assert_eq!(rx1.recv().await.unwrap(), 20); - /// }); + /// tokio::spawn(async move { + /// assert_eq!(rx1.recv().await.unwrap(), 10); + /// assert_eq!(rx1.recv().await.unwrap(), 20); + /// }); /// - /// tokio::spawn(async move { - /// assert_eq!(rx2.recv().await.unwrap(), 10); - /// assert_eq!(rx2.recv().await.unwrap(), 20); - /// }); + /// tokio::spawn(async move { + /// assert_eq!(rx2.recv().await.unwrap(), 10); + /// assert_eq!(rx2.recv().await.unwrap(), 20); + /// }); /// - /// tx.send(10).unwrap(); - /// tx.send(20).unwrap(); - /// } + /// tx.send(10).unwrap(); + /// tx.send(20).unwrap(); + /// # } /// ``` /// /// Handling lag /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = broadcast::channel(2); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = broadcast::channel(2); /// - /// tx.send(10).unwrap(); - /// tx.send(20).unwrap(); - /// tx.send(30).unwrap(); + /// tx.send(10).unwrap(); + /// tx.send(20).unwrap(); + /// tx.send(30).unwrap(); /// - /// // The receiver lagged behind - /// assert!(rx.recv().await.is_err()); + /// // The receiver lagged behind + /// assert!(rx.recv().await.is_err()); /// - /// // At this point, we can abort or continue with lost messages + /// // At this point, we can abort or continue with lost messages /// - /// assert_eq!(20, rx.recv().await.unwrap()); - /// assert_eq!(30, rx.recv().await.unwrap()); - /// } + /// assert_eq!(20, rx.recv().await.unwrap()); + /// assert_eq!(30, rx.recv().await.unwrap()); + /// # } /// ``` pub async fn recv(&mut self) -> Result { cooperative(Recv::new(self)).await @@ -1493,20 +1493,20 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = broadcast::channel(16); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = broadcast::channel(16); /// - /// assert!(rx.try_recv().is_err()); + /// assert!(rx.try_recv().is_err()); /// - /// tx.send(10).unwrap(); + /// tx.send(10).unwrap(); /// - /// let value = rx.try_recv().unwrap(); - /// assert_eq!(10, value); - /// } + /// let value = rx.try_recv().unwrap(); + /// assert_eq!(10, value); + /// # } /// ``` pub fn try_recv(&mut self) -> Result { let guard = self.recv_ref(None)?; @@ -1521,21 +1521,21 @@ impl Receiver { /// context. /// /// # Examples - /// ```ignore-wasm + /// ```should_panic /// use std::thread; /// use tokio::sync::broadcast; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = broadcast::channel(16); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = broadcast::channel(16); /// - /// let sync_code = thread::spawn(move || { - /// assert_eq!(rx.blocking_recv(), Ok(10)); - /// }); + /// let sync_code = thread::spawn(move || { + /// assert_eq!(rx.blocking_recv(), Ok(10)); + /// }); /// - /// let _ = tx.send(10); - /// sync_code.join().unwrap(); - /// } + /// let _ = tx.send(10); + /// sync_code.join().unwrap(); + /// # } /// ``` pub fn blocking_recv(&mut self) -> Result { crate::future::block_on(self.recv()) diff --git a/tokio/src/sync/mod.rs b/tokio/src/sync/mod.rs index 06a8a773a44..55dd8190003 100644 --- a/tokio/src/sync/mod.rs +++ b/tokio/src/sync/mod.rs @@ -35,27 +35,27 @@ //! **Example:** using a [`oneshot` channel][oneshot] to receive the result of a //! computation. //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::oneshot; //! //! async fn some_computation() -> String { //! "represents the result of the computation".to_string() //! } //! -//! #[tokio::main] -//! async fn main() { -//! let (tx, rx) = oneshot::channel(); +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let (tx, rx) = oneshot::channel(); //! -//! tokio::spawn(async move { -//! let res = some_computation().await; -//! tx.send(res).unwrap(); -//! }); +//! tokio::spawn(async move { +//! let res = some_computation().await; +//! tx.send(res).unwrap(); +//! }); //! -//! // Do other work while the computation is happening in the background +//! // Do other work while the computation is happening in the background //! -//! // Wait for the computation result -//! let res = rx.await.unwrap(); -//! } +//! // Wait for the computation result +//! let res = rx.await.unwrap(); +//! # } //! ``` //! //! Note, if the task produces a computation result as its final @@ -67,22 +67,22 @@ //! //! **Example:** //! -//! ```ignore-wasm +//! ``` //! async fn some_computation() -> String { //! "the result of the computation".to_string() //! } //! -//! #[tokio::main] -//! async fn main() { -//! let join_handle = tokio::spawn(async move { -//! some_computation().await -//! }); +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let join_handle = tokio::spawn(async move { +//! some_computation().await +//! }); //! -//! // Do other work while the computation is happening in the background +//! // Do other work while the computation is happening in the background //! -//! // Wait for the computation result -//! let res = join_handle.await.unwrap(); -//! } +//! // Wait for the computation result +//! let res = join_handle.await.unwrap(); +//! # } //! ``` //! //! [`JoinHandle`]: crate::task::JoinHandle @@ -100,28 +100,28 @@ //! **Example:** using an mpsc to incrementally stream the results of a series //! of computations. //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::mpsc; //! //! async fn some_computation(input: u32) -> String { //! format!("the result of computation {}", input) //! } //! -//! #[tokio::main] -//! async fn main() { -//! let (tx, mut rx) = mpsc::channel(100); -//! -//! tokio::spawn(async move { -//! for i in 0..10 { -//! let res = some_computation(i).await; -//! tx.send(res).await.unwrap(); -//! } -//! }); +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let (tx, mut rx) = mpsc::channel(100); //! -//! while let Some(res) = rx.recv().await { -//! println!("got = {}", res); +//! tokio::spawn(async move { +//! for i in 0..10 { +//! let res = some_computation(i).await; +//! tx.send(res).await.unwrap(); //! } +//! }); +//! +//! while let Some(res) = rx.recv().await { +//! println!("got = {}", res); //! } +//! # } //! ``` //! //! The argument to `mpsc::channel` is the channel capacity. This is the maximum @@ -184,7 +184,7 @@ //! "fetch and increment" command. The counter value **before** the increment is //! sent over the provided `oneshot` channel. //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::{oneshot, mpsc}; //! use Command::Increment; //! @@ -193,46 +193,46 @@ //! // Other commands can be added here //! } //! -//! #[tokio::main] -//! async fn main() { -//! let (cmd_tx, mut cmd_rx) = mpsc::channel::<(Command, oneshot::Sender)>(100); -//! -//! // Spawn a task to manage the counter -//! tokio::spawn(async move { -//! let mut counter: u64 = 0; -//! -//! while let Some((cmd, response)) = cmd_rx.recv().await { -//! match cmd { -//! Increment => { -//! let prev = counter; -//! counter += 1; -//! response.send(prev).unwrap(); -//! } +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let (cmd_tx, mut cmd_rx) = mpsc::channel::<(Command, oneshot::Sender)>(100); +//! +//! // Spawn a task to manage the counter +//! tokio::spawn(async move { +//! let mut counter: u64 = 0; +//! +//! while let Some((cmd, response)) = cmd_rx.recv().await { +//! match cmd { +//! Increment => { +//! let prev = counter; +//! counter += 1; +//! response.send(prev).unwrap(); //! } //! } -//! }); +//! } +//! }); //! -//! let mut join_handles = vec![]; +//! let mut join_handles = vec![]; //! -//! // Spawn tasks that will send the increment command. -//! for _ in 0..10 { -//! let cmd_tx = cmd_tx.clone(); +//! // Spawn tasks that will send the increment command. +//! for _ in 0..10 { +//! let cmd_tx = cmd_tx.clone(); //! -//! join_handles.push(tokio::spawn(async move { -//! let (resp_tx, resp_rx) = oneshot::channel(); +//! join_handles.push(tokio::spawn(async move { +//! let (resp_tx, resp_rx) = oneshot::channel(); //! -//! cmd_tx.send((Increment, resp_tx)).await.ok().unwrap(); -//! let res = resp_rx.await.unwrap(); +//! cmd_tx.send((Increment, resp_tx)).await.ok().unwrap(); +//! let res = resp_rx.await.unwrap(); //! -//! println!("previous value = {}", res); -//! })); -//! } +//! println!("previous value = {}", res); +//! })); +//! } //! -//! // Wait for all tasks to complete -//! for join_handle in join_handles.drain(..) { -//! join_handle.await.unwrap(); -//! } +//! // Wait for all tasks to complete +//! for join_handle in join_handles.drain(..) { +//! join_handle.await.unwrap(); //! } +//! # } //! ``` //! //! ## `broadcast` channel @@ -251,27 +251,27 @@ //! //! Basic usage //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::broadcast; //! -//! #[tokio::main] -//! async fn main() { -//! let (tx, mut rx1) = broadcast::channel(16); -//! let mut rx2 = tx.subscribe(); +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let (tx, mut rx1) = broadcast::channel(16); +//! let mut rx2 = tx.subscribe(); //! -//! tokio::spawn(async move { -//! assert_eq!(rx1.recv().await.unwrap(), 10); -//! assert_eq!(rx1.recv().await.unwrap(), 20); -//! }); +//! tokio::spawn(async move { +//! assert_eq!(rx1.recv().await.unwrap(), 10); +//! assert_eq!(rx1.recv().await.unwrap(), 20); +//! }); //! -//! tokio::spawn(async move { -//! assert_eq!(rx2.recv().await.unwrap(), 10); -//! assert_eq!(rx2.recv().await.unwrap(), 20); -//! }); +//! tokio::spawn(async move { +//! assert_eq!(rx2.recv().await.unwrap(), 10); +//! assert_eq!(rx2.recv().await.unwrap(), 20); +//! }); //! -//! tx.send(10).unwrap(); -//! tx.send(20).unwrap(); -//! } +//! tx.send(10).unwrap(); +//! tx.send(20).unwrap(); +//! # } //! ``` //! //! [`broadcast` channel]: crate::sync::broadcast @@ -293,7 +293,7 @@ //! changes. In this example, a configuration file is checked periodically. When //! the file changes, the configuration changes are signalled to consumers. //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::watch; //! use tokio::time::{self, Duration, Instant}; //! @@ -315,92 +315,92 @@ //! // Do something here //! } //! -//! #[tokio::main] -//! async fn main() { -//! // Load initial configuration value -//! let mut config = Config::load_from_file().await.unwrap(); -//! -//! // Create the watch channel, initialized with the loaded configuration -//! let (tx, rx) = watch::channel(config.clone()); +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! // Load initial configuration value +//! let mut config = Config::load_from_file().await.unwrap(); +//! +//! // Create the watch channel, initialized with the loaded configuration +//! let (tx, rx) = watch::channel(config.clone()); +//! +//! // Spawn a task to monitor the file. +//! tokio::spawn(async move { +//! loop { +//! // Wait 10 seconds between checks +//! time::sleep(Duration::from_secs(10)).await; +//! +//! // Load the configuration file +//! let new_config = Config::load_from_file().await.unwrap(); +//! +//! // If the configuration changed, send the new config value +//! // on the watch channel. +//! if new_config != config { +//! tx.send(new_config.clone()).unwrap(); +//! config = new_config; +//! } +//! } +//! }); +//! +//! let mut handles = vec![]; +//! +//! // Spawn tasks that runs the async operation for at most `timeout`. If +//! // the timeout elapses, restart the operation. +//! // +//! // The task simultaneously watches the `Config` for changes. When the +//! // timeout duration changes, the timeout is updated without restarting +//! // the in-flight operation. +//! for _ in 0..5 { +//! // Clone a config watch handle for use in this task +//! let mut rx = rx.clone(); +//! +//! let handle = tokio::spawn(async move { +//! // Start the initial operation and pin the future to the stack. +//! // Pinning to the stack is required to resume the operation +//! // across multiple calls to `select!` +//! let op = my_async_operation(); +//! tokio::pin!(op); +//! +//! // Get the initial config value +//! let mut conf = rx.borrow().clone(); +//! +//! let mut op_start = Instant::now(); +//! let sleep = time::sleep_until(op_start + conf.timeout); +//! tokio::pin!(sleep); //! -//! // Spawn a task to monitor the file. -//! tokio::spawn(async move { //! loop { -//! // Wait 10 seconds between checks -//! time::sleep(Duration::from_secs(10)).await; +//! tokio::select! { +//! _ = &mut sleep => { +//! // The operation elapsed. Restart it +//! op.set(my_async_operation()); //! -//! // Load the configuration file -//! let new_config = Config::load_from_file().await.unwrap(); +//! // Track the new start time +//! op_start = Instant::now(); //! -//! // If the configuration changed, send the new config value -//! // on the watch channel. -//! if new_config != config { -//! tx.send(new_config.clone()).unwrap(); -//! config = new_config; -//! } -//! } -//! }); +//! // Restart the timeout +//! sleep.set(time::sleep_until(op_start + conf.timeout)); +//! } +//! _ = rx.changed() => { +//! conf = rx.borrow_and_update().clone(); //! -//! let mut handles = vec![]; -//! -//! // Spawn tasks that runs the async operation for at most `timeout`. If -//! // the timeout elapses, restart the operation. -//! // -//! // The task simultaneously watches the `Config` for changes. When the -//! // timeout duration changes, the timeout is updated without restarting -//! // the in-flight operation. -//! for _ in 0..5 { -//! // Clone a config watch handle for use in this task -//! let mut rx = rx.clone(); -//! -//! let handle = tokio::spawn(async move { -//! // Start the initial operation and pin the future to the stack. -//! // Pinning to the stack is required to resume the operation -//! // across multiple calls to `select!` -//! let op = my_async_operation(); -//! tokio::pin!(op); -//! -//! // Get the initial config value -//! let mut conf = rx.borrow().clone(); -//! -//! let mut op_start = Instant::now(); -//! let sleep = time::sleep_until(op_start + conf.timeout); -//! tokio::pin!(sleep); -//! -//! loop { -//! tokio::select! { -//! _ = &mut sleep => { -//! // The operation elapsed. Restart it -//! op.set(my_async_operation()); -//! -//! // Track the new start time -//! op_start = Instant::now(); -//! -//! // Restart the timeout -//! sleep.set(time::sleep_until(op_start + conf.timeout)); -//! } -//! _ = rx.changed() => { -//! conf = rx.borrow_and_update().clone(); -//! -//! // The configuration has been updated. Update the -//! // `sleep` using the new `timeout` value. -//! sleep.as_mut().reset(op_start + conf.timeout); -//! } -//! _ = &mut op => { -//! // The operation completed! -//! return -//! } +//! // The configuration has been updated. Update the +//! // `sleep` using the new `timeout` value. +//! sleep.as_mut().reset(op_start + conf.timeout); +//! } +//! _ = &mut op => { +//! // The operation completed! +//! return //! } //! } -//! }); +//! } +//! }); //! -//! handles.push(handle); -//! } +//! handles.push(handle); +//! } //! -//! for handle in handles.drain(..) { -//! handle.await.unwrap(); -//! } +//! for handle in handles.drain(..) { +//! handle.await.unwrap(); //! } +//! # } //! ``` //! //! [`watch` channel]: mod@crate::sync::watch diff --git a/tokio/src/sync/mpsc/bounded.rs b/tokio/src/sync/mpsc/bounded.rs index 51dc8df8b1d..4200420fd6b 100644 --- a/tokio/src/sync/mpsc/bounded.rs +++ b/tokio/src/sync/mpsc/bounded.rs @@ -37,21 +37,21 @@ pub struct Sender { /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::mpsc::channel; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, _rx) = channel::(15); -/// let tx_weak = tx.downgrade(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, _rx) = channel::(15); +/// let tx_weak = tx.downgrade(); /// -/// // Upgrading will succeed because `tx` still exists. -/// assert!(tx_weak.upgrade().is_some()); +/// // Upgrading will succeed because `tx` still exists. +/// assert!(tx_weak.upgrade().is_some()); /// -/// // If we drop `tx`, then it will fail. -/// drop(tx); -/// assert!(tx_weak.clone().upgrade().is_none()); -/// } +/// // If we drop `tx`, then it will fail. +/// drop(tx); +/// assert!(tx_weak.clone().upgrade().is_none()); +/// # } /// ``` pub struct WeakSender { chan: Arc>, @@ -131,26 +131,26 @@ pub struct Receiver { /// /// # Examples /// -/// ```rust,ignore-wasm +/// ```rust /// use tokio::sync::mpsc; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, mut rx) = mpsc::channel(100); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, mut rx) = mpsc::channel(100); /// -/// tokio::spawn(async move { -/// for i in 0..10 { -/// if let Err(_) = tx.send(i).await { -/// println!("receiver dropped"); -/// return; -/// } +/// tokio::spawn(async move { +/// for i in 0..10 { +/// if let Err(_) = tx.send(i).await { +/// println!("receiver dropped"); +/// return; /// } -/// }); -/// -/// while let Some(i) = rx.recv().await { -/// println!("got = {}", i); /// } +/// }); +/// +/// while let Some(i) = rx.recv().await { +/// println!("got = {}", i); /// } +/// # } /// ``` #[track_caller] pub fn channel(buffer: usize) -> (Sender, Receiver) { @@ -205,37 +205,37 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(100); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(100); /// - /// tokio::spawn(async move { - /// tx.send("hello").await.unwrap(); - /// }); + /// tokio::spawn(async move { + /// tx.send("hello").await.unwrap(); + /// }); /// - /// assert_eq!(Some("hello"), rx.recv().await); - /// assert_eq!(None, rx.recv().await); - /// } + /// assert_eq!(Some("hello"), rx.recv().await); + /// assert_eq!(None, rx.recv().await); + /// # } /// ``` /// /// Values are buffered: /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(100); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(100); /// - /// tx.send("hello").await.unwrap(); - /// tx.send("world").await.unwrap(); + /// tx.send("hello").await.unwrap(); + /// tx.send("world").await.unwrap(); /// - /// assert_eq!(Some("hello"), rx.recv().await); - /// assert_eq!(Some("world"), rx.recv().await); - /// } + /// assert_eq!(Some("hello"), rx.recv().await); + /// assert_eq!(Some("world"), rx.recv().await); + /// # } /// ``` pub async fn recv(&mut self) -> Option { use std::future::poll_fn; @@ -275,43 +275,43 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let mut buffer: Vec<&str> = Vec::with_capacity(2); - /// let limit = 2; - /// let (tx, mut rx) = mpsc::channel(100); - /// let tx2 = tx.clone(); - /// tx2.send("first").await.unwrap(); - /// tx2.send("second").await.unwrap(); - /// tx2.send("third").await.unwrap(); - /// - /// // Call `recv_many` to receive up to `limit` (2) values. - /// assert_eq!(2, rx.recv_many(&mut buffer, limit).await); - /// assert_eq!(vec!["first", "second"], buffer); - /// - /// // If the buffer is full, the next call to `recv_many` - /// // reserves additional capacity. - /// assert_eq!(1, rx.recv_many(&mut buffer, 1).await); - /// - /// tokio::spawn(async move { - /// tx.send("fourth").await.unwrap(); - /// }); - /// - /// // 'tx' is dropped, but `recv_many` - /// // is guaranteed not to return 0 as the channel - /// // is not yet closed. - /// assert_eq!(1, rx.recv_many(&mut buffer, 1).await); - /// assert_eq!(vec!["first", "second", "third", "fourth"], buffer); - /// - /// // Once the last sender is dropped, the channel is - /// // closed and `recv_many` returns 0, capacity unchanged. - /// drop(tx2); - /// assert_eq!(0, rx.recv_many(&mut buffer, limit).await); - /// assert_eq!(vec!["first", "second", "third", "fourth"], buffer); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut buffer: Vec<&str> = Vec::with_capacity(2); + /// let limit = 2; + /// let (tx, mut rx) = mpsc::channel(100); + /// let tx2 = tx.clone(); + /// tx2.send("first").await.unwrap(); + /// tx2.send("second").await.unwrap(); + /// tx2.send("third").await.unwrap(); + /// + /// // Call `recv_many` to receive up to `limit` (2) values. + /// assert_eq!(2, rx.recv_many(&mut buffer, limit).await); + /// assert_eq!(vec!["first", "second"], buffer); + /// + /// // If the buffer is full, the next call to `recv_many` + /// // reserves additional capacity. + /// assert_eq!(1, rx.recv_many(&mut buffer, 1).await); + /// + /// tokio::spawn(async move { + /// tx.send("fourth").await.unwrap(); + /// }); + /// + /// // 'tx' is dropped, but `recv_many` + /// // is guaranteed not to return 0 as the channel + /// // is not yet closed. + /// assert_eq!(1, rx.recv_many(&mut buffer, 1).await); + /// assert_eq!(vec!["first", "second", "third", "fourth"], buffer); + /// + /// // Once the last sender is dropped, the channel is + /// // closed and `recv_many` returns 0, capacity unchanged. + /// drop(tx2); + /// assert_eq!(0, rx.recv_many(&mut buffer, limit).await); + /// assert_eq!(vec!["first", "second", "third", "fourth"], buffer); + /// # } /// ``` pub async fn recv_many(&mut self, buffer: &mut Vec, limit: usize) -> usize { use std::future::poll_fn; @@ -337,26 +337,26 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// use tokio::sync::mpsc::error::TryRecvError; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(100); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(100); /// - /// tx.send("hello").await.unwrap(); + /// tx.send("hello").await.unwrap(); /// - /// assert_eq!(Ok("hello"), rx.try_recv()); - /// assert_eq!(Err(TryRecvError::Empty), rx.try_recv()); + /// assert_eq!(Ok("hello"), rx.try_recv()); + /// assert_eq!(Err(TryRecvError::Empty), rx.try_recv()); /// - /// tx.send("hello").await.unwrap(); - /// // Drop the last sender, closing the channel. - /// drop(tx); + /// tx.send("hello").await.unwrap(); + /// // Drop the last sender, closing the channel. + /// drop(tx); /// - /// assert_eq!(Ok("hello"), rx.try_recv()); - /// assert_eq!(Err(TryRecvError::Disconnected), rx.try_recv()); - /// } + /// assert_eq!(Ok("hello"), rx.try_recv()); + /// assert_eq!(Err(TryRecvError::Disconnected), rx.try_recv()); + /// # } /// ``` pub fn try_recv(&mut self) -> Result { self.chan.try_recv() @@ -445,29 +445,29 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(20); - /// - /// tokio::spawn(async move { - /// let mut i = 0; - /// while let Ok(permit) = tx.reserve().await { - /// permit.send(i); - /// i += 1; - /// } - /// }); - /// - /// rx.close(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(20); /// - /// while let Some(msg) = rx.recv().await { - /// println!("got {}", msg); + /// tokio::spawn(async move { + /// let mut i = 0; + /// while let Ok(permit) = tx.reserve().await { + /// permit.send(i); + /// i += 1; /// } + /// }); /// - /// // Channel closed and no messages are lost. + /// rx.close(); + /// + /// while let Some(msg) = rx.recv().await { + /// println!("got {}", msg); /// } + /// + /// // Channel closed and no messages are lost. + /// # } /// ``` pub fn close(&mut self) { self.chan.close(); @@ -482,18 +482,18 @@ impl Receiver { /// [`Receiver::close`]: crate::sync::mpsc::Receiver::close /// /// # Examples - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (_tx, mut rx) = mpsc::channel::<()>(10); - /// assert!(!rx.is_closed()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (_tx, mut rx) = mpsc::channel::<()>(10); + /// assert!(!rx.is_closed()); /// - /// rx.close(); + /// rx.close(); /// - /// assert!(rx.is_closed()); - /// } + /// assert!(rx.is_closed()); + /// # } /// ``` pub fn is_closed(&self) -> bool { self.chan.is_closed() @@ -504,17 +504,17 @@ impl Receiver { /// This method returns `true` if the channel has no messages. /// /// # Examples - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = mpsc::channel(10); - /// assert!(rx.is_empty()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = mpsc::channel(10); + /// assert!(rx.is_empty()); /// - /// tx.send(0).await.unwrap(); - /// assert!(!rx.is_empty()); - /// } + /// tx.send(0).await.unwrap(); + /// assert!(!rx.is_empty()); + /// # } /// /// ``` pub fn is_empty(&self) -> bool { @@ -524,17 +524,17 @@ impl Receiver { /// Returns the number of messages in the channel. /// /// # Examples - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = mpsc::channel(10); - /// assert_eq!(0, rx.len()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = mpsc::channel(10); + /// assert_eq!(0, rx.len()); /// - /// tx.send(0).await.unwrap(); - /// assert_eq!(1, rx.len()); - /// } + /// tx.send(0).await.unwrap(); + /// assert_eq!(1, rx.len()); + /// # } /// ``` pub fn len(&self) -> usize { self.chan.len() @@ -549,36 +549,36 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel::<()>(5); - /// - /// assert_eq!(rx.capacity(), 5); - /// - /// // Making a reservation drops the capacity by one. - /// let permit = tx.reserve().await.unwrap(); - /// assert_eq!(rx.capacity(), 4); - /// assert_eq!(rx.len(), 0); - /// - /// // Sending and receiving a value increases the capacity by one. - /// permit.send(()); - /// assert_eq!(rx.len(), 1); - /// rx.recv().await.unwrap(); - /// assert_eq!(rx.capacity(), 5); - /// - /// // Directly sending a message drops the capacity by one. - /// tx.send(()).await.unwrap(); - /// assert_eq!(rx.capacity(), 4); - /// assert_eq!(rx.len(), 1); - /// - /// // Receiving the message increases the capacity by one. - /// rx.recv().await.unwrap(); - /// assert_eq!(rx.capacity(), 5); - /// assert_eq!(rx.len(), 0); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel::<()>(5); + /// + /// assert_eq!(rx.capacity(), 5); + /// + /// // Making a reservation drops the capacity by one. + /// let permit = tx.reserve().await.unwrap(); + /// assert_eq!(rx.capacity(), 4); + /// assert_eq!(rx.len(), 0); + /// + /// // Sending and receiving a value increases the capacity by one. + /// permit.send(()); + /// assert_eq!(rx.len(), 1); + /// rx.recv().await.unwrap(); + /// assert_eq!(rx.capacity(), 5); + /// + /// // Directly sending a message drops the capacity by one. + /// tx.send(()).await.unwrap(); + /// assert_eq!(rx.capacity(), 4); + /// assert_eq!(rx.len(), 1); + /// + /// // Receiving the message increases the capacity by one. + /// rx.recv().await.unwrap(); + /// assert_eq!(rx.capacity(), 5); + /// assert_eq!(rx.len(), 0); + /// # } /// ``` /// [`capacity`]: Receiver::capacity /// [`max_capacity`]: Receiver::max_capacity @@ -596,23 +596,23 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = mpsc::channel::<()>(5); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = mpsc::channel::<()>(5); /// - /// // both max capacity and capacity are the same at first - /// assert_eq!(rx.max_capacity(), 5); - /// assert_eq!(rx.capacity(), 5); + /// // both max capacity and capacity are the same at first + /// assert_eq!(rx.max_capacity(), 5); + /// assert_eq!(rx.capacity(), 5); /// - /// // Making a reservation doesn't change the max capacity. - /// let permit = tx.reserve().await.unwrap(); - /// assert_eq!(rx.max_capacity(), 5); - /// // but drops the capacity by one - /// assert_eq!(rx.capacity(), 4); - /// } + /// // Making a reservation doesn't change the max capacity. + /// let permit = tx.reserve().await.unwrap(); + /// assert_eq!(rx.max_capacity(), 5); + /// // but drops the capacity by one + /// assert_eq!(rx.capacity(), 4); + /// # } /// ``` /// [`capacity`]: Receiver::capacity /// [`max_capacity`]: Receiver::max_capacity @@ -667,7 +667,7 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::task::{Context, Poll}; /// use std::pin::Pin; /// use tokio::sync::mpsc; @@ -693,25 +693,25 @@ impl Receiver { /// } /// } /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = mpsc::channel(32); - /// let mut buffer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = mpsc::channel(32); + /// let mut buffer = Vec::new(); /// - /// let my_receiver_future = MyReceiverFuture { - /// receiver: rx, - /// buffer: &mut buffer, - /// limit: 3, - /// }; + /// let my_receiver_future = MyReceiverFuture { + /// receiver: rx, + /// buffer: &mut buffer, + /// limit: 3, + /// }; /// - /// for i in 0..10 { - /// tx.send(i).await.unwrap(); - /// } - /// - /// let count = my_receiver_future.await; - /// assert_eq!(count, 3); - /// assert_eq!(buffer, vec![0,1,2]) + /// for i in 0..10 { + /// tx.send(i).await.unwrap(); /// } + /// + /// let count = my_receiver_future.await; + /// assert_eq!(count, 3); + /// assert_eq!(buffer, vec![0,1,2]) + /// # } /// ``` pub fn poll_recv_many( &mut self, @@ -786,26 +786,26 @@ impl Sender { /// In the following example, each call to `send` will block until the /// previously sent value was received. /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(1); /// - /// tokio::spawn(async move { - /// for i in 0..10 { - /// if let Err(_) = tx.send(i).await { - /// println!("receiver dropped"); - /// return; - /// } + /// tokio::spawn(async move { + /// for i in 0..10 { + /// if let Err(_) = tx.send(i).await { + /// println!("receiver dropped"); + /// return; /// } - /// }); - /// - /// while let Some(i) = rx.recv().await { - /// println!("got = {}", i); /// } + /// }); + /// + /// while let Some(i) = rx.recv().await { + /// println!("got = {}", i); /// } + /// # } /// ``` pub async fn send(&self, value: T) -> Result<(), SendError> { match self.reserve().await { @@ -829,29 +829,29 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx1, rx) = mpsc::channel::<()>(1); - /// let tx2 = tx1.clone(); - /// let tx3 = tx1.clone(); - /// let tx4 = tx1.clone(); - /// let tx5 = tx1.clone(); - /// tokio::spawn(async move { - /// drop(rx); - /// }); - /// - /// futures::join!( - /// tx1.closed(), - /// tx2.closed(), - /// tx3.closed(), - /// tx4.closed(), - /// tx5.closed() - /// ); - /// println!("Receiver dropped"); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx1, rx) = mpsc::channel::<()>(1); + /// let tx2 = tx1.clone(); + /// let tx3 = tx1.clone(); + /// let tx4 = tx1.clone(); + /// let tx5 = tx1.clone(); + /// tokio::spawn(async move { + /// drop(rx); + /// }); + /// + /// futures::join!( + /// tx1.closed(), + /// tx2.closed(), + /// tx3.closed(), + /// tx4.closed(), + /// tx5.closed() + /// ); + /// println!("Receiver dropped"); + /// # } /// ``` pub async fn closed(&self) { self.chan.closed().await; @@ -880,40 +880,40 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// // Create a channel with buffer size 1 - /// let (tx1, mut rx) = mpsc::channel(1); - /// let tx2 = tx1.clone(); - /// - /// tokio::spawn(async move { - /// tx1.send(1).await.unwrap(); - /// tx1.send(2).await.unwrap(); - /// // task waits until the receiver receives a value. - /// }); - /// - /// tokio::spawn(async move { - /// // This will return an error and send - /// // no message if the buffer is full - /// let _ = tx2.try_send(3); - /// }); - /// - /// let mut msg; - /// msg = rx.recv().await.unwrap(); - /// println!("message {} received", msg); - /// - /// msg = rx.recv().await.unwrap(); - /// println!("message {} received", msg); - /// - /// // Third message may have never been sent - /// match rx.recv().await { - /// Some(msg) => println!("message {} received", msg), - /// None => println!("the third message was never sent"), - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// // Create a channel with buffer size 1 + /// let (tx1, mut rx) = mpsc::channel(1); + /// let tx2 = tx1.clone(); + /// + /// tokio::spawn(async move { + /// tx1.send(1).await.unwrap(); + /// tx1.send(2).await.unwrap(); + /// // task waits until the receiver receives a value. + /// }); + /// + /// tokio::spawn(async move { + /// // This will return an error and send + /// // no message if the buffer is full + /// let _ = tx2.try_send(3); + /// }); + /// + /// let mut msg; + /// msg = rx.recv().await.unwrap(); + /// println!("message {} received", msg); + /// + /// msg = rx.recv().await.unwrap(); + /// println!("message {} received", msg); + /// + /// // Third message may have never been sent + /// match rx.recv().await { + /// Some(msg) => println!("message {} received", msg), + /// None => println!("the third message was never sent"), /// } + /// # } /// ``` pub fn try_send(&self, message: T) -> Result<(), TrySendError> { match self.chan.semaphore().semaphore.try_acquire(1) { @@ -954,28 +954,28 @@ impl Sender { /// In the following example, each call to `send_timeout` will block until the /// previously sent value was received, unless the timeout has elapsed. /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::sync::mpsc; /// use tokio::time::{sleep, Duration}; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(1); /// - /// tokio::spawn(async move { - /// for i in 0..10 { - /// if let Err(e) = tx.send_timeout(i, Duration::from_millis(100)).await { - /// println!("send error: #{:?}", e); - /// return; - /// } + /// tokio::spawn(async move { + /// for i in 0..10 { + /// if let Err(e) = tx.send_timeout(i, Duration::from_millis(100)).await { + /// println!("send error: #{:?}", e); + /// return; /// } - /// }); - /// - /// while let Some(i) = rx.recv().await { - /// println!("got = {}", i); - /// sleep(Duration::from_millis(200)).await; /// } + /// }); + /// + /// while let Some(i) = rx.recv().await { + /// println!("got = {}", i); + /// sleep(Duration::from_millis(200)).await; /// } + /// # } /// ``` #[cfg(feature = "time")] #[cfg_attr(docsrs, doc(cfg(feature = "time")))] @@ -1083,26 +1083,26 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(1); /// - /// // Reserve capacity - /// let permit = tx.reserve().await.unwrap(); + /// // Reserve capacity + /// let permit = tx.reserve().await.unwrap(); /// - /// // Trying to send directly on the `tx` will fail due to no - /// // available capacity. - /// assert!(tx.try_send(123).is_err()); + /// // Trying to send directly on the `tx` will fail due to no + /// // available capacity. + /// assert!(tx.try_send(123).is_err()); /// - /// // Sending on the permit succeeds - /// permit.send(456); + /// // Sending on the permit succeeds + /// permit.send(456); /// - /// // The value sent on the permit is received - /// assert_eq!(rx.recv().await.unwrap(), 456); - /// } + /// // The value sent on the permit is received + /// assert_eq!(rx.recv().await.unwrap(), 456); + /// # } /// ``` pub async fn reserve(&self) -> Result, SendError<()>> { self.reserve_inner(1).await?; @@ -1139,31 +1139,31 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(2); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(2); /// - /// // Reserve capacity - /// let mut permit = tx.reserve_many(2).await.unwrap(); + /// // Reserve capacity + /// let mut permit = tx.reserve_many(2).await.unwrap(); /// - /// // Trying to send directly on the `tx` will fail due to no - /// // available capacity. - /// assert!(tx.try_send(123).is_err()); + /// // Trying to send directly on the `tx` will fail due to no + /// // available capacity. + /// assert!(tx.try_send(123).is_err()); /// - /// // Sending with the permit iterator succeeds - /// permit.next().unwrap().send(456); - /// permit.next().unwrap().send(457); + /// // Sending with the permit iterator succeeds + /// permit.next().unwrap().send(456); + /// permit.next().unwrap().send(457); /// - /// // The iterator should now be exhausted - /// assert!(permit.next().is_none()); + /// // The iterator should now be exhausted + /// assert!(permit.next().is_none()); /// - /// // The value sent on the permit is received - /// assert_eq!(rx.recv().await.unwrap(), 456); - /// assert_eq!(rx.recv().await.unwrap(), 457); - /// } + /// // The value sent on the permit is received + /// assert_eq!(rx.recv().await.unwrap(), 456); + /// assert_eq!(rx.recv().await.unwrap(), 457); + /// # } /// ``` pub async fn reserve_many(&self, n: usize) -> Result, SendError<()>> { self.reserve_inner(n).await?; @@ -1202,51 +1202,51 @@ impl Sender { /// /// # Examples /// Sending a message using an [`OwnedPermit`]: - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(1); /// - /// // Reserve capacity, moving the sender. - /// let permit = tx.reserve_owned().await.unwrap(); + /// // Reserve capacity, moving the sender. + /// let permit = tx.reserve_owned().await.unwrap(); /// - /// // Send a message, consuming the permit and returning - /// // the moved sender. - /// let tx = permit.send(123); + /// // Send a message, consuming the permit and returning + /// // the moved sender. + /// let tx = permit.send(123); /// - /// // The value sent on the permit is received. - /// assert_eq!(rx.recv().await.unwrap(), 123); + /// // The value sent on the permit is received. + /// assert_eq!(rx.recv().await.unwrap(), 123); /// - /// // The sender can now be used again. - /// tx.send(456).await.unwrap(); - /// } + /// // The sender can now be used again. + /// tx.send(456).await.unwrap(); + /// # } /// ``` /// /// When multiple [`OwnedPermit`]s are needed, or the sender cannot be moved /// by value, it can be inexpensively cloned before calling `reserve_owned`: /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(1); /// - /// // Clone the sender and reserve capacity. - /// let permit = tx.clone().reserve_owned().await.unwrap(); + /// // Clone the sender and reserve capacity. + /// let permit = tx.clone().reserve_owned().await.unwrap(); /// - /// // Trying to send directly on the `tx` will fail due to no - /// // available capacity. - /// assert!(tx.try_send(123).is_err()); + /// // Trying to send directly on the `tx` will fail due to no + /// // available capacity. + /// assert!(tx.try_send(123).is_err()); /// - /// // Sending on the permit succeeds. - /// permit.send(456); + /// // Sending on the permit succeeds. + /// permit.send(456); /// - /// // The value sent on the permit is received - /// assert_eq!(rx.recv().await.unwrap(), 456); - /// } + /// // The value sent on the permit is received + /// assert_eq!(rx.recv().await.unwrap(), 456); + /// # } /// ``` /// /// [`Sender::reserve`]: Sender::reserve @@ -1289,31 +1289,31 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(1); /// - /// // Reserve capacity - /// let permit = tx.try_reserve().unwrap(); + /// // Reserve capacity + /// let permit = tx.try_reserve().unwrap(); /// - /// // Trying to send directly on the `tx` will fail due to no - /// // available capacity. - /// assert!(tx.try_send(123).is_err()); + /// // Trying to send directly on the `tx` will fail due to no + /// // available capacity. + /// assert!(tx.try_send(123).is_err()); /// - /// // Trying to reserve an additional slot on the `tx` will - /// // fail because there is no capacity. - /// assert!(tx.try_reserve().is_err()); + /// // Trying to reserve an additional slot on the `tx` will + /// // fail because there is no capacity. + /// assert!(tx.try_reserve().is_err()); /// - /// // Sending on the permit succeeds - /// permit.send(456); + /// // Sending on the permit succeeds + /// permit.send(456); /// - /// // The value sent on the permit is received - /// assert_eq!(rx.recv().await.unwrap(), 456); + /// // The value sent on the permit is received + /// assert_eq!(rx.recv().await.unwrap(), 456); /// - /// } + /// # } /// ``` pub fn try_reserve(&self) -> Result, TrySendError<()>> { match self.chan.semaphore().semaphore.try_acquire(1) { @@ -1346,52 +1346,52 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(2); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(2); /// - /// // Reserve capacity - /// let mut permit = tx.try_reserve_many(2).unwrap(); + /// // Reserve capacity + /// let mut permit = tx.try_reserve_many(2).unwrap(); /// - /// // Trying to send directly on the `tx` will fail due to no - /// // available capacity. - /// assert!(tx.try_send(123).is_err()); + /// // Trying to send directly on the `tx` will fail due to no + /// // available capacity. + /// assert!(tx.try_send(123).is_err()); /// - /// // Trying to reserve an additional slot on the `tx` will - /// // fail because there is no capacity. - /// assert!(tx.try_reserve().is_err()); + /// // Trying to reserve an additional slot on the `tx` will + /// // fail because there is no capacity. + /// assert!(tx.try_reserve().is_err()); /// - /// // Sending with the permit iterator succeeds - /// permit.next().unwrap().send(456); - /// permit.next().unwrap().send(457); + /// // Sending with the permit iterator succeeds + /// permit.next().unwrap().send(456); + /// permit.next().unwrap().send(457); /// - /// // The iterator should now be exhausted - /// assert!(permit.next().is_none()); + /// // The iterator should now be exhausted + /// assert!(permit.next().is_none()); /// - /// // The value sent on the permit is received - /// assert_eq!(rx.recv().await.unwrap(), 456); - /// assert_eq!(rx.recv().await.unwrap(), 457); + /// // The value sent on the permit is received + /// assert_eq!(rx.recv().await.unwrap(), 456); + /// assert_eq!(rx.recv().await.unwrap(), 457); /// - /// // Trying to call try_reserve_many with 0 will return an empty iterator - /// let mut permit = tx.try_reserve_many(0).unwrap(); - /// assert!(permit.next().is_none()); + /// // Trying to call try_reserve_many with 0 will return an empty iterator + /// let mut permit = tx.try_reserve_many(0).unwrap(); + /// assert!(permit.next().is_none()); /// - /// // Trying to call try_reserve_many with a number greater than the channel - /// // capacity will return an error - /// let permit = tx.try_reserve_many(3); - /// assert!(permit.is_err()); + /// // Trying to call try_reserve_many with a number greater than the channel + /// // capacity will return an error + /// let permit = tx.try_reserve_many(3); + /// assert!(permit.is_err()); /// - /// // Trying to call try_reserve_many on a closed channel will return an error - /// drop(rx); - /// let permit = tx.try_reserve_many(1); - /// assert!(permit.is_err()); + /// // Trying to call try_reserve_many on a closed channel will return an error + /// drop(rx); + /// let permit = tx.try_reserve_many(1); + /// assert!(permit.is_err()); /// - /// let permit = tx.try_reserve_many(0); - /// assert!(permit.is_err()); - /// } + /// let permit = tx.try_reserve_many(0); + /// assert!(permit.is_err()); + /// # } /// ``` pub fn try_reserve_many(&self, n: usize) -> Result, TrySendError<()>> { if n > self.max_capacity() { @@ -1439,31 +1439,31 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(1); /// - /// // Reserve capacity - /// let permit = tx.clone().try_reserve_owned().unwrap(); + /// // Reserve capacity + /// let permit = tx.clone().try_reserve_owned().unwrap(); /// - /// // Trying to send directly on the `tx` will fail due to no - /// // available capacity. - /// assert!(tx.try_send(123).is_err()); + /// // Trying to send directly on the `tx` will fail due to no + /// // available capacity. + /// assert!(tx.try_send(123).is_err()); /// - /// // Trying to reserve an additional slot on the `tx` will - /// // fail because there is no capacity. - /// assert!(tx.try_reserve().is_err()); + /// // Trying to reserve an additional slot on the `tx` will + /// // fail because there is no capacity. + /// assert!(tx.try_reserve().is_err()); /// - /// // Sending on the permit succeeds - /// permit.send(456); + /// // Sending on the permit succeeds + /// permit.send(456); /// - /// // The value sent on the permit is received - /// assert_eq!(rx.recv().await.unwrap(), 456); + /// // The value sent on the permit is received + /// assert_eq!(rx.recv().await.unwrap(), 456); /// - /// } + /// # } /// ``` pub fn try_reserve_owned(self) -> Result, TrySendError> { match self.chan.semaphore().semaphore.try_acquire(1) { @@ -1502,24 +1502,24 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel::<()>(5); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel::<()>(5); /// - /// assert_eq!(tx.capacity(), 5); + /// assert_eq!(tx.capacity(), 5); /// - /// // Making a reservation drops the capacity by one. - /// let permit = tx.reserve().await.unwrap(); - /// assert_eq!(tx.capacity(), 4); + /// // Making a reservation drops the capacity by one. + /// let permit = tx.reserve().await.unwrap(); + /// assert_eq!(tx.capacity(), 4); /// - /// // Sending and receiving a value increases the capacity by one. - /// permit.send(()); - /// rx.recv().await.unwrap(); - /// assert_eq!(tx.capacity(), 5); - /// } + /// // Sending and receiving a value increases the capacity by one. + /// permit.send(()); + /// rx.recv().await.unwrap(); + /// assert_eq!(tx.capacity(), 5); + /// # } /// ``` /// /// [`send`]: Sender::send @@ -1551,23 +1551,23 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, _rx) = mpsc::channel::<()>(5); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, _rx) = mpsc::channel::<()>(5); /// - /// // both max capacity and capacity are the same at first - /// assert_eq!(tx.max_capacity(), 5); - /// assert_eq!(tx.capacity(), 5); + /// // both max capacity and capacity are the same at first + /// assert_eq!(tx.max_capacity(), 5); + /// assert_eq!(tx.capacity(), 5); /// - /// // Making a reservation doesn't change the max capacity. - /// let permit = tx.reserve().await.unwrap(); - /// assert_eq!(tx.max_capacity(), 5); - /// // but drops the capacity by one - /// assert_eq!(tx.capacity(), 4); - /// } + /// // Making a reservation doesn't change the max capacity. + /// let permit = tx.reserve().await.unwrap(); + /// assert_eq!(tx.max_capacity(), 5); + /// // but drops the capacity by one + /// assert_eq!(tx.capacity(), 4); + /// # } /// ``` /// /// [`channel`]: channel @@ -1659,26 +1659,26 @@ impl Permit<'_, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(1); /// - /// // Reserve capacity - /// let permit = tx.reserve().await.unwrap(); + /// // Reserve capacity + /// let permit = tx.reserve().await.unwrap(); /// - /// // Trying to send directly on the `tx` will fail due to no - /// // available capacity. - /// assert!(tx.try_send(123).is_err()); + /// // Trying to send directly on the `tx` will fail due to no + /// // available capacity. + /// assert!(tx.try_send(123).is_err()); /// - /// // Send a message on the permit - /// permit.send(456); + /// // Send a message on the permit + /// permit.send(456); /// - /// // The value sent on the permit is received - /// assert_eq!(rx.recv().await.unwrap(), 456); - /// } + /// // The value sent on the permit is received + /// assert_eq!(rx.recv().await.unwrap(), 456); + /// # } /// ``` pub fn send(self, value: T) { use std::mem; @@ -1784,25 +1784,25 @@ impl OwnedPermit { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::channel(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::channel(1); /// - /// // Reserve capacity - /// let permit = tx.reserve_owned().await.unwrap(); + /// // Reserve capacity + /// let permit = tx.reserve_owned().await.unwrap(); /// - /// // Send a message on the permit, returning the sender. - /// let tx = permit.send(456); + /// // Send a message on the permit, returning the sender. + /// let tx = permit.send(456); /// - /// // The value sent on the permit is received - /// assert_eq!(rx.recv().await.unwrap(), 456); + /// // The value sent on the permit is received + /// assert_eq!(rx.recv().await.unwrap(), 456); /// - /// // We may now reuse `tx` to send another message. - /// tx.send(789).await.unwrap(); - /// } + /// // We may now reuse `tx` to send another message. + /// tx.send(789).await.unwrap(); + /// # } /// ``` pub fn send(mut self, value: T) -> Sender { let chan = self.chan.take().unwrap_or_else(|| { @@ -1818,28 +1818,28 @@ impl OwnedPermit { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = mpsc::channel(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = mpsc::channel(1); /// - /// // Clone the sender and reserve capacity - /// let permit = tx.clone().reserve_owned().await.unwrap(); + /// // Clone the sender and reserve capacity + /// let permit = tx.clone().reserve_owned().await.unwrap(); /// - /// // Trying to send on the original `tx` will fail, since the `permit` - /// // has reserved all the available capacity. - /// assert!(tx.try_send(123).is_err()); + /// // Trying to send on the original `tx` will fail, since the `permit` + /// // has reserved all the available capacity. + /// assert!(tx.try_send(123).is_err()); /// - /// // Release the permit without sending a message, returning the clone - /// // of the sender. - /// let tx2 = permit.release(); + /// // Release the permit without sending a message, returning the clone + /// // of the sender. + /// let tx2 = permit.release(); /// - /// // We may now reuse `tx` to send another message. - /// tx.send(789).await.unwrap(); - /// # drop(rx); drop(tx2); - /// } + /// // We may now reuse `tx` to send another message. + /// tx.send(789).await.unwrap(); + /// # drop(rx); drop(tx2); + /// # } /// ``` /// /// [`Sender`]: Sender @@ -1859,22 +1859,22 @@ impl OwnedPermit { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = mpsc::channel::<()>(2); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = mpsc::channel::<()>(2); /// - /// let permit1 = tx.clone().reserve_owned().await.unwrap(); - /// let permit2 = tx.clone().reserve_owned().await.unwrap(); - /// assert!(permit1.same_channel(&permit2)); + /// let permit1 = tx.clone().reserve_owned().await.unwrap(); + /// let permit2 = tx.clone().reserve_owned().await.unwrap(); + /// assert!(permit1.same_channel(&permit2)); /// - /// let (tx2, rx2) = mpsc::channel::<()>(1); + /// let (tx2, rx2) = mpsc::channel::<()>(1); /// - /// let permit3 = tx2.clone().reserve_owned().await.unwrap(); - /// assert!(!permit3.same_channel(&permit2)); - /// } + /// let permit3 = tx2.clone().reserve_owned().await.unwrap(); + /// assert!(!permit3.same_channel(&permit2)); + /// # } /// ``` pub fn same_channel(&self, other: &Self) -> bool { self.chan @@ -1887,19 +1887,19 @@ impl OwnedPermit { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = mpsc::channel::<()>(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = mpsc::channel::<()>(1); /// - /// let permit = tx.clone().reserve_owned().await.unwrap(); - /// assert!(permit.same_channel_as_sender(&tx)); + /// let permit = tx.clone().reserve_owned().await.unwrap(); + /// assert!(permit.same_channel_as_sender(&tx)); /// - /// let (tx2, rx2) = mpsc::channel::<()>(1); - /// assert!(!permit.same_channel_as_sender(&tx2)); - /// } + /// let (tx2, rx2) = mpsc::channel::<()>(1); + /// assert!(!permit.same_channel_as_sender(&tx2)); + /// # } /// ``` pub fn same_channel_as_sender(&self, sender: &Sender) -> bool { self.chan diff --git a/tokio/src/sync/mpsc/unbounded.rs b/tokio/src/sync/mpsc/unbounded.rs index 23503f0b2f6..99778517dba 100644 --- a/tokio/src/sync/mpsc/unbounded.rs +++ b/tokio/src/sync/mpsc/unbounded.rs @@ -26,21 +26,21 @@ pub struct UnboundedSender { /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::mpsc::unbounded_channel; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, _rx) = unbounded_channel::(); -/// let tx_weak = tx.downgrade(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, _rx) = unbounded_channel::(); +/// let tx_weak = tx.downgrade(); /// -/// // Upgrading will succeed because `tx` still exists. -/// assert!(tx_weak.upgrade().is_some()); +/// // Upgrading will succeed because `tx` still exists. +/// assert!(tx_weak.upgrade().is_some()); /// -/// // If we drop `tx`, then it will fail. -/// drop(tx); -/// assert!(tx_weak.clone().upgrade().is_none()); -/// } +/// // If we drop `tx`, then it will fail. +/// drop(tx); +/// assert!(tx_weak.clone().upgrade().is_none()); +/// # } /// ``` pub struct WeakUnboundedSender { chan: Arc>, @@ -132,37 +132,37 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::unbounded_channel(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::unbounded_channel(); /// - /// tokio::spawn(async move { - /// tx.send("hello").unwrap(); - /// }); + /// tokio::spawn(async move { + /// tx.send("hello").unwrap(); + /// }); /// - /// assert_eq!(Some("hello"), rx.recv().await); - /// assert_eq!(None, rx.recv().await); - /// } + /// assert_eq!(Some("hello"), rx.recv().await); + /// assert_eq!(None, rx.recv().await); + /// # } /// ``` /// /// Values are buffered: /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::unbounded_channel(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::unbounded_channel(); /// - /// tx.send("hello").unwrap(); - /// tx.send("world").unwrap(); + /// tx.send("hello").unwrap(); + /// tx.send("world").unwrap(); /// - /// assert_eq!(Some("hello"), rx.recv().await); - /// assert_eq!(Some("world"), rx.recv().await); - /// } + /// assert_eq!(Some("hello"), rx.recv().await); + /// assert_eq!(Some("world"), rx.recv().await); + /// # } /// ``` pub async fn recv(&mut self) -> Option { use std::future::poll_fn; @@ -200,43 +200,43 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let mut buffer: Vec<&str> = Vec::with_capacity(2); - /// let limit = 2; - /// let (tx, mut rx) = mpsc::unbounded_channel(); - /// let tx2 = tx.clone(); - /// tx2.send("first").unwrap(); - /// tx2.send("second").unwrap(); - /// tx2.send("third").unwrap(); - /// - /// // Call `recv_many` to receive up to `limit` (2) values. - /// assert_eq!(2, rx.recv_many(&mut buffer, limit).await); - /// assert_eq!(vec!["first", "second"], buffer); - /// - /// // If the buffer is full, the next call to `recv_many` - /// // reserves additional capacity. - /// assert_eq!(1, rx.recv_many(&mut buffer, limit).await); - /// - /// tokio::spawn(async move { - /// tx.send("fourth").unwrap(); - /// }); - /// - /// // 'tx' is dropped, but `recv_many` - /// // is guaranteed not to return 0 as the channel - /// // is not yet closed. - /// assert_eq!(1, rx.recv_many(&mut buffer, limit).await); - /// assert_eq!(vec!["first", "second", "third", "fourth"], buffer); - /// - /// // Once the last sender is dropped, the channel is - /// // closed and `recv_many` returns 0, capacity unchanged. - /// drop(tx2); - /// assert_eq!(0, rx.recv_many(&mut buffer, limit).await); - /// assert_eq!(vec!["first", "second", "third", "fourth"], buffer); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut buffer: Vec<&str> = Vec::with_capacity(2); + /// let limit = 2; + /// let (tx, mut rx) = mpsc::unbounded_channel(); + /// let tx2 = tx.clone(); + /// tx2.send("first").unwrap(); + /// tx2.send("second").unwrap(); + /// tx2.send("third").unwrap(); + /// + /// // Call `recv_many` to receive up to `limit` (2) values. + /// assert_eq!(2, rx.recv_many(&mut buffer, limit).await); + /// assert_eq!(vec!["first", "second"], buffer); + /// + /// // If the buffer is full, the next call to `recv_many` + /// // reserves additional capacity. + /// assert_eq!(1, rx.recv_many(&mut buffer, limit).await); + /// + /// tokio::spawn(async move { + /// tx.send("fourth").unwrap(); + /// }); + /// + /// // 'tx' is dropped, but `recv_many` + /// // is guaranteed not to return 0 as the channel + /// // is not yet closed. + /// assert_eq!(1, rx.recv_many(&mut buffer, limit).await); + /// assert_eq!(vec!["first", "second", "third", "fourth"], buffer); + /// + /// // Once the last sender is dropped, the channel is + /// // closed and `recv_many` returns 0, capacity unchanged. + /// drop(tx2); + /// assert_eq!(0, rx.recv_many(&mut buffer, limit).await); + /// assert_eq!(vec!["first", "second", "third", "fourth"], buffer); + /// # } /// ``` pub async fn recv_many(&mut self, buffer: &mut Vec, limit: usize) -> usize { use std::future::poll_fn; @@ -262,26 +262,26 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// use tokio::sync::mpsc::error::TryRecvError; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::unbounded_channel(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::unbounded_channel(); /// - /// tx.send("hello").unwrap(); + /// tx.send("hello").unwrap(); /// - /// assert_eq!(Ok("hello"), rx.try_recv()); - /// assert_eq!(Err(TryRecvError::Empty), rx.try_recv()); + /// assert_eq!(Ok("hello"), rx.try_recv()); + /// assert_eq!(Err(TryRecvError::Empty), rx.try_recv()); /// - /// tx.send("hello").unwrap(); - /// // Drop the last sender, closing the channel. - /// drop(tx); + /// tx.send("hello").unwrap(); + /// // Drop the last sender, closing the channel. + /// drop(tx); /// - /// assert_eq!(Ok("hello"), rx.try_recv()); - /// assert_eq!(Err(TryRecvError::Disconnected), rx.try_recv()); - /// } + /// assert_eq!(Ok("hello"), rx.try_recv()); + /// assert_eq!(Err(TryRecvError::Disconnected), rx.try_recv()); + /// # } /// ``` pub fn try_recv(&mut self) -> Result { self.chan.try_recv() @@ -296,21 +296,21 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ```ignore-wasm + /// ```should_panic /// use std::thread; /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = mpsc::unbounded_channel::(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = mpsc::unbounded_channel::(); /// - /// let sync_code = thread::spawn(move || { - /// assert_eq!(Some(10), rx.blocking_recv()); - /// }); + /// let sync_code = thread::spawn(move || { + /// assert_eq!(Some(10), rx.blocking_recv()); + /// }); /// - /// let _ = tx.send(10); - /// sync_code.join().unwrap(); - /// } + /// let _ = tx.send(10); + /// sync_code.join().unwrap(); + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] @@ -349,18 +349,18 @@ impl UnboundedReceiver { /// [`UnboundedReceiver::close`]: crate::sync::mpsc::UnboundedReceiver::close /// /// # Examples - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (_tx, mut rx) = mpsc::unbounded_channel::<()>(); - /// assert!(!rx.is_closed()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (_tx, mut rx) = mpsc::unbounded_channel::<()>(); + /// assert!(!rx.is_closed()); /// - /// rx.close(); + /// rx.close(); /// - /// assert!(rx.is_closed()); - /// } + /// assert!(rx.is_closed()); + /// # } /// ``` pub fn is_closed(&self) -> bool { self.chan.is_closed() @@ -371,17 +371,17 @@ impl UnboundedReceiver { /// This method returns `true` if the channel has no messages. /// /// # Examples - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = mpsc::unbounded_channel(); - /// assert!(rx.is_empty()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = mpsc::unbounded_channel(); + /// assert!(rx.is_empty()); /// - /// tx.send(0).unwrap(); - /// assert!(!rx.is_empty()); - /// } + /// tx.send(0).unwrap(); + /// assert!(!rx.is_empty()); + /// # } /// /// ``` pub fn is_empty(&self) -> bool { @@ -391,17 +391,17 @@ impl UnboundedReceiver { /// Returns the number of messages in the channel. /// /// # Examples - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = mpsc::unbounded_channel(); - /// assert_eq!(0, rx.len()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = mpsc::unbounded_channel(); + /// assert_eq!(0, rx.len()); /// - /// tx.send(0).unwrap(); - /// assert_eq!(1, rx.len()); - /// } + /// tx.send(0).unwrap(); + /// assert_eq!(1, rx.len()); + /// # } /// ``` pub fn len(&self) -> usize { self.chan.len() @@ -480,25 +480,25 @@ impl UnboundedReceiver { /// } /// } /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = mpsc::unbounded_channel::(); - /// let mut buffer = Vec::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = mpsc::unbounded_channel::(); + /// let mut buffer = Vec::new(); /// - /// let my_receiver_future = MyReceiverFuture { - /// receiver: rx, - /// buffer: &mut buffer, - /// limit: 3, - /// }; - /// - /// for i in 0..10 { - /// tx.send(i).expect("Unable to send integer"); - /// } + /// let my_receiver_future = MyReceiverFuture { + /// receiver: rx, + /// buffer: &mut buffer, + /// limit: 3, + /// }; /// - /// let count = my_receiver_future.await; - /// assert_eq!(count, 3); - /// assert_eq!(buffer, vec![0,1,2]) + /// for i in 0..10 { + /// tx.send(i).expect("Unable to send integer"); /// } + /// + /// let count = my_receiver_future.await; + /// assert_eq!(count, 3); + /// assert_eq!(buffer, vec![0,1,2]) + /// # } /// ``` pub fn poll_recv_many( &mut self, @@ -589,29 +589,29 @@ impl UnboundedSender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::mpsc; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx1, rx) = mpsc::unbounded_channel::<()>(); - /// let tx2 = tx1.clone(); - /// let tx3 = tx1.clone(); - /// let tx4 = tx1.clone(); - /// let tx5 = tx1.clone(); - /// tokio::spawn(async move { - /// drop(rx); - /// }); - /// - /// futures::join!( - /// tx1.closed(), - /// tx2.closed(), - /// tx3.closed(), - /// tx4.closed(), - /// tx5.closed() - /// ); - //// println!("Receiver dropped"); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx1, rx) = mpsc::unbounded_channel::<()>(); + /// let tx2 = tx1.clone(); + /// let tx3 = tx1.clone(); + /// let tx4 = tx1.clone(); + /// let tx5 = tx1.clone(); + /// tokio::spawn(async move { + /// drop(rx); + /// }); + /// + /// futures::join!( + /// tx1.closed(), + /// tx2.closed(), + /// tx3.closed(), + /// tx4.closed(), + /// tx5.closed() + /// ); + /// println!("Receiver dropped"); + /// # } /// ``` pub async fn closed(&self) { self.chan.closed().await; diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index b892f597d65..a38f85db93f 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -55,52 +55,52 @@ use std::{fmt, mem, ptr}; /// /// # Examples: /// -/// ```rust,no_run,ignore-wasm +/// ```rust,no_run /// use tokio::sync::Mutex; /// use std::sync::Arc; /// -/// #[tokio::main] -/// async fn main() { -/// let data1 = Arc::new(Mutex::new(0)); -/// let data2 = Arc::clone(&data1); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let data1 = Arc::new(Mutex::new(0)); +/// let data2 = Arc::clone(&data1); /// -/// tokio::spawn(async move { -/// let mut lock = data2.lock().await; -/// *lock += 1; -/// }); -/// -/// let mut lock = data1.lock().await; +/// tokio::spawn(async move { +/// let mut lock = data2.lock().await; /// *lock += 1; -/// } +/// }); +/// +/// let mut lock = data1.lock().await; +/// *lock += 1; +/// # } /// ``` /// /// -/// ```rust,no_run,ignore-wasm +/// ```rust,no_run /// use tokio::sync::Mutex; /// use std::sync::Arc; /// -/// #[tokio::main] -/// async fn main() { -/// let count = Arc::new(Mutex::new(0)); -/// -/// for i in 0..5 { -/// let my_count = Arc::clone(&count); -/// tokio::spawn(async move { -/// for j in 0..10 { -/// let mut lock = my_count.lock().await; -/// *lock += 1; -/// println!("{} {} {}", i, j, lock); -/// } -/// }); -/// } +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let count = Arc::new(Mutex::new(0)); /// -/// loop { -/// if *count.lock().await >= 50 { -/// break; +/// for i in 0..5 { +/// let my_count = Arc::clone(&count); +/// tokio::spawn(async move { +/// for j in 0..10 { +/// let mut lock = my_count.lock().await; +/// *lock += 1; +/// println!("{} {} {}", i, j, lock); /// } +/// }); +/// } +/// +/// loop { +/// if *count.lock().await >= 50 { +/// break; /// } -/// println!("Count hit 50."); /// } +/// println!("Count hit 50."); +/// # } /// ``` /// There are a few things of note here to pay attention to in this example. /// 1. The mutex is wrapped in an [`Arc`] to allow it to be shared across @@ -420,16 +420,16 @@ impl Mutex { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::Mutex; /// - /// #[tokio::main] - /// async fn main() { - /// let mutex = Mutex::new(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mutex = Mutex::new(1); /// - /// let mut n = mutex.lock().await; - /// *n = 2; - /// } + /// let mut n = mutex.lock().await; + /// *n = 2; + /// # } /// ``` pub async fn lock(&self) -> MutexGuard<'_, T> { let acquire_fut = async { @@ -597,17 +597,17 @@ impl Mutex { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::Mutex; /// use std::sync::Arc; /// - /// #[tokio::main] - /// async fn main() { - /// let mutex = Arc::new(Mutex::new(1)); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mutex = Arc::new(Mutex::new(1)); /// - /// let mut n = mutex.clone().lock_owned().await; - /// *n = 2; - /// } + /// let mut n = mutex.clone().lock_owned().await; + /// *n = 2; + /// # } /// ``` /// /// [`Arc`]: std::sync::Arc @@ -772,16 +772,16 @@ impl Mutex { /// Consumes the mutex, returning the underlying data. /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::Mutex; /// - /// #[tokio::main] - /// async fn main() { - /// let mutex = Mutex::new(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mutex = Mutex::new(1); /// - /// let n = mutex.into_inner(); - /// assert_eq!(n, 1); - /// } + /// let n = mutex.into_inner(); + /// assert_eq!(n, 1); + /// # } /// ``` pub fn into_inner(self) -> T where @@ -843,13 +843,13 @@ impl<'a, T: ?Sized> MutexGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{Mutex, MutexGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let foo = Mutex::new(Foo(1)); /// @@ -891,13 +891,13 @@ impl<'a, T: ?Sized> MutexGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{Mutex, MutexGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let foo = Mutex::new(Foo(1)); /// @@ -935,7 +935,7 @@ impl<'a, T: ?Sized> MutexGuard<'a, T> { /// Returns a reference to the original `Mutex`. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{Mutex, MutexGuard}; /// /// async fn unlock_and_relock<'l>(guard: MutexGuard<'l, u32>) -> MutexGuard<'l, u32> { @@ -947,7 +947,7 @@ impl<'a, T: ?Sized> MutexGuard<'a, T> { /// guard /// } /// # - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// # let mutex = Mutex::new(0u32); /// # let guard = mutex.lock().await; @@ -1024,14 +1024,14 @@ impl OwnedMutexGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{Mutex, OwnedMutexGuard}; /// use std::sync::Arc; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let foo = Arc::new(Mutex::new(Foo(1))); /// @@ -1072,14 +1072,14 @@ impl OwnedMutexGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{Mutex, OwnedMutexGuard}; /// use std::sync::Arc; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let foo = Arc::new(Mutex::new(Foo(1))); /// @@ -1116,7 +1116,7 @@ impl OwnedMutexGuard { /// Returns a reference to the original `Arc`. /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{Mutex, OwnedMutexGuard}; /// @@ -1129,7 +1129,7 @@ impl OwnedMutexGuard { /// guard /// } /// # - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// # let mutex = Arc::new(Mutex::new(0u32)); /// # let guard = mutex.lock_owned().await; diff --git a/tokio/src/sync/notify.rs b/tokio/src/sync/notify.rs index 10120275140..5a848040802 100644 --- a/tokio/src/sync/notify.rs +++ b/tokio/src/sync/notify.rs @@ -52,26 +52,26 @@ type GuardedWaitList = GuardedLinkedList:: /// /// Basic usage. /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::Notify; /// use std::sync::Arc; /// -/// #[tokio::main] -/// async fn main() { -/// let notify = Arc::new(Notify::new()); -/// let notify2 = notify.clone(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let notify = Arc::new(Notify::new()); +/// let notify2 = notify.clone(); /// -/// let handle = tokio::spawn(async move { -/// notify2.notified().await; -/// println!("received notification"); -/// }); +/// let handle = tokio::spawn(async move { +/// notify2.notified().await; +/// println!("received notification"); +/// }); /// -/// println!("sending notification"); -/// notify.notify_one(); +/// println!("sending notification"); +/// notify.notify_one(); /// -/// // Wait for task to receive notification. -/// handle.await.unwrap(); -/// } +/// // Wait for task to receive notification. +/// handle.await.unwrap(); +/// # } /// ``` /// /// Unbound multi-producer single-consumer (mpsc) channel. @@ -544,23 +544,23 @@ impl Notify { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::Notify; /// use std::sync::Arc; /// - /// #[tokio::main] - /// async fn main() { - /// let notify = Arc::new(Notify::new()); - /// let notify2 = notify.clone(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let notify = Arc::new(Notify::new()); + /// let notify2 = notify.clone(); /// - /// tokio::spawn(async move { - /// notify2.notified().await; - /// println!("received notification"); - /// }); + /// tokio::spawn(async move { + /// notify2.notified().await; + /// println!("received notification"); + /// }); /// - /// println!("sending notification"); - /// notify.notify_one(); - /// } + /// println!("sending notification"); + /// notify.notify_one(); + /// # } /// ``` pub fn notified(&self) -> Notified<'_> { // we load the number of times notify_waiters @@ -590,25 +590,25 @@ impl Notify { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::Notify; /// - /// #[tokio::main] - /// async fn main() { - /// let notify = Arc::new(Notify::new()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let notify = Arc::new(Notify::new()); /// - /// for _ in 0..10 { - /// let notified = notify.clone().notified_owned(); - /// tokio::spawn(async move { - /// notified.await; - /// println!("received notification"); - /// }); - /// } - /// - /// println!("sending notification"); - /// notify.notify_waiters(); + /// for _ in 0..10 { + /// let notified = notify.clone().notified_owned(); + /// tokio::spawn(async move { + /// notified.await; + /// println!("received notification"); + /// }); /// } + /// + /// println!("sending notification"); + /// notify.notify_waiters(); + /// # } /// ``` pub fn notified_owned(self: Arc) -> OwnedNotified { // we load the number of times notify_waiters @@ -637,23 +637,23 @@ impl Notify { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::Notify; /// use std::sync::Arc; /// - /// #[tokio::main] - /// async fn main() { - /// let notify = Arc::new(Notify::new()); - /// let notify2 = notify.clone(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let notify = Arc::new(Notify::new()); + /// let notify2 = notify.clone(); /// - /// tokio::spawn(async move { - /// notify2.notified().await; - /// println!("received notification"); - /// }); + /// tokio::spawn(async move { + /// notify2.notified().await; + /// println!("received notification"); + /// }); /// - /// println!("sending notification"); - /// notify.notify_one(); - /// } + /// println!("sending notification"); + /// notify.notify_one(); + /// # } /// ``` // Alias for old name in 0.x #[cfg_attr(docsrs, doc(alias = "notify"))] @@ -718,27 +718,27 @@ impl Notify { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::Notify; /// use std::sync::Arc; /// - /// #[tokio::main] - /// async fn main() { - /// let notify = Arc::new(Notify::new()); - /// let notify2 = notify.clone(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let notify = Arc::new(Notify::new()); + /// let notify2 = notify.clone(); /// - /// let notified1 = notify.notified(); - /// let notified2 = notify.notified(); + /// let notified1 = notify.notified(); + /// let notified2 = notify.notified(); /// - /// let handle = tokio::spawn(async move { - /// println!("sending notifications"); - /// notify2.notify_waiters(); - /// }); + /// let handle = tokio::spawn(async move { + /// println!("sending notifications"); + /// notify2.notify_waiters(); + /// }); /// - /// notified1.await; - /// notified2.await; - /// println!("received notifications"); - /// } + /// notified1.await; + /// notified2.await; + /// println!("received notifications"); + /// # } /// ``` pub fn notify_waiters(&self) { let mut waiters = self.waiters.lock(); diff --git a/tokio/src/sync/once_cell.rs b/tokio/src/sync/once_cell.rs index 8d5f48ad83b..92194a5404e 100644 --- a/tokio/src/sync/once_cell.rs +++ b/tokio/src/sync/once_cell.rs @@ -32,7 +32,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::OnceCell; /// /// async fn some_computation() -> u32 { @@ -41,16 +41,16 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// /// static ONCE: OnceCell = OnceCell::const_new(); /// -/// #[tokio::main] -/// async fn main() { -/// let result = ONCE.get_or_init(some_computation).await; -/// assert_eq!(*result, 2); -/// } +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let result = ONCE.get_or_init(some_computation).await; +/// assert_eq!(*result, 2); +/// # } /// ``` /// /// It is often useful to write a wrapper method for accessing the value. /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::OnceCell; /// /// static ONCE: OnceCell = OnceCell::const_new(); @@ -61,11 +61,11 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// }).await /// } /// -/// #[tokio::main] -/// async fn main() { -/// let result = get_global_integer().await; -/// assert_eq!(*result, 2); -/// } +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let result = get_global_integer().await; +/// assert_eq!(*result, 2); +/// # } /// ``` pub struct OnceCell { value_set: AtomicBool, @@ -144,7 +144,7 @@ impl OnceCell { /// /// # Example /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::OnceCell; /// /// static ONCE: OnceCell = OnceCell::const_new(); @@ -155,11 +155,11 @@ impl OnceCell { /// }).await /// } /// - /// #[tokio::main] - /// async fn main() { - /// let result = get_global_integer().await; - /// assert_eq!(*result, 2); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let result = get_global_integer().await; + /// assert_eq!(*result, 2); + /// # } /// ``` /// /// [`tokio-console`]: https://github.com/tokio-rs/console @@ -199,7 +199,7 @@ impl OnceCell { /// visible in [`tokio-console`]. Instead, [`OnceCell::new_with`] should be /// used to create an instrumented object if that is needed. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::OnceCell; /// /// static ONCE: OnceCell = OnceCell::const_new_with(1); @@ -210,11 +210,11 @@ impl OnceCell { /// }).await /// } /// - /// #[tokio::main] - /// async fn main() { - /// let result = get_global_integer().await; - /// assert_eq!(*result, 1); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let result = get_global_integer().await; + /// assert_eq!(*result, 1); + /// # } /// ``` /// /// [`tokio-console`]: https://github.com/tokio-rs/console diff --git a/tokio/src/sync/oneshot.rs b/tokio/src/sync/oneshot.rs index f87a295fa8d..eab9052c960 100644 --- a/tokio/src/sync/oneshot.rs +++ b/tokio/src/sync/oneshot.rs @@ -18,84 +18,84 @@ //! //! # Examples //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::oneshot; //! -//! #[tokio::main] -//! async fn main() { -//! let (tx, rx) = oneshot::channel(); -//! -//! tokio::spawn(async move { -//! if let Err(_) = tx.send(3) { -//! println!("the receiver dropped"); -//! } -//! }); +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let (tx, rx) = oneshot::channel(); //! -//! match rx.await { -//! Ok(v) => println!("got = {:?}", v), -//! Err(_) => println!("the sender dropped"), +//! tokio::spawn(async move { +//! if let Err(_) = tx.send(3) { +//! println!("the receiver dropped"); //! } +//! }); +//! +//! match rx.await { +//! Ok(v) => println!("got = {:?}", v), +//! Err(_) => println!("the sender dropped"), //! } +//! # } //! ``` //! //! If the sender is dropped without sending, the receiver will fail with //! [`error::RecvError`]: //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::oneshot; //! -//! #[tokio::main] -//! async fn main() { -//! let (tx, rx) = oneshot::channel::(); +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let (tx, rx) = oneshot::channel::(); //! -//! tokio::spawn(async move { -//! drop(tx); -//! }); +//! tokio::spawn(async move { +//! drop(tx); +//! }); //! -//! match rx.await { -//! Ok(_) => panic!("This doesn't happen"), -//! Err(_) => println!("the sender dropped"), -//! } +//! match rx.await { +//! Ok(_) => panic!("This doesn't happen"), +//! Err(_) => println!("the sender dropped"), //! } +//! # } //! ``` //! //! To use a `oneshot` channel in a `tokio::select!` loop, add `&mut` in front of //! the channel. //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::oneshot; //! use tokio::time::{interval, sleep, Duration}; //! -//! #[tokio::main] +//! # #[tokio::main(flavor = "current_thread")] //! # async fn _doc() {} //! # #[tokio::main(flavor = "current_thread", start_paused = true)] -//! async fn main() { -//! let (send, mut recv) = oneshot::channel(); -//! let mut interval = interval(Duration::from_millis(100)); +//! # async fn main() { +//! let (send, mut recv) = oneshot::channel(); +//! let mut interval = interval(Duration::from_millis(100)); //! -//! # let handle = -//! tokio::spawn(async move { -//! sleep(Duration::from_secs(1)).await; -//! send.send("shut down").unwrap(); -//! }); +//! # let handle = +//! tokio::spawn(async move { +//! sleep(Duration::from_secs(1)).await; +//! send.send("shut down").unwrap(); +//! }); //! -//! loop { -//! tokio::select! { -//! _ = interval.tick() => println!("Another 100ms"), -//! msg = &mut recv => { -//! println!("Got message: {}", msg.unwrap()); -//! break; -//! } +//! loop { +//! tokio::select! { +//! _ = interval.tick() => println!("Another 100ms"), +//! msg = &mut recv => { +//! println!("Got message: {}", msg.unwrap()); +//! break; //! } //! } -//! # handle.await.unwrap(); //! } +//! # handle.await.unwrap(); +//! # } //! ``` //! //! To use a `Sender` from a destructor, put it in an [`Option`] and call //! [`Option::take`]. //! -//! ```ignore-wasm +//! ``` //! use tokio::sync::oneshot; //! //! struct SendOnDrop { @@ -110,17 +110,17 @@ //! } //! } //! -//! #[tokio::main] +//! # #[tokio::main(flavor = "current_thread")] //! # async fn _doc() {} //! # #[tokio::main(flavor = "current_thread")] -//! async fn main() { -//! let (send, recv) = oneshot::channel(); +//! # async fn main() { +//! let (send, recv) = oneshot::channel(); //! -//! let send_on_drop = SendOnDrop { sender: Some(send) }; -//! drop(send_on_drop); +//! let send_on_drop = SendOnDrop { sender: Some(send) }; +//! drop(send_on_drop); //! -//! assert_eq!(recv.await, Ok("I got dropped!")); -//! } +//! assert_eq!(recv.await, Ok("I got dropped!")); +//! # } //! ``` use crate::loom::cell::UnsafeCell; @@ -144,51 +144,51 @@ use std::task::{ready, Context, Poll, Waker}; /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::oneshot; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, rx) = oneshot::channel(); -/// -/// tokio::spawn(async move { -/// if let Err(_) = tx.send(3) { -/// println!("the receiver dropped"); -/// } -/// }); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, rx) = oneshot::channel(); /// -/// match rx.await { -/// Ok(v) => println!("got = {:?}", v), -/// Err(_) => println!("the sender dropped"), +/// tokio::spawn(async move { +/// if let Err(_) = tx.send(3) { +/// println!("the receiver dropped"); /// } +/// }); +/// +/// match rx.await { +/// Ok(v) => println!("got = {:?}", v), +/// Err(_) => println!("the sender dropped"), /// } +/// # } /// ``` /// /// If the sender is dropped without sending, the receiver will fail with /// [`error::RecvError`]: /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::oneshot; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, rx) = oneshot::channel::(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, rx) = oneshot::channel::(); /// -/// tokio::spawn(async move { -/// drop(tx); -/// }); +/// tokio::spawn(async move { +/// drop(tx); +/// }); /// -/// match rx.await { -/// Ok(_) => panic!("This doesn't happen"), -/// Err(_) => println!("the sender dropped"), -/// } +/// match rx.await { +/// Ok(_) => panic!("This doesn't happen"), +/// Err(_) => println!("the sender dropped"), /// } +/// # } /// ``` /// /// To use a `Sender` from a destructor, put it in an [`Option`] and call /// [`Option::take`]. /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::oneshot; /// /// struct SendOnDrop { @@ -203,17 +203,17 @@ use std::task::{ready, Context, Poll, Waker}; /// } /// } /// -/// #[tokio::main] +/// # #[tokio::main(flavor = "current_thread")] /// # async fn _doc() {} /// # #[tokio::main(flavor = "current_thread")] -/// async fn main() { -/// let (send, recv) = oneshot::channel(); +/// # async fn main() { +/// let (send, recv) = oneshot::channel(); /// -/// let send_on_drop = SendOnDrop { sender: Some(send) }; -/// drop(send_on_drop); +/// let send_on_drop = SendOnDrop { sender: Some(send) }; +/// drop(send_on_drop); /// -/// assert_eq!(recv.await, Ok("I got dropped!")); -/// } +/// assert_eq!(recv.await, Ok("I got dropped!")); +/// # } /// ``` /// /// [`Option`]: std::option::Option @@ -245,78 +245,78 @@ pub struct Sender { /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::oneshot; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, rx) = oneshot::channel(); -/// -/// tokio::spawn(async move { -/// if let Err(_) = tx.send(3) { -/// println!("the receiver dropped"); -/// } -/// }); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, rx) = oneshot::channel(); /// -/// match rx.await { -/// Ok(v) => println!("got = {:?}", v), -/// Err(_) => println!("the sender dropped"), +/// tokio::spawn(async move { +/// if let Err(_) = tx.send(3) { +/// println!("the receiver dropped"); /// } +/// }); +/// +/// match rx.await { +/// Ok(v) => println!("got = {:?}", v), +/// Err(_) => println!("the sender dropped"), /// } +/// # } /// ``` /// /// If the sender is dropped without sending, the receiver will fail with /// [`error::RecvError`]: /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::oneshot; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, rx) = oneshot::channel::(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, rx) = oneshot::channel::(); /// -/// tokio::spawn(async move { -/// drop(tx); -/// }); +/// tokio::spawn(async move { +/// drop(tx); +/// }); /// -/// match rx.await { -/// Ok(_) => panic!("This doesn't happen"), -/// Err(_) => println!("the sender dropped"), -/// } +/// match rx.await { +/// Ok(_) => panic!("This doesn't happen"), +/// Err(_) => println!("the sender dropped"), /// } +/// # } /// ``` /// /// To use a `Receiver` in a `tokio::select!` loop, add `&mut` in front of the /// channel. /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::oneshot; /// use tokio::time::{interval, sleep, Duration}; /// -/// #[tokio::main] +/// # #[tokio::main(flavor = "current_thread")] /// # async fn _doc() {} /// # #[tokio::main(flavor = "current_thread", start_paused = true)] -/// async fn main() { -/// let (send, mut recv) = oneshot::channel(); -/// let mut interval = interval(Duration::from_millis(100)); +/// # async fn main() { +/// let (send, mut recv) = oneshot::channel(); +/// let mut interval = interval(Duration::from_millis(100)); /// -/// # let handle = -/// tokio::spawn(async move { -/// sleep(Duration::from_secs(1)).await; -/// send.send("shut down").unwrap(); -/// }); +/// # let handle = +/// tokio::spawn(async move { +/// sleep(Duration::from_secs(1)).await; +/// send.send("shut down").unwrap(); +/// }); /// -/// loop { -/// tokio::select! { -/// _ = interval.tick() => println!("Another 100ms"), -/// msg = &mut recv => { -/// println!("Got message: {}", msg.unwrap()); -/// break; -/// } +/// loop { +/// tokio::select! { +/// _ = interval.tick() => println!("Another 100ms"), +/// msg = &mut recv => { +/// println!("Got message: {}", msg.unwrap()); +/// break; /// } /// } -/// # handle.await.unwrap(); /// } +/// # handle.await.unwrap(); +/// # } /// ``` #[derive(Debug)] pub struct Receiver { @@ -447,24 +447,24 @@ struct State(usize); /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::oneshot; /// -/// #[tokio::main] -/// async fn main() { -/// let (tx, rx) = oneshot::channel(); -/// -/// tokio::spawn(async move { -/// if let Err(_) = tx.send(3) { -/// println!("the receiver dropped"); -/// } -/// }); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let (tx, rx) = oneshot::channel(); /// -/// match rx.await { -/// Ok(v) => println!("got = {:?}", v), -/// Err(_) => println!("the sender dropped"), +/// tokio::spawn(async move { +/// if let Err(_) = tx.send(3) { +/// println!("the receiver dropped"); /// } +/// }); +/// +/// match rx.await { +/// Ok(v) => println!("got = {:?}", v), +/// Err(_) => println!("the sender dropped"), /// } +/// # } /// ``` #[track_caller] pub fn channel() -> (Sender, Receiver) { @@ -573,24 +573,24 @@ impl Sender { /// /// Send a value to another task /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = oneshot::channel(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = oneshot::channel(); /// - /// tokio::spawn(async move { - /// if let Err(_) = tx.send(3) { - /// println!("the receiver dropped"); - /// } - /// }); - /// - /// match rx.await { - /// Ok(v) => println!("got = {:?}", v), - /// Err(_) => println!("the sender dropped"), + /// tokio::spawn(async move { + /// if let Err(_) = tx.send(3) { + /// println!("the receiver dropped"); /// } + /// }); + /// + /// match rx.await { + /// Ok(v) => println!("got = {:?}", v), + /// Err(_) => println!("the sender dropped"), /// } + /// # } /// ``` pub fn send(mut self, t: T) -> Result<(), T> { let inner = self.inner.take().unwrap(); @@ -649,25 +649,25 @@ impl Sender { /// /// Basic usage /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// - /// #[tokio::main] - /// async fn main() { - /// let (mut tx, rx) = oneshot::channel::<()>(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (mut tx, rx) = oneshot::channel::<()>(); /// - /// tokio::spawn(async move { - /// drop(rx); - /// }); + /// tokio::spawn(async move { + /// drop(rx); + /// }); /// - /// tx.closed().await; - /// println!("the receiver dropped"); - /// } + /// tx.closed().await; + /// println!("the receiver dropped"); + /// # } /// ``` /// /// Paired with select /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// use tokio::time::{self, Duration}; /// @@ -676,26 +676,26 @@ impl Sender { /// # "hello".to_string() /// } /// - /// #[tokio::main] - /// async fn main() { - /// let (mut tx, rx) = oneshot::channel(); - /// - /// tokio::spawn(async move { - /// tokio::select! { - /// _ = tx.closed() => { - /// // The receiver dropped, no need to do any further work - /// } - /// value = compute() => { - /// // The send can fail if the channel was closed at the exact same - /// // time as when compute() finished, so just ignore the failure. - /// let _ = tx.send(value); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (mut tx, rx) = oneshot::channel(); + /// + /// tokio::spawn(async move { + /// tokio::select! { + /// _ = tx.closed() => { + /// // The receiver dropped, no need to do any further work /// } - /// }); + /// value = compute() => { + /// // The send can fail if the channel was closed at the exact same + /// // time as when compute() finished, so just ignore the failure. + /// let _ = tx.send(value); + /// } + /// } + /// }); /// - /// // Wait for up to 10 seconds - /// let _ = time::timeout(Duration::from_secs(10), rx).await; - /// } + /// // Wait for up to 10 seconds + /// let _ = time::timeout(Duration::from_secs(10), rx).await; + /// # } /// ``` pub async fn closed(&mut self) { use std::future::poll_fn; @@ -728,20 +728,20 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = oneshot::channel(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = oneshot::channel(); /// - /// assert!(!tx.is_closed()); + /// assert!(!tx.is_closed()); /// - /// drop(rx); + /// drop(rx); /// - /// assert!(tx.is_closed()); - /// assert!(tx.send("never received").is_err()); - /// } + /// assert!(tx.is_closed()); + /// assert!(tx.send("never received").is_err()); + /// # } /// ``` pub fn is_closed(&self) -> bool { let inner = self.inner.as_ref().unwrap(); @@ -772,23 +772,23 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// /// use std::future::poll_fn; /// - /// #[tokio::main] - /// async fn main() { - /// let (mut tx, mut rx) = oneshot::channel::<()>(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (mut tx, mut rx) = oneshot::channel::<()>(); /// - /// tokio::spawn(async move { - /// rx.close(); - /// }); + /// tokio::spawn(async move { + /// rx.close(); + /// }); /// - /// poll_fn(|cx| tx.poll_closed(cx)).await; + /// poll_fn(|cx| tx.poll_closed(cx)).await; /// - /// println!("the receiver dropped"); - /// } + /// println!("the receiver dropped"); + /// # } /// ``` pub fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll<()> { ready!(crate::trace::trace_leaf(cx)); @@ -878,44 +878,44 @@ impl Receiver { /// /// Prevent a value from being sent /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// use tokio::sync::oneshot::error::TryRecvError; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = oneshot::channel(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = oneshot::channel(); /// - /// assert!(!tx.is_closed()); + /// assert!(!tx.is_closed()); /// - /// rx.close(); + /// rx.close(); /// - /// assert!(tx.is_closed()); - /// assert!(tx.send("never received").is_err()); + /// assert!(tx.is_closed()); + /// assert!(tx.send("never received").is_err()); /// - /// match rx.try_recv() { - /// Err(TryRecvError::Closed) => {} - /// _ => unreachable!(), - /// } + /// match rx.try_recv() { + /// Err(TryRecvError::Closed) => {} + /// _ => unreachable!(), /// } + /// # } /// ``` /// /// Receive a value sent **before** calling `close` /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = oneshot::channel(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = oneshot::channel(); /// - /// assert!(tx.send("will receive").is_ok()); + /// assert!(tx.send("will receive").is_ok()); /// - /// rx.close(); + /// rx.close(); /// - /// let msg = rx.try_recv().unwrap(); - /// assert_eq!(msg, "will receive"); - /// } + /// let msg = rx.try_recv().unwrap(); + /// assert_eq!(msg, "will receive"); + /// # } /// ``` pub fn close(&mut self) { if let Some(inner) = self.inner.as_ref() { @@ -940,50 +940,50 @@ impl Receiver { /// /// Sending a value and polling it. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// /// use std::task::Poll; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = oneshot::channel(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = oneshot::channel(); /// - /// // A receiver is not terminated when it is initialized. - /// assert!(!rx.is_terminated()); + /// // A receiver is not terminated when it is initialized. + /// assert!(!rx.is_terminated()); /// - /// // A receiver is not terminated it is polled and is still pending. - /// let poll = futures::poll!(&mut rx); - /// assert_eq!(poll, Poll::Pending); - /// assert!(!rx.is_terminated()); + /// // A receiver is not terminated it is polled and is still pending. + /// let poll = futures::poll!(&mut rx); + /// assert_eq!(poll, Poll::Pending); + /// assert!(!rx.is_terminated()); /// - /// // A receiver is not terminated if a value has been sent, but not yet read. - /// tx.send(0).unwrap(); - /// assert!(!rx.is_terminated()); + /// // A receiver is not terminated if a value has been sent, but not yet read. + /// tx.send(0).unwrap(); + /// assert!(!rx.is_terminated()); /// - /// // A receiver *is* terminated after it has been polled and yielded a value. - /// assert_eq!((&mut rx).await, Ok(0)); - /// assert!(rx.is_terminated()); - /// } + /// // A receiver *is* terminated after it has been polled and yielded a value. + /// assert_eq!((&mut rx).await, Ok(0)); + /// assert!(rx.is_terminated()); + /// # } /// ``` /// /// Dropping the sender. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = oneshot::channel::<()>(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = oneshot::channel::<()>(); /// - /// // A receiver is not immediately terminated when the sender is dropped. - /// drop(tx); - /// assert!(!rx.is_terminated()); + /// // A receiver is not immediately terminated when the sender is dropped. + /// drop(tx); + /// assert!(!rx.is_terminated()); /// - /// // A receiver *is* terminated after it has been polled and yielded an error. - /// let _ = (&mut rx).await.unwrap_err(); - /// assert!(rx.is_terminated()); - /// } + /// // A receiver *is* terminated after it has been polled and yielded an error. + /// let _ = (&mut rx).await.unwrap_err(); + /// assert!(rx.is_terminated()); + /// # } /// ``` pub fn is_terminated(&self) -> bool { self.inner.is_none() @@ -1001,56 +1001,56 @@ impl Receiver { /// /// Sending a value. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = oneshot::channel(); - /// assert!(rx.is_empty()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = oneshot::channel(); + /// assert!(rx.is_empty()); /// - /// tx.send(0).unwrap(); - /// assert!(!rx.is_empty()); + /// tx.send(0).unwrap(); + /// assert!(!rx.is_empty()); /// - /// let _ = (&mut rx).await; - /// assert!(rx.is_empty()); - /// } + /// let _ = (&mut rx).await; + /// assert!(rx.is_empty()); + /// # } /// ``` /// /// Dropping the sender. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = oneshot::channel::<()>(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = oneshot::channel::<()>(); /// - /// // A channel is empty if the sender is dropped. - /// drop(tx); - /// assert!(rx.is_empty()); + /// // A channel is empty if the sender is dropped. + /// drop(tx); + /// assert!(rx.is_empty()); /// - /// // A closed channel still yields an error, however. - /// (&mut rx).await.expect_err("should yield an error"); - /// assert!(rx.is_empty()); - /// } + /// // A closed channel still yields an error, however. + /// (&mut rx).await.expect_err("should yield an error"); + /// assert!(rx.is_empty()); + /// # } /// ``` /// /// Terminated channels are empty. /// - /// ```should_panic,ignore-wasm + /// ```should_panic /// use tokio::sync::oneshot; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = oneshot::channel(); - /// tx.send(0).unwrap(); - /// let _ = (&mut rx).await; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = oneshot::channel(); + /// tx.send(0).unwrap(); + /// let _ = (&mut rx).await; /// - /// // NB: an empty channel is not necessarily safe to poll! - /// assert!(rx.is_empty()); - /// let _ = (&mut rx).await; - /// } + /// // NB: an empty channel is not necessarily safe to poll! + /// assert!(rx.is_empty()); + /// let _ = (&mut rx).await; + /// # } /// ``` pub fn is_empty(&self) -> bool { let Some(inner) = self.inner.as_ref() else { @@ -1098,48 +1098,48 @@ impl Receiver { /// /// `try_recv` before a value is sent, then after. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// use tokio::sync::oneshot::error::TryRecvError; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = oneshot::channel(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = oneshot::channel(); /// - /// match rx.try_recv() { - /// // The channel is currently empty - /// Err(TryRecvError::Empty) => {} - /// _ => unreachable!(), - /// } + /// match rx.try_recv() { + /// // The channel is currently empty + /// Err(TryRecvError::Empty) => {} + /// _ => unreachable!(), + /// } /// - /// // Send a value - /// tx.send("hello").unwrap(); + /// // Send a value + /// tx.send("hello").unwrap(); /// - /// match rx.try_recv() { - /// Ok(value) => assert_eq!(value, "hello"), - /// _ => unreachable!(), - /// } + /// match rx.try_recv() { + /// Ok(value) => assert_eq!(value, "hello"), + /// _ => unreachable!(), /// } + /// # } /// ``` /// /// `try_recv` when the sender dropped before sending a value /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::oneshot; /// use tokio::sync::oneshot::error::TryRecvError; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = oneshot::channel::<()>(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = oneshot::channel::<()>(); /// - /// drop(tx); + /// drop(tx); /// - /// match rx.try_recv() { - /// // The channel will never receive a value. - /// Err(TryRecvError::Closed) => {} - /// _ => unreachable!(), - /// } + /// match rx.try_recv() { + /// // The channel will never receive a value. + /// Err(TryRecvError::Closed) => {} + /// _ => unreachable!(), /// } + /// # } /// ``` pub fn try_recv(&mut self) -> Result { let result = if let Some(inner) = self.inner.as_ref() { @@ -1188,21 +1188,21 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ```should_panic /// use std::thread; /// use tokio::sync::oneshot; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = oneshot::channel::(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = oneshot::channel::(); /// - /// let sync_code = thread::spawn(move || { - /// assert_eq!(Ok(10), rx.blocking_recv()); - /// }); + /// let sync_code = thread::spawn(move || { + /// assert_eq!(Ok(10), rx.blocking_recv()); + /// }); /// - /// let _ = tx.send(10); - /// sync_code.join().unwrap(); - /// } + /// let _ = tx.send(10); + /// sync_code.join().unwrap(); + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] diff --git a/tokio/src/sync/rwlock.rs b/tokio/src/sync/rwlock.rs index 7cf765e5f67..69ebf921d78 100644 --- a/tokio/src/sync/rwlock.rs +++ b/tokio/src/sync/rwlock.rs @@ -55,28 +55,28 @@ const MAX_READS: u32 = 10; /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::RwLock; /// -/// #[tokio::main] -/// async fn main() { -/// let lock = RwLock::new(5); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let lock = RwLock::new(5); /// -/// // many reader locks can be held at once -/// { -/// let r1 = lock.read().await; -/// let r2 = lock.read().await; -/// assert_eq!(*r1, 5); -/// assert_eq!(*r2, 5); -/// } // read locks are dropped at this point +/// // many reader locks can be held at once +/// { +/// let r1 = lock.read().await; +/// let r2 = lock.read().await; +/// assert_eq!(*r1, 5); +/// assert_eq!(*r2, 5); +/// } // read locks are dropped at this point /// -/// // only one write lock may be held, however -/// { -/// let mut w = lock.write().await; -/// *w += 1; -/// assert_eq!(*w, 6); -/// } // write lock is dropped here -/// } +/// // only one write lock may be held, however +/// { +/// let mut w = lock.write().await; +/// *w += 1; +/// assert_eq!(*w, 6); +/// } // write lock is dropped here +/// # } /// ``` /// /// [`Mutex`]: struct@super::Mutex @@ -406,27 +406,27 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::RwLock; /// - /// #[tokio::main] - /// async fn main() { - /// let lock = Arc::new(RwLock::new(1)); - /// let c_lock = lock.clone(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let lock = Arc::new(RwLock::new(1)); + /// let c_lock = lock.clone(); /// - /// let n = lock.read().await; - /// assert_eq!(*n, 1); + /// let n = lock.read().await; + /// assert_eq!(*n, 1); /// - /// tokio::spawn(async move { - /// // While main has an active read lock, we acquire one too. - /// let r = c_lock.read().await; - /// assert_eq!(*r, 1); - /// }).await.expect("The spawned task has panicked"); + /// tokio::spawn(async move { + /// // While main has an active read lock, we acquire one too. + /// let r = c_lock.read().await; + /// assert_eq!(*r, 1); + /// }).await.expect("The spawned task has panicked"); /// - /// // Drop the guard after the spawned task finishes. - /// drop(n); - /// } + /// // Drop the guard after the spawned task finishes. + /// drop(n); + /// # } /// ``` pub async fn read(&self) -> RwLockReadGuard<'_, T> { let acquire_fut = async { @@ -488,33 +488,33 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ```should_panic /// use std::sync::Arc; /// use tokio::sync::RwLock; /// - /// #[tokio::main] - /// async fn main() { - /// let rwlock = Arc::new(RwLock::new(1)); - /// let mut write_lock = rwlock.write().await; - /// - /// let blocking_task = tokio::task::spawn_blocking({ - /// let rwlock = Arc::clone(&rwlock); - /// move || { - /// // This shall block until the `write_lock` is released. - /// let read_lock = rwlock.blocking_read(); - /// assert_eq!(*read_lock, 0); - /// } - /// }); - /// - /// *write_lock -= 1; - /// drop(write_lock); // release the lock. - /// - /// // Await the completion of the blocking task. - /// blocking_task.await.unwrap(); - /// - /// // Assert uncontended. - /// assert!(rwlock.try_write().is_ok()); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let rwlock = Arc::new(RwLock::new(1)); + /// let mut write_lock = rwlock.write().await; + /// + /// let blocking_task = tokio::task::spawn_blocking({ + /// let rwlock = Arc::clone(&rwlock); + /// move || { + /// // This shall block until the `write_lock` is released. + /// let read_lock = rwlock.blocking_read(); + /// assert_eq!(*read_lock, 0); + /// } + /// }); + /// + /// *write_lock -= 1; + /// drop(write_lock); // release the lock. + /// + /// // Await the completion of the blocking task. + /// blocking_task.await.unwrap(); + /// + /// // Assert uncontended. + /// assert!(rwlock.try_write().is_ok()); + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] @@ -551,26 +551,26 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::RwLock; /// - /// #[tokio::main] - /// async fn main() { - /// let lock = Arc::new(RwLock::new(1)); - /// let c_lock = lock.clone(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let lock = Arc::new(RwLock::new(1)); + /// let c_lock = lock.clone(); /// - /// let n = lock.read_owned().await; - /// assert_eq!(*n, 1); + /// let n = lock.read_owned().await; + /// assert_eq!(*n, 1); /// - /// tokio::spawn(async move { - /// // While main has an active read lock, we acquire one too. - /// let r = c_lock.read_owned().await; - /// assert_eq!(*r, 1); - /// }).await.expect("The spawned task has panicked"); + /// tokio::spawn(async move { + /// // While main has an active read lock, we acquire one too. + /// let r = c_lock.read_owned().await; + /// assert_eq!(*r, 1); + /// }).await.expect("The spawned task has panicked"); /// - /// // Drop the guard after the spawned task finishes. - /// drop(n); + /// // Drop the guard after the spawned task finishes. + /// drop(n); ///} /// ``` pub async fn read_owned(self: Arc) -> OwnedRwLockReadGuard { @@ -627,27 +627,27 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::RwLock; /// - /// #[tokio::main] - /// async fn main() { - /// let lock = Arc::new(RwLock::new(1)); - /// let c_lock = lock.clone(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let lock = Arc::new(RwLock::new(1)); + /// let c_lock = lock.clone(); /// - /// let v = lock.try_read().unwrap(); - /// assert_eq!(*v, 1); + /// let v = lock.try_read().unwrap(); + /// assert_eq!(*v, 1); /// - /// tokio::spawn(async move { - /// // While main has an active read lock, we acquire one too. - /// let n = c_lock.read().await; - /// assert_eq!(*n, 1); - /// }).await.expect("The spawned task has panicked"); + /// tokio::spawn(async move { + /// // While main has an active read lock, we acquire one too. + /// let n = c_lock.read().await; + /// assert_eq!(*n, 1); + /// }).await.expect("The spawned task has panicked"); /// - /// // Drop the guard when spawned task finishes. - /// drop(v); - /// } + /// // Drop the guard when spawned task finishes. + /// drop(v); + /// # } /// ``` pub fn try_read(&self) -> Result, TryLockError> { match self.s.try_acquire(1) { @@ -692,27 +692,27 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::RwLock; /// - /// #[tokio::main] - /// async fn main() { - /// let lock = Arc::new(RwLock::new(1)); - /// let c_lock = lock.clone(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let lock = Arc::new(RwLock::new(1)); + /// let c_lock = lock.clone(); /// - /// let v = lock.try_read_owned().unwrap(); - /// assert_eq!(*v, 1); + /// let v = lock.try_read_owned().unwrap(); + /// assert_eq!(*v, 1); /// - /// tokio::spawn(async move { - /// // While main has an active read lock, we acquire one too. - /// let n = c_lock.read_owned().await; - /// assert_eq!(*n, 1); - /// }).await.expect("The spawned task has panicked"); + /// tokio::spawn(async move { + /// // While main has an active read lock, we acquire one too. + /// let n = c_lock.read_owned().await; + /// assert_eq!(*n, 1); + /// }).await.expect("The spawned task has panicked"); /// - /// // Drop the guard when spawned task finishes. - /// drop(v); - /// } + /// // Drop the guard when spawned task finishes. + /// drop(v); + /// # } /// ``` pub fn try_read_owned(self: Arc) -> Result, TryLockError> { match self.s.try_acquire(1) { @@ -758,16 +758,16 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::RwLock; /// - /// #[tokio::main] - /// async fn main() { - /// let lock = RwLock::new(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let lock = RwLock::new(1); /// - /// let mut n = lock.write().await; - /// *n = 2; - ///} + /// let mut n = lock.write().await; + /// *n = 2; + /// # } /// ``` pub async fn write(&self) -> RwLockWriteGuard<'_, T> { let acquire_fut = async { @@ -830,35 +830,35 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ```should_panic /// use std::sync::Arc; /// use tokio::{sync::RwLock}; /// - /// #[tokio::main] - /// async fn main() { - /// let rwlock = Arc::new(RwLock::new(1)); - /// let read_lock = rwlock.read().await; - /// - /// let blocking_task = tokio::task::spawn_blocking({ - /// let rwlock = Arc::clone(&rwlock); - /// move || { - /// // This shall block until the `read_lock` is released. - /// let mut write_lock = rwlock.blocking_write(); - /// *write_lock = 2; - /// } - /// }); - /// - /// assert_eq!(*read_lock, 1); - /// // Release the last outstanding read lock. - /// drop(read_lock); - /// - /// // Await the completion of the blocking task. - /// blocking_task.await.unwrap(); - /// - /// // Assert uncontended. - /// let read_lock = rwlock.try_read().unwrap(); - /// assert_eq!(*read_lock, 2); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let rwlock = Arc::new(RwLock::new(1)); + /// let read_lock = rwlock.read().await; + /// + /// let blocking_task = tokio::task::spawn_blocking({ + /// let rwlock = Arc::clone(&rwlock); + /// move || { + /// // This shall block until the `read_lock` is released. + /// let mut write_lock = rwlock.blocking_write(); + /// *write_lock = 2; + /// } + /// }); + /// + /// assert_eq!(*read_lock, 1); + /// // Release the last outstanding read lock. + /// drop(read_lock); + /// + /// // Await the completion of the blocking task. + /// blocking_task.await.unwrap(); + /// + /// // Assert uncontended. + /// let read_lock = rwlock.try_read().unwrap(); + /// assert_eq!(*read_lock, 2); + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] @@ -889,16 +889,16 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::RwLock; /// - /// #[tokio::main] - /// async fn main() { - /// let lock = Arc::new(RwLock::new(1)); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let lock = Arc::new(RwLock::new(1)); /// - /// let mut n = lock.write_owned().await; - /// *n = 2; + /// let mut n = lock.write_owned().await; + /// *n = 2; ///} /// ``` pub async fn write_owned(self: Arc) -> OwnedRwLockWriteGuard { @@ -956,18 +956,18 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::RwLock; /// - /// #[tokio::main] - /// async fn main() { - /// let rw = RwLock::new(1); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let rw = RwLock::new(1); /// - /// let v = rw.read().await; - /// assert_eq!(*v, 1); + /// let v = rw.read().await; + /// assert_eq!(*v, 1); /// - /// assert!(rw.try_write().is_err()); - /// } + /// assert!(rw.try_write().is_err()); + /// # } /// ``` pub fn try_write(&self) -> Result, TryLockError> { match self.s.try_acquire(self.mr as usize) { @@ -1013,19 +1013,19 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::RwLock; /// - /// #[tokio::main] - /// async fn main() { - /// let rw = Arc::new(RwLock::new(1)); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let rw = Arc::new(RwLock::new(1)); /// - /// let v = Arc::clone(&rw).read_owned().await; - /// assert_eq!(*v, 1); + /// let v = Arc::clone(&rw).read_owned().await; + /// assert_eq!(*v, 1); /// - /// assert!(rw.try_write_owned().is_err()); - /// } + /// assert!(rw.try_write_owned().is_err()); + /// # } /// ``` pub fn try_write_owned(self: Arc) -> Result, TryLockError> { match self.s.try_acquire(self.mr as usize) { diff --git a/tokio/src/sync/rwlock/owned_read_guard.rs b/tokio/src/sync/rwlock/owned_read_guard.rs index 7be97908dfe..019f61023a1 100644 --- a/tokio/src/sync/rwlock/owned_read_guard.rs +++ b/tokio/src/sync/rwlock/owned_read_guard.rs @@ -55,14 +55,14 @@ impl OwnedRwLockReadGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockReadGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(Foo(1))); /// @@ -102,14 +102,14 @@ impl OwnedRwLockReadGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockReadGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(Foo(1))); /// @@ -143,14 +143,14 @@ impl OwnedRwLockReadGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockReadGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(Foo(1))); /// diff --git a/tokio/src/sync/rwlock/owned_write_guard.rs b/tokio/src/sync/rwlock/owned_write_guard.rs index 34e20eff62c..7b34561bd7c 100644 --- a/tokio/src/sync/rwlock/owned_write_guard.rs +++ b/tokio/src/sync/rwlock/owned_write_guard.rs @@ -62,14 +62,14 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(Foo(1))); /// @@ -114,14 +114,14 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(Foo(1))); /// @@ -186,14 +186,14 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(Foo(1))); /// @@ -248,14 +248,14 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(Foo(1))); /// @@ -333,11 +333,11 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// # use tokio::sync::RwLock; /// # use std::sync::Arc; /// # - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(1)); /// @@ -395,11 +395,11 @@ impl OwnedRwLockWriteGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(1)); /// diff --git a/tokio/src/sync/rwlock/owned_write_guard_mapped.rs b/tokio/src/sync/rwlock/owned_write_guard_mapped.rs index bcdbfee7f6e..d8de3f8a89b 100644 --- a/tokio/src/sync/rwlock/owned_write_guard_mapped.rs +++ b/tokio/src/sync/rwlock/owned_write_guard_mapped.rs @@ -61,14 +61,14 @@ impl OwnedRwLockMappedWriteGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(Foo(1))); /// @@ -112,14 +112,14 @@ impl OwnedRwLockMappedWriteGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{RwLock, OwnedRwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(Foo(1))); /// @@ -160,7 +160,7 @@ impl OwnedRwLockMappedWriteGuard { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::{ /// RwLock, @@ -168,7 +168,7 @@ impl OwnedRwLockMappedWriteGuard { /// OwnedRwLockMappedWriteGuard, /// }; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(1)); /// diff --git a/tokio/src/sync/rwlock/read_guard.rs b/tokio/src/sync/rwlock/read_guard.rs index fa4b17858f1..a3a5ba82af8 100644 --- a/tokio/src/sync/rwlock/read_guard.rs +++ b/tokio/src/sync/rwlock/read_guard.rs @@ -60,13 +60,13 @@ impl<'a, T: ?Sized> RwLockReadGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{RwLock, RwLockReadGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = RwLock::new(Foo(1)); /// @@ -112,13 +112,13 @@ impl<'a, T: ?Sized> RwLockReadGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{RwLock, RwLockReadGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = RwLock::new(Foo(1)); /// diff --git a/tokio/src/sync/rwlock/write_guard.rs b/tokio/src/sync/rwlock/write_guard.rs index 1af2a6f507b..766b26e00ad 100644 --- a/tokio/src/sync/rwlock/write_guard.rs +++ b/tokio/src/sync/rwlock/write_guard.rs @@ -66,13 +66,13 @@ impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = RwLock::new(Foo(1)); /// @@ -124,13 +124,13 @@ impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = RwLock::new(Foo(1)); /// @@ -199,13 +199,13 @@ impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = RwLock::new(Foo(1)); /// @@ -268,13 +268,13 @@ impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = RwLock::new(Foo(1)); /// @@ -348,11 +348,11 @@ impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// # use tokio::sync::RwLock; /// # use std::sync::Arc; /// # - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = Arc::new(RwLock::new(1)); /// diff --git a/tokio/src/sync/rwlock/write_guard_mapped.rs b/tokio/src/sync/rwlock/write_guard_mapped.rs index 96c35aa447b..dc67f2556ee 100644 --- a/tokio/src/sync/rwlock/write_guard_mapped.rs +++ b/tokio/src/sync/rwlock/write_guard_mapped.rs @@ -63,13 +63,13 @@ impl<'a, T: ?Sized> RwLockMappedWriteGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = RwLock::new(Foo(1)); /// @@ -118,13 +118,13 @@ impl<'a, T: ?Sized> RwLockMappedWriteGuard<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{RwLock, RwLockWriteGuard}; /// /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// struct Foo(u32); /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let lock = RwLock::new(Foo(1)); /// diff --git a/tokio/src/sync/semaphore.rs b/tokio/src/sync/semaphore.rs index 7b8e9d681df..69bb3122733 100644 --- a/tokio/src/sync/semaphore.rs +++ b/tokio/src/sync/semaphore.rs @@ -30,21 +30,21 @@ use std::sync::Arc; /// /// Basic usage: /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::{Semaphore, TryAcquireError}; /// -/// #[tokio::main] -/// async fn main() { -/// let semaphore = Semaphore::new(3); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let semaphore = Semaphore::new(3); /// -/// let a_permit = semaphore.acquire().await.unwrap(); -/// let two_permits = semaphore.acquire_many(2).await.unwrap(); +/// let a_permit = semaphore.acquire().await.unwrap(); +/// let two_permits = semaphore.acquire_many(2).await.unwrap(); /// -/// assert_eq!(semaphore.available_permits(), 0); +/// assert_eq!(semaphore.available_permits(), 0); /// -/// let permit_attempt = semaphore.try_acquire(); -/// assert_eq!(permit_attempt.err(), Some(TryAcquireError::NoPermits)); -/// } +/// let permit_attempt = semaphore.try_acquire(); +/// assert_eq!(permit_attempt.err(), Some(TryAcquireError::NoPermits)); +/// # } /// ``` /// /// ## Limit the number of simultaneously opened files in your program @@ -89,41 +89,41 @@ use std::sync::Arc; /// sent in parallel at any given time. After a task has sent a request, it /// drops the permit to allow other tasks to send requests. /// -/// ```ignore-wasm +/// ``` /// use std::sync::Arc; /// use tokio::sync::Semaphore; /// -/// #[tokio::main] -/// async fn main() { -/// // Define maximum number of parallel requests. -/// let semaphore = Arc::new(Semaphore::new(10)); -/// // Spawn many tasks that will send requests. -/// let mut jhs = Vec::new(); -/// for task_id in 0..100 { -/// let semaphore = semaphore.clone(); -/// let jh = tokio::spawn(async move { -/// // Acquire permit before sending request. -/// let _permit = semaphore.acquire().await.unwrap(); -/// // Send the request. -/// let response = send_request(task_id).await; -/// // Drop the permit after the request has been sent. -/// drop(_permit); -/// // Handle response. -/// // ... -/// -/// response -/// }); -/// jhs.push(jh); -/// } -/// // Collect responses from tasks. -/// let mut responses = Vec::new(); -/// for jh in jhs { -/// let response = jh.await.unwrap(); -/// responses.push(response); -/// } -/// // Process responses. -/// // ... +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// // Define maximum number of parallel requests. +/// let semaphore = Arc::new(Semaphore::new(5)); +/// // Spawn many tasks that will send requests. +/// let mut jhs = Vec::new(); +/// for task_id in 0..50 { +/// let semaphore = semaphore.clone(); +/// let jh = tokio::spawn(async move { +/// // Acquire permit before sending request. +/// let _permit = semaphore.acquire().await.unwrap(); +/// // Send the request. +/// let response = send_request(task_id).await; +/// // Drop the permit after the request has been sent. +/// drop(_permit); +/// // Handle response. +/// // ... +/// +/// response +/// }); +/// jhs.push(jh); /// } +/// // Collect responses from tasks. +/// let mut responses = Vec::new(); +/// for jh in jhs { +/// let response = jh.await.unwrap(); +/// responses.push(response); +/// } +/// // Process responses. +/// // ... +/// # } /// # async fn send_request(task_id: usize) { /// # // Send request. /// # } @@ -318,7 +318,7 @@ use std::sync::Arc; /// [token bucket]: https://en.wikipedia.org/wiki/Token_bucket /// [`add_permits`]: crate::sync::Semaphore::add_permits /// [`SemaphorePermit::forget`]: crate::sync::SemaphorePermit::forget -/// ```ignore-wasm +/// ``` /// use std::sync::Arc; /// use tokio::sync::Semaphore; /// use tokio::time::{interval, Duration}; @@ -370,20 +370,20 @@ use std::sync::Arc; /// } /// } /// -/// #[tokio::main] +/// # #[tokio::main(flavor = "current_thread")] /// # async fn _hidden() {} /// # #[tokio::main(flavor = "current_thread", start_paused = true)] -/// async fn main() { -/// let capacity = 5; -/// let update_interval = Duration::from_secs_f32(1.0 / capacity as f32); -/// let bucket = TokenBucket::new(update_interval, capacity); +/// # async fn main() { +/// let capacity = 5; +/// let update_interval = Duration::from_secs_f32(1.0 / capacity as f32); +/// let bucket = TokenBucket::new(update_interval, capacity); /// -/// for _ in 0..5 { -/// bucket.acquire().await; +/// for _ in 0..5 { +/// bucket.acquire().await; /// -/// // do the operation -/// } +/// // do the operation /// } +/// # } /// ``` /// /// [`PollSemaphore`]: https://docs.rs/tokio-util/latest/tokio_util/sync/struct.PollSemaphore.html @@ -556,22 +556,22 @@ impl Semaphore { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::Semaphore; /// - /// #[tokio::main] - /// async fn main() { - /// let semaphore = Semaphore::new(2); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let semaphore = Semaphore::new(2); /// - /// let permit_1 = semaphore.acquire().await.unwrap(); - /// assert_eq!(semaphore.available_permits(), 1); + /// let permit_1 = semaphore.acquire().await.unwrap(); + /// assert_eq!(semaphore.available_permits(), 1); /// - /// let permit_2 = semaphore.acquire().await.unwrap(); - /// assert_eq!(semaphore.available_permits(), 0); + /// let permit_2 = semaphore.acquire().await.unwrap(); + /// assert_eq!(semaphore.available_permits(), 0); /// - /// drop(permit_1); - /// assert_eq!(semaphore.available_permits(), 1); - /// } + /// drop(permit_1); + /// assert_eq!(semaphore.available_permits(), 1); + /// # } /// ``` /// /// [`AcquireError`]: crate::sync::AcquireError @@ -609,16 +609,16 @@ impl Semaphore { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::Semaphore; /// - /// #[tokio::main] - /// async fn main() { - /// let semaphore = Semaphore::new(5); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let semaphore = Semaphore::new(5); /// - /// let permit = semaphore.acquire_many(3).await.unwrap(); - /// assert_eq!(semaphore.available_permits(), 2); - /// } + /// let permit = semaphore.acquire_many(3).await.unwrap(); + /// assert_eq!(semaphore.available_permits(), 2); + /// # } /// ``` /// /// [`AcquireError`]: crate::sync::AcquireError @@ -731,28 +731,28 @@ impl Semaphore { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::Semaphore; /// - /// #[tokio::main] - /// async fn main() { - /// let semaphore = Arc::new(Semaphore::new(3)); - /// let mut join_handles = Vec::new(); - /// - /// for _ in 0..5 { - /// let permit = semaphore.clone().acquire_owned().await.unwrap(); - /// join_handles.push(tokio::spawn(async move { - /// // perform task... - /// // explicitly own `permit` in the task - /// drop(permit); - /// })); - /// } - /// - /// for handle in join_handles { - /// handle.await.unwrap(); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let semaphore = Arc::new(Semaphore::new(3)); + /// let mut join_handles = Vec::new(); + /// + /// for _ in 0..5 { + /// let permit = semaphore.clone().acquire_owned().await.unwrap(); + /// join_handles.push(tokio::spawn(async move { + /// // perform task... + /// // explicitly own `permit` in the task + /// drop(permit); + /// })); + /// } + /// + /// for handle in join_handles { + /// handle.await.unwrap(); /// } + /// # } /// ``` /// /// [`Arc`]: std::sync::Arc @@ -792,28 +792,28 @@ impl Semaphore { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use std::sync::Arc; /// use tokio::sync::Semaphore; /// - /// #[tokio::main] - /// async fn main() { - /// let semaphore = Arc::new(Semaphore::new(10)); - /// let mut join_handles = Vec::new(); - /// - /// for _ in 0..5 { - /// let permit = semaphore.clone().acquire_many_owned(2).await.unwrap(); - /// join_handles.push(tokio::spawn(async move { - /// // perform task... - /// // explicitly own `permit` in the task - /// drop(permit); - /// })); - /// } - /// - /// for handle in join_handles { - /// handle.await.unwrap(); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let semaphore = Arc::new(Semaphore::new(10)); + /// let mut join_handles = Vec::new(); + /// + /// for _ in 0..5 { + /// let permit = semaphore.clone().acquire_many_owned(2).await.unwrap(); + /// join_handles.push(tokio::spawn(async move { + /// // perform task... + /// // explicitly own `permit` in the task + /// drop(permit); + /// })); /// } + /// + /// for handle in join_handles { + /// handle.await.unwrap(); + /// } + /// # } /// ``` /// /// [`Arc`]: std::sync::Arc @@ -931,28 +931,28 @@ impl Semaphore { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::Semaphore; /// use std::sync::Arc; /// use tokio::sync::TryAcquireError; /// - /// #[tokio::main] - /// async fn main() { - /// let semaphore = Arc::new(Semaphore::new(1)); - /// let semaphore2 = semaphore.clone(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let semaphore = Arc::new(Semaphore::new(1)); + /// let semaphore2 = semaphore.clone(); /// - /// tokio::spawn(async move { - /// let permit = semaphore.acquire_many(2).await; - /// assert!(permit.is_err()); - /// println!("waiter received error"); - /// }); + /// tokio::spawn(async move { + /// let permit = semaphore.acquire_many(2).await; + /// assert!(permit.is_err()); + /// println!("waiter received error"); + /// }); /// - /// println!("closing semaphore"); - /// semaphore2.close(); + /// println!("closing semaphore"); + /// semaphore2.close(); /// - /// // Cannot obtain more permits - /// assert_eq!(semaphore2.try_acquire().err(), Some(TryAcquireError::Closed)) - /// } + /// // Cannot obtain more permits + /// assert_eq!(semaphore2.try_acquire().err(), Some(TryAcquireError::Closed)) + /// # } /// ``` pub fn close(&self) { self.ll_sem.close(); diff --git a/tokio/src/sync/set_once.rs b/tokio/src/sync/set_once.rs index 682fbab38e3..eab1329e051 100644 --- a/tokio/src/sync/set_once.rs +++ b/tokio/src/sync/set_once.rs @@ -28,25 +28,25 @@ use std::sync::atomic::Ordering; /// /// # Example /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::{SetOnce, SetOnceError}; /// /// static ONCE: SetOnce = SetOnce::const_new(); /// -/// #[tokio::main] -/// async fn main() -> Result<(), SetOnceError> { +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() -> Result<(), SetOnceError> { /// -/// // set the value inside a task somewhere... -/// tokio::spawn(async move { ONCE.set(20) }); +/// // set the value inside a task somewhere... +/// tokio::spawn(async move { ONCE.set(20) }); /// -/// // checking with .get doesn't block main thread -/// println!("{:?}", ONCE.get()); +/// // checking with .get doesn't block main thread +/// println!("{:?}", ONCE.get()); /// -/// // wait until the value is set, blocks the thread -/// println!("{:?}", ONCE.wait().await); +/// // wait until the value is set, blocks the thread +/// println!("{:?}", ONCE.wait().await); /// -/// Ok(()) -/// } +/// Ok(()) +/// # } /// ``` /// /// A `SetOnce` is typically used for global variables that need to be @@ -55,34 +55,34 @@ use std::sync::atomic::Ordering; /// /// # Example /// -/// ```ignore-wasm +/// ``` /// use tokio::sync::{SetOnce, SetOnceError}; /// use std::sync::Arc; /// -/// #[tokio::main] -/// async fn main() -> Result<(), SetOnceError> { -/// let once = SetOnce::new(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() -> Result<(), SetOnceError> { +/// let once = SetOnce::new(); /// -/// let arc = Arc::new(once); -/// let first_cl = Arc::clone(&arc); -/// let second_cl = Arc::clone(&arc); +/// let arc = Arc::new(once); +/// let first_cl = Arc::clone(&arc); +/// let second_cl = Arc::clone(&arc); /// -/// // set the value inside a task -/// tokio::spawn(async move { first_cl.set(20) }).await.unwrap()?; +/// // set the value inside a task +/// tokio::spawn(async move { first_cl.set(20) }).await.unwrap()?; /// -/// // wait inside task to not block the main thread -/// tokio::spawn(async move { -/// // wait inside async context for the value to be set -/// assert_eq!(*second_cl.wait().await, 20); -/// }).await.unwrap(); +/// // wait inside task to not block the main thread +/// tokio::spawn(async move { +/// // wait inside async context for the value to be set +/// assert_eq!(*second_cl.wait().await, 20); +/// }).await.unwrap(); /// -/// // subsequent set calls will fail -/// assert!(arc.set(30).is_err()); +/// // subsequent set calls will fail +/// assert!(arc.set(30).is_err()); /// -/// println!("{:?}", arc.get()); +/// println!("{:?}", arc.get()); /// -/// Ok(()) -/// } +/// Ok(()) +/// # } /// ``` /// /// [`asyncio.Event`]: https://docs.python.org/3/library/asyncio-sync.html#asyncio.Event @@ -168,7 +168,7 @@ impl SetOnce { /// /// # Example /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::{SetOnce, SetOnceError}; /// /// static ONCE: SetOnce = SetOnce::const_new(); @@ -178,13 +178,13 @@ impl SetOnce { /// Ok(ONCE.get()) /// } /// - /// #[tokio::main] - /// async fn main() -> Result<(), SetOnceError> { - /// let result = get_global_integer()?; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> Result<(), SetOnceError> { + /// let result = get_global_integer()?; /// - /// assert_eq!(result, Some(&2)); - /// Ok(()) - /// } + /// assert_eq!(result, Some(&2)); + /// Ok(()) + /// # } /// ``` /// /// [`tokio-console`]: https://github.com/tokio-rs/console @@ -221,7 +221,7 @@ impl SetOnce { /// visible in [`tokio-console`]. Instead, [`SetOnce::new_with`] should be /// used to create an instrumented object if that is needed. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::SetOnce; /// /// static ONCE: SetOnce = SetOnce::const_new_with(1); @@ -230,12 +230,12 @@ impl SetOnce { /// ONCE.get() /// } /// - /// #[tokio::main] - /// async fn main() { - /// let result = get_global_integer(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let result = get_global_integer(); /// - /// assert_eq!(result, Some(&1)); - /// } + /// assert_eq!(result, Some(&1)); + /// # } /// ``` /// /// [`tokio-console`]: https://github.com/tokio-rs/console diff --git a/tokio/src/sync/watch.rs b/tokio/src/sync/watch.rs index 65effc01b21..552293f16d9 100644 --- a/tokio/src/sync/watch.rs +++ b/tokio/src/sync/watch.rs @@ -204,38 +204,38 @@ impl<'a, T> Ref<'a, T> { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::watch; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = watch::channel("hello"); - /// - /// tx.send("goodbye").unwrap(); - /// // The sender does never consider the value as changed. - /// assert!(!tx.borrow().has_changed()); - /// - /// // Drop the sender immediately, just for testing purposes. - /// drop(tx); - /// - /// // Even if the sender has already been dropped... - /// assert!(rx.has_changed().is_err()); - /// // ...the modified value is still readable and detected as changed. - /// assert_eq!(*rx.borrow(), "goodbye"); - /// assert!(rx.borrow().has_changed()); - /// - /// // Read the changed value and mark it as seen. - /// { - /// let received = rx.borrow_and_update(); - /// assert_eq!(*received, "goodbye"); - /// assert!(received.has_changed()); - /// // Release the read lock when leaving this scope. - /// } - /// - /// // Now the value has already been marked as seen and could - /// // never be modified again (after the sender has been dropped). - /// assert!(!rx.borrow().has_changed()); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = watch::channel("hello"); + /// + /// tx.send("goodbye").unwrap(); + /// // The sender does never consider the value as changed. + /// assert!(!tx.borrow().has_changed()); + /// + /// // Drop the sender immediately, just for testing purposes. + /// drop(tx); + /// + /// // Even if the sender has already been dropped... + /// assert!(rx.has_changed().is_err()); + /// // ...the modified value is still readable and detected as changed. + /// assert_eq!(*rx.borrow(), "goodbye"); + /// assert!(rx.borrow().has_changed()); + /// + /// // Read the changed value and mark it as seen. + /// { + /// let received = rx.borrow_and_update(); + /// assert_eq!(*received, "goodbye"); + /// assert!(received.has_changed()); + /// // Release the read lock when leaving this scope. /// } + /// + /// // Now the value has already been marked as seen and could + /// // never be modified again (after the sender has been dropped). + /// assert!(!rx.borrow().has_changed()); + /// # } /// ``` pub fn has_changed(&self) -> bool { self.has_changed @@ -646,25 +646,25 @@ impl Receiver { /// Returns an error if the channel has been closed. /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::watch; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = watch::channel("hello"); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = watch::channel("hello"); /// - /// tx.send("goodbye").unwrap(); + /// tx.send("goodbye").unwrap(); /// - /// assert!(rx.has_changed().unwrap()); - /// assert_eq!(*rx.borrow_and_update(), "goodbye"); + /// assert!(rx.has_changed().unwrap()); + /// assert_eq!(*rx.borrow_and_update(), "goodbye"); /// - /// // The value has been marked as seen - /// assert!(!rx.has_changed().unwrap()); + /// // The value has been marked as seen + /// assert!(!rx.has_changed().unwrap()); /// - /// drop(tx); - /// // The `tx` handle has been dropped - /// assert!(rx.has_changed().is_err()); - /// } + /// drop(tx); + /// // The `tx` handle has been dropped + /// assert!(rx.has_changed().is_err()); + /// # } /// ``` pub fn has_changed(&self) -> Result { // Load the version from the state @@ -725,23 +725,23 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::watch; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, mut rx) = watch::channel("hello"); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, mut rx) = watch::channel("hello"); /// - /// tokio::spawn(async move { - /// tx.send("goodbye").unwrap(); - /// }); + /// tokio::spawn(async move { + /// tx.send("goodbye").unwrap(); + /// }); /// - /// assert!(rx.changed().await.is_ok()); - /// assert_eq!(*rx.borrow_and_update(), "goodbye"); + /// assert!(rx.changed().await.is_ok()); + /// assert_eq!(*rx.borrow_and_update(), "goodbye"); /// - /// // The `tx` handle has been dropped - /// assert!(rx.changed().await.is_err()); - /// } + /// // The `tx` handle has been dropped + /// assert!(rx.changed().await.is_err()); + /// # } /// ``` pub async fn changed(&mut self) -> Result<(), error::RecvError> { cooperative(changed_impl(&self.shared, &mut self.version)).await @@ -1221,22 +1221,22 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::watch; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx) = watch::channel("hello"); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx) = watch::channel("hello"); /// - /// tokio::spawn(async move { - /// // use `rx` - /// drop(rx); - /// }); + /// tokio::spawn(async move { + /// // use `rx` + /// drop(rx); + /// }); /// - /// // Waits for `rx` to drop - /// tx.closed().await; - /// println!("the `rx` handles dropped") - /// } + /// // Waits for `rx` to drop + /// tx.closed().await; + /// println!("the `rx` handles dropped") + /// # } /// ``` pub async fn closed(&self) { cooperative(async { @@ -1269,48 +1269,48 @@ impl Sender { /// /// The new channel will receive messages sent on this `Sender`. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::watch; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, _rx) = watch::channel(0u64); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, _rx) = watch::channel(0u64); /// - /// tx.send(5).unwrap(); + /// tx.send(5).unwrap(); /// - /// let rx = tx.subscribe(); - /// assert_eq!(5, *rx.borrow()); + /// let rx = tx.subscribe(); + /// assert_eq!(5, *rx.borrow()); /// - /// tx.send(10).unwrap(); - /// assert_eq!(10, *rx.borrow()); - /// } + /// tx.send(10).unwrap(); + /// assert_eq!(10, *rx.borrow()); + /// # } /// ``` /// /// The most recent message is considered seen by the channel, so this test /// is guaranteed to pass. /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::watch; /// use tokio::time::Duration; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, _rx) = watch::channel(0u64); - /// tx.send(5).unwrap(); - /// let mut rx = tx.subscribe(); - /// - /// tokio::spawn(async move { - /// // by spawning and sleeping, the message is sent after `main` - /// // hits the call to `changed`. - /// # if false { - /// tokio::time::sleep(Duration::from_millis(10)).await; - /// # } - /// tx.send(100).unwrap(); - /// }); - /// - /// rx.changed().await.unwrap(); - /// assert_eq!(100, *rx.borrow()); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, _rx) = watch::channel(0u64); + /// tx.send(5).unwrap(); + /// let mut rx = tx.subscribe(); + /// + /// tokio::spawn(async move { + /// // by spawning and sleeping, the message is sent after `main` + /// // hits the call to `changed`. + /// # if false { + /// tokio::time::sleep(Duration::from_millis(10)).await; + /// # } + /// tx.send(100).unwrap(); + /// }); + /// + /// rx.changed().await.unwrap(); + /// assert_eq!(100, *rx.borrow()); + /// # } /// ``` pub fn subscribe(&self) -> Receiver { let shared = self.shared.clone(); @@ -1325,19 +1325,19 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::watch; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx, rx1) = watch::channel("hello"); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx, rx1) = watch::channel("hello"); /// - /// assert_eq!(1, tx.receiver_count()); + /// assert_eq!(1, tx.receiver_count()); /// - /// let mut _rx2 = rx1.clone(); + /// let mut _rx2 = rx1.clone(); /// - /// assert_eq!(2, tx.receiver_count()); - /// } + /// assert_eq!(2, tx.receiver_count()); + /// # } /// ``` pub fn receiver_count(&self) -> usize { self.shared.ref_count_rx.load(Relaxed) @@ -1347,20 +1347,20 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::sync::watch; /// - /// #[tokio::main] - /// async fn main() { - /// let (tx1, rx) = watch::channel("hello"); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let (tx1, rx) = watch::channel("hello"); /// - /// assert_eq!(1, tx1.sender_count()); + /// assert_eq!(1, tx1.sender_count()); /// - /// let tx2 = tx1.clone(); + /// let tx2 = tx1.clone(); /// - /// assert_eq!(2, tx1.sender_count()); - /// assert_eq!(2, tx2.sender_count()); - /// } + /// assert_eq!(2, tx1.sender_count()); + /// assert_eq!(2, tx2.sender_count()); + /// # } /// ``` pub fn sender_count(&self) -> usize { self.shared.ref_count_tx.load(Relaxed) diff --git a/tokio/src/task/coop/mod.rs b/tokio/src/task/coop/mod.rs index dc8570531c4..d8cffbdceef 100644 --- a/tokio/src/task/coop/mod.rs +++ b/tokio/src/task/coop/mod.rs @@ -36,8 +36,8 @@ //! scheduling. When a future is wrapped with `unconstrained`, it will never be forced to yield to //! Tokio. For example: //! -//! ```ignore-wasm -//! # #[tokio::main] +//! ``` +//! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! use tokio::{task, sync::mpsc}; //! diff --git a/tokio/src/task/join_set.rs b/tokio/src/task/join_set.rs index 029b082c612..6bd99710d6d 100644 --- a/tokio/src/task/join_set.rs +++ b/tokio/src/task/join_set.rs @@ -28,27 +28,27 @@ use crate::util::IdleNotifiedSet; /// /// Spawn multiple tasks and wait for them. /// -/// ```ignore-wasm +/// ``` /// use tokio::task::JoinSet; /// -/// #[tokio::main] -/// async fn main() { -/// let mut set = JoinSet::new(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let mut set = JoinSet::new(); /// -/// for i in 0..10 { -/// set.spawn(async move { i }); -/// } +/// for i in 0..10 { +/// set.spawn(async move { i }); +/// } /// -/// let mut seen = [false; 10]; -/// while let Some(res) = set.join_next().await { -/// let idx = res.unwrap(); -/// seen[idx] = true; -/// } +/// let mut seen = [false; 10]; +/// while let Some(res) = set.join_next().await { +/// let idx = res.unwrap(); +/// seen[idx] = true; +/// } /// -/// for i in 0..10 { -/// assert!(seen[i]); -/// } +/// for i in 0..10 { +/// assert!(seen[i]); /// } +/// # } /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "rt")))] pub struct JoinSet { @@ -208,27 +208,27 @@ impl JoinSet { /// /// Spawn multiple blocking tasks and wait for them. /// - /// ```ignore-wasm + /// ```should_panic /// use tokio::task::JoinSet; /// - /// #[tokio::main] - /// async fn main() { - /// let mut set = JoinSet::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut set = JoinSet::new(); /// - /// for i in 0..10 { - /// set.spawn_blocking(move || { i }); - /// } + /// for i in 0..10 { + /// set.spawn_blocking(move || { i }); + /// } /// - /// let mut seen = [false; 10]; - /// while let Some(res) = set.join_next().await { - /// let idx = res.unwrap(); - /// seen[idx] = true; - /// } + /// let mut seen = [false; 10]; + /// while let Some(res) = set.join_next().await { + /// let idx = res.unwrap(); + /// seen[idx] = true; + /// } /// - /// for i in 0..10 { - /// assert!(seen[i]); - /// } + /// for i in 0..10 { + /// assert!(seen[i]); /// } + /// # } /// ``` /// /// # Panics @@ -382,50 +382,50 @@ impl JoinSet { /// /// Spawn multiple tasks and `join_all` them. /// - /// ```ignore-wasm + /// ``` /// use tokio::task::JoinSet; /// use std::time::Duration; /// - /// #[tokio::main] - /// async fn main() { - /// let mut set = JoinSet::new(); - /// - /// for i in 0..3 { - /// set.spawn(async move { - /// tokio::time::sleep(Duration::from_secs(3 - i)).await; - /// i - /// }); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut set = JoinSet::new(); /// - /// let output = set.join_all().await; - /// assert_eq!(output, vec![2, 1, 0]); + /// for i in 0..3 { + /// set.spawn(async move { + /// tokio::time::sleep(Duration::from_secs(3 - i)).await; + /// i + /// }); /// } + /// + /// let output = set.join_all().await; + /// assert_eq!(output, vec![2, 1, 0]); + /// # } /// ``` /// /// Equivalent implementation of `join_all`, using [`join_next`] and loop. /// - /// ```ignore-wasm + /// ``` /// use tokio::task::JoinSet; /// use std::panic; /// - /// #[tokio::main] - /// async fn main() { - /// let mut set = JoinSet::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut set = JoinSet::new(); /// - /// for i in 0..3 { - /// set.spawn(async move {i}); - /// } + /// for i in 0..3 { + /// set.spawn(async move {i}); + /// } /// - /// let mut output = Vec::new(); - /// while let Some(res) = set.join_next().await{ - /// match res { - /// Ok(t) => output.push(t), - /// Err(err) if err.is_panic() => panic::resume_unwind(err.into_panic()), - /// Err(err) => panic!("{err}"), - /// } + /// let mut output = Vec::new(); + /// while let Some(res) = set.join_next().await{ + /// match res { + /// Ok(t) => output.push(t), + /// Err(err) if err.is_panic() => panic::resume_unwind(err.into_panic()), + /// Err(err) => panic!("{err}"), /// } - /// assert_eq!(output.len(),3); /// } + /// assert_eq!(output.len(),3); + /// # } /// ``` /// [`join_next`]: fn@Self::join_next /// [`JoinError::id`]: fn@crate::task::JoinError::id @@ -600,23 +600,23 @@ impl Default for JoinSet { /// /// The main example from [`JoinSet`]'s documentation can also be written using [`collect`]: /// -/// ```ignore-wasm +/// ``` /// use tokio::task::JoinSet; /// -/// #[tokio::main] -/// async fn main() { -/// let mut set: JoinSet<_> = (0..10).map(|i| async move { i }).collect(); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let mut set: JoinSet<_> = (0..10).map(|i| async move { i }).collect(); /// -/// let mut seen = [false; 10]; -/// while let Some(res) = set.join_next().await { -/// let idx = res.unwrap(); -/// seen[idx] = true; -/// } +/// let mut seen = [false; 10]; +/// while let Some(res) = set.join_next().await { +/// let idx = res.unwrap(); +/// seen[idx] = true; +/// } /// -/// for i in 0..10 { -/// assert!(seen[i]); -/// } +/// for i in 0..10 { +/// assert!(seen[i]); /// } +/// # } /// ``` /// /// [`collect`]: std::iter::Iterator::collect diff --git a/tokio/src/task/local.rs b/tokio/src/task/local.rs index e90a125a469..42ca0f8d043 100644 --- a/tokio/src/task/local.rs +++ b/tokio/src/task/local.rs @@ -60,28 +60,28 @@ cfg_rt! { /// local task set, we can use [`task::spawn_local`], which can spawn /// `!Send` futures. For example: /// - /// ```rust,ignore-wasm + /// ```rust /// use std::rc::Rc; /// use tokio::task; /// - /// #[tokio::main] - /// async fn main() { - /// let nonsend_data = Rc::new("my nonsend data..."); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let nonsend_data = Rc::new("my nonsend data..."); /// - /// // Construct a local task set that can run `!Send` futures. - /// let local = task::LocalSet::new(); + /// // Construct a local task set that can run `!Send` futures. + /// let local = task::LocalSet::new(); /// - /// // Run the local task set. - /// local.run_until(async move { - /// let nonsend_data = nonsend_data.clone(); - /// // `spawn_local` ensures that the future is spawned on the local - /// // task set. - /// task::spawn_local(async move { - /// println!("{}", nonsend_data); - /// // ... - /// }).await.unwrap(); - /// }).await; - /// } + /// // Run the local task set. + /// local.run_until(async move { + /// let nonsend_data = nonsend_data.clone(); + /// // `spawn_local` ensures that the future is spawned on the local + /// // task set. + /// task::spawn_local(async move { + /// println!("{}", nonsend_data); + /// // ... + /// }).await.unwrap(); + /// }).await; + /// # } /// ``` /// **Note:** The `run_until` method can only be used in `#[tokio::main]`, /// `#[tokio::test]` or directly inside a call to [`Runtime::block_on`]. It @@ -94,30 +94,30 @@ cfg_rt! { /// several futures on a `LocalSet` and drive the whole set until they /// complete. For example, /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::{task, time}; /// use std::rc::Rc; /// - /// #[tokio::main] - /// async fn main() { - /// let nonsend_data = Rc::new("world"); - /// let local = task::LocalSet::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let nonsend_data = Rc::new("world"); + /// let local = task::LocalSet::new(); /// - /// let nonsend_data2 = nonsend_data.clone(); - /// local.spawn_local(async move { - /// // ... - /// println!("hello {}", nonsend_data2) - /// }); + /// let nonsend_data2 = nonsend_data.clone(); + /// local.spawn_local(async move { + /// // ... + /// println!("hello {}", nonsend_data2) + /// }); /// - /// local.spawn_local(async move { - /// time::sleep(time::Duration::from_millis(100)).await; - /// println!("goodbye {}", nonsend_data) - /// }); + /// local.spawn_local(async move { + /// time::sleep(time::Duration::from_millis(100)).await; + /// println!("goodbye {}", nonsend_data) + /// }); /// - /// // ... + /// // ... /// - /// local.await; - /// } + /// local.await; + /// # } /// ``` /// **Note:** Awaiting a `LocalSet` can only be done inside /// `#[tokio::main]`, `#[tokio::test]` or directly inside a call to @@ -350,25 +350,25 @@ cfg_rt! { /// /// # Examples /// - /// ```rust,ignore-wasm + /// ```rust /// use std::rc::Rc; /// use tokio::task; /// - /// #[tokio::main] - /// async fn main() { - /// let nonsend_data = Rc::new("my nonsend data..."); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let nonsend_data = Rc::new("my nonsend data..."); /// - /// let local = task::LocalSet::new(); + /// let local = task::LocalSet::new(); /// - /// // Run the local task set. - /// local.run_until(async move { - /// let nonsend_data = nonsend_data.clone(); - /// task::spawn_local(async move { - /// println!("{}", nonsend_data); - /// // ... - /// }).await.unwrap(); - /// }).await; - /// } + /// // Run the local task set. + /// local.run_until(async move { + /// let nonsend_data = nonsend_data.clone(); + /// task::spawn_local(async move { + /// println!("{}", nonsend_data); + /// // ... + /// }).await.unwrap(); + /// }).await; + /// # } /// ``` /// /// [`LocalSet`]: struct@crate::task::LocalSet @@ -540,34 +540,34 @@ impl LocalSet { /// /// # Examples /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::task; /// - /// #[tokio::main] - /// async fn main() { - /// let local = task::LocalSet::new(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let local = task::LocalSet::new(); /// - /// // Spawn a future on the local set. This future will be run when - /// // we call `run_until` to drive the task set. - /// local.spawn_local(async { - /// // ... - /// }); + /// // Spawn a future on the local set. This future will be run when + /// // we call `run_until` to drive the task set. + /// local.spawn_local(async { + /// // ... + /// }); /// - /// // Run the local task set. - /// local.run_until(async move { - /// // ... - /// }).await; + /// // Run the local task set. + /// local.run_until(async move { + /// // ... + /// }).await; /// - /// // When `run` finishes, we can spawn _more_ futures, which will - /// // run in subsequent calls to `run_until`. - /// local.spawn_local(async { - /// // ... - /// }); + /// // When `run` finishes, we can spawn _more_ futures, which will + /// // run in subsequent calls to `run_until`. + /// local.spawn_local(async { + /// // ... + /// }); /// - /// local.run_until(async move { - /// // ... - /// }).await; - /// } + /// local.run_until(async move { + /// // ... + /// }).await; + /// # } /// ``` /// [`spawn_local`]: fn@spawn_local #[track_caller] @@ -672,18 +672,18 @@ impl LocalSet { /// /// # Examples /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::task; /// - /// #[tokio::main] - /// async fn main() { - /// task::LocalSet::new().run_until(async { - /// task::spawn_local(async move { - /// // ... - /// }).await.unwrap(); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// task::LocalSet::new().run_until(async { + /// task::spawn_local(async move { /// // ... - /// }).await; - /// } + /// }).await.unwrap(); + /// // ... + /// }).await; + /// # } /// ``` /// /// [`spawn_local`]: fn@spawn_local @@ -860,10 +860,10 @@ cfg_unstable! { /// execute. The call to `run_until` will panic due to the runtime being /// forcibly shutdown. /// - /// ```should_panic,ignore-wasm + /// ```should_panic /// use tokio::runtime::UnhandledPanic; /// - /// # #[tokio::main] + /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// tokio::task::LocalSet::new() /// .unhandled_panic(UnhandledPanic::ShutdownRuntime) @@ -894,14 +894,14 @@ cfg_unstable! { /// /// # Examples /// - /// ```rust,ignore-wasm + /// ```rust /// use tokio::task; /// - /// #[tokio::main] - /// async fn main() { - /// let local_set = task::LocalSet::new(); - /// println!("Local set id: {}", local_set.id()); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let local_set = task::LocalSet::new(); + /// println!("Local set id: {}", local_set.id()); + /// # } /// ``` /// /// **Note**: This is an [unstable API][unstable]. The public API of this type diff --git a/tokio/src/task/mod.rs b/tokio/src/task/mod.rs index fbe9a580802..e2987c5f32a 100644 --- a/tokio/src/task/mod.rs +++ b/tokio/src/task/mod.rs @@ -67,10 +67,11 @@ //! A `JoinHandle` is itself a future which may be used to await the output of //! the spawned task. For example: //! -//! ```ignore-wasm +//! ``` //! use tokio::task; //! -//! # #[tokio::main] async fn main() -> Result<(), Box> { +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() -> Result<(), Box> { //! let join = task::spawn(async { //! // ... //! "hello world!" @@ -89,10 +90,11 @@ //! task panics, awaiting its `JoinHandle` will return a [`JoinError`]. For //! example: //! -//! ```ignore-wasm +//! ```should_panic //! use tokio::task; //! -//! # #[tokio::main] async fn main() { +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { //! let join = task::spawn(async { //! panic!("something bad happened!") //! }); @@ -242,10 +244,11 @@ //! scheduled. Eventually, the yielding task will be polled again, allowing it //! to execute. For example: //! -//! ```rust,ignore-wasm +//! ```rust //! use tokio::task; //! -//! # #[tokio::main] async fn main() { +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { //! async { //! task::spawn(async { //! // ... diff --git a/tokio/src/task/spawn.rs b/tokio/src/task/spawn.rs index b275a1900d2..7b765078a22 100644 --- a/tokio/src/task/spawn.rs +++ b/tokio/src/task/spawn.rs @@ -102,7 +102,7 @@ cfg_rt! { /// /// For example, this will work: /// - /// ```ignore-wasm + /// ``` /// use tokio::task; /// /// use std::rc::Rc; @@ -112,18 +112,18 @@ cfg_rt! { /// # drop(rc); /// } /// - /// #[tokio::main] - /// async fn main() { - /// tokio::spawn(async { - /// // Force the `Rc` to stay in a scope with no `.await` - /// { - /// let rc = Rc::new(()); - /// use_rc(rc.clone()); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// tokio::spawn(async { + /// // Force the `Rc` to stay in a scope with no `.await` + /// { + /// let rc = Rc::new(()); + /// use_rc(rc.clone()); + /// } /// - /// task::yield_now().await; - /// }).await.unwrap(); - /// } + /// task::yield_now().await; + /// }).await.unwrap(); + /// # } /// ``` /// /// This will **not** work: diff --git a/tokio/src/time/instant.rs b/tokio/src/time/instant.rs index c0d6f7f06c4..faf62ee59e3 100644 --- a/tokio/src/time/instant.rs +++ b/tokio/src/time/instant.rs @@ -78,17 +78,17 @@ impl Instant { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::time::{Duration, Instant, sleep}; /// - /// #[tokio::main] - /// async fn main() { - /// let now = Instant::now(); - /// sleep(Duration::new(1, 0)).await; - /// let new_now = Instant::now(); - /// println!("{:?}", new_now.checked_duration_since(now)); - /// println!("{:?}", now.checked_duration_since(new_now)); // None - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let now = Instant::now(); + /// sleep(Duration::new(1, 0)).await; + /// let new_now = Instant::now(); + /// println!("{:?}", new_now.checked_duration_since(now)); + /// println!("{:?}", now.checked_duration_since(new_now)); // None + /// # } /// ``` pub fn checked_duration_since(&self, earlier: Instant) -> Option { self.std.checked_duration_since(earlier.std) @@ -99,16 +99,16 @@ impl Instant { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::time::{Duration, Instant, sleep}; /// - /// #[tokio::main] - /// async fn main() { - /// let now = Instant::now(); - /// sleep(Duration::new(1, 0)).await; - /// let new_now = Instant::now(); - /// println!("{:?}", new_now.saturating_duration_since(now)); - /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let now = Instant::now(); + /// sleep(Duration::new(1, 0)).await; + /// let new_now = Instant::now(); + /// println!("{:?}", new_now.saturating_duration_since(now)); + /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns /// } /// ``` pub fn saturating_duration_since(&self, earlier: Instant) -> Duration { @@ -120,16 +120,16 @@ impl Instant { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::time::{Duration, Instant, sleep}; /// - /// #[tokio::main] - /// async fn main() { - /// let instant = Instant::now(); - /// let three_secs = Duration::from_secs(3); - /// sleep(three_secs).await; - /// assert!(instant.elapsed() >= three_secs); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let instant = Instant::now(); + /// let three_secs = Duration::from_secs(3); + /// sleep(three_secs).await; + /// assert!(instant.elapsed() >= three_secs); + /// # } /// ``` pub fn elapsed(&self) -> Duration { Instant::now().saturating_duration_since(*self) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index c209009cefb..02cecc6ec1a 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -23,19 +23,19 @@ use std::task::{ready, Context, Poll}; /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::time::{self, Duration}; /// -/// #[tokio::main] -/// async fn main() { -/// let mut interval = time::interval(Duration::from_millis(10)); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let mut interval = time::interval(Duration::from_millis(10)); /// -/// interval.tick().await; // ticks immediately -/// interval.tick().await; // ticks after 10ms -/// interval.tick().await; // ticks after 10ms +/// interval.tick().await; // ticks immediately +/// interval.tick().await; // ticks after 10ms +/// interval.tick().await; // ticks after 10ms /// -/// // approximately 20ms have elapsed. -/// } +/// // approximately 20ms have elapsed. +/// # } /// ``` /// /// A simple example using `interval` to execute a task every two seconds. @@ -49,7 +49,7 @@ use std::task::{ready, Context, Poll}; /// would only be executed once every three seconds, and not every two /// seconds. /// -/// ```ignore-wasm +/// ``` /// use tokio::time; /// /// async fn task_that_takes_a_second() { @@ -57,14 +57,14 @@ use std::task::{ready, Context, Poll}; /// time::sleep(time::Duration::from_secs(1)).await /// } /// -/// #[tokio::main] -/// async fn main() { -/// let mut interval = time::interval(time::Duration::from_secs(2)); -/// for _i in 0..5 { -/// interval.tick().await; -/// task_that_takes_a_second().await; -/// } +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let mut interval = time::interval(time::Duration::from_secs(2)); +/// for _i in 0..5 { +/// interval.tick().await; +/// task_that_takes_a_second().await; /// } +/// # } /// ``` /// /// [`sleep`]: crate::time::sleep() @@ -89,20 +89,20 @@ pub fn interval(period: Duration) -> Interval { /// /// # Examples /// -/// ```ignore-wasm +/// ``` /// use tokio::time::{interval_at, Duration, Instant}; /// -/// #[tokio::main] -/// async fn main() { -/// let start = Instant::now() + Duration::from_millis(50); -/// let mut interval = interval_at(start, Duration::from_millis(10)); +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// let start = Instant::now() + Duration::from_millis(50); +/// let mut interval = interval_at(start, Duration::from_millis(10)); /// -/// interval.tick().await; // ticks after 50ms -/// interval.tick().await; // ticks after 10ms -/// interval.tick().await; // ticks after 10ms +/// interval.tick().await; // ticks after 50ms +/// interval.tick().await; // ticks after 10ms +/// interval.tick().await; // ticks after 10ms /// -/// // approximately 70ms have elapsed. -/// } +/// // approximately 70ms have elapsed. +/// # } /// ``` #[track_caller] pub fn interval_at(start: Instant, period: Duration) -> Interval { @@ -151,20 +151,20 @@ fn internal_interval_at( /// Sometimes, an [`Interval`]'s tick is missed. For example, consider the /// following: /// -/// ```ignore-wasm +/// ``` /// use tokio::time::{self, Duration}; /// # async fn task_that_takes_one_to_three_millis() {} /// -/// #[tokio::main] -/// async fn main() { -/// // ticks every 2 milliseconds -/// let mut interval = time::interval(Duration::from_millis(2)); -/// for _ in 0..5 { -/// interval.tick().await; -/// // if this takes more than 2 milliseconds, a tick will be delayed -/// task_that_takes_one_to_three_millis().await; -/// } +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// // ticks every 2 milliseconds +/// let mut interval = time::interval(Duration::from_millis(2)); +/// for _ in 0..5 { +/// interval.tick().await; +/// // if this takes more than 2 milliseconds, a tick will be delayed +/// task_that_takes_one_to_three_millis().await; /// } +/// # } /// ``` /// /// Generally, a tick is missed if too much time is spent without calling @@ -413,22 +413,22 @@ impl Interval { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::time; /// /// use std::time::Duration; /// - /// #[tokio::main] - /// async fn main() { - /// let mut interval = time::interval(Duration::from_millis(10)); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut interval = time::interval(Duration::from_millis(10)); /// - /// interval.tick().await; - /// // approximately 0ms have elapsed. The first tick completes immediately. - /// interval.tick().await; - /// interval.tick().await; + /// interval.tick().await; + /// // approximately 0ms have elapsed. The first tick completes immediately. + /// interval.tick().await; + /// interval.tick().await; /// - /// // approximately 20ms have elapsed. - /// } + /// // approximately 20ms have elapsed. + /// # } /// ``` pub async fn tick(&mut self) -> Instant { #[cfg(all(tokio_unstable, feature = "tracing"))] @@ -501,25 +501,25 @@ impl Interval { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::time; /// /// use std::time::Duration; /// - /// #[tokio::main] - /// async fn main() { - /// let mut interval = time::interval(Duration::from_millis(100)); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut interval = time::interval(Duration::from_millis(100)); /// - /// interval.tick().await; + /// interval.tick().await; /// - /// time::sleep(Duration::from_millis(50)).await; - /// interval.reset(); + /// time::sleep(Duration::from_millis(50)).await; + /// interval.reset(); /// - /// interval.tick().await; - /// interval.tick().await; + /// interval.tick().await; + /// interval.tick().await; /// - /// // approximately 250ms have elapsed. - /// } + /// // approximately 250ms have elapsed. + /// # } /// ``` pub fn reset(&mut self) { self.delay.as_mut().reset(Instant::now() + self.period); @@ -533,25 +533,25 @@ impl Interval { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::time; /// /// use std::time::Duration; /// - /// #[tokio::main] - /// async fn main() { - /// let mut interval = time::interval(Duration::from_millis(100)); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut interval = time::interval(Duration::from_millis(100)); /// - /// interval.tick().await; + /// interval.tick().await; /// - /// time::sleep(Duration::from_millis(50)).await; - /// interval.reset_immediately(); + /// time::sleep(Duration::from_millis(50)).await; + /// interval.reset_immediately(); /// - /// interval.tick().await; - /// interval.tick().await; + /// interval.tick().await; + /// interval.tick().await; /// - /// // approximately 150ms have elapsed. - /// } + /// // approximately 150ms have elapsed. + /// # } /// ``` pub fn reset_immediately(&mut self) { self.delay.as_mut().reset(Instant::now()); @@ -565,26 +565,26 @@ impl Interval { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::time; /// /// use std::time::Duration; /// - /// #[tokio::main] - /// async fn main() { - /// let mut interval = time::interval(Duration::from_millis(100)); - /// interval.tick().await; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut interval = time::interval(Duration::from_millis(100)); + /// interval.tick().await; /// - /// time::sleep(Duration::from_millis(50)).await; + /// time::sleep(Duration::from_millis(50)).await; /// - /// let after = Duration::from_millis(20); - /// interval.reset_after(after); + /// let after = Duration::from_millis(20); + /// interval.reset_after(after); /// - /// interval.tick().await; - /// interval.tick().await; + /// interval.tick().await; + /// interval.tick().await; /// - /// // approximately 170ms have elapsed. - /// } + /// // approximately 170ms have elapsed. + /// # } /// ``` pub fn reset_after(&mut self, after: Duration) { self.delay.as_mut().reset(Instant::now() + after); @@ -601,26 +601,26 @@ impl Interval { /// /// # Examples /// - /// ```ignore-wasm + /// ``` /// use tokio::time::{self, Instant}; /// /// use std::time::Duration; /// - /// #[tokio::main] - /// async fn main() { - /// let mut interval = time::interval(Duration::from_millis(100)); - /// interval.tick().await; + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut interval = time::interval(Duration::from_millis(100)); + /// interval.tick().await; /// - /// time::sleep(Duration::from_millis(50)).await; + /// time::sleep(Duration::from_millis(50)).await; /// - /// let deadline = Instant::now() + Duration::from_millis(30); - /// interval.reset_at(deadline); + /// let deadline = Instant::now() + Duration::from_millis(30); + /// interval.reset_at(deadline); /// - /// interval.tick().await; - /// interval.tick().await; + /// interval.tick().await; + /// interval.tick().await; /// - /// // approximately 180ms have elapsed. - /// } + /// // approximately 180ms have elapsed. + /// # } /// ``` pub fn reset_at(&mut self, deadline: Instant) { self.delay.as_mut().reset(deadline); diff --git a/tokio/src/time/mod.rs b/tokio/src/time/mod.rs index e314d0f29ca..8cfbf6ab2c2 100644 --- a/tokio/src/time/mod.rs +++ b/tokio/src/time/mod.rs @@ -23,15 +23,15 @@ //! //! Wait 100ms and print "100 ms have elapsed" //! -//! ```ignore-wasm +//! ``` //! use std::time::Duration; //! use tokio::time::sleep; //! -//! #[tokio::main] -//! async fn main() { +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { //! sleep(Duration::from_millis(100)).await; //! println!("100 ms have elapsed"); -//! } +//! # } //! ``` //! //! Require that an operation takes no more than 1s. @@ -63,7 +63,7 @@ //! would only be executed once every three seconds, and not every two //! seconds. //! -//! ```ignore-wasm +//! ``` //! use tokio::time; //! //! async fn task_that_takes_a_second() { @@ -71,14 +71,14 @@ //! time::sleep(time::Duration::from_secs(1)).await //! } //! -//! #[tokio::main] -//! async fn main() { -//! let mut interval = time::interval(time::Duration::from_secs(2)); -//! for _i in 0..5 { -//! interval.tick().await; -//! task_that_takes_a_second().await; -//! } +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() { +//! let mut interval = time::interval(time::Duration::from_secs(2)); +//! for _i in 0..5 { +//! interval.tick().await; +//! task_that_takes_a_second().await; //! } +//! # } //! ``` //! //! [`interval`]: crate::time::interval() diff --git a/tokio/src/time/sleep.rs b/tokio/src/time/sleep.rs index 0cbf413dadc..87261057bfe 100644 --- a/tokio/src/time/sleep.rs +++ b/tokio/src/time/sleep.rs @@ -25,14 +25,14 @@ use std::task::{self, ready, Poll}; /// /// Wait 100ms and print "100 ms have elapsed". /// -/// ```ignore-wasm +/// ``` /// use tokio::time::{sleep_until, Instant, Duration}; /// -/// #[tokio::main] -/// async fn main() { -/// sleep_until(Instant::now() + Duration::from_millis(100)).await; -/// println!("100 ms have elapsed"); -/// } +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// sleep_until(Instant::now() + Duration::from_millis(100)).await; +/// println!("100 ms have elapsed"); +/// # } /// ``` /// /// See the documentation for the [`Sleep`] type for more examples. @@ -85,14 +85,14 @@ pub fn sleep_until(deadline: Instant) -> Sleep { /// /// Wait 100ms and print "100 ms have elapsed". /// -/// ```ignore-wasm +/// ``` /// use tokio::time::{sleep, Duration}; /// -/// #[tokio::main] -/// async fn main() { -/// sleep(Duration::from_millis(100)).await; -/// println!("100 ms have elapsed"); -/// } +/// # #[tokio::main(flavor = "current_thread")] +/// # async fn main() { +/// sleep(Duration::from_millis(100)).await; +/// println!("100 ms have elapsed"); +/// # } /// ``` /// /// See the documentation for the [`Sleep`] type for more examples. @@ -140,35 +140,35 @@ pin_project! { /// /// Wait 100ms and print "100 ms have elapsed". /// - /// ```ignore-wasm + /// ``` /// use tokio::time::{sleep, Duration}; /// - /// #[tokio::main] - /// async fn main() { - /// sleep(Duration::from_millis(100)).await; - /// println!("100 ms have elapsed"); - /// } + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// sleep(Duration::from_millis(100)).await; + /// println!("100 ms have elapsed"); + /// # } /// ``` /// /// Use with [`select!`]. Pinning the `Sleep` with [`tokio::pin!`] is /// necessary when the same `Sleep` is selected on multiple times. - /// ```no_run,ignore-wasm + /// ```no_run /// use tokio::time::{self, Duration, Instant}; /// - /// #[tokio::main] - /// async fn main() { - /// let sleep = time::sleep(Duration::from_millis(10)); - /// tokio::pin!(sleep); + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let sleep = time::sleep(Duration::from_millis(10)); + /// tokio::pin!(sleep); /// - /// loop { - /// tokio::select! { - /// () = &mut sleep => { - /// println!("timer elapsed"); - /// sleep.as_mut().reset(Instant::now() + Duration::from_millis(50)); - /// }, - /// } + /// loop { + /// tokio::select! { + /// () = &mut sleep => { + /// println!("timer elapsed"); + /// sleep.as_mut().reset(Instant::now() + Duration::from_millis(50)); + /// }, /// } /// } + /// # } /// ``` /// Use in a struct with boxing. By pinning the `Sleep` with a `Box`, the /// `HasSleep` struct implements `Unpin`, even though `Sleep` does not. From 5ada9322bc309a11fe861801e2127e2c1b025b8f Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Wed, 10 Sep 2025 16:42:37 -0700 Subject: [PATCH 16/19] add back annotations to conflicting test failures --- tokio/src/runtime/builder.rs | 2 +- tokio/src/runtime/task/error.rs | 16 ++--- tokio/src/runtime/task/join.rs | 20 +++---- tokio/src/sync/broadcast.rs | 20 +++---- tokio/src/sync/mpsc/unbounded.rs | 20 +++---- tokio/src/sync/oneshot.rs | 40 ++++++------- tokio/src/sync/rwlock.rs | 100 +++++++++++++++---------------- tokio/src/task/join_set.rs | 30 +++++----- tokio/src/task/mod.rs | 5 +- 9 files changed, 126 insertions(+), 127 deletions(-) diff --git a/tokio/src/runtime/builder.rs b/tokio/src/runtime/builder.rs index a3ffc04c355..d8ebfc77207 100644 --- a/tokio/src/runtime/builder.rs +++ b/tokio/src/runtime/builder.rs @@ -151,7 +151,7 @@ cfg_unstable! { /// /// # Examples /// - /// ```should_panic + /// ```ignore-wasm /// use tokio::runtime::{self, UnhandledPanic}; /// /// # pub fn main() { diff --git a/tokio/src/runtime/task/error.rs b/tokio/src/runtime/task/error.rs index 0971ba6c1d6..8a6d5f89789 100644 --- a/tokio/src/runtime/task/error.rs +++ b/tokio/src/runtime/task/error.rs @@ -45,17 +45,17 @@ impl JoinError { /// /// # Examples /// - /// ```should_panic + /// ```ignore-wasm /// use std::panic; /// - /// # #[tokio::main(flavor = "current_thread")] - /// # async fn main() { - /// let err = tokio::spawn(async { - /// panic!("boom"); - /// }).await.unwrap_err(); + /// #[tokio::main] + /// async fn main() { + /// let err = tokio::spawn(async { + /// panic!("boom"); + /// }).await.unwrap_err(); /// - /// assert!(err.is_panic()); - /// # } + /// assert!(err.is_panic()); + /// } /// ``` pub fn is_panic(&self) -> bool { matches!(&self.repr, Repr::Panic(_)) diff --git a/tokio/src/runtime/task/join.rs b/tokio/src/runtime/task/join.rs index d101f5f875f..45c293ca25d 100644 --- a/tokio/src/runtime/task/join.rs +++ b/tokio/src/runtime/task/join.rs @@ -105,21 +105,21 @@ cfg_rt! { /// /// If the task panics, the error is a [`JoinError`] that contains the panic: /// - /// ```should_panic + /// ```ignore-wasm /// use tokio::task; /// use std::io; /// use std::panic; /// - /// # #[tokio::main(flavor = "current_thread")] - /// # async fn main() -> io::Result<()> { - /// let join_handle: task::JoinHandle> = tokio::spawn(async { - /// panic!("boom"); - /// }); + /// #[tokio::main] + /// async fn main() -> io::Result<()> { + /// let join_handle: task::JoinHandle> = tokio::spawn(async { + /// panic!("boom"); + /// }); /// - /// let err = join_handle.await.unwrap_err(); - /// assert!(err.is_panic()); - /// Ok(()) - /// # } + /// let err = join_handle.await.unwrap_err(); + /// assert!(err.is_panic()); + /// Ok(()) + /// } /// /// ``` /// Child being detached and outliving its parent: diff --git a/tokio/src/sync/broadcast.rs b/tokio/src/sync/broadcast.rs index 2094a7f398d..d4c2300065c 100644 --- a/tokio/src/sync/broadcast.rs +++ b/tokio/src/sync/broadcast.rs @@ -1521,21 +1521,21 @@ impl Receiver { /// context. /// /// # Examples - /// ```should_panic + /// ```ignore-wasm /// use std::thread; /// use tokio::sync::broadcast; /// - /// # #[tokio::main(flavor = "current_thread")] - /// # async fn main() { - /// let (tx, mut rx) = broadcast::channel(16); + /// #[tokio::main] + /// async fn main() { + /// let (tx, mut rx) = broadcast::channel(16); /// - /// let sync_code = thread::spawn(move || { - /// assert_eq!(rx.blocking_recv(), Ok(10)); - /// }); + /// let sync_code = thread::spawn(move || { + /// assert_eq!(rx.blocking_recv(), Ok(10)); + /// }); /// - /// let _ = tx.send(10); - /// sync_code.join().unwrap(); - /// # } + /// let _ = tx.send(10); + /// sync_code.join().unwrap(); + /// } /// ``` pub fn blocking_recv(&mut self) -> Result { crate::future::block_on(self.recv()) diff --git a/tokio/src/sync/mpsc/unbounded.rs b/tokio/src/sync/mpsc/unbounded.rs index 99778517dba..5cf5d0f1799 100644 --- a/tokio/src/sync/mpsc/unbounded.rs +++ b/tokio/src/sync/mpsc/unbounded.rs @@ -296,21 +296,21 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ```should_panic + /// ```ignore-wasm /// use std::thread; /// use tokio::sync::mpsc; /// - /// # #[tokio::main(flavor = "current_thread")] - /// # async fn main() { - /// let (tx, mut rx) = mpsc::unbounded_channel::(); + /// #[tokio::main] + /// async fn main() { + /// let (tx, mut rx) = mpsc::unbounded_channel::(); /// - /// let sync_code = thread::spawn(move || { - /// assert_eq!(Some(10), rx.blocking_recv()); - /// }); + /// let sync_code = thread::spawn(move || { + /// assert_eq!(Some(10), rx.blocking_recv()); + /// }); /// - /// let _ = tx.send(10); - /// sync_code.join().unwrap(); - /// # } + /// let _ = tx.send(10); + /// sync_code.join().unwrap(); + /// } /// ``` #[track_caller] #[cfg(feature = "sync")] diff --git a/tokio/src/sync/oneshot.rs b/tokio/src/sync/oneshot.rs index eab9052c960..36af8372952 100644 --- a/tokio/src/sync/oneshot.rs +++ b/tokio/src/sync/oneshot.rs @@ -1038,19 +1038,19 @@ impl Receiver { /// /// Terminated channels are empty. /// - /// ```should_panic + /// ```should_panic,ignore-wasm /// use tokio::sync::oneshot; /// - /// # #[tokio::main(flavor = "current_thread")] - /// # async fn main() { - /// let (tx, mut rx) = oneshot::channel(); - /// tx.send(0).unwrap(); - /// let _ = (&mut rx).await; + /// #[tokio::main] + /// async fn main() { + /// let (tx, mut rx) = oneshot::channel(); + /// tx.send(0).unwrap(); + /// let _ = (&mut rx).await; /// - /// // NB: an empty channel is not necessarily safe to poll! - /// assert!(rx.is_empty()); - /// let _ = (&mut rx).await; - /// # } + /// // NB: an empty channel is not necessarily safe to poll! + /// assert!(rx.is_empty()); + /// let _ = (&mut rx).await; + /// } /// ``` pub fn is_empty(&self) -> bool { let Some(inner) = self.inner.as_ref() else { @@ -1188,21 +1188,21 @@ impl Receiver { /// /// # Examples /// - /// ```should_panic + /// ```ignore-wasm /// use std::thread; /// use tokio::sync::oneshot; /// - /// # #[tokio::main(flavor = "current_thread")] - /// # async fn main() { - /// let (tx, rx) = oneshot::channel::(); + /// #[tokio::main] + /// async fn main() { + /// let (tx, rx) = oneshot::channel::(); /// - /// let sync_code = thread::spawn(move || { - /// assert_eq!(Ok(10), rx.blocking_recv()); - /// }); + /// let sync_code = thread::spawn(move || { + /// assert_eq!(Ok(10), rx.blocking_recv()); + /// }); /// - /// let _ = tx.send(10); - /// sync_code.join().unwrap(); - /// # } + /// let _ = tx.send(10); + /// sync_code.join().unwrap(); + /// } /// ``` #[track_caller] #[cfg(feature = "sync")] diff --git a/tokio/src/sync/rwlock.rs b/tokio/src/sync/rwlock.rs index 69ebf921d78..9d014751d13 100644 --- a/tokio/src/sync/rwlock.rs +++ b/tokio/src/sync/rwlock.rs @@ -488,33 +488,33 @@ impl RwLock { /// /// # Examples /// - /// ```should_panic + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::sync::RwLock; /// - /// # #[tokio::main(flavor = "current_thread")] - /// # async fn main() { - /// let rwlock = Arc::new(RwLock::new(1)); - /// let mut write_lock = rwlock.write().await; - /// - /// let blocking_task = tokio::task::spawn_blocking({ - /// let rwlock = Arc::clone(&rwlock); - /// move || { - /// // This shall block until the `write_lock` is released. - /// let read_lock = rwlock.blocking_read(); - /// assert_eq!(*read_lock, 0); - /// } - /// }); - /// - /// *write_lock -= 1; - /// drop(write_lock); // release the lock. - /// - /// // Await the completion of the blocking task. - /// blocking_task.await.unwrap(); - /// - /// // Assert uncontended. - /// assert!(rwlock.try_write().is_ok()); - /// # } + /// #[tokio::main] + /// async fn main() { + /// let rwlock = Arc::new(RwLock::new(1)); + /// let mut write_lock = rwlock.write().await; + /// + /// let blocking_task = tokio::task::spawn_blocking({ + /// let rwlock = Arc::clone(&rwlock); + /// move || { + /// // This shall block until the `write_lock` is released. + /// let read_lock = rwlock.blocking_read(); + /// assert_eq!(*read_lock, 0); + /// } + /// }); + /// + /// *write_lock -= 1; + /// drop(write_lock); // release the lock. + /// + /// // Await the completion of the blocking task. + /// blocking_task.await.unwrap(); + /// + /// // Assert uncontended. + /// assert!(rwlock.try_write().is_ok()); + /// } /// ``` #[track_caller] #[cfg(feature = "sync")] @@ -830,35 +830,35 @@ impl RwLock { /// /// # Examples /// - /// ```should_panic + /// ```ignore-wasm /// use std::sync::Arc; /// use tokio::{sync::RwLock}; /// - /// # #[tokio::main(flavor = "current_thread")] - /// # async fn main() { - /// let rwlock = Arc::new(RwLock::new(1)); - /// let read_lock = rwlock.read().await; - /// - /// let blocking_task = tokio::task::spawn_blocking({ - /// let rwlock = Arc::clone(&rwlock); - /// move || { - /// // This shall block until the `read_lock` is released. - /// let mut write_lock = rwlock.blocking_write(); - /// *write_lock = 2; - /// } - /// }); - /// - /// assert_eq!(*read_lock, 1); - /// // Release the last outstanding read lock. - /// drop(read_lock); - /// - /// // Await the completion of the blocking task. - /// blocking_task.await.unwrap(); - /// - /// // Assert uncontended. - /// let read_lock = rwlock.try_read().unwrap(); - /// assert_eq!(*read_lock, 2); - /// # } + /// #[tokio::main] + /// async fn main() { + /// let rwlock = Arc::new(RwLock::new(1)); + /// let read_lock = rwlock.read().await; + /// + /// let blocking_task = tokio::task::spawn_blocking({ + /// let rwlock = Arc::clone(&rwlock); + /// move || { + /// // This shall block until the `read_lock` is released. + /// let mut write_lock = rwlock.blocking_write(); + /// *write_lock = 2; + /// } + /// }); + /// + /// assert_eq!(*read_lock, 1); + /// // Release the last outstanding read lock. + /// drop(read_lock); + /// + /// // Await the completion of the blocking task. + /// blocking_task.await.unwrap(); + /// + /// // Assert uncontended. + /// let read_lock = rwlock.try_read().unwrap(); + /// assert_eq!(*read_lock, 2); + /// } /// ``` #[track_caller] #[cfg(feature = "sync")] diff --git a/tokio/src/task/join_set.rs b/tokio/src/task/join_set.rs index 6bd99710d6d..78b3c17ae18 100644 --- a/tokio/src/task/join_set.rs +++ b/tokio/src/task/join_set.rs @@ -208,27 +208,27 @@ impl JoinSet { /// /// Spawn multiple blocking tasks and wait for them. /// - /// ```should_panic + /// ```ignore-wasm /// use tokio::task::JoinSet; /// - /// # #[tokio::main(flavor = "current_thread")] - /// # async fn main() { - /// let mut set = JoinSet::new(); + /// #[tokio::main] + /// async fn main() { + /// let mut set = JoinSet::new(); /// - /// for i in 0..10 { - /// set.spawn_blocking(move || { i }); - /// } + /// for i in 0..10 { + /// set.spawn_blocking(move || { i }); + /// } /// - /// let mut seen = [false; 10]; - /// while let Some(res) = set.join_next().await { - /// let idx = res.unwrap(); - /// seen[idx] = true; - /// } + /// let mut seen = [false; 10]; + /// while let Some(res) = set.join_next().await { + /// let idx = res.unwrap(); + /// seen[idx] = true; + /// } /// - /// for i in 0..10 { - /// assert!(seen[i]); + /// for i in 0..10 { + /// assert!(seen[i]); + /// } /// } - /// # } /// ``` /// /// # Panics diff --git a/tokio/src/task/mod.rs b/tokio/src/task/mod.rs index e2987c5f32a..fa62858b90a 100644 --- a/tokio/src/task/mod.rs +++ b/tokio/src/task/mod.rs @@ -90,11 +90,10 @@ //! task panics, awaiting its `JoinHandle` will return a [`JoinError`]. For //! example: //! -//! ```should_panic +//! ```ignore-wasm //! use tokio::task; //! -//! # #[tokio::main(flavor = "current_thread")] -//! # async fn main() { +//! # #[tokio::main] async fn main() { //! let join = task::spawn(async { //! panic!("something bad happened!") //! }); From a86c4832699061ea6ae20ba7a4c6262344f95700 Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Wed, 10 Sep 2025 18:10:32 -0700 Subject: [PATCH 17/19] minor inconsistencies in formatting --- tokio-stream/src/stream_map.rs | 12 +++++----- tokio/src/macros/try_join.rs | 20 ++++++++--------- tokio/src/sync/mod.rs | 40 +++++++++++++++++----------------- tokio/src/sync/oneshot.rs | 4 ++-- tokio/src/sync/semaphore.rs | 6 ++--- tokio/src/sync/set_once.rs | 4 ++-- tokio/src/time/mod.rs | 4 ++-- 7 files changed, 45 insertions(+), 45 deletions(-) diff --git a/tokio-stream/src/stream_map.rs b/tokio-stream/src/stream_map.rs index b015c053f33..49ccc926811 100644 --- a/tokio-stream/src/stream_map.rs +++ b/tokio-stream/src/stream_map.rs @@ -72,15 +72,15 @@ use std::task::{ready, Context, Poll}; /// /// // Convert the channels to a `Stream`. /// let rx1 = Box::pin(async_stream::stream! { -/// while let Some(item) = rx1.recv().await { -/// yield item; -/// } +/// while let Some(item) = rx1.recv().await { +/// yield item; +/// } /// }) as Pin + Send>>; /// /// let rx2 = Box::pin(async_stream::stream! { -/// while let Some(item) = rx2.recv().await { -/// yield item; -/// } +/// while let Some(item) = rx2.recv().await { +/// yield item; +/// } /// }) as Pin + Send>>; /// /// tokio::spawn(async move { diff --git a/tokio/src/macros/try_join.rs b/tokio/src/macros/try_join.rs index fda5f08fa4a..e7d791e6a98 100644 --- a/tokio/src/macros/try_join.rs +++ b/tokio/src/macros/try_join.rs @@ -71,12 +71,12 @@ macro_rules! doc { /// more_async_work()); /// /// match res { - /// Ok((first, second)) => { - /// // do something with the values - /// } - /// Err(err) => { + /// Ok((first, second)) => { + /// // do something with the values + /// } + /// Err(err) => { /// println!("processing failed; error = {}", err); - /// } + /// } /// } /// # } /// ``` @@ -141,12 +141,12 @@ macro_rules! doc { /// ); /// /// match res { - /// Ok((first, second)) => { - /// // do something with the values - /// } - /// Err(err) => { + /// Ok((first, second)) => { + /// // do something with the values + /// } + /// Err(err) => { /// println!("processing failed; error = {}", err); - /// } + /// } /// } /// # } /// ``` diff --git a/tokio/src/sync/mod.rs b/tokio/src/sync/mod.rs index 55dd8190003..15b7fb21545 100644 --- a/tokio/src/sync/mod.rs +++ b/tokio/src/sync/mod.rs @@ -47,8 +47,8 @@ //! let (tx, rx) = oneshot::channel(); //! //! tokio::spawn(async move { -//! let res = some_computation().await; -//! tx.send(res).unwrap(); +//! let res = some_computation().await; +//! tx.send(res).unwrap(); //! }); //! //! // Do other work while the computation is happening in the background @@ -75,7 +75,7 @@ //! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { //! let join_handle = tokio::spawn(async move { -//! some_computation().await +//! some_computation().await //! }); //! //! // Do other work while the computation is happening in the background @@ -260,13 +260,13 @@ //! let mut rx2 = tx.subscribe(); //! //! tokio::spawn(async move { -//! assert_eq!(rx1.recv().await.unwrap(), 10); -//! assert_eq!(rx1.recv().await.unwrap(), 20); +//! assert_eq!(rx1.recv().await.unwrap(), 10); +//! assert_eq!(rx1.recv().await.unwrap(), 20); //! }); //! //! tokio::spawn(async move { -//! assert_eq!(rx2.recv().await.unwrap(), 10); -//! assert_eq!(rx2.recv().await.unwrap(), 20); +//! assert_eq!(rx2.recv().await.unwrap(), 10); +//! assert_eq!(rx2.recv().await.unwrap(), 20); //! }); //! //! tx.send(10).unwrap(); @@ -325,19 +325,19 @@ //! //! // Spawn a task to monitor the file. //! tokio::spawn(async move { -//! loop { -//! // Wait 10 seconds between checks -//! time::sleep(Duration::from_secs(10)).await; -//! -//! // Load the configuration file -//! let new_config = Config::load_from_file().await.unwrap(); -//! -//! // If the configuration changed, send the new config value -//! // on the watch channel. -//! if new_config != config { -//! tx.send(new_config.clone()).unwrap(); -//! config = new_config; -//! } +//! loop { +//! // Wait 10 seconds between checks +//! time::sleep(Duration::from_secs(10)).await; +//! +//! // Load the configuration file +//! let new_config = Config::load_from_file().await.unwrap(); +//! +//! // If the configuration changed, send the new config value +//! // on the watch channel. +//! if new_config != config { +//! tx.send(new_config.clone()).unwrap(); +//! config = new_config; +//! } //! } //! }); //! diff --git a/tokio/src/sync/oneshot.rs b/tokio/src/sync/oneshot.rs index 36af8372952..06a4bb84e96 100644 --- a/tokio/src/sync/oneshot.rs +++ b/tokio/src/sync/oneshot.rs @@ -259,8 +259,8 @@ pub struct Sender { /// }); /// /// match rx.await { -/// Ok(v) => println!("got = {:?}", v), -/// Err(_) => println!("the sender dropped"), +/// Ok(v) => println!("got = {:?}", v), +/// Err(_) => println!("the sender dropped"), /// } /// # } /// ``` diff --git a/tokio/src/sync/semaphore.rs b/tokio/src/sync/semaphore.rs index 69bb3122733..e7a61645f2b 100644 --- a/tokio/src/sync/semaphore.rs +++ b/tokio/src/sync/semaphore.rs @@ -118,8 +118,8 @@ use std::sync::Arc; /// // Collect responses from tasks. /// let mut responses = Vec::new(); /// for jh in jhs { -/// let response = jh.await.unwrap(); -/// responses.push(response); +/// let response = jh.await.unwrap(); +/// responses.push(response); /// } /// // Process responses. /// // ... @@ -811,7 +811,7 @@ impl Semaphore { /// } /// /// for handle in join_handles { - /// handle.await.unwrap(); + /// handle.await.unwrap(); /// } /// # } /// ``` diff --git a/tokio/src/sync/set_once.rs b/tokio/src/sync/set_once.rs index 9ac05576eb2..3c4228e6a34 100644 --- a/tokio/src/sync/set_once.rs +++ b/tokio/src/sync/set_once.rs @@ -74,8 +74,8 @@ use std::task::Poll; /// /// // wait inside task to not block the main thread /// tokio::spawn(async move { -/// // wait inside async context for the value to be set -/// assert_eq!(*second_cl.wait().await, 20); +/// // wait inside async context for the value to be set +/// assert_eq!(*second_cl.wait().await, 20); /// }).await.unwrap(); /// /// // subsequent set calls will fail diff --git a/tokio/src/time/mod.rs b/tokio/src/time/mod.rs index 8cfbf6ab2c2..8627a7838aa 100644 --- a/tokio/src/time/mod.rs +++ b/tokio/src/time/mod.rs @@ -29,8 +29,8 @@ //! //! # #[tokio::main(flavor = "current_thread")] //! # async fn main() { -//! sleep(Duration::from_millis(100)).await; -//! println!("100 ms have elapsed"); +//! sleep(Duration::from_millis(100)).await; +//! println!("100 ms have elapsed"); //! # } //! ``` //! From 82afcd202584d82d0b081086b38a97c25564b7f5 Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Mon, 22 Sep 2025 09:54:23 -0700 Subject: [PATCH 18/19] partially enable tests with conditional compilation --- tokio-stream/src/wrappers/tcp_listener.rs | 5 +- tokio-util/src/compat.rs | 10 +- tokio-util/src/context.rs | 15 ++- tokio-util/src/io/sync_bridge.rs | 5 +- tokio-util/src/task/spawn_pinned.rs | 15 ++- tokio/src/io/mod.rs | 15 ++- tokio/src/io/util/async_read_ext.rs | 40 +++++-- tokio/src/io/util/async_seek_ext.rs | 5 +- tokio/src/io/util/async_write_ext.rs | 40 +++++-- tokio/src/lib.rs | 10 +- tokio/src/loom/std/barrier.rs | 10 +- tokio/src/macros/join.rs | 5 +- tokio/src/runtime/builder.rs | 130 ++++++++++++++++----- tokio/src/runtime/handle.rs | 36 ++++-- tokio/src/runtime/id.rs | 5 +- tokio/src/runtime/local_runtime/runtime.rs | 5 +- tokio/src/runtime/metrics/runtime.rs | 10 +- tokio/src/runtime/mod.rs | 15 ++- tokio/src/runtime/runtime.rs | 35 ++++-- tokio/src/runtime/task/error.rs | 5 +- tokio/src/runtime/task/join.rs | 6 +- tokio/src/sync/broadcast.rs | 5 +- tokio/src/sync/mod.rs | 5 +- tokio/src/sync/mpsc/bounded.rs | 10 +- tokio/src/sync/mpsc/unbounded.rs | 10 +- tokio/src/sync/mutex.rs | 12 +- tokio/src/sync/rwlock.rs | 10 +- tokio/src/sync/semaphore.rs | 10 +- tokio/src/task/join_set.rs | 5 +- tokio/src/task/local.rs | 10 +- tokio/src/task/mod.rs | 10 +- tokio/src/task/spawn.rs | 5 +- 32 files changed, 409 insertions(+), 105 deletions(-) diff --git a/tokio-stream/src/wrappers/tcp_listener.rs b/tokio-stream/src/wrappers/tcp_listener.rs index 1b958f70741..c589dd90c0b 100644 --- a/tokio-stream/src/wrappers/tcp_listener.rs +++ b/tokio-stream/src/wrappers/tcp_listener.rs @@ -10,7 +10,9 @@ use tokio::net::{TcpListener, TcpStream}; /// /// Accept connections from both IPv4 and IPv6 listeners in the same loop: /// -/// ```no_run,ignore-wasm +/// ```no_run +/// # #[cfg(not(target_family = "wasm"))] +/// # { /// use std::net::{Ipv4Addr, Ipv6Addr}; /// /// use tokio::net::TcpListener; @@ -31,6 +33,7 @@ use tokio::net::{TcpListener, TcpStream}; /// } /// # Ok(()) /// # } +/// # } /// ``` /// /// [`TcpListener`]: struct@tokio::net::TcpListener diff --git a/tokio-util/src/compat.rs b/tokio-util/src/compat.rs index 7d9707492e2..c68b864c8bc 100644 --- a/tokio-util/src/compat.rs +++ b/tokio-util/src/compat.rs @@ -33,7 +33,9 @@ //! [`futures::io::AsyncReadExt::read`] from the `futures` crate to read it after adapting the //! stream via [`compat()`]. //! -//! ```no_run,ignore-wasm +//! ```no_run +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::net::{TcpListener, TcpStream}; //! use tokio::io::AsyncWriteExt; //! use tokio_util::compat::TokioAsyncReadCompatExt; @@ -58,6 +60,7 @@ //! //! Ok(()) //! } +//! # } //! ``` //! //! ## Example 2: Futures -> Tokio (`AsyncRead`) @@ -65,7 +68,9 @@ //! The reverse is also possible: you can take a [`futures::io::AsyncRead`] (e.g. a cursor) and //! adapt it to be used with [`tokio::io::AsyncReadExt::read_to_end`] //! -//! ```ignore-wasm +//! ``` +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use futures::io::Cursor; //! use tokio_util::compat::FuturesAsyncReadCompatExt; //! use tokio::io::AsyncReadExt; @@ -82,6 +87,7 @@ //! // Run the future inside a Tokio runtime //! tokio::runtime::Runtime::new().unwrap().block_on(future); //! } +//! # } //! ``` //! //! ## Common Use Cases diff --git a/tokio-util/src/context.rs b/tokio-util/src/context.rs index 88d4dc0bb82..c4d5728694d 100644 --- a/tokio-util/src/context.rs +++ b/tokio-util/src/context.rs @@ -36,7 +36,9 @@ pin_project! { /// This example creates two runtimes, but only [enables time] on one of /// them. It then uses the context of the runtime with the timer enabled to /// execute a [`sleep`] future on the runtime with timing disabled. - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::time::{sleep, Duration}; /// use tokio_util::context::RuntimeExt; /// @@ -56,6 +58,7 @@ pin_project! { /// /// // Execute the future on rt2. /// rt2.block_on(fut); + /// # } /// ``` /// /// [`Handle`]: struct@tokio::runtime::Handle @@ -87,7 +90,9 @@ impl TokioContext { /// /// [`RuntimeExt::wrap`]: fn@RuntimeExt::wrap /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::time::{sleep, Duration}; /// use tokio_util::context::TokioContext; /// @@ -109,6 +114,7 @@ impl TokioContext { /// /// // Execute the future on rt2. /// rt2.block_on(fut); + /// # } /// ``` pub fn new(future: F, handle: Handle) -> TokioContext { TokioContext { @@ -152,7 +158,9 @@ pub trait RuntimeExt { /// them. It then uses the context of the runtime with the timer enabled to /// execute a [`sleep`] future on the runtime with timing disabled. /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::time::{sleep, Duration}; /// use tokio_util::context::RuntimeExt; /// @@ -172,6 +180,7 @@ pub trait RuntimeExt { /// /// // Execute the future on rt2. /// rt2.block_on(fut); + /// # } /// ``` /// /// [`TokioContext`]: struct@crate::context::TokioContext diff --git a/tokio-util/src/io/sync_bridge.rs b/tokio-util/src/io/sync_bridge.rs index c42ff577992..a412eb0301a 100644 --- a/tokio-util/src/io/sync_bridge.rs +++ b/tokio-util/src/io/sync_bridge.rs @@ -217,7 +217,9 @@ use tokio::io::{ /// `spawn_blocking` ensures that the synchronous code is offloaded to a dedicated /// thread pool, preventing it from interfering with the async tasks. /// -/// ```rust,ignore-wasm +/// ```rust +/// # #[cfg(not(target_family = "wasm"))] +/// # { /// use tokio::task::spawn_blocking; /// use tokio_util::io::SyncIoBridge; /// use tokio::io::AsyncRead; @@ -255,6 +257,7 @@ use tokio::io::{ /// /// Ok(()) /// } +/// # } /// ``` /// #[derive(Debug)] diff --git a/tokio-util/src/task/spawn_pinned.rs b/tokio-util/src/task/spawn_pinned.rs index f6ba5b68327..3f692d3cf2c 100644 --- a/tokio-util/src/task/spawn_pinned.rs +++ b/tokio-util/src/task/spawn_pinned.rs @@ -21,7 +21,9 @@ use tokio::task::{spawn_local, JoinHandle, LocalSet}; /// /// # Examples /// -/// ```ignore-wasm +/// ``` +/// # #[cfg(not(target_family = "wasm"))] +/// # { /// use std::rc::Rc; /// use tokio::task; /// use tokio_util::task::LocalPoolHandle; @@ -45,6 +47,7 @@ use tokio::task::{spawn_local, JoinHandle, LocalSet}; /// }).await.unwrap(); /// println!("output: {}", output); /// } +/// # } /// ``` /// #[derive(Clone)] @@ -93,7 +96,9 @@ impl LocalPoolHandle { /// [`FnOnce`] which creates it is. /// /// # Examples - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::rc::Rc; /// use tokio_util::task::LocalPoolHandle; /// @@ -116,6 +121,7 @@ impl LocalPoolHandle { /// /// assert_eq!(output, "test"); /// } + /// # } /// ``` pub fn spawn_pinned(&self, create_task: F) -> JoinHandle where @@ -143,7 +149,9 @@ impl LocalPoolHandle { /// /// This method can be used to spawn a task on all worker threads of the pool: /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio_util::task::LocalPoolHandle; /// /// #[tokio::main] @@ -167,6 +175,7 @@ impl LocalPoolHandle { /// handle.await.unwrap(); /// } /// } + /// # } /// ``` /// #[track_caller] diff --git a/tokio/src/io/mod.rs b/tokio/src/io/mod.rs index aa9d0a52a72..f1b0b547284 100644 --- a/tokio/src/io/mod.rs +++ b/tokio/src/io/mod.rs @@ -35,7 +35,9 @@ //! [demonstrating][std_example] reading some bytes from a [`std::fs::File`]. We //! can do the same with [`tokio::fs::File`][`File`]: //! -//! ```no_run,ignore-wasm +//! ```no_run +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::io::{self, AsyncReadExt}; //! use tokio::fs::File; //! @@ -50,6 +52,7 @@ //! println!("The bytes: {:?}", &buffer[..n]); //! Ok(()) //! } +//! # } //! ``` //! //! [`File`]: crate::fs::File @@ -72,7 +75,9 @@ //! For example, [`BufReader`] works with the [`AsyncBufRead`] trait to add //! extra methods to any async reader: //! -//! ```no_run,ignore-wasm +//! ```no_run +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::io::{self, BufReader, AsyncBufReadExt}; //! use tokio::fs::File; //! @@ -88,13 +93,16 @@ //! println!("{}", buffer); //! Ok(()) //! } +//! # } //! ``` //! //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call //! to [`write`](crate::io::AsyncWriteExt::write). However, you **must** flush //! [`BufWriter`] to ensure that any buffered data is written. //! -//! ```no_run,ignore-wasm +//! ```no_run +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::io::{self, BufWriter, AsyncWriteExt}; //! use tokio::fs::File; //! @@ -114,6 +122,7 @@ //! //! Ok(()) //! } +//! # } //! ``` //! //! [stdbuf]: std::io#bufreader-and-bufwriter diff --git a/tokio/src/io/util/async_read_ext.rs b/tokio/src/io/util/async_read_ext.rs index d6befce1e62..59de6cdb1e1 100644 --- a/tokio/src/io/util/async_read_ext.rs +++ b/tokio/src/io/util/async_read_ext.rs @@ -40,7 +40,9 @@ cfg_io_util! { /// [`AsyncRead`] types. Callers will tend to import this trait instead of /// [`AsyncRead`]. /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::fs::File; /// use tokio::io::{self, AsyncReadExt}; /// @@ -54,6 +56,7 @@ cfg_io_util! { /// /// Ok(()) /// } + /// # } /// ``` /// /// See [module][crate::io] documentation for more details. @@ -71,7 +74,9 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `AsyncRead`: /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::fs::File; /// use tokio::io::{self, AsyncReadExt}; /// @@ -88,6 +93,7 @@ cfg_io_util! { /// handle.read_to_string(&mut buffer).await?; /// Ok(()) /// } + /// # } /// ``` fn chain(self, next: R) -> Chain where @@ -149,7 +155,9 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `Read`: /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::fs::File; /// use tokio::io::{self, AsyncReadExt}; /// @@ -164,6 +172,7 @@ cfg_io_util! { /// println!("The bytes: {:?}", &buffer[..n]); /// Ok(()) /// } + /// # } /// ``` fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self> where @@ -218,7 +227,9 @@ cfg_io_util! { /// [`BytesMut`]: bytes::BytesMut /// [`BufMut`]: bytes::BufMut /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::fs::File; /// use tokio::io::{self, AsyncReadExt}; /// @@ -242,6 +253,7 @@ cfg_io_util! { /// println!("The bytes: {:?}", &buffer[..]); /// Ok(()) /// } + /// # } /// ``` fn read_buf<'a, B>(&'a mut self, buf: &'a mut B) -> ReadBuf<'a, Self, B> where @@ -288,7 +300,9 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `Read`: /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::fs::File; /// use tokio::io::{self, AsyncReadExt}; /// @@ -302,6 +316,7 @@ cfg_io_util! { /// f.read_exact(&mut buffer).await?; /// Ok(()) /// } + /// # } /// ``` /// /// [`ErrorKind::UnexpectedEof`]: std::io::ErrorKind::UnexpectedEof @@ -1314,7 +1329,9 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `Read`: /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, AsyncReadExt}; /// use tokio::fs::File; /// @@ -1327,6 +1344,7 @@ cfg_io_util! { /// f.read_to_end(&mut buffer).await?; /// Ok(()) /// } + /// # } /// ``` /// /// (See also the [`tokio::fs::read`] convenience function for reading from a @@ -1362,7 +1380,9 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `Read`: /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, AsyncReadExt}; /// use tokio::fs::File; /// @@ -1374,6 +1394,7 @@ cfg_io_util! { /// f.read_to_string(&mut buffer).await?; /// Ok(()) /// } + /// # } /// ``` /// /// (See also the [`crate::fs::read_to_string`] convenience function for @@ -1402,7 +1423,9 @@ cfg_io_util! { /// /// [`File`][crate::fs::File]s implement `Read`: /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, AsyncReadExt}; /// use tokio::fs::File; /// @@ -1417,6 +1440,7 @@ cfg_io_util! { /// handle.read(&mut buffer).await?; /// Ok(()) /// } + /// # } /// ``` fn take(self, limit: u64) -> Take where diff --git a/tokio/src/io/util/async_seek_ext.rs b/tokio/src/io/util/async_seek_ext.rs index 0dc4b0552e0..c45139303bc 100644 --- a/tokio/src/io/util/async_seek_ext.rs +++ b/tokio/src/io/util/async_seek_ext.rs @@ -45,7 +45,9 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::fs::File; /// use tokio::io::{AsyncSeekExt, AsyncReadExt}; /// @@ -59,6 +61,7 @@ cfg_io_util! { /// file.read_exact(&mut contents).await?; /// # Ok(()) /// # } + /// # } /// ``` fn seek(&mut self, pos: SeekFrom) -> Seek<'_, Self> where diff --git a/tokio/src/io/util/async_write_ext.rs b/tokio/src/io/util/async_write_ext.rs index 3e56c38c32d..db4400bb7d2 100644 --- a/tokio/src/io/util/async_write_ext.rs +++ b/tokio/src/io/util/async_write_ext.rs @@ -43,7 +43,9 @@ cfg_io_util! { /// [`AsyncWrite`] types. Callers will tend to import this trait instead of /// [`AsyncWrite`]. /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -61,6 +63,7 @@ cfg_io_util! { /// /// Ok(()) /// } + /// # } /// ``` /// /// See [module][crate::io] documentation for more details. @@ -107,7 +110,9 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -120,6 +125,7 @@ cfg_io_util! { /// file.flush().await?; /// Ok(()) /// } + /// # } /// ``` fn write<'a>(&'a mut self, src: &'a [u8]) -> Write<'a, Self> where @@ -147,7 +153,9 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// use std::io::IoSlice; @@ -167,6 +175,7 @@ cfg_io_util! { /// /// Ok(()) /// } + /// # } /// ``` /// /// [`write`]: AsyncWriteExt::write @@ -227,7 +236,9 @@ cfg_io_util! { /// [`Buf`]: bytes::Buf /// [`Cursor`]: std::io::Cursor /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -250,6 +261,7 @@ cfg_io_util! { /// /// Ok(()) /// } + /// # } /// ``` fn write_buf<'a, B>(&'a mut self, src: &'a mut B) -> WriteBuf<'a, Self, B> where @@ -298,7 +310,9 @@ cfg_io_util! { /// [`Cursor`]: std::io::Cursor /// [advanced]: bytes::Buf::advance /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -313,6 +327,7 @@ cfg_io_util! { /// file.flush().await?; /// Ok(()) /// } + /// # } /// ``` /// /// [`write`]: AsyncWriteExt::write @@ -351,7 +366,9 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -363,6 +380,7 @@ cfg_io_util! { /// file.flush().await?; /// Ok(()) /// } + /// # } /// ``` /// /// [`write`]: AsyncWriteExt::write @@ -1243,7 +1261,9 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, BufWriter, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -1256,6 +1276,7 @@ cfg_io_util! { /// buffer.flush().await?; /// Ok(()) /// } + /// # } /// ``` fn flush(&mut self) -> Flush<'_, Self> where @@ -1282,7 +1303,9 @@ cfg_io_util! { /// /// # Examples /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::io::{self, BufWriter, AsyncWriteExt}; /// use tokio::fs::File; /// @@ -1295,6 +1318,7 @@ cfg_io_util! { /// buffer.shutdown().await?; /// Ok(()) /// } + /// # } /// ``` fn shutdown(&mut self) -> Shutdown<'_, Self> where diff --git a/tokio/src/lib.rs b/tokio/src/lib.rs index cc7ee992ce3..33ee9eb87f2 100644 --- a/tokio/src/lib.rs +++ b/tokio/src/lib.rs @@ -193,7 +193,9 @@ //! [`spawn_blocking`]: crate::task::spawn_blocking() //! [`thread_keep_alive`]: crate::runtime::Builder::thread_keep_alive() //! -//! ```ignore-wasm +//! ``` +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! #[tokio::main] //! async fn main() { //! // This is running on a core thread. @@ -208,6 +210,7 @@ //! // panic. //! blocking_task.await.unwrap(); //! } +//! # } //! ``` //! //! If your code is CPU-bound and you wish to limit the number of threads used @@ -265,7 +268,9 @@ //! //! A simple TCP echo server: //! -//! ```no_run,ignore-wasm +//! ```no_run +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::net::TcpListener; //! use tokio::io::{AsyncReadExt, AsyncWriteExt}; //! @@ -300,6 +305,7 @@ //! }); //! } //! } +//! # } //! ``` //! //! # Feature flags diff --git a/tokio/src/loom/std/barrier.rs b/tokio/src/loom/std/barrier.rs index 468395d8e16..083fc45e274 100644 --- a/tokio/src/loom/std/barrier.rs +++ b/tokio/src/loom/std/barrier.rs @@ -11,7 +11,9 @@ use std::time::{Duration, Instant}; /// /// # Examples /// -/// ```ignore-wasm +/// ``` +/// # #[cfg(not(target_family = "wasm"))] +/// # { /// use std::sync::{Arc, Barrier}; /// use std::thread; /// @@ -31,6 +33,7 @@ use std::time::{Duration, Instant}; /// for handle in handles { /// handle.join().unwrap(); /// } +/// # } /// ``` pub(crate) struct Barrier { lock: Mutex, @@ -102,7 +105,9 @@ impl Barrier { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::sync::{Arc, Barrier}; /// use std::thread; /// @@ -122,6 +127,7 @@ impl Barrier { /// for handle in handles { /// handle.join().unwrap(); /// } + /// # } /// ``` pub(crate) fn wait(&self) -> BarrierWaitResult { let mut lock = self.lock.lock(); diff --git a/tokio/src/macros/join.rs b/tokio/src/macros/join.rs index 37482dad02d..33f0bf2acba 100644 --- a/tokio/src/macros/join.rs +++ b/tokio/src/macros/join.rs @@ -76,7 +76,9 @@ macro_rules! doc { /// /// Using the `biased;` mode to control polling order. /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// async fn do_stuff_async() { /// // async work /// } @@ -95,6 +97,7 @@ macro_rules! doc { /// /// // do something with the values /// # } + /// # } /// ``` #[macro_export] diff --git a/tokio/src/runtime/builder.rs b/tokio/src/runtime/builder.rs index d8ebfc77207..a3dbf5e8e23 100644 --- a/tokio/src/runtime/builder.rs +++ b/tokio/src/runtime/builder.rs @@ -30,7 +30,9 @@ use std::time::Duration; /// /// # Examples /// -/// ```ignore-wasm +/// ``` +/// # #[cfg(not(target_family = "wasm"))] +/// # { /// use tokio::runtime::Builder; /// /// fn main() { @@ -44,6 +46,7 @@ use std::time::Duration; /// /// // use runtime ... /// } +/// # } /// ``` pub struct Builder { /// Runtime type @@ -151,7 +154,9 @@ cfg_unstable! { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::{self, UnhandledPanic}; /// /// # pub fn main() { @@ -174,6 +179,7 @@ cfg_unstable! { /// assert!(task2.await.is_ok()); /// }) /// # } + /// # } /// ``` /// /// [`JoinHandle`]: struct@crate::task::JoinHandle @@ -323,13 +329,16 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime; /// /// let rt = runtime::Builder::new_multi_thread() /// .enable_all() /// .build() /// .unwrap(); + /// # } /// ``` pub fn enable_all(&mut self) -> &mut Self { #[cfg(any( @@ -365,7 +374,9 @@ impl Builder { /// /// ## Multi threaded runtime with 4 threads /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime; /// /// // This will spawn a work-stealing runtime with 4 worker threads. @@ -375,6 +386,7 @@ impl Builder { /// .unwrap(); /// /// rt.spawn(async move {}); + /// # } /// ``` /// /// ## Current thread runtime (will only run on the current thread via `Runtime::block_on`) @@ -459,7 +471,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use tokio::runtime; /// /// # pub fn main() { @@ -467,6 +481,7 @@ impl Builder { /// .thread_name("my-pool") /// .build(); /// # } + /// # } /// ``` pub fn thread_name(&mut self, val: impl Into) -> &mut Self { let val = val.into(); @@ -480,7 +495,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use tokio::runtime; /// # use std::sync::atomic::{AtomicUsize, Ordering}; /// # pub fn main() { @@ -492,6 +509,7 @@ impl Builder { /// }) /// .build(); /// # } + /// # } /// ``` pub fn thread_name_fn(&mut self, f: F) -> &mut Self where @@ -511,7 +529,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use tokio::runtime; /// /// # pub fn main() { @@ -519,6 +539,7 @@ impl Builder { /// .thread_stack_size(32 * 1024) /// .build(); /// # } + /// # } /// ``` pub fn thread_stack_size(&mut self, val: usize) -> &mut Self { self.thread_stack_size = Some(val); @@ -532,7 +553,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use tokio::runtime; /// # pub fn main() { /// let runtime = runtime::Builder::new_multi_thread() @@ -541,6 +564,7 @@ impl Builder { /// }) /// .build(); /// # } + /// # } /// ``` #[cfg(not(loom))] pub fn on_thread_start(&mut self, f: F) -> &mut Self @@ -557,7 +581,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// { /// # use tokio::runtime; /// # pub fn main() { /// let runtime = runtime::Builder::new_multi_thread() @@ -566,6 +592,7 @@ impl Builder { /// }) /// .build(); /// # } + /// # } /// ``` #[cfg(not(loom))] pub fn on_thread_stop(&mut self, f: F) -> &mut Self @@ -589,7 +616,9 @@ impl Builder { /// # Examples /// /// ## Multithreaded executor - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use std::sync::Arc; /// # use std::sync::atomic::{AtomicBool, Ordering}; /// # use tokio::runtime; @@ -616,6 +645,7 @@ impl Builder { /// barrier.wait().await; /// }) /// # } + /// # } /// ``` /// ## Current thread executor /// ``` @@ -665,7 +695,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use tokio::runtime; /// # pub fn main() { /// let runtime = runtime::Builder::new_multi_thread() @@ -679,6 +711,7 @@ impl Builder { /// println!("Hello from Tokio!"); /// }) /// # } + /// # } /// ``` #[cfg(not(loom))] pub fn on_thread_unpark(&mut self, f: F) -> &mut Self @@ -753,7 +786,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use std::sync::{atomic::AtomicUsize, Arc}; /// # use tokio::task::yield_now; /// # pub fn main() { @@ -772,6 +807,7 @@ impl Builder { /// let _ = rt.block_on(task); /// /// # } + /// # } /// ``` #[cfg(tokio_unstable)] #[cfg_attr(docsrs, doc(cfg(tokio_unstable)))] @@ -797,7 +833,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use std::sync::{atomic::AtomicUsize, Arc}; /// # use tokio::task::yield_now; /// # pub fn main() { @@ -816,6 +854,7 @@ impl Builder { /// let _ = rt.block_on(task); /// /// # } + /// # } /// ``` #[cfg(tokio_unstable)] #[cfg_attr(docsrs, doc(cfg(tokio_unstable)))] @@ -882,7 +921,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Builder; /// /// let rt = Builder::new_multi_thread().build().unwrap(); @@ -890,6 +931,7 @@ impl Builder { /// rt.block_on(async { /// println!("Hello from the Tokio runtime"); /// }); + /// # } /// ``` pub fn build(&mut self) -> io::Result { match &self.kind { @@ -954,7 +996,9 @@ impl Builder { /// /// # Example /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use tokio::runtime; /// # use std::time::Duration; /// # pub fn main() { @@ -962,6 +1006,7 @@ impl Builder { /// .thread_keep_alive(Duration::from_millis(100)) /// .build(); /// # } + /// # } /// ``` pub fn thread_keep_alive(&mut self, duration: Duration) -> &mut Self { self.keep_alive = Some(duration); @@ -991,13 +1036,16 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use tokio::runtime; /// # pub fn main() { /// let rt = runtime::Builder::new_multi_thread() /// .global_queue_interval(31) /// .build(); /// # } + /// # } /// ``` #[track_caller] pub fn global_queue_interval(&mut self, val: u32) -> &mut Self { @@ -1025,13 +1073,16 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use tokio::runtime; /// # pub fn main() { /// let rt = runtime::Builder::new_multi_thread() /// .event_interval(31) /// .build(); /// # } + /// # } /// ``` pub fn event_interval(&mut self, val: u32) -> &mut Self { self.event_interval = val; @@ -1135,13 +1186,16 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime; /// /// let rt = runtime::Builder::new_multi_thread() /// .disable_lifo_slot() /// .build() /// .unwrap(); + /// # } /// ``` /// /// [tokio-rs/tokio-metrics]: https://github.com/tokio-rs/tokio-metrics @@ -1205,7 +1259,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime; /// /// let rt = runtime::Builder::new_multi_thread() @@ -1218,6 +1274,7 @@ impl Builder { /// # assert_eq!(m.poll_time_histogram_num_buckets(), 10); /// # assert_eq!(m.poll_time_histogram_bucket_range(0), us(0)..us(100)); /// # assert_eq!(m.poll_time_histogram_bucket_range(1), us(100)..us(200)); + /// # } /// ``` /// /// [`Handle::metrics()`]: crate::runtime::Handle::metrics @@ -1251,7 +1308,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::{self, HistogramScale}; /// /// # #[allow(deprecated)] @@ -1260,6 +1319,7 @@ impl Builder { /// .metrics_poll_count_histogram_scale(HistogramScale::Log) /// .build() /// .unwrap(); + /// # } /// ``` #[deprecated(note = "use `metrics_poll_time_histogram_configuration`")] pub fn metrics_poll_count_histogram_scale(&mut self, histogram_scale: crate::runtime::HistogramScale) -> &mut Self { @@ -1275,7 +1335,9 @@ impl Builder { /// /// # Examples /// Configure a [`LogHistogram`] with [default configuration]: - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime; /// use tokio::runtime::{HistogramConfiguration, LogHistogram}; /// @@ -1286,10 +1348,13 @@ impl Builder { /// ) /// .build() /// .unwrap(); + /// # } /// ``` /// /// Configure a linear histogram with 100 buckets, each 10μs wide - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime; /// use std::time::Duration; /// use tokio::runtime::HistogramConfiguration; @@ -1301,13 +1366,16 @@ impl Builder { /// ) /// .build() /// .unwrap(); + /// # } /// ``` /// /// Configure a [`LogHistogram`] with the following settings: /// - Measure times from 100ns to 120s /// - Max error of 0.1 /// - No more than 1024 buckets - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::time::Duration; /// use tokio::runtime; /// use tokio::runtime::{HistogramConfiguration, LogHistogram}; @@ -1325,6 +1393,7 @@ impl Builder { /// ) /// .build() /// .unwrap(); + /// # } /// ``` /// /// When migrating from the legacy histogram ([`HistogramScale::Log`]) and wanting @@ -1373,7 +1442,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime; /// use std::time::Duration; /// @@ -1383,6 +1454,7 @@ impl Builder { /// .metrics_poll_count_histogram_resolution(Duration::from_micros(100)) /// .build() /// .unwrap(); + /// # } /// ``` #[deprecated(note = "use `metrics_poll_time_histogram_configuration`")] pub fn metrics_poll_count_histogram_resolution(&mut self, resolution: Duration) -> &mut Self { @@ -1408,7 +1480,9 @@ impl Builder { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime; /// /// # #[allow(deprecated)] @@ -1417,6 +1491,7 @@ impl Builder { /// .metrics_poll_count_histogram_buckets(15) /// .build() /// .unwrap(); + /// # } /// ``` #[deprecated(note = "use `metrics_poll_time_histogram_configuration`")] pub fn metrics_poll_count_histogram_buckets(&mut self, buckets: usize) -> &mut Self { @@ -1567,13 +1642,16 @@ cfg_time! { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime; /// /// let rt = runtime::Builder::new_multi_thread() /// .enable_time() /// .build() /// .unwrap(); + /// # } /// ``` pub fn enable_time(&mut self) -> &mut Self { self.enable_time = true; diff --git a/tokio/src/runtime/handle.rs b/tokio/src/runtime/handle.rs index a26252a19fb..95803a80c33 100644 --- a/tokio/src/runtime/handle.rs +++ b/tokio/src/runtime/handle.rs @@ -51,7 +51,9 @@ impl Handle { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// /// let rt = Runtime::new().unwrap(); @@ -60,6 +62,7 @@ impl Handle { /// tokio::spawn(async { /// println!("Hello world!"); /// }); + /// # } /// ``` /// /// Do **not** do the following, this shows a scenario that will result in a @@ -105,7 +108,9 @@ impl Handle { /// This can be used to obtain the handle of the surrounding runtime from an async /// block or function running on that runtime. /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// # use std::thread; /// # use tokio::runtime::Runtime; /// # fn dox() { @@ -134,6 +139,7 @@ impl Handle { /// # handle.join().unwrap(); /// # }); /// # } + /// # } /// ``` #[track_caller] pub fn current() -> Self { @@ -169,7 +175,9 @@ impl Handle { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// /// # fn dox() { @@ -183,6 +191,7 @@ impl Handle { /// println!("now running on a worker thread"); /// }); /// # } + /// # } /// ``` #[track_caller] pub fn spawn(&self, future: F) -> JoinHandle @@ -203,7 +212,9 @@ impl Handle { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// /// # fn dox() { @@ -217,6 +228,8 @@ impl Handle { /// println!("now running on a worker thread"); /// }); /// # } + /// # } + /// ``` #[track_caller] pub fn spawn_blocking(&self, func: F) -> JoinHandle where @@ -255,7 +268,9 @@ impl Handle { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// /// // Create the runtime @@ -268,11 +283,14 @@ impl Handle { /// handle.block_on(async { /// println!("hello"); /// }); + /// # } /// ``` /// /// Or using `Handle::current`: /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -285,6 +303,7 @@ impl Handle { /// }); /// }); /// } + /// # } /// ``` /// /// [`JoinError`]: struct@crate::task::JoinError @@ -386,13 +405,16 @@ impl Handle { /// } /// ``` /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::{Handle, RuntimeFlavor}; /// /// #[tokio::main(flavor = "multi_thread", worker_threads = 4)] /// async fn main() { /// assert_eq!(RuntimeFlavor::MultiThread, Handle::current().runtime_flavor()); /// } + /// # } /// ``` pub fn runtime_flavor(&self) -> RuntimeFlavor { match self.inner { diff --git a/tokio/src/runtime/id.rs b/tokio/src/runtime/id.rs index 14c724f7bd7..dc223bdcf72 100644 --- a/tokio/src/runtime/id.rs +++ b/tokio/src/runtime/id.rs @@ -15,13 +15,16 @@ use std::num::{NonZeroU32, NonZeroU64}; /// /// # Examples /// -/// ```ignore-wasm +/// ``` +/// # #[cfg(not(target_family = "wasm"))] +/// # { /// use tokio::runtime::Handle; /// /// #[tokio::main(flavor = "multi_thread", worker_threads = 4)] /// async fn main() { /// println!("Current runtime id: {}", Handle::current().id()); /// } +/// # } /// ``` /// /// **Note**: This is an [unstable API][unstable]. The public API of this type diff --git a/tokio/src/runtime/local_runtime/runtime.rs b/tokio/src/runtime/local_runtime/runtime.rs index e72ea1fa4e6..62c3c582460 100644 --- a/tokio/src/runtime/local_runtime/runtime.rs +++ b/tokio/src/runtime/local_runtime/runtime.rs @@ -312,7 +312,9 @@ impl LocalRuntime { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::LocalRuntime; /// use tokio::task; /// @@ -330,6 +332,7 @@ impl LocalRuntime { /// /// runtime.shutdown_timeout(Duration::from_millis(100)); /// } + /// # } /// ``` pub fn shutdown_timeout(mut self, duration: Duration) { // Wakeup and shutdown all the worker threads diff --git a/tokio/src/runtime/metrics/runtime.rs b/tokio/src/runtime/metrics/runtime.rs index 9ca3b88967d..adb84416cc2 100644 --- a/tokio/src/runtime/metrics/runtime.rs +++ b/tokio/src/runtime/metrics/runtime.rs @@ -251,7 +251,9 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Handle; /// /// # #[tokio::main(flavor = "current_thread")] @@ -265,6 +267,7 @@ impl RuntimeMetrics { /// let n = metrics.num_blocking_threads(); /// println!("Runtime has created {} threads", n); /// # } + /// # } /// ``` pub fn num_blocking_threads(&self) -> usize { self.handle.inner.num_blocking_threads() @@ -281,7 +284,9 @@ impl RuntimeMetrics { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Handle; /// /// #[tokio::main] @@ -295,6 +300,7 @@ impl RuntimeMetrics { /// let n = metrics.num_idle_blocking_threads(); /// println!("Runtime has {} idle blocking thread pool threads", n); /// } + /// # } /// ``` pub fn num_idle_blocking_threads(&self) -> usize { self.handle.inner.num_idle_blocking_threads() diff --git a/tokio/src/runtime/mod.rs b/tokio/src/runtime/mod.rs index 872b6171950..3a74dda2d73 100644 --- a/tokio/src/runtime/mod.rs +++ b/tokio/src/runtime/mod.rs @@ -18,7 +18,9 @@ //! When no fine tuning is required, the [`tokio::main`] attribute macro can be //! used. //! -//! ```no_run,ignore-wasm +//! ```no_run +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::net::TcpListener; //! use tokio::io::{AsyncReadExt, AsyncWriteExt}; //! @@ -53,6 +55,7 @@ //! }); //! } //! } +//! # } //! ``` //! //! From within the context of the runtime, additional tasks are spawned using @@ -61,7 +64,9 @@ //! //! A [`Runtime`] instance can also be used directly. //! -//! ```no_run,ignore-wasm +//! ```no_run +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::net::TcpListener; //! use tokio::io::{AsyncReadExt, AsyncWriteExt}; //! use tokio::runtime::Runtime; @@ -102,6 +107,7 @@ //! } //! }) //! } +//! # } //! ``` //! //! ## Runtime Configurations @@ -117,12 +123,15 @@ //! CPU core available on the system. This tends to be the ideal configuration //! for most applications. The multi-thread scheduler requires the `rt-multi-thread` //! feature flag, and is selected by default: -//! ```ignore-wasm +//! ``` +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::runtime; //! //! # fn main() -> Result<(), Box> { //! let threaded_rt = runtime::Runtime::new()?; //! # Ok(()) } +//! # } //! ``` //! //! Most applications should use the multi-thread scheduler, except in some diff --git a/tokio/src/runtime/runtime.rs b/tokio/src/runtime/runtime.rs index adee31ee43e..120f7710229 100644 --- a/tokio/src/runtime/runtime.rs +++ b/tokio/src/runtime/runtime.rs @@ -183,7 +183,9 @@ impl Runtime { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// /// let rt = Runtime::new() @@ -192,6 +194,7 @@ impl Runtime { /// let handle = rt.handle(); /// /// // Use the handle... + /// # } /// ``` pub fn handle(&self) -> &Handle { &self.handle @@ -213,7 +216,9 @@ impl Runtime { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// /// # fn dox() { @@ -225,6 +230,7 @@ impl Runtime { /// println!("now running on a worker thread"); /// }); /// # } + /// # } /// ``` #[track_caller] pub fn spawn(&self, future: F) -> JoinHandle @@ -246,7 +252,9 @@ impl Runtime { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// /// # fn dox() { @@ -258,6 +266,7 @@ impl Runtime { /// println!("now running on a worker thread"); /// }); /// # } + /// # } /// ``` #[track_caller] pub fn spawn_blocking(&self, func: F) -> JoinHandle @@ -308,7 +317,9 @@ impl Runtime { /// /// # Examples /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// /// // Create the runtime @@ -318,6 +329,7 @@ impl Runtime { /// rt.block_on(async { /// println!("hello"); /// }); + /// # } /// ``` /// /// [handle]: fn@Handle::block_on @@ -371,7 +383,9 @@ impl Runtime { /// /// # Example /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// use tokio::task::JoinHandle; /// @@ -394,6 +408,7 @@ impl Runtime { /// // Wait for the task before we end the test. /// rt.block_on(handle).unwrap(); /// } + /// # } /// ``` pub fn enter(&self) -> EnterGuard<'_> { self.handle.enter() @@ -406,7 +421,9 @@ impl Runtime { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// use tokio::task; /// @@ -425,6 +442,7 @@ impl Runtime { /// /// runtime.shutdown_timeout(Duration::from_millis(100)); /// } + /// # } /// ``` pub fn shutdown_timeout(mut self, duration: Duration) { // Wakeup and shutdown all the worker threads @@ -447,7 +465,9 @@ impl Runtime { /// /// This function is equivalent to calling `shutdown_timeout(Duration::from_nanos(0))`. /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// /// fn main() { @@ -459,6 +479,7 @@ impl Runtime { /// inner_runtime.shutdown_background(); /// }); /// } + /// # } /// ``` pub fn shutdown_background(self) { self.shutdown_timeout(Duration::from_nanos(0)); diff --git a/tokio/src/runtime/task/error.rs b/tokio/src/runtime/task/error.rs index 8a6d5f89789..552b4efd15f 100644 --- a/tokio/src/runtime/task/error.rs +++ b/tokio/src/runtime/task/error.rs @@ -45,7 +45,9 @@ impl JoinError { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::panic; /// /// #[tokio::main] @@ -56,6 +58,7 @@ impl JoinError { /// /// assert!(err.is_panic()); /// } + /// # } /// ``` pub fn is_panic(&self) -> bool { matches!(&self.repr, Repr::Panic(_)) diff --git a/tokio/src/runtime/task/join.rs b/tokio/src/runtime/task/join.rs index 45c293ca25d..f90bc85e37a 100644 --- a/tokio/src/runtime/task/join.rs +++ b/tokio/src/runtime/task/join.rs @@ -105,7 +105,9 @@ cfg_rt! { /// /// If the task panics, the error is a [`JoinError`] that contains the panic: /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::task; /// use std::io; /// use std::panic; @@ -120,7 +122,7 @@ cfg_rt! { /// assert!(err.is_panic()); /// Ok(()) /// } - /// + /// # } /// ``` /// Child being detached and outliving its parent: /// diff --git a/tokio/src/sync/broadcast.rs b/tokio/src/sync/broadcast.rs index 759f22f90a4..86b9c4bedcd 100644 --- a/tokio/src/sync/broadcast.rs +++ b/tokio/src/sync/broadcast.rs @@ -1521,7 +1521,9 @@ impl Receiver { /// context. /// /// # Examples - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::thread; /// use tokio::sync::broadcast; /// @@ -1536,6 +1538,7 @@ impl Receiver { /// let _ = tx.send(10); /// sync_code.join().unwrap(); /// } + /// # } /// ``` pub fn blocking_recv(&mut self) -> Result { crate::future::block_on(self.recv()) diff --git a/tokio/src/sync/mod.rs b/tokio/src/sync/mod.rs index 15b7fb21545..98189c19f63 100644 --- a/tokio/src/sync/mod.rs +++ b/tokio/src/sync/mod.rs @@ -140,7 +140,9 @@ //! **Example:** sending data from many tasks over a single socket using message //! passing. //! -//! ```no_run,ignore-wasm +//! ```no_run +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::io::{self, AsyncWriteExt}; //! use tokio::net::TcpStream; //! use tokio::sync::mpsc; @@ -172,6 +174,7 @@ //! //! Ok(()) //! } +//! # } //! ``` //! //! The [`mpsc`] and [`oneshot`] channels can be combined to provide a request / diff --git a/tokio/src/sync/mpsc/bounded.rs b/tokio/src/sync/mpsc/bounded.rs index 4200420fd6b..2bbffcecb25 100644 --- a/tokio/src/sync/mpsc/bounded.rs +++ b/tokio/src/sync/mpsc/bounded.rs @@ -392,7 +392,9 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::thread; /// use tokio::runtime::Runtime; /// use tokio::sync::mpsc; @@ -411,6 +413,7 @@ impl Receiver { /// }); /// sync_code.join().unwrap() /// } + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] @@ -1013,7 +1016,9 @@ impl Sender { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::thread; /// use tokio::runtime::Runtime; /// use tokio::sync::mpsc; @@ -1030,6 +1035,7 @@ impl Sender { /// }); /// sync_code.join().unwrap() /// } + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] diff --git a/tokio/src/sync/mpsc/unbounded.rs b/tokio/src/sync/mpsc/unbounded.rs index 5cf5d0f1799..add38672e77 100644 --- a/tokio/src/sync/mpsc/unbounded.rs +++ b/tokio/src/sync/mpsc/unbounded.rs @@ -296,7 +296,9 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::thread; /// use tokio::sync::mpsc; /// @@ -311,6 +313,7 @@ impl UnboundedReceiver { /// let _ = tx.send(10); /// sync_code.join().unwrap(); /// } + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] @@ -454,7 +457,9 @@ impl UnboundedReceiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::task::{Context, Poll}; /// use std::pin::Pin; /// use tokio::sync::mpsc; @@ -499,6 +504,7 @@ impl UnboundedReceiver { /// assert_eq!(count, 3); /// assert_eq!(buffer, vec![0,1,2]) /// # } + /// # } /// ``` pub fn poll_recv_many( &mut self, diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index 7bdac0772d1..2c7d807661e 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -483,7 +483,9 @@ impl Mutex { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::sync::Arc; /// use tokio::sync::Mutex; /// @@ -510,7 +512,7 @@ impl Mutex { /// let n = mutex.try_lock().unwrap(); /// assert_eq!(*n, 2); /// } - /// + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] @@ -540,7 +542,9 @@ impl Mutex { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::sync::Arc; /// use tokio::sync::Mutex; /// @@ -567,7 +571,7 @@ impl Mutex { /// let n = mutex.try_lock().unwrap(); /// assert_eq!(*n, 2); /// } - /// + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] diff --git a/tokio/src/sync/rwlock.rs b/tokio/src/sync/rwlock.rs index 4721f40aff0..c8a35db2ad8 100644 --- a/tokio/src/sync/rwlock.rs +++ b/tokio/src/sync/rwlock.rs @@ -488,7 +488,9 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::sync::Arc; /// use tokio::sync::RwLock; /// @@ -515,6 +517,7 @@ impl RwLock { /// // Assert uncontended. /// assert!(rwlock.try_write().is_ok()); /// } + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] @@ -830,7 +833,9 @@ impl RwLock { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::sync::Arc; /// use tokio::{sync::RwLock}; /// @@ -859,6 +864,7 @@ impl RwLock { /// let read_lock = rwlock.try_read().unwrap(); /// assert_eq!(*read_lock, 2); /// } + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")] diff --git a/tokio/src/sync/semaphore.rs b/tokio/src/sync/semaphore.rs index e7a61645f2b..8af5b54e88b 100644 --- a/tokio/src/sync/semaphore.rs +++ b/tokio/src/sync/semaphore.rs @@ -60,7 +60,9 @@ use std::sync::Arc; /// no more than 100 files at a time. When trying to open the 101st /// file, the program will wait until a permit becomes available before /// proceeding to open another file. -/// ```ignore-wasm +/// ``` +/// # #[cfg(not(target_family = "wasm"))] +/// # { /// use std::io::Result; /// use tokio::fs::File; /// use tokio::sync::Semaphore; @@ -74,6 +76,7 @@ use std::sync::Arc; /// buffer.write_all(message).await?; /// Ok(()) // Permit goes out of scope here, and is available again for acquisition /// } +/// # } /// ``` /// /// ## Limit the number of outgoing requests being sent at the same time @@ -143,7 +146,9 @@ use std::sync::Arc; /// [`Semaphore::acquire_owned`] to be movable across the task boundary. /// (Since our semaphore is not a global variable — if it was, then `acquire` would be enough.) /// -/// ```no_run,ignore-wasm +/// ```no_run +/// # #[cfg(not(target_family = "wasm"))] +/// # { /// use std::sync::Arc; /// use tokio::sync::Semaphore; /// use tokio::net::TcpListener; @@ -174,6 +179,7 @@ use std::sync::Arc; /// # async fn handle_connection(_socket: &mut tokio::net::TcpStream) { /// # // Do work /// # } +/// # } /// ``` /// /// ## Prevent tests from running in parallel diff --git a/tokio/src/task/join_set.rs b/tokio/src/task/join_set.rs index 78b3c17ae18..4d11a7b18f3 100644 --- a/tokio/src/task/join_set.rs +++ b/tokio/src/task/join_set.rs @@ -208,7 +208,9 @@ impl JoinSet { /// /// Spawn multiple blocking tasks and wait for them. /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::task::JoinSet; /// /// #[tokio::main] @@ -229,6 +231,7 @@ impl JoinSet { /// assert!(seen[i]); /// } /// } + /// # } /// ``` /// /// # Panics diff --git a/tokio/src/task/local.rs b/tokio/src/task/local.rs index 42ca0f8d043..40f1605336e 100644 --- a/tokio/src/task/local.rs +++ b/tokio/src/task/local.rs @@ -132,7 +132,9 @@ cfg_rt! { /// and communicate with it using an [`mpsc`] channel. /// /// The following example puts the `LocalSet` inside a new thread. - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Builder; /// use tokio::sync::{mpsc, oneshot}; /// use tokio::task::LocalSet; @@ -212,6 +214,7 @@ cfg_rt! { /// let eleven = response.await.unwrap(); /// assert_eq!(eleven, 11); /// } + /// # } /// ``` /// /// [`Send`]: trait@std::marker::Send @@ -625,7 +628,9 @@ impl LocalSet { /// }) /// ``` /// This, however, will not panic: - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::runtime::Runtime; /// use tokio::task; /// @@ -640,6 +645,7 @@ impl LocalSet { /// }); /// join.await.unwrap(); /// }) + /// # } /// ``` /// /// [`spawn_local`]: fn@spawn_local diff --git a/tokio/src/task/mod.rs b/tokio/src/task/mod.rs index fa62858b90a..ebd3a1bcecd 100644 --- a/tokio/src/task/mod.rs +++ b/tokio/src/task/mod.rs @@ -90,7 +90,9 @@ //! task panics, awaiting its `JoinHandle` will return a [`JoinError`]. For //! example: //! -//! ```ignore-wasm +//! ``` +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::task; //! //! # #[tokio::main] async fn main() { @@ -101,6 +103,7 @@ //! // The returned result indicates that the task failed. //! assert!(join.await.is_err()); //! # } +//! # } //! ``` //! //! `spawn`, `JoinHandle`, and `JoinError` are present when the "rt" @@ -221,7 +224,9 @@ //! //! For example: //! -//! ```ignore-wasm +//! ``` +//! # #[cfg(not(target_family = "wasm"))] +//! # { //! use tokio::task; //! //! # async fn docs() { @@ -232,6 +237,7 @@ //! //! assert_eq!(result, "blocking completed"); //! # } +//! # } //! ``` //! //! #### `yield_now` diff --git a/tokio/src/task/spawn.rs b/tokio/src/task/spawn.rs index 7b765078a22..1b219a28f60 100644 --- a/tokio/src/task/spawn.rs +++ b/tokio/src/task/spawn.rs @@ -34,7 +34,9 @@ cfg_rt! { /// In this example, a server is started and `spawn` is used to start a new task /// that processes each received connection. /// - /// ```no_run,ignore-wasm + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use tokio::net::{TcpListener, TcpStream}; /// /// use std::io; @@ -57,6 +59,7 @@ cfg_rt! { /// }); /// } /// } + /// # } /// ``` /// /// To run multiple tasks in parallel and receive their results, join From 6b5c4ee30743c9c02bd03396808022d2071be35b Mon Sep 17 00:00:00 2001 From: Lucas Black Date: Thu, 25 Sep 2025 16:41:07 -0700 Subject: [PATCH 19/19] partially enable `sync::oneshot::Receiver::blocking_recv` test --- tokio/src/sync/oneshot.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tokio/src/sync/oneshot.rs b/tokio/src/sync/oneshot.rs index 06a4bb84e96..a93cea2367d 100644 --- a/tokio/src/sync/oneshot.rs +++ b/tokio/src/sync/oneshot.rs @@ -1188,7 +1188,9 @@ impl Receiver { /// /// # Examples /// - /// ```ignore-wasm + /// ``` + /// # #[cfg(not(target_family = "wasm"))] + /// # { /// use std::thread; /// use tokio::sync::oneshot; /// @@ -1203,6 +1205,7 @@ impl Receiver { /// let _ = tx.send(10); /// sync_code.join().unwrap(); /// } + /// # } /// ``` #[track_caller] #[cfg(feature = "sync")]