### UDP Echo Server Example using async-std::net Source: https://docs.rs/async-std/latest/async_std/net/index This example demonstrates how to create a simple UDP echo server using `async_std::net::UdpSocket`. It binds to a local address, receives data, and sends it back to the sender. It requires the `async-std` crate. ```rust use async_std::net::UdpSocket; let socket = UdpSocket::bind("127.0.0.1:8080").await?; let mut buf = vec![0u8; 1024]; loop { let (n, peer) = socket.recv_from(&mut buf).await?; socket.send_to(&buf[..n], &peer).await?; } ``` -------------------------------- ### Example: Using Pin::set - Rust Source: https://docs.rs/async-std/latest/async_std/pin/struct Provides a practical example of using `Pin::set` to change the value of a pinned variable and printing the value before and after the update. ```rust use std::pin::Pin; let mut val: u8 = 5; let mut pinned: Pin<&mut u8> = Pin::new(&mut val); println!("{}", pinned); // 5 pinned.set(10); println!("{}", pinned); // 10 ``` -------------------------------- ### async-std WriteExt Example: Writing to a File Source: https://docs.rs/async-std/latest/async_std/io/prelude/trait Demonstrates how to use the `write` method from `WriteExt` to write data to an asynchronous file. This example shows the creation of a file, writing a byte slice to it, and handling the result. ```rust use async_std::fs::File; use async_std::prelude::*; let mut file = File::create("a.txt").await?; let n = file.write(b"hello world").await?; ``` -------------------------------- ### async-std writeln! Macro Usage Example Source: https://docs.rs/async-std/latest/async_std/macro This example demonstrates how to use the `writeln!` macro to write plain text and formatted strings to a `Vec` buffer. It shows basic usage and assertion of the expected output. ```rust use std::io::{Write, Result}; fn main() -> Result<()> { let mut w = Vec::new(); writeln!(&mut w)?; writeln!(&mut w, "test")?; writeln!(&mut w, "formatted {}", "arguments")?; assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes()); Ok(()) } ``` -------------------------------- ### Configuring a Task with async-std Builder Source: https://docs.rs/async-std/latest/async_std/task/index Shows how to use the `task::Builder` to configure a new task before spawning it. This example specifically demonstrates setting a name for the child task. ```rust use async_std::task; task::Builder::new().name("child1".to_string()).spawn(async { println!("Hello, world!"); }); ``` -------------------------------- ### async-std WriteExt Example: Writing Formatted String to File Source: https://docs.rs/async-std/latest/async_std/io/prelude/trait Demonstrates writing a formatted string to an asynchronous writer using the `write_fmt` method from `WriteExt`. This example shows how to write formatted data, similar to the `write!` macro, but asynchronously. ```rust use async_std::io::prelude::*; use async_std::fs::File; let mut buffer = File::create("foo.txt").await?; // this call write!(buffer, "{:.*}", 2, 1.234567).await?; // turns into this: buffer.write_fmt(format_args!("{:.*}", 2, 1.234567)).await?; ``` -------------------------------- ### async-std WriteExt Example: Flushing a File Source: https://docs.rs/async-std/latest/async_std/io/prelude/trait Illustrates the use of the `flush` method from `WriteExt` to ensure all buffered data is written to the destination. This example writes data to a file and then explicitly flushes the stream. ```rust use async_std::fs::File; use async_std::prelude::*; let mut file = File::create("a.txt").await?; file.write_all(b"hello world").await?; file.flush().await?; ``` -------------------------------- ### Rust Mutex Example Source: https://docs.rs/async-std/latest/async_std/sync/index Demonstrates the basic usage of a Mutex for mutual exclusion in an asynchronous context. It shows how to lock and unlock the mutex to protect shared data. ```rust use async_std::sync::Mutex; use async_std::task; #[async_std::main] async fn main() { let data = Mutex::new(0); let handle1 = task::spawn(async { let mut data = data.lock().await; *data += 1; }); let handle2 = task::spawn(async { let mut data = data.lock().await; *data += 2; }); handle1.await; handle2.await; let data = data.lock().await; println!("Final value: {}", *data); } ``` -------------------------------- ### Rust RwLock Example Source: https://docs.rs/async-std/latest/async_std/sync/index Illustrates the use of RwLock for managing concurrent read and write access to shared data. It shows how multiple readers can access data simultaneously, while writers acquire exclusive access. ```rust use async_std::sync::RwLock; use async_std::task; use std::sync::Arc; #[async_std::main] async fn main() { let data = Arc::new(RwLock::new(0)); let mut handles = vec![]; for _ in 0..5 { // Multiple readers let data = Arc::clone(&data); handles.push(task::spawn(async move { let value = data.read().await; println!("Reader got: {}", *value); })); } let data_clone = Arc::clone(&data); handles.push(task::spawn(async move { task::sleep(std::time::Duration::from_millis(50)).await; // Give readers a chance to start let mut value = data_clone.write().await; *value += 10; println!("Writer updated value."); })); for handle in handles { handle.await; } let final_value = data.read().await; println!("Final value: {}", *final_value); } ``` -------------------------------- ### Rust Barrier Example Source: https://docs.rs/async-std/latest/async_std/sync/index Shows how to use a Barrier to synchronize multiple asynchronous tasks, ensuring they all reach a specific point before any of them proceed. This is useful for coordinating concurrent operations. ```rust use async_std::sync::Barrier; use async_std::task; use std::sync::Arc; #[async_std::main] async fn main() { let num_tasks = 3; let barrier = Arc::new(Barrier::new(num_tasks)); let mut handles = vec![]; for i in 0..num_tasks { let barrier_clone = Arc::clone(&barrier); handles.push(task::spawn(async move { println!("Task {} reached the first barrier.", i); barrier_clone.wait().await; println!("Task {} passed the first barrier.", i); // Simulate some work task::sleep(std::time::Duration::from_millis(100 * (i as u64 + 1))).await; println!("Task {} reached the second barrier.", i); barrier_clone.wait().await; println!("Task {} passed the second barrier.", i); })); } for handle in handles { handle.await; } println!("All tasks completed."); } ``` -------------------------------- ### Rust: Async Example using ToSocketAddrs Source: https://docs.rs/async-std/latest/async_std/net/trait Provides a practical example of using the `to_socket_addrs` method asynchronously. It demonstrates resolving a string address like "localhost:8080" into a `SocketAddr` and printing the result. ```rust use async_std::net::ToSocketAddrs; let addr = "localhost:8080".to_socket_addrs().await?.next().unwrap(); println!("resolved: {:?}", addr); ``` -------------------------------- ### Create a UDP echo server with async_std::net::UdpSocket Source: https://docs.rs/async-std/latest/async_std/index This example sets up a UDP server that binds to a local address, listens for incoming datagrams, and echoes each received message back to the sender. It utilizes `async_std::net::UdpSocket` for network operations and requires the `attributes` feature. ```rust use async_std::net::UdpSocket; #[async_std::main] async fn main() -> std::io::Result<()> { let socket = UdpSocket::bind("127.0.0.1:8080").await?; println!("Listening on {}", socket.local_addr()?); let mut buf = vec![0u8; 1024]; loop { let (recv, peer) = socket.recv_from(&mut buf).await?; let sent = socket.send_to(&buf[..recv], &peer).await?; println!("Sent {} out of {} bytes to {}", sent, recv, peer); } } ``` -------------------------------- ### Example: Calling Method Twice with Pin - Rust Source: https://docs.rs/async-std/latest/async_std/pin/struct Provides an example of how to safely call a method multiple times on a pinned mutable self by using `Pin::as_mut` to reborrow the `Pin<&mut Self>` each time. ```rust use std::pin::Pin; impl Type { fn method(self: Pin<&mut Self>) { // do something } fn call_method_twice(mut self: Pin<&mut Self>) { // `method` consumes `self`, so reborrow the `Pin<&mut Self>` via `as_mut`. self.as_mut().method(); self.as_mut().method(); } } ``` -------------------------------- ### Rust: Creating Weak pointer with allocator Source: https://docs.rs/async-std/latest/async_std/sync/struct This example showcases the nightly-only experimental API `into_raw_with_allocator` for consuming a Weak pointer and returning the raw pointer along with its allocator. It demonstrates how to reconstruct a Weak pointer from the raw pointer and allocator, verifying the strong count and data access. ```rust #![feature(allocator_api)] use std::sync::{Arc, Weak}; use std::alloc::System; let strong = Arc::new_in("hello".to_owned(), System); let weak = Arc::downgrade(&strong); let (raw, alloc) = weak.into_raw_with_allocator(); assert_eq!(1, Arc::weak_count(&strong)); assert_eq!("hello", unsafe { &*raw }); drop(unsafe { Weak::from_raw_in(raw, alloc) }); assert_eq!(0, Arc::weak_count(&strong)); ``` -------------------------------- ### async-std WriteExt Example: Writing All Bytes to a File Source: https://docs.rs/async-std/latest/async_std/io/prelude/trait Shows how to use the `write_all` method from `WriteExt` to guarantee that an entire byte slice is written to the output. This method repeatedly calls `write` until all data is sent or an error occurs. ```rust use async_std::fs::File; use async_std::prelude::*; let mut file = File::create("a.txt").await?; file.write_all(b"hello world").await?; ``` -------------------------------- ### Seeking within a File with async-std Source: https://docs.rs/async-std/latest/async_std/io/index Shows how to use the `Seek` trait to navigate to a specific position within a file before reading. This example seeks to the last 10 bytes of the file. ```Rust use async_std::fs::File; use async_std::io::SeekFrom; use async_std::prelude::*; let mut f = File::open("foo.txt").await?; let mut buffer = [0; 10]; // skip to the last 10 bytes of the file f.seek(SeekFrom::End(-10)).await?; // read up to 10 bytes let n = f.read(&mut buffer).await?; println!("The bytes: {:?}", &buffer[..n]); ``` -------------------------------- ### Rust Arc Example Source: https://docs.rs/async-std/latest/async_std/sync/index Demonstrates the use of Arc (Atomically Reference-Counted) for shared ownership of data across multiple asynchronous tasks. This allows data to live as long as it's being referenced. ```rust use async_std::task; use std::sync::Arc; #[async_std::main] async fn main() { let shared_data = Arc::new(vec![1, 2, 3]); let mut handles = vec![]; for i in 0..3 { let shared_data_clone = Arc::clone(&shared_data); handles.push(task::spawn(async move { println!("Task {} sees data: {:?}", i, *shared_data_clone); })); } for handle in handles { handle.await; } println!("Original data: {:?}", *shared_data); } ``` -------------------------------- ### Rust Unsafe Static Variable Example Source: https://docs.rs/async-std/latest/async_std/sync/index Illustrates a scenario with static mutable variables in Rust, highlighting the need for `unsafe` blocks and the potential for race conditions and unexpected behavior without proper synchronization. ```rust static mut A: u32 = 0; static mut B: u32 = 0; static mut C: u32 = 0; fn main() { unsafe { A = 3; B = 4; A = A + B; C = B; println!("{} {} {}", A, B, C); C = A; } } ``` -------------------------------- ### Example Usage of Path Prefixes - Rust Source: https://docs.rs/async-std/latest/async_std/path/enum This Rust code demonstrates how to extract and identify the `Prefix` kind from a given path string. It utilizes `Path::new` and `path.components().next()` to access the first component of a path and match its prefix type. ```rust use std::path::{Component, Path, Prefix}; use std::path::Prefix::*; use std::ffi::OsStr; fn get_path_prefix(s: &str) -> Prefix<'_> { let path = Path::new(s); match path.components().next().unwrap() { Component::Prefix(prefix_component) => prefix_component.kind(), _ => panic!(), } } assert_eq!(Verbatim(OsStr::new("pictures")), get_path_prefix(r"\\?\pictures\kittens")); assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")), get_path_prefix(r"\\?\UNC\server\share")); assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\")); assert_eq!(DeviceNS(OsStr::new("BrainInterface")), get_path_prefix(r"\\.\BrainInterface")); assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")), get_path_prefix(r"\\server\share")); assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris")); ``` -------------------------------- ### Handling Finite Streams from Infinite Streams Source: https://docs.rs/async-std/latest/async_std/stream/index Demonstrates how to create a finite stream from an infinite one using the `take` adapter. This is useful for limiting the number of elements processed from potentially endless streams, such as those generated by `stream::repeat` or ranges without an upper bound. The example shows taking the first five numbers from an infinite sequence. ```rust let numbers = stream::from_iter(0u8..); let mut five_numbers = numbers.take(5); while let Some(number) = five_numbers.next().await { println!("{}", number); } ``` -------------------------------- ### Get Mutable Reference to Inner Reader in Rust Source: https://docs.rs/async-std/latest/async_std/io/struct Explains how to get a mutable reference to the underlying reader within a `Take` adaptor. Care must be taken not to corrupt the internal state of `Take` by modifying the reader directly. This example relies on `async_std`. ```rust use async_std::prelude::* use async_std::fs::File; // Assume "foo.txt" exists and is readable. // let file = File::open("foo.txt").await?; // let mut buffer = [0; 5]; // let mut handle = file.take(5); // handle.read(&mut buffer).await?; // let file = handle.get_mut(); ``` -------------------------------- ### Get Reference to Inner Reader in Rust Source: https://docs.rs/async-std/latest/async_std/io/struct Demonstrates how to obtain an immutable reference to the underlying reader wrapped by `Take`. This allows inspecting the inner reader without consuming the `Take` adaptor. This example uses `async_std`. ```rust use async_std::prelude::* use async_std::fs::File; // Assume "foo.txt" exists and is readable. // let file = File::open("foo.txt").await?; // let mut buffer = [0; 5]; // let mut handle = file.take(5); // handle.read(&mut buffer).await?; // let file = handle.get_ref(); ``` -------------------------------- ### Spawning a Task and Awaiting Completion Source: https://docs.rs/async-std/latest/async_std/task/index Shows how to spawn a task and obtain a `JoinHandle` to await its completion and retrieve its result. ```APIDOC ## POST /task/spawn/await ### Description Spawns a new asynchronous task and returns a `JoinHandle`. The `JoinHandle` can be awaited to get the result of the task. ### Method POST ### Endpoint `/task/spawn/await` ### Parameters #### Request Body - **async_block** (async block) - Required - The asynchronous code block to execute in the new task. ### Request Example ```json { "async_block": "async { 42 }" } ``` ### Response #### Success Response (200) - **join_handle** (string) - A handle that implements `Future` and can be awaited for the task's result. #### Response Example ```json { "join_handle": "" } ``` #### Awaiting the JoinHandle (Conceptual) To get the result: ```rust let result = join_handle.await; ``` ``` -------------------------------- ### Get Port from SocketAddrV6 in Rust Source: https://docs.rs/async-std/latest/async_std/net/struct Shows how to get the port number from a SocketAddrV6 instance using the `port` method. This method returns the 16-bit port number. It is a const function. ```rust use std::net::{SocketAddrV6, Ipv6Addr}; let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0); assert_eq!(socket.port(), 8080); ``` -------------------------------- ### Import async-std Prelude in Rust Source: https://docs.rs/async-std/latest/async_std/prelude/index This snippet shows how to import the entire async-std prelude, making commonly used asynchronous traits and macros available in your Rust code. This avoids the need to import each item individually. ```rust use async_std::prelude::*; ``` -------------------------------- ### Create Directory Symbolic Link (Windows) - async-std Rust Source: https://docs.rs/async-std/latest/async_std/os/windows/fs/fn Creates a new directory symbolic link on the filesystem. The `dst` path will be a directory symbolic link pointing to the `src` path. This function is an async version of `std::os::windows::fs::symlink_dir`. It is available only on `unstable`. ```rust use async_std::os::windows::fs::symlink_dir; symlink_dir("a", "b").await?; ``` -------------------------------- ### Configuring and Spawning a Task Source: https://docs.rs/async-std/latest/async_std/task/index Illustrates using `task::Builder` to configure task properties, such as its name, before spawning. ```APIDOC ## POST /task/builder/spawn ### Description Configures a new task using `task::Builder` before spawning it. Currently allows setting the task name. ### Method POST ### Endpoint `/task/builder/spawn` ### Parameters #### Request Body - **name** (string) - Optional - The name to assign to the new task. - **async_block** (async block) - Required - The asynchronous code block to execute in the new task. ### Request Example ```json { "name": "my-custom-task", "async_block": "async { println!(\"Configured task running!\"); }" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates the task was successfully spawned with configuration. #### Response Example ```json { "message": "Configured task spawned successfully." } ``` ``` -------------------------------- ### Example Usage of I/O Result - Rust Source: https://docs.rs/async-std/latest/async_std/io/type Demonstrates how to use the specialized `io::Result` type for handling potential errors during asynchronous I/O operations. The example shows reading a line from standard input and returning it, propagating any I/O errors using the `?` operator. ```rust use std::io; fn get_string() -> io::Result { let mut buffer = String::new(); io::stdin().read_line(&mut buffer)?; Ok(buffer) } ``` -------------------------------- ### Skip Elements in Async-Std Stream Source: https://docs.rs/async-std/latest/async_std/prelude/trait Creates a combinator that skips the first `n` elements from an async stream. It returns a new stream that starts yielding elements after the specified number have been skipped. This is useful for pagination or when you need to process a stream starting from a certain point. ```rust use async_std::prelude::*; use async_std::stream; let s = stream::from_iter(vec![1u8, 2, 3]); let mut skipped = s.skip(2); assert_eq!(skipped.next().await, Some(3)); assert_eq!(skipped.next().await, None); ``` -------------------------------- ### Import Async IO Traits with async-std Prelude Source: https://docs.rs/async-std/latest/async_std/io/prelude/index This snippet demonstrates how to import common asynchronous I/O traits using the async-std prelude. It is useful in I/O-heavy modules to reduce the verbosity of individual trait imports. ```rust use async_std::io::prelude::*; ``` -------------------------------- ### Pin::as_deref_mut Source: https://docs.rs/async-std/latest/async_std/pin/struct Gets `Pin<&mut T>` to the underlying pinned value from a nested `Pin`-pointer. ```APIDOC ## GET /pin/as_deref_mut ### Description Gets `Pin<&mut T>` to the underlying pinned value from this nested `Pin`-pointer. It is safe because the existence of a `Pin>` ensures that the pointee, `T`, cannot move in the future, and this method does not enable the pointee to move. ### Method GET ### Endpoint `/pin/as_deref_mut` ### Parameters ### Request Body None ### Request Example None ### Response #### Success Response (200) - **underlying_pinned_value** (Pin<&mut T>) - A mutable reference to the underlying pinned value. #### Response Example ```json { "underlying_pinned_value": "" } ``` ``` -------------------------------- ### Pin::as_ref Source: https://docs.rs/async-std/latest/async_std/pin/struct Gets a shared reference to the pinned value. This is safe because the pointee cannot move after `Pin>` is created. ```APIDOC ## GET /pin/as_ref ### Description Gets a shared reference to the pinned value this `Pin` points to. It is safe because the pointee cannot move after `Pin>` got created. ### Method GET ### Endpoint `/pin/as_ref` ### Parameters ### Request Body None ### Request Example None ### Response #### Success Response (200) - **pinned_value** (Pin<&T>) - A shared reference to the pinned value. #### Response Example ```json { "pinned_value": "" } ``` ``` -------------------------------- ### Create and Use Take Reader in Rust Source: https://docs.rs/async-std/latest/async_std/io/struct Demonstrates how to create a `Take` reader adaptor from a file and set a limit on the number of bytes to read. It shows how to check the limit and then read from the limited reader. This requires the `async_std` crate and its prelude. ```rust use async_std::prelude::* use async_std::fs::File; // Assume "foo.txt" exists and is readable. // let f = File::open("foo.txt").await?; // read at most five bytes // let handle = f.take(5); // println!("limit: {}", handle.limit()); ``` -------------------------------- ### Pin::as_mut Source: https://docs.rs/async-std/latest/async_std/pin/struct Gets a mutable reference to the pinned value. Useful for multiple calls to functions that consume the pinning pointer. ```APIDOC ## GET /pin/as_mut ### Description Gets a mutable reference to the pinned value this `Pin` points to. This method is safe because the pointee cannot move after `Pin>` got created. It is useful when doing multiple calls to functions that consume the pinning pointer. ### Method GET ### Endpoint `/pin/as_mut` ### Parameters ### Request Body None ### Request Example None ### Response #### Success Response (200) - **pinned_mutable_value** (Pin<&mut T>) - A mutable reference to the pinned value. #### Response Example ```json { "pinned_mutable_value": "" } ``` ### Example Usage ```rust use std::pin::Pin; struct Type; impl Type { fn method(self: Pin<&mut Self>) { // do something } fn call_method_twice(mut self: Pin<&mut Self>) { // `method` consumes `self`, so reborrow the `Pin<&mut Self>` via `as_mut`. self.as_mut().method(); self.as_mut().method(); } } ``` ``` -------------------------------- ### Async UnixStream Socket Operations (Rust) Source: https://docs.rs/async-std/latest/async_std/os/unix/net/struct Demonstrates basic asynchronous operations with UnixStream, including connecting to a socket, writing data, and reading the response. Requires the async-std crate and its prelude. ```Rust use async_std::os::unix::net::UnixStream; use async_std::prelude::*; let mut stream = UnixStream::connect("/tmp/socket").await?; stream.write_all(b"hello world").await?; let mut response = Vec::new(); stream.read_to_end(&mut response).await?; ``` -------------------------------- ### Getting the Current Task Source: https://docs.rs/async-std/latest/async_std/task/index Explains how to retrieve a handle to the currently executing task using `task::current`. ```APIDOC ## GET /task/current ### Description Retrieves a handle to the currently executing asynchronous task. ### Method GET ### Endpoint `/task/current` ### Parameters None ### Response #### Success Response (200) - **task_handle** (string) - A handle representing the current task. #### Response Example ```json { "task_handle": "" } ``` ``` -------------------------------- ### Get allocator reference (Rust) Source: https://docs.rs/async-std/latest/async_std/sync/struct Returns a reference to the underlying allocator used by the `Weak` pointer. This is a nightly-only experimental API. ```Rust #![feature(allocator_api)] use std::sync::Weak; use std::alloc::System; let weak: Weak = Weak::new_in(System); let allocator = weak.allocator(); // You can now use the 'allocator' reference. ``` -------------------------------- ### Enable tokio03 compatibility feature for async-std Source: https://docs.rs/async-std/latest/async_std/index Configuration snippet for enabling the 'tokio03' Cargo feature for the async-std crate, allowing compatibility with the Tokio 0.3 runtime. ```toml [dependencies.async-std] version = "1.7.0" features = ["tokio03"] ``` -------------------------------- ### Connect to a Unix Domain Socket (Rust) Source: https://docs.rs/async-std/latest/async_std/os/unix/net/struct Shows how to establish an asynchronous connection to a Unix domain socket using the `connect` function. This is a fundamental operation for client-side socket communication. ```Rust use async_std::os::unix::net::UnixStream; let stream = UnixStream::connect("/tmp/socket").await?; ``` -------------------------------- ### Get TypeId of Any Type Source: https://docs.rs/async-std/latest/async_std/net/struct Implements the `Any` trait for any type `T`. The `type_id` method returns the `TypeId` of the trait object, which is used for runtime type identification. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Counting Elements in a Stream (Rust) Source: https://docs.rs/async-std/latest/async_std/prelude/trait Provides an example of counting the total number of elements within an asynchronous stream. This function is available on `unstable`. ```rust use async_std::prelude::*; use async_std::stream; let s1 = stream::from_iter(vec![0]); let s2 = stream::from_iter(vec![1, 2, 3]); assert_eq!(s1.count().await, 1); assert_eq!(s2.count().await, 3); ``` -------------------------------- ### Enable tokio02 compatibility feature for async-std Source: https://docs.rs/async-std/latest/async_std/index Configuration snippet for enabling the 'tokio02' Cargo feature for the async-std crate, allowing compatibility with the Tokio 0.2 runtime. ```toml [dependencies.async-std] version = "1.7.0" features = ["tokio02"] ``` -------------------------------- ### Unwrap Pin - Rust Source: https://docs.rs/async-std/latest/async_std/pin/struct Shows how to unwrap a `Pin` to get the underlying `Ptr` using `Pin::into_inner_unchecked`. This operation is unsafe and should be used with caution, ensuring all pinning invariants are maintained. ```rust pub const unsafe fn into_inner_unchecked(pin: Pin) -> Ptr Unwraps this `Pin`, returning the underlying `Ptr`. ``` -------------------------------- ### async_std::pin::Pin Struct Source: https://docs.rs/async-std/latest/async_std/pin/struct Documentation for the Pin struct, which pins its pointee in place. ```APIDOC ## Struct Pin ### Description A pointer which pins its pointee in place. `Pin` is a wrapper around some kind of pointer `Ptr` which makes that pointer “pin” its pointee value in place, thus preventing the value referenced by that pointer from being moved or otherwise invalidated at that place in memory unless it implements `Unpin`. _See the `pin` module documentation for a more thorough exploration of pinning._ ### Available on `unstable` only. ### Fields (Private fields, not typically exposed or used directly) ### Methods (Associated functions and methods of `Pin`) #### `new` (unstable) Creates a new `Pin`. #### `new_unchecked` (unstable) Creates a new `Pin` without runtime checks. #### `as_ref` Borrows the inner pointer immutably. #### `as_mut` Borrows the inner pointer mutably (requires `Pin` of a mutable pointer). #### `get_ref` Gets an immutable reference to the pointee. #### `get_mut` Gets a mutable reference to the pointee (requires `Pin` of a mutable pointer). #### `set` Sets the value behind the pinned pointer. #### `into_inner` Consumes the `Pin` and returns the inner pointer. ### Trait Implementations `Pin` implements various traits including `Debug`, `Deref`, `DerefMut`, `Future`, `Stream`, and many more, enabling its use in different contexts. ``` -------------------------------- ### Get Size Hint for Stream using async-std Source: https://docs.rs/async-std/latest/async_std/pin/struct Returns the lower and upper bounds of the remaining length of the stream. This method is useful for estimating the total number of items a stream might produce. ```Rust fn size_hint(&self) -> (usize, Option) ``` -------------------------------- ### PartialOrd for Prefix<'a> Source: https://docs.rs/async-std/latest/async_std/path/enum Provides comparison methods for the Prefix<'a> type. ```APIDOC ## impl<'a> PartialOrd for Prefix<'a> ### Description Provides comparison methods for the Prefix<'a> type. ### Methods #### fn partial_cmp(&self, other: &Prefix<'a>) -> Option ##### Description This method returns an ordering between `self` and `other` values if one exists. ##### Method `partial_cmp` #### fn lt(&self, other: &Rhs) -> bool ##### Description Tests less than (for `self` and `other`) and is used by the `<` operator. ##### Method `lt` #### fn le(&self, other: &Rhs) -> bool ##### Description Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. ##### Method `le` #### fn gt(&self, other: &Rhs) -> bool ##### Description Tests greater than (for `self` and `other`) and is used by the `>` operator. ##### Method `gt` #### fn ge(&self, other: &Rhs) -> bool ##### Description Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. ##### Method `ge` #### fn ne(&self, other: &Rhs) -> bool ##### Description Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. ##### Method `ne` ``` -------------------------------- ### Enable tokio1 compatibility feature for async-std Source: https://docs.rs/async-std/latest/async_std/index Configuration snippet for enabling the 'tokio1' Cargo feature for the async-std crate, allowing compatibility with the Tokio 1.0 runtime. ```toml [dependencies.async-std] version = "1.7.0" features = ["tokio1"] ``` -------------------------------- ### Create and Write to File with async-std Source: https://docs.rs/async-std/latest/async_std/fs/index Demonstrates how to create a new file and write byte data to it asynchronously using `async_std::fs::File`. This requires the `async_std` crate and its prelude for async operations. ```rust use async_std::fs::File; use async_std::prelude::*; let mut file = File::create("a.txt").await?; file.write_all(b"Hello, world!").await?; ``` -------------------------------- ### Type Conversion Traits Source: https://docs.rs/async-std/latest/async_std/os/unix/net/struct Documentation for `ToOwned`, `TryFrom`, and `TryInto` traits. ```APIDOC ## Type Conversion Traits This section details traits related to type conversion. ### `impl ToOwned for T` Trait for obtaining ownership of data. - **Type Alias**: `Owned = T` - The resulting type after obtaining ownership. - **Method**: `to_owned(&self) -> T` - Creates owned data from borrowed data, usually by cloning. - **Method**: `clone_into(&self, target: &mut T)` - Uses borrowed data to replace owned data, usually by cloning. ### `impl TryFrom for T` Trait for fallible conversion from one type to another. - **Type Alias**: `Error = Infallible` - The type returned in the event of a conversion error. - **Method**: `try_from(value: U) -> Result>::Error>` - Performs the conversion. ### `impl TryInto for T` Trait for fallible conversion from one type to another, implemented for the source type. - **Type Alias**: `Error = >::Error` - The type returned in the event of a conversion error. - **Method**: `try_into(self) -> Result>::Error>` - Performs the conversion. ``` -------------------------------- ### Get Shared Reference from Pin - Rust Source: https://docs.rs/async-std/latest/async_std/pin/struct Demonstrates how to obtain a shared reference to the pinned value using `Pin::as_ref`. This is safe because the `Pin::new_unchecked` contract guarantees the pointee cannot move after the `Pin` is created. ```rust pub fn as_ref(&self) -> Pin<&::Target> Gets a shared reference to the pinned value this `Pin` points to. This is a generic method to go from `&Pin>` to `Pin<&T>`. It is safe because, as part of the contract of `Pin::new_unchecked`, the pointee cannot move after `Pin>` got created. “Malicious” implementations of `Pointer::Deref` are likewise ruled out by the contract of `Pin::new_unchecked`. ``` -------------------------------- ### Handling Errors when Reading from Standard Input with async-std Source: https://docs.rs/async-std/latest/async_std/io/index Provides an alternative to the `?` operator for handling potential errors during standard input reading. This example uses `.unwrap()` to handle the `Result`. ```Rust use async_std::io; let mut input = String::new(); io::stdin().read_line(&mut input).await.unwrap(); ``` -------------------------------- ### Ord, PartialEq, and PartialOrd for Pin Source: https://docs.rs/async-std/latest/async_std/pin/struct Provides comparison capabilities for `Pin` instances. ```APIDOC ## Ord, PartialEq, and PartialOrd for Pin ### Description Implements comparison traits (`Ord`, `PartialEq`, `PartialOrd`) for `Pin`. These comparisons operate on the dereferenced `Target` type, provided it also implements the respective comparison traits. ### Method `cmp`, `max`, `min`, `clamp`, `eq`, `ne`, `partial_cmp`, `lt`, `le`, `gt`, `ge` ### Endpoint N/A (Struct implementation) ### Parameters None ### Request Body None ### Response #### Success Response (200) N/A (Methods return comparison results like `Ordering` or `bool`) #### Response Example N/A ``` -------------------------------- ### Generic Blanket Implementations for Rust Types Source: https://docs.rs/async-std/latest/async_std/future/struct Demonstrates various blanket implementations for generic types in Rust, including Any, Borrow, BorrowMut, CloneToUninit, From, Into, ToOwned, ToString, TryFrom, and TryInto. These implementations provide common functionalities for many types without explicit definition. ```rust // Example blanket implementations impl Any for T where T: 'static + ?Sized { ... } impl Borrow for T where T: ?Sized { ... } impl BorrowMut for T where T: ?Sized { ... } impl CloneToUninit for T where T: Clone { ... } impl From for T { ... } impl Into for T where U: From { ... } impl ToOwned for T where T: Clone { ... } impl ToString for T where T: Display + ?Sized { ... } impl TryFrom where U: Into { ... } impl TryInto where U: TryFrom { ... } ``` -------------------------------- ### Get raw pointer (Rust) Source: https://docs.rs/async-std/latest/async_std/sync/struct Returns a raw pointer to the object `T` pointed to by this `Weak`. The pointer is only valid if there are strong references to the object; otherwise, it may be dangling, unaligned, or null. ```Rust use std::sync::{Arc, Weak}; let strong = Arc::new(10); let weak = Arc::downgrade(&strong); let ptr = weak.as_ptr(); // The pointer is valid here because 'strong' exists. unsafe { assert_eq!(*ptr, 10); } drop(strong); // The pointer is no longer guaranteed to be valid after dropping 'strong'. ``` -------------------------------- ### Get IP Address from SocketAddrV6 in Rust Source: https://docs.rs/async-std/latest/async_std/net/struct Illustrates how to retrieve the IPv6 address component from a SocketAddrV6 instance using the `ip` method. This method returns a reference to the `Ipv6Addr`. It is a const function. ```rust use std::net::{SocketAddrV6, Ipv6Addr}; let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0); assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); ``` -------------------------------- ### Build and Modify Paths with async-std::path::PathBuf Source: https://docs.rs/async-std/latest/async_std/path/index Illustrates how to construct and modify paths using `PathBuf` from async-std. It shows methods for pushing components, setting extensions, and collecting path segments into a `PathBuf`. ```Rust use async_std::path::PathBuf; // This way works... let mut path = PathBuf::from("c:\\"); path.push("windows"); path.push("system32"); path.set_extension("dll"); // ... but push is best used if you don't know everything up // front. If you do, this way is better: let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect(); ``` -------------------------------- ### Get Nested Mutable Reference from Pin - Rust Source: https://docs.rs/async-std/latest/async_std/pin/struct Explains `Pin::as_deref_mut`, which retrieves a `Pin<&mut T>` from a nested `Pin<&mut Pin>`. This operation is safe as the outer `Pin` guarantees the inner pointee cannot move. ```rust pub fn as_deref_mut( self: Pin<&mut Pin>, ) -> Pin<&mut ::Target> Gets `Pin<&mut T>` to the underlying pinned value from this nested `Pin`-pointer. This is a generic method to go from `Pin<&mut Pin>>` to `Pin<&mut T>`. It is safe because the existence of a `Pin>` ensures that the pointee, `T`, cannot move in the future, and this method does not enable the pointee to move. “Malicious” implementations of `Ptr::DerefMut` are likewise ruled out by the contract of `Pin::new_unchecked`. ``` -------------------------------- ### Create a Pair of Connected Unix Sockets (Rust) Source: https://docs.rs/async-std/latest/async_std/os/unix/net/struct Illustrates creating an unnamed pair of connected Unix domain sockets using the `pair` function. This is useful for inter-process communication on the same machine. ```Rust use async_std::os::unix::net::UnixStream; let stream = UnixStream::pair()?; ``` -------------------------------- ### Seek in Async Stream using async-std Source: https://docs.rs/async-std/latest/async_std/pin/struct Seeks to a new position within an asynchronous byte stream. The `SeekFrom` enum specifies the reference point for the seek operation (start, current, or end). Requires the stream to be `Unpin`. ```Rust fn seek(&mut self, pos: SeekFrom) -> SeekFuture<'_, Self> ``` -------------------------------- ### Create a new Weak pointer with allocator (Rust) Source: https://docs.rs/async-std/latest/async_std/sync/struct Constructs a new `Weak` using a provided allocator. This is a nightly-only experimental API. Similar to `Weak::new()`, calling `upgrade` on the result will always return `None`. ```Rust #![feature(allocator_api)] use std::sync::Weak; use std::alloc::System; let empty: Weak = Weak::new_in(System); assert!(empty.upgrade().is_none()); ``` -------------------------------- ### Rust CloneToUninit Experimental API Source: https://docs.rs/async-std/latest/async_std/path/enum Presents the experimental `clone_to_uninit` method from the nightly-only CloneToUninit trait. This method is designed for performing copy-assignment to uninitialized memory, requiring careful usage. ```rust impl CloneToUninit for T where T: Clone { unsafe fn clone_to_uninit(&self, dest: *mut u8) { // ... implementation ... } } ``` -------------------------------- ### Illustrate Pinning Violation with &mut T in Rust Source: https://docs.rs/async-std/latest/async_std/pin/struct This example demonstrates a violation of the pinning API contract. By using `Pin::new_unchecked` on a mutable reference and then swapping the underlying data, the pinned invariant is broken, potentially leading to undefined behavior. ```rust use std::mem; use std::pin::Pin; fn move_pinned_ref(mut a: T, mut b: T) { unsafe { let p: Pin<&mut T> = Pin::new_unchecked(&mut a); // This should mean the pointee `a` can never move again. } mem::swap(&mut a, &mut b); // Potential UB down the road ⚠️ // The address of `a` changed to `b`'s stack slot, so `a` got moved even // though we have previously pinned it! We have violated the pinning API contract. } ``` -------------------------------- ### Display for Pin Source: https://docs.rs/async-std/latest/async_std/pin/struct Enables formatting `Pin` for display. ```APIDOC ## Display for Pin ### Description Implements the `Display` trait for `Pin`, allowing instances to be formatted into strings. ### Method `fmt` ### Endpoint N/A (Struct implementation) ### Parameters None ### Request Body None ### Response #### Success Response (200) N/A (Method returns `Result<(), Error>`) #### Response Example N/A ``` -------------------------------- ### Get Mutable Reference from Pin - Rust Source: https://docs.rs/async-std/latest/async_std/pin/struct Illustrates obtaining a mutable reference to the pinned value using `Pin::as_mut`. This is useful when multiple operations need to be performed on the pinned value, and it's safe due to the pinning contract. ```rust pub fn as_mut(&mut self) -> Pin<&mut ::Target> Gets a mutable reference to the pinned value this `Pin` points to. This is a generic method to go from `&mut Pin>` to `Pin<&mut T>`. It is safe because, as part of the contract of `Pin::new_unchecked`, the pointee cannot move after `Pin>` got created. “Malicious” implementations of `Pointer::DerefMut` are likewise ruled out by the contract of `Pin::new_unchecked`. This method is useful when doing multiple calls to functions that consume the pinning pointer. ``` -------------------------------- ### last: Get the last element of an async stream Source: https://docs.rs/async-std/latest/async_std/prelude/trait The `last` method consumes an async stream and returns a future that resolves to the last element yielded by the stream. If the stream is empty, it resolves to `None`. ```Rust use async_std::prelude::*; use async_std::stream; let s = stream::from_iter(vec![1, 2, 3]); let last_item = s.last().await; assert_eq!(last_item, Some(3)); ```