### Start a server and process connections concurrently Source: https://docs.rs/tokio/latest/tokio/task/fn.spawn.html This example demonstrates starting a TCP server and using `tokio::spawn` to process each incoming connection in a separate asynchronous task, enabling concurrent handling of multiple clients. ```rust use tokio::net::{TcpListener, TcpStream}; use std::io; async fn process(socket: TcpStream) { // ... } #[tokio::main] async fn main() -> io::Result<()> { let listener = TcpListener::bind("127.0.0.1:8080").await?; loop { let (socket, _) = listener.accept().await?; tokio::spawn(async move { // Process each socket concurrently. process(socket).await }); } } ``` -------------------------------- ### Create a Named Pipe Server Source: https://docs.rs/tokio/latest/src/tokio/net/windows/named_pipe.rs.html Use `ServerOptions::new()` to create a builder and then call `create()` with the pipe name to establish a named pipe server. This example demonstrates the basic setup for a server. ```rust use tokio::net::windows::named_pipe::ServerOptions; const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-new"; #[tokio::main] async fn main() -> std::io::Result<()> { let server = ServerOptions::new().create(PIPE_NAME)?; Ok(()) } ``` -------------------------------- ### Example of using Tokio Task Builder Source: https://docs.rs/tokio/latest/src/tokio/task/builder.rs.html Demonstrates how to create a task builder, set a name for the task, and spawn an asynchronous task to handle TCP connections concurrently. This example requires a Tokio runtime. ```rust use tokio::net::{TcpListener, TcpStream}; use std::io; async fn process(socket: TcpStream) { // ... # drop(socket); } #[tokio::main] async fn main() -> io::Result<()> { let listener = TcpListener::bind("127.0.0.1:8080").await?; loop { let (socket, _) = listener.accept().await?; tokio::task::Builder::new() .name("tcp connection handler") .spawn(async move { // Process each socket concurrently. process(socket).await })?; } } ``` -------------------------------- ### UnixSocket::connect Example Source: https://docs.rs/tokio/latest/src/tokio/net/unix/socket.rs.html This example demonstrates how to use `UnixSocket::new_stream` to create a Unix socket and then connect it to a specified path, equivalent to `UnixStream::connect`. ```rust use tokio::net::UnixSocket; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("bind_path"); let socket = UnixSocket::new_stream()?; let stream = socket.connect(path).await?; Ok(()) } ``` -------------------------------- ### Example: Create Sender from File Source: https://docs.rs/tokio/latest/src/tokio/net/unix/pipe.rs.html Demonstrates creating a `Sender` from a `File` opened with write access and non-blocking mode, after checking if it's a FIFO. This example requires a running Tokio runtime. ```rust use tokio::net::unix::pipe; use std::fs::OpenOptions; use std::os::unix::fs::{FileTypeExt, OpenOptionsExt}; # use std::error::Error; const FIFO_NAME: &str = "path/to/a/fifo"; # async fn dox() -> Result<(), Box> { let file = OpenOptions::new() .write(true) .custom_flags(libc::O_NONBLOCK) .open(FIFO_NAME)?; if file.metadata()?.file_type().is_fifo() { let tx = pipe::Sender::from_file_unchecked(file)?; /* use the Sender */ } # Ok(()) # } ``` -------------------------------- ### Stdout Usage Example Source: https://docs.rs/tokio/latest/tokio/io/struct.Stdout.html This example demonstrates how to write to standard output using the `Stdout` handle. ```APIDOC ## Stdout ### Description A handle to the standard output stream of a process. Concurrent writes to stdout must be executed with care: Only individual writes to this `AsyncWrite` are guaranteed to be intact. In particular you should be aware that writes using `write_all` are not guaranteed to occur as a single write, so multiple threads writing data with `write_all` may result in interleaved output. Created by the `stdout` function. ### Examples ```rust use tokio::io::{self, AsyncWriteExt}; #[tokio::main] async fn main() -> io::Result<()> { let mut stdout = io::stdout(); stdout.write_all(b"Hello world!").await?; Ok(()) } ``` ### Example with Loop ```rust use tokio::io::{self, AsyncWriteExt}; #[tokio::main] async fn main() { let messages = vec!["hello", " world\n"]; // When you use `stdio` in a loop, it is recommended to create // a single `stdio` instance outside the loop and call a write // operation against that instance on each loop. // // Repeatedly creating `stdout` instances inside the loop and // writing to that handle could result in mangled output since // each write operation is handled by a different blocking thread. let mut stdout = io::stdout(); for message in &messages { stdout.write_all(message.as_bytes()).await.unwrap(); stdout.flush().await.unwrap(); } } ``` ### Trait Implementations #### `impl AsyncWrite for Stdout` ##### `fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll>` Attempt to write bytes from `buf` into the object. Read more ##### `fn poll_flush( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll>` Attempts to flush the object, ensuring that any buffered data reach their destination. Read more ##### `fn poll_shutdown( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll>` Initiates or attempts to shut down this writer, returning success when the I/O connection has completely shut down. Read more ##### `fn poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>], ) -> Poll>` Like `poll_write`, except that it writes from a slice of buffers. Read more ##### `fn is_write_vectored(&self) -> bool` Determines if this writer has an efficient `poll_write_vectored` implementation. Read more ``` -------------------------------- ### Task Tracing Example Source: https://docs.rs/tokio/latest/src/tokio/runtime/handle.rs.html This example demonstrates how to obtain and print detailed traces of tasks running on the Tokio runtime. Ensure debug info is available and the `taskdump` feature is enabled. ```rust let rt = tokio::runtime::Builder::new_multi_thread() .enable_time() .enable_io() .build() .unwrap(); rt.block_on(async { let mut tasks = Vec::new(); for i in 0..3 { let task = tokio::spawn(async move { // Simulate some work tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; // This inner closure is just to create a deeper call stack // for demonstration purposes. let _ = std::future::ready(()).await; }); tasks.push(task); } // Wait for all tasks to complete for task in tasks { task.await.unwrap(); } // Dump the runtime's tasks let dump = tokio::runtime::Handle::current().dump().await; for (i, task) in dump.tasks.iter().enumerate() { let trace = task.trace(); println!("TASK {i}:"); println!("{trace}\n"); } }); ``` -------------------------------- ### Example Task Trace Output Source: https://docs.rs/tokio/latest/tokio/runtime/struct.Handle.html This is an example of the detailed traces that can be produced for tasks within the Tokio runtime. ```text TASK 0: ╼ dump::main::{{closure}}::a::{{closure}} at /tokio/examples/dump.rs:18:20 └╼ dump::main::{{closure}}::b::{{closure}} at /tokio/examples/dump.rs:23:20 └╼ dump::main::{{closure}}::c::{{closure}} at /tokio/examples/dump.rs:28:24 └╼ tokio::sync::barrier::Barrier::wait::{{closure}} at /tokio/tokio/src/sync/barrier.rs:129:10 └╼ as core::future::future::Future>::poll at /tokio/tokio/src/util/trace.rs:77:46 └╼ tokio::sync::barrier::Barrier::wait_internal::{{closure}} at /tokio/tokio/src/sync/barrier.rs:183:36 └╼ tokio::sync::watch::Receiver::changed::{{closure}} at /tokio/tokio/src/sync/watch.rs:604:55 └╼ tokio::sync::watch::changed_impl::{{closure}} at /tokio/tokio/src/sync/watch.rs:755:18 └╼ ::poll at /tokio/tokio/src/sync/notify.rs:1103:9 └╼ tokio::sync::notify::Notified::poll_notified at /tokio/tokio/src/sync/notify.rs:996:32 ``` -------------------------------- ### AsyncSeekExt Example: Seeking with File Source: https://docs.rs/tokio/latest/src/tokio/io/util/async_seek_ext.rs.html Shows how to use the `seek` method with a Tokio `File` to move to a specific byte offset. This example is marked with `no_run` as it requires a file to exist. ```rust use tokio::fs::File; use tokio::io::{AsyncSeekExt, AsyncReadExt}; use std::io::SeekFrom; # async fn dox() -> std::io::Result<()> { let mut file = File::open("foo.txt").await?; file.seek(SeekFrom::Start(6)).await?; let mut contents = vec![0u8; 10]; file.read_exact(&mut contents).await?; # Ok(()) # } ``` -------------------------------- ### build Source: https://docs.rs/tokio/latest/src/tokio/runtime/builder.rs.html Creates the configured `Runtime` instance, ready to spawn tasks. ```APIDOC ## build ### Description Creates the configured `Runtime` instance. The returned `Runtime` instance is ready to spawn tasks. ### Signature ```rust pub fn build(&mut self) -> io::Result ``` ### Returns A `Result` containing the configured `Runtime` on success, or an `io::Error` on failure. ``` -------------------------------- ### Get Current Instant Source: https://docs.rs/tokio/latest/src/tokio/time/instant.rs.html Use `Instant::now()` to get the current time. This is useful for starting timers or marking points in time. ```rust use tokio::time::Instant; let now = Instant::now(); ``` -------------------------------- ### Example: Get Worker Park Count Source: https://docs.rs/tokio/latest/src/tokio/runtime/metrics/runtime.rs.html Demonstrates how to get the park count for worker 0 using the runtime's Handle. Ensure the runtime is running to access current metrics. ```rust use tokio::runtime::Handle; # #[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); # } ``` -------------------------------- ### Opening a file with specific options Source: https://docs.rs/tokio/latest/tokio/fs/struct.OpenOptions.html This example demonstrates how to use `OpenOptions` to configure file opening behavior, such as enabling write access, creating the file if it doesn't exist, and setting security quality of service flags. ```APIDOC ## OpenOptions::new() ### Description Creates a new `OpenOptions` instance with default settings. ### Method `new()` ### Example ```rust use tokio::fs::OpenOptions; let mut options = OpenOptions::new(); ``` ## OpenOptions::write() ### Description Enables write access to the file. ### Method `write(true)` ### Example ```rust use tokio::fs::OpenOptions; let file = OpenOptions::new().write(true).open("path/to/file").await?; ``` ## OpenOptions::create() ### Description Creates the file if it does not exist. ### Method `create(true)` ### Example ```rust use tokio::fs::OpenOptions; let file = OpenOptions::new().create(true).open("path/to/file").await?; ``` ## OpenOptions::security_qos_flags() ### Description Sets the security quality of service flags for the file. ### Parameters #### Path Parameters - **flags** (u32) - Required - The security QoS flags to set. ### Example ```rust use windows_sys::Win32::Storage::FileSystem::SECURITY_IDENTIFICATION; use tokio::fs::OpenOptions; let file = OpenOptions::new() .write(true) .create(true) .security_qos_flags(SECURITY_IDENTIFICATION) .open(r"\\.\pipe\MyPipe").await?; ``` ## OpenOptions::open() ### Description Opens a file with the configured options. ### Parameters #### Path Parameters - **path** (&str) - Required - The path to the file. ### Example ```rust use tokio::fs::OpenOptions; let file = OpenOptions::new().open("path/to/file").await?; ``` ``` -------------------------------- ### Get Receiver Count in Tokio Watch Channel Source: https://docs.rs/tokio/latest/src/tokio/sync/watch.rs.html This example shows how to use `receiver_count()` to get the current number of active receivers for a watch channel. It demonstrates incrementing the count when a new receiver is cloned. ```rust use tokio::sync::watch; # #[tokio::main(flavor = "current_thread")] # async fn main() { let (tx, rx1) = watch::channel("hello"); assert_eq!(1, tx.receiver_count()); let mut _rx2 = rx1.clone(); assert_eq!(2, tx.receiver_count()); # } ``` -------------------------------- ### SimplexStream example Source: https://docs.rs/tokio/latest/src/tokio/io/util/mem.rs.html Demonstrates creating a `SimplexStream`, splitting it into reader and writer halves, and then using them to send and receive data. It shows how to write data using `write_all` and read data using `read_exact`. ```rust # async fn ex() -> std::io::Result<()> { # use tokio::io::{AsyncReadExt, AsyncWriteExt}; let (reader, writer) = tokio::io::simplex(64); let mut simplex_stream = reader.unsplit(writer); simplex_stream.write_all(b"hello").await?; let mut buf = [0u8; 5]; simplex_stream.read_exact(&mut buf).await?; assert_eq!(&buf, b"hello"); # Ok(()) # } ``` -------------------------------- ### Get Symbol Address - BacktraceFrame Source: https://docs.rs/tokio/latest/tokio/runtime/dump/struct.BacktraceFrame.html Returns the starting address of the symbol for the function associated with this backtrace frame. ```rust pub fn symbol_address(&self) -> *mut c_void ``` -------------------------------- ### Create Named Pipe Client Example Source: https://docs.rs/tokio/latest/src/tokio/net/windows/named_pipe.rs.html Demonstrates creating a named pipe client using `ClientOptions::new()` and `open()`. This requires a server to be created first for the client connection to succeed. ```rust /// ``` /// use tokio::net::windows::named_pipe::{ServerOptions, ClientOptions}; /// /// const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-new"; /// /// # #[tokio::main] async fn main() -> std::io::Result<()> { /// // Server must be created in order for the client creation to succeed. /// let server = ServerOptions::new().create(PIPE_NAME)?; /// let client = ClientOptions::new().open(PIPE_NAME)?; /// # Ok(()) /// # } /// ``` ``` -------------------------------- ### Enable All Tokio Features Source: https://docs.rs/tokio/latest/index.html This is the quickest way to get started with Tokio by enabling all feature flags. Recommended for applications. ```toml tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Tokio Named Pipe Server Example Source: https://docs.rs/tokio/latest/src/tokio/net/windows/named_pipe.rs.html This example demonstrates setting up a Tokio named pipe server that continuously listens for and handles readable and writable events. It shows how to create a server, wait for readiness, and use `try_read` and `try_write` with error handling for `WouldBlock`. ```rust use std::error::Error; use std::io; const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-server-ready"; #[tokio::main] async fn main() -> Result<(), Box> { let server = named_pipe::ServerOptions::new() .create(PIPE_NAME)?; loop { let ready = server.ready(Interest::READABLE | Interest::WRITABLE).await?; if ready.is_readable() { let mut data = vec![0; 1024]; // Try to read data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match server.try_read(&mut data) { Ok(n) => { println!("read {} bytes", n); } Err(e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e.into()); } } } if ready.is_writable() { // Try to write data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match server.try_write(b"hello world") { Ok(n) => { println!("write {} bytes", n); } Err(e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e.into()); } } } } } ``` -------------------------------- ### Equivalent Code Without `#[tokio::test]` (Start Paused) Source: https://docs.rs/tokio/latest/tokio/attr.test.html Shows the manual setup for a runtime that starts with time paused, using `tokio::runtime::Builder::start_paused(true)`, as an alternative to `#[tokio::test(start_paused = true)]`. ```rust #[test] fn my_test() { tokio::runtime::Builder::new_current_thread() .enable_all() .start_paused(true) .build() .unwrap() .block_on(async { assert!(true); }) } ``` -------------------------------- ### Static Initialization with SetOnce::const_new Source: https://docs.rs/tokio/latest/tokio/sync/struct.SetOnce.html Shows how to use `SetOnce::const_new` for static variables. This example demonstrates setting a value and retrieving it, handling potential errors. ```rust use tokio::sync::{SetOnce, SetOnceError}; static ONCE: SetOnce = SetOnce::const_new(); fn get_global_integer() -> Result, SetOnceError> { ONCE.set(2)?; Ok(ONCE.get()) } let result = get_global_integer()?; assert_eq!(result, Some(&2)); Ok(()) ``` -------------------------------- ### Get Start Time (Test Helper) Source: https://docs.rs/tokio/latest/src/tokio/runtime/time/source.rs.html A helper function, available only in test configurations, to retrieve the `Instant` at which the `TimeSource` was initialized. ```rust #[cfg(test)] #[allow(dead_code)] pub(super) fn start_time(&self) -> Instant { self.start_time } ``` -------------------------------- ### Example: Peeking and Reading Data from TcpStream Source: https://docs.rs/tokio/latest/src/tokio/net/tcp/split.rs.html Demonstrates how to connect to a peer, split the stream, peek at incoming data using `ReadHalf::peek`, and then read the same data using `AsyncReadExt::read` to verify. ```rust use tokio::net::TcpStream; use tokio::io::AsyncReadExt; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { // Connect to a peer let mut stream = TcpStream::connect("127.0.0.1:8080").await?; let (mut read_half, _) = stream.split(); let mut b1 = [0; 10]; let mut b2 = [0; 10]; // Peek at the data let n = read_half.peek(&mut b1).await?; // Read the data assert_eq!(n, read_half.read(&mut b2[..n]).await?); assert_eq!(&b1[..n], &b2[..n]); Ok(()) } ``` -------------------------------- ### Reading lines from AsyncBufRead Source: https://docs.rs/tokio/latest/tokio/io/struct.Lines.html Iterates over lines from an AsyncBufRead. This example demonstrates how to use the `lines()` method to get an iterator over lines and process them. ```rust use tokio::io::AsyncBufReadExt; let mut lines = my_buf_read.lines(); while let Some(line) = lines.next_line().await? { println!("length = {}", line.len()) } ``` -------------------------------- ### MutexGuard::mutex Example Source: https://docs.rs/tokio/latest/src/tokio/sync/mutex.rs.html Use `MutexGuard::mutex` to get a reference to the original `Mutex` from a `MutexGuard`. This allows unlocking and relocking the mutex. ```rust use tokio::sync::{Mutex, MutexGuard}; async fn unlock_and_relock<'l>(guard: MutexGuard<'l, u32>) -> MutexGuard<'l, u32> { println!("1. contains: {:?}", *guard); let mutex = MutexGuard::mutex(&guard); drop(guard); let guard = mutex.lock().await; println!("2. contains: {:?}", *guard); guard } # # #[tokio::main(flavor = "current_thread")] # async fn main() { ``` -------------------------------- ### OpenOptions::new Source: https://docs.rs/tokio/latest/tokio/fs/struct.OpenOptions.html Creates a new `OpenOptions` instance with default settings. ```APIDOC ## OpenOptions::new ### Description Creates a new `OpenOptions` instance with default settings. ### Method `OpenOptions::new()` ### Example ```rust use tokio::fs::OpenOptions; let mut options = OpenOptions::new(); ``` ``` -------------------------------- ### Get Bucket Range (Linear) Source: https://docs.rs/tokio/latest/src/tokio/runtime/metrics/histogram.rs.html Calculates the start and end range for a given bucket in a linear histogram. The last bucket extends to `u64::MAX`. ```rust HistogramType::Linear(LinearHistogram { num_buckets, bucket_width, }) => Range { start: bucket_width * bucket as u64, end: if bucket == num_buckets - 1 { u64::MAX } else { ``` -------------------------------- ### Bind and Accept TCP Connections Source: https://docs.rs/tokio/latest/src/tokio/net/tcp/listener.rs.html This example demonstrates how to bind a `TcpListener` to an address and then enter a loop to continuously accept incoming connections. Each accepted connection is processed asynchronously. ```rust use tokio::net::TcpListener; use std::io; async fn process_socket(socket: T) { # drop(socket); // do work with socket here } #[tokio::main] async fn main() -> io::Result<()> { let listener = TcpListener::bind("127.0.0.1:8080").await?; loop { let (socket, _) = listener.accept().await?; process_socket(socket).await; } } ``` -------------------------------- ### Get Worker Thread ID Source: https://docs.rs/tokio/latest/tokio/runtime/struct.RuntimeMetrics.html Retrieve the `ThreadId` of a specific worker thread. Returns `None` if the worker thread has not yet finished starting up. This metric is only available on `tokio_unstable`. ```rust use tokio::runtime::Handle; let metrics = Handle::current().metrics(); let id = metrics.worker_thread_id(0); println!("worker 0 has id {:?}", id); ``` -------------------------------- ### Example: Receive Data with UdpSocket Source: https://docs.rs/tokio/latest/src/tokio/net/udp.rs.html Demonstrates how to bind a UDP socket, connect to a peer, wait for read readiness, and attempt to receive data. Handles `WouldBlock` errors by continuing the loop. ```rust use tokio::net::UdpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { // Connect to a peer let socket = UdpSocket::bind("127.0.0.1:8080").await?; socket.connect("127.0.0.1:8081").await?; loop { // Wait for the socket to be readable socket.readable().await?; // The buffer is **not** included in the async task and will // only exist on the stack. let mut buf = [0; 1024]; // Try to recv data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match socket.try_recv(&mut buf) { Ok(n) => { println!("GOT {:?}", &buf[..n]); break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e); } } } Ok(()) } ``` -------------------------------- ### Get Spawned Tasks Count Source: https://docs.rs/tokio/latest/src/tokio/runtime/scheduler/multi_thread/handle/metrics.rs.html Returns the total count of tasks that have been spawned since the runtime started. This metric is available when the `unstable-metrics` and `64bit-metrics` feature flags are enabled. ```rust pub(crate) fn spawned_tasks_count(&self) -> u64 { self.shared.owned.spawned_tasks_count() } ``` -------------------------------- ### Example: Get Worker Park/Unpark Count Source: https://docs.rs/tokio/latest/src/tokio/runtime/metrics/runtime.rs.html Shows how to retrieve the park/unpark count for worker 0 and determine if the worker is currently active or parked based on the count's parity. ```rust use tokio::runtime::Handle; # #[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); if n % 2 == 0 { println!("worker 0 is active"); } else { println!("worker 0 is parked"); } # } ``` -------------------------------- ### Create a pipe and pass the writing end to a spawned process Source: https://docs.rs/tokio/latest/tokio/net/unix/pipe/fn.pipe.html This example demonstrates creating a pipe, writing to it using `Command::stdout`, and reading from it. Ensure the code is run within a Tokio runtime with IO enabled. ```rust use tokio::net::unix::pipe; use tokio::process::Command; let (tx, mut rx) = pipe::pipe()?; let mut buffer = String::new(); let status = Command::new("echo") .arg("Hello, world!") .stdout(tx.into_blocking_fd()?) .status(); rx.read_to_string(&mut buffer).await?; assert!(status.await?.success()); assert_eq!(buffer, "Hello, world!\n"); ``` -------------------------------- ### Get Worker Local Schedule Count Source: https://docs.rs/tokio/latest/tokio/runtime/struct.RuntimeMetrics.html Retrieve the number of tasks scheduled from within the runtime on a specific worker's local queue. This metric is monotonically increasing and starts at zero. ```rust use tokio::runtime::Handle; let metrics = Handle::current().metrics(); let n = metrics.worker_local_schedule_count(0); println!("{} tasks were scheduled on the worker's local queue", n); ``` -------------------------------- ### Example: Safely extracting panic reason Source: https://docs.rs/tokio/latest/src/tokio/runtime/task/error.rs.html Shows how to use `try_into_panic` to safely get the panic reason from a `JoinError`. If the error is a panic, the reason is unwound; otherwise, the original error is returned. ```rust use std::panic; #[tokio::main] async fn main() { let err = tokio::spawn(async { panic!("boom"); }).await.unwrap_err(); if let Ok(reason) = err.try_into_panic() { // Resume the panic on the main task panic::resume_unwind(reason); } } ``` -------------------------------- ### Take Source: https://docs.rs/tokio/latest/tokio/fs/struct.File.html Creates an adaptor which reads at most `limit` bytes from it. Requires the `io-util` crate feature. ```APIDOC ## fn take(self, limit: u64) -> Take ### Description Creates an adaptor which reads at most `limit` bytes from it. ### Parameters - `limit` (u64): The maximum number of bytes to read. ### Constraints - `Self` must implement `Sized`. - Available on `crate feature`io-util` only. ### Returns A `Take` adaptor that limits the number of bytes read from the underlying reader. ``` -------------------------------- ### Get Sender Count in Tokio Watch Channel Source: https://docs.rs/tokio/latest/src/tokio/sync/watch.rs.html This example demonstrates using `sender_count()` to retrieve the number of active senders associated with a watch channel. It shows that cloning a sender increases this count. ```rust use tokio::sync::watch; # #[tokio::main(flavor = "current_thread")] # async fn main() { let (tx1, rx) = watch::channel("hello"); assert_eq!(1, tx1.sender_count()); let tx2 = tx1.clone(); assert_eq!(2, tx1.sender_count()); # } ``` -------------------------------- ### Take Source: https://docs.rs/tokio/latest/tokio/io/struct.Stdin.html Creates an adaptor which reads at most `limit` bytes from it. Requires the `io-util` crate feature. ```APIDOC ## fn take(self, limit: u64) -> Take ### Description Creates an adaptor which reads at most `limit` bytes from it. ### Parameters - `self`: The reader to adapt. - `limit`: The maximum number of bytes to read. ### Returns A `Take` adaptor that limits the number of bytes read. ``` -------------------------------- ### Example: Reading a file into a String Source: https://docs.rs/tokio/latest/src/tokio/io/util/async_read_ext.rs.html Demonstrates how to open a file and read its entire content into a String using `read_to_string`. Ensure the file exists and is accessible. ```rust # #[cfg(not(target_family = "wasm"))] # { use tokio::io::{self, AsyncReadExt}; use tokio::fs::File; #[tokio::main] async fn main() -> io::Result<()> { let mut f = File::open("foo.txt").await?; let mut buffer = String::new(); f.read_to_string(&mut buffer).await?; Ok(()) } # } ``` -------------------------------- ### Iterate Through Directory Entries and Get File Type Source: https://docs.rs/tokio/latest/src/tokio/fs/read_dir.rs.html This example demonstrates how to asynchronously read a directory, iterate through its entries, and determine the file type for each entry. It handles potential errors when retrieving file types. ```rust use tokio::fs; # async fn dox() -> std::io::Result<()> { let mut entries = fs::read_dir(".").await?; while let Some(entry) = entries.next_entry().await? { if let Ok(file_type) = entry.file_type().await { // Now let's show our entry's file type! println!("{:?}: {:?}", entry.path(), file_type); } else { println!("Couldn't get file type for {:?}", entry.path()); } } # Ok(()) # } ``` -------------------------------- ### Bind and Accept Unix Connections Source: https://docs.rs/tokio/latest/src/tokio/net/unix/listener.rs.html Demonstrates how to bind a UnixListener to a path and continuously accept incoming connections in a loop. Errors during acceptance are handled. ```rust use tokio::net::UnixListener; #[tokio::main] async fn main() { let listener = UnixListener::bind("/path/to/the/socket").unwrap(); loop { match listener.accept().await { Ok((stream, _addr)) => { println!("new client!"); } Err(e) => { /* connection failed */ } } } } ``` -------------------------------- ### Writing Data to a UnixStream Source: https://docs.rs/tokio/latest/src/tokio/net/unix/stream.rs.html Connects to a UnixStream and writes 'hello world' to it. This example demonstrates waiting for the stream to be writable and then attempting to write data, handling potential `WouldBlock` errors. ```rust use tokio::net::UnixStream; use std::error::Error; use std::io; #[tokio::main] async fn main() -> Result<(), Box> { // Connect to a peer let dir = tempfile::tempdir().unwrap(); let bind_path = dir.path().join("bind_path"); let stream = UnixStream::connect(bind_path).await?; loop { // Wait for the socket to be writable stream.writable().await?; // Try to write data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match stream.try_write(b"hello world") { Ok(n) => { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e.into()); } } } Ok(()) } ``` -------------------------------- ### Delay MissedTickBehavior Example Source: https://docs.rs/tokio/latest/tokio/time/enum.MissedTickBehavior.html Demonstrates the Delay behavior where subsequent ticks are scheduled at a regular `period` from the time `tick` was called, rather than from the initial start time. This ensures a consistent delay between ticks after a missed one. ```rust use tokio::time::{interval, Duration, MissedTickBehavior}; let mut interval = interval(Duration::from_millis(50)); interval.set_missed_tick_behavior(MissedTickBehavior::Delay); task_that_takes_more_than_50_millis().await; // The `Interval` has missed a tick // Since we have exceeded our timeout, this will resolve immediately interval.tick().await; // But this one, rather than also resolving immediately, as might happen // with the `Burst` or `Skip` behaviors, will not resolve until // 50ms after the call to `tick` up above. That is, in `tick`, when we // recognize that we missed a tick, we schedule the next tick to happen // 50ms (or whatever the `period` is) from right then, not from when // were *supposed* to tick interval.tick().await; ``` -------------------------------- ### Subscribe to Tokio Watch Channel Updates Source: https://docs.rs/tokio/latest/src/tokio/sync/watch.rs.html This example shows how to create a new receiver using `subscribe()` and receive the latest value. It also demonstrates sending a new value and verifying that the new receiver gets it. ```rust use tokio::sync::watch; # #[tokio::main(flavor = "current_thread")] # async fn main() { let (tx, _rx) = watch::channel(0u64); tx.send(5).unwrap(); let rx = tx.subscribe(); assert_eq!(5, *rx.borrow()); tx.send(10).unwrap(); assert_eq!(10, *rx.borrow()); # } ``` -------------------------------- ### Spawn and Wait for Child Processes Source: https://docs.rs/tokio/latest/tokio/process/index.html This example shows how to spawn multiple child processes, wait for them to complete, and assert their success and output. It requires the `join!` macro from Tokio. ```rust tokio::spawn(async move { let mut echo = Command::new("echo"); echo.arg("HELLO WORLD!"); echo.spawn().expect("failed to spawn echo"); }); let mut tr = Command::new("tr"); tr.arg("a-z").arg("A-Z"); let mut tr = tr.spawn().expect("failed to spawn tr"); let (echo_result, tr_output) = join!(echo.wait(), tr.wait_with_output()); assert!(echo_result.unwrap().success()); let tr_output = tr_output.expect("failed to await tr"); assert!(tr_output.status.success()); assert_eq!(tr_output.stdout, b"HELLO WORLD!\n"); Ok(()) } ``` -------------------------------- ### Equivalent Code without tokio::main (Start Paused) Source: https://docs.rs/tokio/latest/tokio/attr.main.html This shows the manual setup for a current-thread Tokio runtime with `start_paused` enabled, equivalent to `#[tokio::main(flavor = "current_thread", start_paused = true)]`. ```rust fn main() { tokio::runtime::Builder::new_current_thread() .enable_all() .start_paused(true) .build() .unwrap() .block_on(async { println!("Hello world"); }) } ``` -------------------------------- ### Example of using on_task_terminate callback Source: https://docs.rs/tokio/latest/src/tokio/runtime/builder.rs.html Demonstrates setting up a runtime with a task termination callback and spawning a task. ```rust # use tokio::runtime; # pub fn main() { let runtime = runtime::Builder::new_current_thread() .on_task_terminate(|_| { println!("killing task"); }) .build() .unwrap(); runtime.block_on(async { tokio::task::spawn(std::future::ready(())); for _ in 0..64 { tokio::task::yield_now().await; } }) # } ``` -------------------------------- ### Get Worker Thread ID Source: https://docs.rs/tokio/latest/src/tokio/runtime/metrics/runtime.rs.html Retrieves the thread ID for a specific worker thread. The returned value is `None` if the worker thread has not yet finished starting up. This can be used to correlate runtime threads with native thread information. ```rust /// use tokio::runtime::Handle; /// /// # #[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); /// # } /// ``` ``` -------------------------------- ### Get worker index within a spawned task Source: https://docs.rs/tokio/latest/tokio/runtime/fn.worker_index.html This example demonstrates how to obtain the worker index from within a task spawned on a multi-threaded Tokio runtime. The `worker_index()` function is called inside the async block passed to `tokio::spawn`. ```rust #[tokio::main(flavor = "multi_thread", worker_threads = 4)] async fn main() { let index = tokio::spawn(async { tokio::runtime::worker_index() }).await.unwrap(); println!("Task ran on worker {:?}", index); } ``` -------------------------------- ### Open File with Create Option Source: https://docs.rs/tokio/latest/src/tokio/fs/open_options.rs.html Use `OpenOptions` to open a file, creating it if it does not exist. Requires `write` or `append` access. ```rust /// ```no_run /// use tokio::fs::OpenOptions; /// use std::io; /// /// #[tokio::main] /// async fn main() -> io::Result<()> { /// let file = OpenOptions::new() /// .write(true) /// .create(true) /// .open("foo.txt") /// .await?; /// /// Ok(()) /// } /// ``` ``` -------------------------------- ### Direct Runtime Instance Usage Source: https://docs.rs/tokio/latest/src/tokio/runtime/mod.rs.html This example shows how to create and use a Tokio `Runtime` instance directly, rather than relying on the `tokio::main` macro. This approach offers more control over runtime configuration and lifecycle. ```rust use tokio::net::TcpListener; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::runtime::Runtime; ``` -------------------------------- ### Start Polling Task Source: https://docs.rs/tokio/latest/src/tokio/runtime/metrics/batch.rs.html Records the start of polling an individual task. In the unstable variant, it also records the start time for poll duration measurement. ```APIDOC ## start_poll ### Description Records the start of polling an individual task. In the unstable variant, it also records the start time for poll duration measurement. ### Method `start_poll(&mut self)` ### Parameters None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Example: Spawning and Joining Blocking Tasks Source: https://docs.rs/tokio/latest/src/tokio/task/join_set.rs.html Demonstrates spawning multiple blocking tasks using `spawn_blocking` and awaiting their results using `join_next`. ```rust # #[cfg(not(target_family = "wasm"))] # { use tokio::task::JoinSet; #[tokio::main] async fn main() { let mut set = JoinSet::new(); 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; } for i in 0..10 { assert!(seen[i]); } } # } ``` -------------------------------- ### Builder::on_thread_start Source: https://docs.rs/tokio/latest/tokio/runtime/struct.Builder.html Executes a function after each thread is started but before it starts doing work. ```APIDOC ## Builder::on_thread_start ### Description Executes function `f` after each thread is started but before it starts doing work. This is intended for bookkeeping and monitoring use cases. ### Example ```rust use tokio::runtime; let runtime = runtime::Builder::new_multi_thread() .on_thread_start(|| { println!("thread started"); }) .build(); ``` ``` -------------------------------- ### Get reference to underlying writer Source: https://docs.rs/tokio/latest/tokio/io/struct.BufWriter.html Gets a reference to the underlying writer. ```rust pub fn get_ref(&self) -> &W ``` -------------------------------- ### Getting a Cloned Task-Local Value with `get` Source: https://docs.rs/tokio/latest/src/tokio/task/task_local.rs.html Use `get` to retrieve a cloned copy of the task-local value. This requires the task-local type `T` to implement `Clone`. Panics if the value is not set. ```rust pub fn get(&'static self) -> T { self.with(|v| v.clone()) } ``` -------------------------------- ### TokenBucket example using Semaphore Source: https://docs.rs/tokio/latest/src/tokio/sync/semaphore.rs.html Demonstrates the usage of a `TokenBucket` which internally uses a `Semaphore` to limit the rate of operations. This example acquires permits from the bucket to perform operations, ensuring that the rate does not exceed the bucket's capacity. ```rust 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; // do the operation } ``` -------------------------------- ### Driver::new Source: https://docs.rs/tokio/latest/src/tokio/runtime/driver.rs.html Creates a new Driver and Handle, initializing the necessary sub-drivers based on configuration. ```APIDOC ## new ### Description Creates a new `Driver` and `Handle` by initializing the IO, signal, and time drivers based on the provided configuration. ### Signature ```rust pub(crate) fn new(cfg: Cfg) -> io::Result<(Self, Handle)> ``` ### Parameters * `cfg` (Cfg) - Configuration options for the runtime drivers. ``` -------------------------------- ### Start Processing Scheduled Tasks Source: https://docs.rs/tokio/latest/src/tokio/runtime/metrics/batch.rs.html Records the start time for processing a batch of scheduled tasks. ```APIDOC ## start_processing_scheduled_tasks ### Description Records the start time for processing a batch of scheduled tasks. ### Method `start_processing_scheduled_tasks(&mut self)` ### Parameters None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Tokio Main Attribute Macro Example Source: https://docs.rs/tokio/latest/src/tokio/runtime/mod.rs.html This example demonstrates the basic usage of the `tokio::main` attribute macro to set up an asynchronous TCP server. It binds to a port, accepts incoming connections, and spawns a new task for each connection to handle reading and writing data. ```rust use tokio::net::TcpListener; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[tokio::main] async fn main() -> Result<(), Box> { let listener = TcpListener::bind("127.0.0.1:8080").await?; loop { let (mut socket, _) = listener.accept().await?; tokio::spawn(async move { let mut buf = [0; 1024]; // In a loop, read data from the socket and write the data back. loop { let n = match socket.read(&mut buf).await { // socket closed Ok(0) => return, Ok(n) => n, Err(e) => { println!("failed to read from socket; err = {:?}", e); return; } }; // Write the data back if let Err(e) = socket.write_all(&buf[0..n]).await { println!("failed to write to socket; err = {:?}", e); return; } } }); } } ``` -------------------------------- ### Start processing scheduled tasks Source: https://docs.rs/tokio/latest/src/tokio/runtime/metrics/batch.rs.html Records the start time for processing a batch of scheduled tasks. ```rust /// Start processing a batch of tasks pub(crate) fn start_processing_scheduled_tasks(&mut self) { self.processing_scheduled_tasks_started_at = now(); } ``` -------------------------------- ### get_or_try_init Source: https://docs.rs/tokio/latest/tokio/sync/struct.OnceCell.html Gets the value currently in the `OnceCell`, or initialize it with the given asynchronous operation. If some other task is currently working on initializing the `OnceCell`, this call will wait for that other task to finish, then return the value that the other task produced. If the provided operation returns an error, is cancelled or panics, the initialization attempt is cancelled. If there are other tasks waiting for the value to be initialized, one of them will start another attempt at initializing the value. This will deadlock if `f` tries to initialize the cell recursively. ```APIDOC ## pub async fn get_or_try_init(&self, f: F) -> Result<&T, E> ### Description Gets the value currently in the `OnceCell`, or initialize it with the given asynchronous operation. If some other task is currently working on initializing the `OnceCell`, this call will wait for that other task to finish, then return the value that the other task produced. If the provided operation returns an error, is cancelled or panics, the initialization attempt is cancelled. If there are other tasks waiting for the value to be initialized, one of them will start another attempt at initializing the value. This will deadlock if `f` tries to initialize the cell recursively. ### Parameters #### Closure `f` - `f`: A closure that returns a `Future` which resolves to `Result`. ``` -------------------------------- ### Example: Reading from empty Source: https://docs.rs/tokio/latest/tokio/io/fn.empty.html Demonstrates reading from an empty asynchronous source, showing that the buffer remains empty. ```APIDOC ## §Examples A slightly sad example of not reading anything into a buffer: ```rust use tokio::io::{self, AsyncReadExt}; let mut buffer = String::new(); io::empty().read_to_string(&mut buffer).await.unwrap(); assert!(buffer.is_empty()); ``` ``` -------------------------------- ### Create and use an interval with a specific start time Source: https://docs.rs/tokio/latest/tokio/time/fn.interval_at.html Use this snippet to create an interval that starts ticking after a specified duration and then continues at a set period. The first tick will occur at `start`, and subsequent ticks will occur every `period` duration. ```rust use tokio::time::{interval_at, Duration, Instant}; 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 // approximately 70ms have elapsed. ``` -------------------------------- ### ServerOptions::new().create() Source: https://docs.rs/tokio/latest/src/tokio/net/windows/named_pipe.rs.html Creates a new named pipe server with the specified name. This is the entry point for setting up a named pipe server. ```APIDOC ## ServerOptions::new().create() ### Description Creates a new named pipe server with the specified name. This is the entry point for setting up a named pipe server. ### Method `create(name: &str)` ### Parameters #### Path Parameters - **name** (string) - Required - The name of the named pipe to create. ### Request Example ```rust use tokio::net::windows::named_pipe; let server = named_pipe::ServerOptions::new() .create(r"\\.\pipe\my_pipe_name")?; ``` ### Response #### Success Response - Returns a `named_pipe::Server` instance on success. #### Error Response - Returns an `io::Error` if the pipe creation fails. ```