### Basic write_all example Source: https://docs.rs/tokio/1.49.0/src/tokio/io/util/async_write_ext.rs.html?search= Initial setup for a write_all example. ```rust # #[cfg(not(target_family = "wasm"))] # { use tokio::io::{self, AsyncWriteExt}; use tokio::fs::File; #[tokio::main] async fn main() -> io::Result<()> { ``` -------------------------------- ### Try Write Example Source: https://docs.rs/tokio/1.49.0/tokio/net/unix/pipe/struct.Sender.html?search= Demonstrates the basic setup for using the pipe module. ```rust use tokio::net::unix::pipe; use std::io; ``` -------------------------------- ### Initialize UnixStream connection for writing Source: https://docs.rs/tokio/1.49.0/src/tokio/net/unix/stream.rs.html Partial example showing the setup of a UnixStream connection before performing write operations. ```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(); ``` -------------------------------- ### Join All Tasks Example Source: https://docs.rs/tokio/1.49.0/src/tokio/task/join_set.rs.html Example usage of joining multiple tasks. ```rust use tokio::task::JoinSet; use std::time::Duration; # #[tokio::main(flavor = "current_thread")] ``` -------------------------------- ### Non-blocking read example Source: https://docs.rs/tokio/1.49.0/src/tokio/net/unix/pipe.rs.html?search= Shows the initial setup for a non-blocking read loop using try_read. ```rust use tokio::net::unix::pipe; use std::io; #[tokio::main] async fn main() -> io::Result<()> { // Open a reading end of a fifo let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?; let mut msg = vec![0; 1024]; loop { // Wait for the pipe to be readable rx.readable().await?; // Try to read data, this may still fail with `WouldBlock` // if the readiness event is a false positive. ``` -------------------------------- ### UnixSocket Usage Examples Source: https://docs.rs/tokio/1.49.0/src/tokio/net/unix/socket.rs.html?search=u32+-%3E+bool Examples demonstrating how to use UnixSocket to connect, bind, and listen with Unix sockets. ```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(()) } ``` ```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_datagram()?; socket.bind(path)?; let datagram = socket.datagram()?; Ok(()) } ``` ```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()?; socket.bind(path)?; let listener = socket.listen(1024)?; Ok(()) } ``` -------------------------------- ### Example: Create Sender from File Source: https://docs.rs/tokio/1.49.0/src/tokio/net/unix/pipe.rs.html Demonstrates creating a Sender from a File, ensuring it's a FIFO opened with write access and non-blocking mode. 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(()) # } ``` -------------------------------- ### UnixDatagram Examples Source: https://docs.rs/tokio/1.49.0/tokio/net/struct.UnixDatagram.html Examples demonstrating how to use UnixDatagram for peer-to-peer communication. ```APIDOC ## UnixDatagram Examples ### Description Examples demonstrating how to use UnixDatagram for peer-to-peer communication. ### For a peer with a local path ```rust use tokio::net::UnixDatagram; use tempfile::tempdir; // Create an unbound socket let tx = UnixDatagram::unbound()?; // Create another, bound socket let tmp = tempdir()?; let rx_path = tmp.path().join("rx"); let rx = UnixDatagram::bind(&rx_path)?; // Connect to the bound socket tx.connect(&rx_path)?; assert_eq!(tx.peer_addr()?.as_pathname().unwrap(), &rx_path); ``` ### For an unbound peer ```rust use tokio::net::UnixDatagram; // Create the pair of sockets let (sock1, sock2) = UnixDatagram::pair()?; assert!(sock1.peer_addr()?.is_unnamed()); ``` ``` -------------------------------- ### TcpSocket Usage Examples Source: https://docs.rs/tokio/1.49.0/src/tokio/net/tcp/socket.rs.html?search=u32+-%3E+bool Examples demonstrating how to use TcpSocket to connect to a remote address or bind a listener with custom configuration. ```rust use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; let stream = socket.connect(addr).await?; # drop(stream); Ok(()) } ``` ```rust use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; // On platforms with Berkeley-derived sockets, this allows to quickly // rebind a socket, without needing to wait for the OS to clean up the // previous one. // // On Windows, this allows rebinding sockets which are actively in use, // which allows "socket hijacking", so we explicitly don't set it here. // https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse socket.set_reuseaddr(true)?; socket.bind(addr)?; // Note: the actual backlog used by `TcpListener::bind` is platform-dependent, // as Tokio relies on Mio's default backlog value configuration. The `1024` here is only // illustrative and does not reflect the real value used. let listener = socket.listen(1024)?; # drop(listener); Ok(()) } ``` ```rust use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; socket.bind(addr)?; let listener = socket.listen(128)?; # drop(listener); Ok(()) } ``` -------------------------------- ### Example: Receiving Data with UnixDatagram Source: https://docs.rs/tokio/1.49.0/src/tokio/net/unix/datagram/socket.rs.html This example demonstrates how to use `UnixDatagram::bind` and `readable().await` to receive data. It includes error handling for `WouldBlock` and other I/O errors. ```rust use tokio::net::UnixDatagram; use std::io; #[tokio::main] async fn main() -> io::Result<()> { // Connect to a peer let dir = tempfile::tempdir().unwrap(); let client_path = dir.path().join("client.sock"); let server_path = dir.path().join("server.sock"); let socket = UnixDatagram::bind(&client_path)?; socket.connect(&server_path)?; 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 Current Instant Source: https://docs.rs/tokio/1.49.0/src/tokio/time/instant.rs.html Use `Instant::now()` to get the current time from a monotonically nondecreasing clock. This is useful for starting timers or marking points in time. ```rust use tokio::time::Instant; let now = Instant::now(); ``` -------------------------------- ### Example: Create and Open a File with Tokio Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/open_options.rs.html Demonstrates creating a new file (`foo.txt`) with write access using `tokio::fs::OpenOptions` and its `create` method within an async main function. ```rust 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(()) } ``` -------------------------------- ### Corrected sleep pattern Source: https://docs.rs/tokio/1.49.0/tokio/macro.select.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Partial example showing the setup for a race-free sleep pattern. ```rust use tokio::time::{self, Duration}; async fn some_async_work() { // do work } let sleep = time::sleep(Duration::from_millis(50)); tokio::pin!(sleep); ``` -------------------------------- ### Command Execution Examples Source: https://docs.rs/tokio/1.49.0/tokio/process/struct.Command.html Demonstrates basic usage of creating and executing a command with Tokio. ```APIDOC ## Basic Command Execution ### Description Executes a command and captures its output. ### Method POST (conceptual, as it involves execution) ### Endpoint N/A (This is a library function, not a REST endpoint) ### Parameters None for this basic example. ### Request Example ```rust use tokio::process::Command; let output = Command::new("ls") .env_clear() .output().await.unwrap(); ``` ### Response #### Success Response (200) - **output** (Vec) - The captured standard output of the command. #### Response Example (Output will vary based on the `ls` command execution) ``` -------------------------------- ### Create a TcpListener Source: https://docs.rs/tokio/1.49.0/src/tokio/net/tcp/socket.rs.html Demonstrates how to create a TcpSocket, bind it to an address, and start listening for connections. ```rust use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; socket.bind(addr)?; let listener = socket.listen(1024)?; # drop(listener); Ok(()) } ``` -------------------------------- ### Iterate Directory Entries and Get File Types Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/read_dir.rs.html Example demonstrating how to read directory entries asynchronously and retrieve the file type for each entry. It handles potential errors when getting the file type. ```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(()) # } ``` -------------------------------- ### Initialize OpenOptions Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/open_options.rs.html Create a new `OpenOptions` builder. All options are initially false. This is the starting point for configuring file opening. ```rust use tokio::fs::OpenOptions; let mut options = OpenOptions::new(); let future = options.read(true).open("foo.txt"); ``` -------------------------------- ### Example: Implementing a Future for poll_recv_many Source: https://docs.rs/tokio/1.49.0/src/tokio/sync/mpsc/unbounded.rs.html This example demonstrates how to create a `Future` that utilizes `poll_recv_many` to receive messages into a buffer. It shows the setup for a custom receiver future and its integration within an async context. ```rust # #[cfg(not(target_family = "wasm"))] # { use std::task::{Context, Poll}; use std::pin::Pin; use tokio::sync::mpsc; use futures::Future; struct MyReceiverFuture<'a> { receiver: mpsc::UnboundedReceiver, buffer: &'a mut Vec, limit: usize, } impl<'a> Future for MyReceiverFuture<'a> { type Output = usize; // Number of messages received fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let MyReceiverFuture { receiver, buffer, limit } = &mut *self; // Now `receiver` and `buffer` are mutable references, and `limit` is copied match receiver.poll_recv_many(cx, *buffer, *limit) { Poll::Pending => Poll::Pending, Poll::Ready(count) => Poll::Ready(count), } } } # #[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 count = my_receiver_future.await; assert_eq!(count, 3); assert_eq!(buffer, vec![0,1,2]) # } # } ``` -------------------------------- ### Get and Set UDP Socket TTL Source: https://docs.rs/tokio/1.49.0/src/tokio/net/udp.rs.html?search=u32+-%3E+bool Examples for retrieving and configuring the IP_TTL option on a UDP socket. ```rust use tokio::net::UdpSocket; # use std::io; # async fn dox() -> io::Result<()> { let sock = UdpSocket::bind("127.0.0.1:8080").await?; println!("{:?}", sock.ttl()?); # Ok(()) # } ``` ```rust use tokio::net::UdpSocket; # use std::io; # async fn dox() -> io::Result<()> { let sock = UdpSocket::bind("127.0.0.1:8080").await?; sock.set_ttl(60)?; # Ok(()) # } ``` -------------------------------- ### Read Command Output Line by Line Source: https://docs.rs/tokio/1.49.0/src/tokio/process/mod.rs.html This example demonstrates how to spawn a command, pipe its standard output, and read from it line by line asynchronously. It's crucial to spawn the child process in a separate task to allow it to make progress while you read its output. ```rust use tokio::io::{BufReader, AsyncBufReadExt}; use tokio::process::Command; use std::process::Stdio; #[tokio::main] async fn main() -> Result<(), Box> { let mut cmd = Command::new("cat"); // Specify that we want the command's standard output piped back to us. // By default, standard input/output/error will be inherited from the // current process (for example, this means that standard input will // come from the keyboard and standard output/error will go directly to // the terminal if this process is invoked from the command line). cmd.stdout(Stdio::piped()); let mut child = cmd.spawn() .expect("failed to spawn command"); let stdout = child.stdout.take() .expect("child did not have a handle to stdout"); let mut reader = BufReader::new(stdout).lines(); // Ensure the child process is spawned in the runtime so it can // make progress on its own while we await for any output. tokio::spawn(async move { let status = child.wait().await .expect("child process encountered an error"); println!("child status was: {}", status); }); while let Some(line) = reader.next_line().await? { println!("Line: {}", line); } Ok(()) } ``` -------------------------------- ### Enable All Tokio Features Source: https://docs.rs/tokio/1.49.0/index.html This is the quickest way to get started with Tokio by enabling all feature flags. It is recommended for most applications. ```toml tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Runtime Creation and Usage Source: https://docs.rs/tokio/1.49.0/tokio/runtime/struct.Runtime.html Demonstrates how to create a new Tokio Runtime instance with default configuration and how to obtain a handle for interacting with the runtime. ```APIDOC ## Runtime Creation and Management ### `Runtime::new()` Creates a new runtime instance with default configuration values. This initializes the multi-threaded scheduler, I/O driver, and time driver. **Availability**: Available on `crate feature 'rt-multi-thread'` only. **Example**: ```rust use tokio::runtime::Runtime; let rt = Runtime::new().unwrap(); // Use the runtime... ``` ### `Runtime::handle()` Returns a handle to the runtime’s spawner. This handle can be used to spawn tasks that run on this runtime and can be cloned to allow moving the `Handle` to other threads. **Example**: ```rust use tokio::runtime::Runtime; let rt = Runtime::new().unwrap(); let handle = rt.handle(); // Use the handle... ``` ``` -------------------------------- ### Create a Named Pipe Server Source: https://docs.rs/tokio/1.49.0/src/tokio/net/windows/named_pipe.rs.html Demonstrates how to initialize a named pipe server using ServerOptions and a specified pipe name. ```rust use tokio::net::windows::named_pipe::ServerOptions; const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-create"; # #[tokio::main] async fn main() -> std::io::Result<()> { let server = ServerOptions::new().create(PIPE_NAME)?; # Ok(()) } ``` -------------------------------- ### Connect with TcpSocket Source: https://docs.rs/tokio/1.49.0/tokio/net/struct.TcpSocket.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example demonstrating how to connect to an address using a manually configured TcpSocket. ```rust use tokio::net::TcpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let addr = "127.0.0.1:8080".parse().unwrap(); let socket = TcpSocket::new_v4()?; let stream = socket.connect(addr).await?; Ok(()) } ``` -------------------------------- ### Get Slice of Available Bytes in Buf Source: https://docs.rs/tokio/1.49.0/src/tokio/io/blocking.rs.html Returns a slice of the bytes currently available in the buffer, starting from the current position. ```rust pub(crate) fn bytes(&self) -> &[u8] { &self.buf[self.pos..] } ``` -------------------------------- ### Get Spawned Tasks Count (Unstable) Source: https://docs.rs/tokio/1.49.0/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 only available when the `unstable-metrics` feature is enabled and the system is 64-bit. ```rust cfg_unstable_metrics! { cfg_64bit_metrics! { pub(crate) fn spawned_tasks_count(&self) -> u64 { self.shared.owned.spawned_tasks_count() } } } ``` -------------------------------- ### Configure File Open Options Source: https://docs.rs/tokio/1.49.0/tokio/fs/struct.File.html Use `File::options()` to create an `OpenOptions` object for granular control over file opening. This example appends to a log file. `AsyncWriteExt` is required for `write_all`. ```rust use tokio::fs::File; use tokio::io::AsyncWriteExt; let mut f = File::options().append(true).open("example.log").await?; f.write_all(b"new line\n").await?; ``` -------------------------------- ### Use Handle::current() in a New Thread Source: https://docs.rs/tokio/1.49.0/src/tokio/runtime/handle.rs.html Shows how to get the current runtime handle and use `block_on` within a spawned thread. This example requires the `#[tokio::main]` attribute. ```rust #[cfg(not(target_family = "wasm"))] { use tokio::runtime::Handle; #[tokio::main] async fn main () { let handle = Handle::current(); std::thread::spawn(move || { // Using Handle::block_on to run async code in the new thread. handle.block_on(async { println!("hello"); }); }); } } ``` -------------------------------- ### TokenBucket Implementation Example Source: https://docs.rs/tokio/1.49.0/src/tokio/sync/semaphore.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates using a semaphore to manage a token bucket rate limiter. ```rust // This can return an error if the semaphore is closed, but we // never close it, so this error can never happen. let permit = self.sem.acquire().await.unwrap(); // To avoid releasing the permit back to the semaphore, we use // the `SemaphorePermit::forget` method. permit.forget(); } } impl Drop for TokenBucket { fn drop(&mut self) { // Kill the background task so it stops taking up resources when we // don't need it anymore. self.jh.abort(); } } # #[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); for _ in 0..5 { bucket.acquire().await; // do the operation } # } ``` -------------------------------- ### Example: Tokio Runtime with Task Poll Callback Source: https://docs.rs/tokio/1.49.0/src/tokio/runtime/builder.rs.html Shows how to set up a multi-threaded Tokio runtime with a callback that increments a counter each time a task starts polling. This is useful for monitoring task execution frequency. ```rust # #[cfg(not(target_family = "wasm"))] # # { # # use std::sync::{atomic::AtomicUsize, Arc}; # # use tokio::task::yield_now; # # pub fn main() { # let poll_start_counter = Arc::new(AtomicUsize::new(0)); # let poll_start = poll_start_counter.clone(); # let rt = tokio::runtime::Builder::new_multi_thread() # .enable_all() ``` -------------------------------- ### Get Mutable Uninitialized Slice from ReadBuf Source: https://docs.rs/tokio/1.49.0/tokio/io/struct.ReadBuf.html Returns a mutable slice of uninitialized bytes starting at the current position. The length of the slice is between 0 and the remaining mutable capacity, and it may be shorter than the total remainder. ```rust fn chunk_mut(&mut self) -> &mut UninitSlice ``` -------------------------------- ### TokenBucket Example Source: https://docs.rs/tokio/1.49.0/src/tokio/sync/semaphore.rs.html Demonstrates the usage of a TokenBucket, which likely uses a Semaphore internally, to acquire permits over time. ```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 } ``` -------------------------------- ### Example: Get Worker Overflow Count Source: https://docs.rs/tokio/1.49.0/src/tokio/runtime/metrics/runtime.rs.html Demonstrates how to retrieve and print the overflow count for a specific worker thread using the Tokio runtime Handle. Ensure the runtime is built with metrics enabled if needed. ```rust use tokio::runtime::Handle; # #[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); # } ``` -------------------------------- ### Start Polling Task (Unstable) Source: https://docs.rs/tokio/1.49.0/src/tokio/runtime/metrics/batch.rs.html Unstable implementation for starting a task poll. Increments poll count and records start time if `poll_timer` is configured. ```rust pub(crate) fn start_poll(&mut self) { self.poll_count += 1; if let Some(poll_timer) = &mut self.poll_timer { poll_timer.poll_started_at = Instant::now(); } } ``` -------------------------------- ### Configuring File Opening with Security QoS Source: https://docs.rs/tokio/1.49.0/tokio/fs/struct.OpenOptions.html Demonstrates how to use OpenOptions to open a file (or pipe) with specific write, create, and Windows security quality of service flags. ```APIDOC ## OpenOptions::security_qos_flags ### Description Sets the security quality of service flags for the file opening operation. This is particularly useful on Windows for specifying security identification levels. ### Method Builder Pattern (Method chaining) ### Parameters #### Request Body - **flags** (SECURITY_IDENTIFICATION) - Required - The security quality of service flags to apply to the file handle. ### Request 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?; ``` ``` -------------------------------- ### Example of using SimplexStream Source: https://docs.rs/tokio/1.49.0/src/tokio/io/util/mem.rs.html Demonstrates how to use `SimplexStream` for bidirectional communication by writing data and then reading it back. ```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(()) # } ``` -------------------------------- ### on_thread_start Source: https://docs.rs/tokio/1.49.0/tokio/runtime/struct.Builder.html?search= Executes a function after each thread is started but before it starts doing work. ```APIDOC ## pub fn on_thread_start(&mut self, f: F) -> &mut Self ### Description Executes function `f` after each thread is started but before it starts doing work. Available on non-`loom` only. ``` -------------------------------- ### Creating a new OpenOptions instance Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/open_options.rs.html?search= Initializes a new set of options for file configuration. ```rust use tokio::fs::OpenOptions; let mut options = OpenOptions::new(); let future = options.read(true).open("foo.txt"); ``` -------------------------------- ### Implementing an Idiomatic Named Pipe Server Source: https://docs.rs/tokio/1.49.0/src/tokio/net/windows/named_pipe.rs.html?search=std%3A%3Avec This example demonstrates how to correctly manage server instances to avoid client connection errors by ensuring a new server is created before the current one is moved to a task. ```rust use std::io; use tokio::net::windows::named_pipe::ServerOptions; const PIPE_NAME: &str = r"\\.\pipe\named-pipe-idiomatic-server"; # #[tokio::main] async fn main() -> std::io::Result<()> { // The first server needs to be constructed early so that clients can // be correctly connected. Otherwise calling .wait will cause the client to // error. // // Here we also make use of `first_pipe_instance`, which will ensure that // there are no other servers up and running already. let mut server = ServerOptions::new() .first_pipe_instance(true) .create(PIPE_NAME)?; // Spawn the server loop. let server = tokio::spawn(async move { loop { // Wait for a client to connect. server.connect().await?; let connected_client = server; // Construct the next server to be connected before sending the one // we already have of onto a task. This ensures that the server // isn't closed (after it's done in the task) before a new one is // available. Otherwise the client might error with // `io::ErrorKind::NotFound`. server = ServerOptions::new().create(PIPE_NAME)?; let client = tokio::spawn(async move { /* use the connected client */ # Ok::<_, std::io::Error>(()) }); # if true { break } // needed for type inference to work } Ok::<_, io::Error>(()) }); /* do something else not server related here */ # Ok(()) } ``` -------------------------------- ### Initialize UringOpenOptions Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/open_options/uring_open_options.rs.html Creates a new instance of UringOpenOptions with default settings. Use this to begin configuring file opening parameters. ```rust pub(crate) fn new() -> Self { Self { read: false, write: false, append: false, truncate: false, create: false, create_new: false, mode: 0o666, custom_flags: 0, } } ``` -------------------------------- ### Write i128 Example Source: https://docs.rs/tokio/1.49.0/src/tokio/io/util/async_write_ext.rs.html?search=std%3A%3Avec Example of writing a 128-bit integer to a writer. ```rust 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(()) ``` -------------------------------- ### Split segments example Source: https://docs.rs/tokio/1.49.0/src/tokio/io/util/async_buf_read_ext.rs.html?search=std%3A%3Avec Example usage of the split method to iterate over segments. ```rust /// while let Some(segment) = segments.next_segment().await? { /// println!("length = {}", segment.len()) /// } /// # Ok(()) /// # } ``` -------------------------------- ### Configure File Creation with OpenOptions Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/open_options.rs.html Use the `create` method to specify if a new file should be created if it does not exist. Requires write or append access. This is an async version of `std::fs::OpenOptions::create`. ```rust pub fn create(&mut self, create: bool) -> &mut OpenOptions { match &mut self.inner { Kind::Std(opts) => { opts.create(create); } #[cfg(all( tokio_unstable, feature = "io-uring", feature = "rt", feature = "fs", target_os = "linux" ))] Kind::Uring(opts) => { opts.create(create); } } self } ``` -------------------------------- ### OnceCell Get or Initialize Source: https://docs.rs/tokio/1.49.0/tokio/sync/struct.OnceCell.html Asynchronously get the value or initialize it if it's not set. ```APIDOC #### pub async fn get_or_init(&self, f: F) -> &T where F: FnOnce() -> Fut, Fut: Future, 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 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. ``` -------------------------------- ### Start Polling Task (Stable) Source: https://docs.rs/tokio/1.49.0/src/tokio/runtime/metrics/batch.rs.html Stable implementation for starting a task poll. Does nothing. ```rust pub(crate) fn start_poll(&mut self) {} ``` -------------------------------- ### UdpSocket - One to One Example Source: https://docs.rs/tokio/1.49.0/tokio/net/struct.UdpSocket.html Illustrates using `bind`, `connect`, `send`, and `recv` for a one-to-one UDP communication pattern. ```APIDOC ## Example: one to one (connect) Or using `connect` we can echo with a single remote address using `send` and `recv`: ```rust use tokio::net::UdpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let sock = UdpSocket::bind("0.0.0.0:8080").await?; let remote_addr = "127.0.0.1:59611"; sock.connect(remote_addr).await?; let mut buf = [0; 1024]; loop { let len = sock.recv(&mut buf).await?; println!("{:?} bytes received from {:?}", len, remote_addr); let len = sock.send(&buf[..len]).await?; println!("{:?} bytes sent", len); } } ``` ``` -------------------------------- ### Example: Create New Exclusive File with Tokio Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/open_options.rs.html Shows how to use `OpenOptions` to exclusively create a new file (`foo.txt`) with write access, ensuring it doesn't already exist. This uses the `create_new` method. ```rust use tokio::fs::OpenOptions; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let file = OpenOptions::new() .write(true) .create_new(true) .open("foo.txt") .await?; Ok(()) } ``` -------------------------------- ### OnceCell Initialization Examples Source: https://docs.rs/tokio/1.49.0/tokio/sync/struct.OnceCell.html Examples demonstrating how to initialize a OnceCell using asynchronous operations. ```APIDOC ## §Examples ```rust use tokio::sync::OnceCell; async fn some_computation() -> u32 { 1 + 1 } static ONCE: OnceCell = OnceCell::const_new(); 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. ```rust use tokio::sync::OnceCell; static ONCE: OnceCell = OnceCell::const_new(); async fn get_global_integer() -> &'static u32 { ONCE.get_or_init(|| async { 1 + 1 }).await } let result = get_global_integer().await; assert_eq!(*result, 2); ``` ``` -------------------------------- ### Receiver Usage Examples Source: https://docs.rs/tokio/1.49.0/tokio/net/unix/pipe/struct.Receiver.html Examples demonstrating how to use the Receiver to read messages from a named pipe. ```APIDOC ## Receiver tokio::net::unix::pipe ### Description Reading end of a Unix pipe. It can be constructed from a FIFO file with `OpenOptions::open_receiver`. ### Examples #### Receiving messages from a named pipe in a loop: ```rust use tokio::net::unix::pipe; use tokio::io::{self, AsyncReadExt}; const FIFO_NAME: &str = "path/to/a/fifo"; let mut rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?; loop { let mut msg = vec![0; 256]; match rx.read_exact(&mut msg).await { Ok(_) => { /* handle the message */ } Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => { // Writing end has been closed, we should reopen the pipe. rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?; } Err(e) => return Err(e.into()), } } ``` #### Using read-write access mode on Linux: ```rust use tokio::net::unix::pipe; use tokio::io::AsyncReadExt; const FIFO_NAME: &str = "path/to/a/fifo"; let mut rx = pipe::OpenOptions::new() .read_write(true) .open_receiver(FIFO_NAME)?; loop { let mut msg = vec![0; 256]; rx.read_exact(&mut msg).await?; /* handle the message */ } ``` ``` -------------------------------- ### Budgeting Test Example Source: https://docs.rs/tokio/1.49.0/src/tokio/task/coop/mod.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to test budget consumption and restoration within the cooperative scheduling system. ```rust use std::future::poll_fn; use tokio_test::*; assert!(get().0.is_none()); let coop = assert_ready!(task::spawn(()).enter(|cx, _| poll_proceed(cx))); assert!(get().0.is_none()); drop(coop); assert!(get().0.is_none()); budget(|| { assert_eq!(get().0, Budget::initial().0); let coop = assert_ready!(task::spawn(()).enter(|cx, _| poll_proceed(cx))); assert_eq!(get().0.unwrap(), Budget::initial().0.unwrap() - 1); drop(coop); // we didn't make progress assert_eq!(get().0, Budget::initial().0); let coop = assert_ready!(task::spawn(()).enter(|cx, _| poll_proceed(cx))); ``` -------------------------------- ### Register thread start callback Source: https://docs.rs/tokio/1.49.0/src/tokio/runtime/builder.rs.html Executes a function after each thread starts but before it begins work, useful for monitoring. ```rust # #[cfg(not(target_family = "wasm"))] # { # use tokio::runtime; # pub fn main() { let runtime = runtime::Builder::new_multi_thread() .on_thread_start(|| { println!("thread started"); }) .build(); # } # } ``` -------------------------------- ### tokio::fs::create_dir_all Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/create_dir_all.rs.html Asynchronously creates a directory and all of its parent components if they are missing. ```APIDOC ## tokio::fs::create_dir_all ### Description Recursively creates a directory and all of its parent components if they are missing. This is an async version of std::fs::create_dir_all. ### Parameters #### Path Parameters - **path** (impl AsRef) - Required - The path to the directory to be created. ### Errors - Returns an io::Result<()> error if any directory in the path cannot be created, unless the failure is due to concurrent creation by another process or thread. ### Request Example ```rust use tokio::fs; #[tokio::main] async fn main() -> std::io::Result<()> { fs::create_dir_all("/some/dir").await?; Ok(()) } ``` ``` -------------------------------- ### AsyncBufReadExt - lines Example Source: https://docs.rs/tokio/1.49.0/tokio/io/trait.AsyncBufReadExt.html Example showing how to use the `lines` method to iterate over lines in an asynchronous reader. ```APIDOC ## AsyncBufReadExt - lines Example ### Description This example demonstrates using `std::io::Cursor` to iterate over all the lines in a byte slice asynchronously. ### Method `lines` ### Endpoint N/A (In-memory operation) ### Request Example ```rust use tokio::io::AsyncBufReadExt; use std::io::Cursor; let cursor = Cursor::new(b"lorem\nipsum\r\ndolor"); 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); ``` ### Response N/A (Illustrative code, not an API response) ``` -------------------------------- ### Create a file with OpenOptions Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/open_options.rs.html?search= Configures the file to be created if it does not already exist, requiring write or append access. ```rust 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(()) } ``` -------------------------------- ### Open File for Reading/Writing and Create if Not Exists Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/open_options.rs.html Configure `OpenOptions` to allow reading and writing, and create the file if it doesn't exist. This is useful for files that should always be present. ```rust use tokio::fs::OpenOptions; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let file = OpenOptions::new() .read(true) .write(true) .create(true) .open("foo.txt") .await?; Ok(()) } ``` -------------------------------- ### AsyncFd - Get References Source: https://docs.rs/tokio/1.49.0/tokio/io/unix/struct.AsyncFd.html Provides methods to get shared or mutable references to the backing object of an AsyncFd. ```APIDOC ## GET /api/async_fd/get_ref ### Description Returns a shared reference to the backing object of this `AsyncFd`. ### Method GET ### Endpoint `/api/async_fd/get_ref` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **T** (object) - A shared reference to the backing object. #### Response Example ```json { "example": "backing_object_reference" } ``` ## GET /api/async_fd/get_mut ### Description Returns a mutable reference to the backing object of this `AsyncFd`. ### Method GET ### Endpoint `/api/async_fd/get_mut` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **T** (object) - A mutable reference to the backing object. #### Response Example ```json { "example": "mutable_backing_object_reference" } ``` ``` -------------------------------- ### Get IPv4 TOS (Deprecated) Source: https://docs.rs/tokio/1.49.0/src/tokio/net/tcp/socket.rs.html Deprecated method to get the IPv4 TOS value. Use `tos_v4()` instead. ```rust pub fn tos(&self) -> io::Result ``` -------------------------------- ### Configure Runtime Threading Source: https://docs.rs/tokio/1.49.0/src/tokio/runtime/builder.rs.html?search=std%3A%3Avec Examples of initializing multi-threaded and current-thread runtimes. ```rust let rt = runtime::Builder::new_multi_thread() .worker_threads(4) .build() .unwrap(); rt.spawn(async move {}); ``` ```rust use tokio::runtime; // Create a runtime that _must_ be driven from a call // to `Runtime::block_on`. let rt = runtime::Builder::new_current_thread() .build() .unwrap(); // This will run the runtime and future on the current thread rt.block_on(async move {}); ``` -------------------------------- ### Open File for Reading with Tokio Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/open_options.rs.html Use `OpenOptions` to configure file access. This example opens 'foo.txt' for reading. ```rust use tokio::fs::OpenOptions; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let file = OpenOptions::new() .read(true) .open("foo.txt") .await?; Ok(()) } ``` -------------------------------- ### Start Processing Scheduled Tasks Source: https://docs.rs/tokio/1.49.0/src/tokio/runtime/metrics/batch.rs.html Records the start time for processing scheduled tasks. Used to calculate busy duration. ```rust pub(crate) fn start_processing_scheduled_tasks(&mut self) { self.processing_scheduled_tasks_started_at = now(); } ``` -------------------------------- ### UnboundedReceiver Usage Example Source: https://docs.rs/tokio/1.49.0/tokio/sync/mpsc/struct.UnboundedReceiver.html An example demonstrating how to use UnboundedReceiver with a custom Future to receive multiple messages up to a specified limit. ```APIDOC ## UnboundedReceiver Usage Example ### Description This example shows how to create a `Future` that polls an `UnboundedReceiver` to receive multiple messages into a buffer until a limit is reached or the sender is dropped. ### Method N/A (Illustrative Example) ### Endpoint N/A ### Request Body N/A ### Request Example ```rust use std::task::{Context, Poll}; use std::pin::Pin; use tokio::sync::mpsc; use futures::Future; struct MyReceiverFuture<'a> { receiver: mpsc::UnboundedReceiver, buffer: &'a mut Vec, limit: usize, } impl<'a> Future for MyReceiverFuture<'a> { type Output = usize; // Number of messages received fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let MyReceiverFuture { receiver, buffer, limit } = &mut *self; match receiver.poll_recv_many(cx, *buffer, *limit) { Poll::Pending => Poll::Pending, Poll::Ready(count) => Poll::Ready(count), } } } 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"); } // In an async context, you would await my_receiver_future // let count = my_receiver_future.await; // assert_eq!(count, 3); // assert_eq!(buffer, vec![0,1,2]) ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### UDP Socket peek_from Example Source: https://docs.rs/tokio/1.49.0/tokio/net/struct.UdpSocket.html Example demonstrating how to use `peek_from` to read data from a UDP socket without consuming it. ```APIDOC ## UDP Socket peek_from Example ### Description This example demonstrates how to use the `peek_from` method to read data from a UDP socket without removing it from the input queue. It binds to a local address, then peeks at incoming data, printing the number of bytes read and the sender's address. ### Method `peek_from` ### Endpoint N/A (This is a method on a socket object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use tokio::net::UdpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let socket = UdpSocket::bind("127.0.0.1:8080").await?; let mut buf = vec![0u8; 32]; let (len, addr) = socket.peek_from(&mut buf).await?; println!("peeked {:?} bytes from {:?}", len, addr); Ok(()) } ``` ### Response #### Success Response (200) This method does not return a direct HTTP response. It returns a `Result` containing a tuple of `(usize, SocketAddr)` on success, where `usize` is the number of bytes read and `SocketAddr` is the sender's address. #### Response Example ``` peeked 32 bytes from 127.0.0.1:12345 ``` ``` -------------------------------- ### OpenOptions::create() Source: https://docs.rs/tokio/1.49.0/tokio/fs/struct.OpenOptions.html?search=u32+-%3E+bool Sets the option for creating a new file. ```APIDOC ## pub fn create(&mut self, create: bool) -> &mut OpenOptions ### Description Sets the option for creating a new file. This option indicates whether a new file will be created if the file does not yet already exist. ``` -------------------------------- ### Create and Write to a File Source: https://docs.rs/tokio/1.49.0/src/tokio/fs/file.rs.html Use `File::create` to create a new file and `AsyncWriteExt::write_all` to write bytes to it. Ensure `AsyncWriteExt` is imported. ```rust use tokio::fs::File; use tokio::io::AsyncWriteExt; // for write_all() # async fn dox() -> std::io::Result<()> { let mut file = File::create("foo.txt").await?; file.write_all(b"hello, world!").await?; # Ok(()) # } ``` -------------------------------- ### Basic Usage Source: https://docs.rs/tokio/1.49.0/tokio/io/fn.copy_buf.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example demonstrating how to copy data from a byte slice reader to a vector writer. ```rust use tokio::io; let mut reader: &[u8] = b"hello"; let mut writer: Vec = vec![]; io::copy_buf(&mut reader, &mut writer).await?; assert_eq!(b"hello", &writer[..]); ```