### Forward Stream to Sink Example Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/sink.md A placeholder example for forwarding data from one stream to a sink. Note that this pattern requires mutable references for both stream and sink. ```rust use futures::sink::SinkExt; use futures::stream::StreamExt; use futures::channel::mpsc; use futures::executor::block_on; async fn example() { let (_tx1, rx1) = mpsc::channel::(10); let (tx2, _rx2) = mpsc::channel::(10); // This pattern requires both to be mutable // See advanced patterns for better approaches } ``` -------------------------------- ### Simple Send Example Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/sink.md Demonstrates a basic asynchronous send operation to an MPSC channel using `SinkExt::send`. ```rust use futures::sink::SinkExt; use futures::channel::mpsc; use futures::executor::block_on; async fn example() { let (mut tx, _rx) = mpsc::channel(10); tx.send(42).await.expect("Send failed"); } ``` -------------------------------- ### Sink with Transformation Example Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/sink.md Demonstrates using `SinkExt::with` to transform data before sending it to the underlying sink. The example shows a sink that accepts `String` but sends the length of the string as an `i32`. ```rust use futures::sink::SinkExt; use futures::channel::mpsc; use futures::executor::block_on; async fn example() { let (tx, _rx) = mpsc::channel::(10); let transformed = tx.with(|x: String| async move { Ok::(x.len() as i32) }); // transformed sink accepts String but sends i32 lengths } ``` -------------------------------- ### Stream Usage Example Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/futures-core.md Demonstrates creating a stream from an iterator and applying transformations using StreamExt methods. ```rust use futures::stream::{Stream, StreamExt}; // Create a stream from an async generator or channel let mut stream = futures::stream::iter(vec![1, 2, 3]); // Use StreamExt methods to process the stream let doubled = stream.map(|x| x * 2); ``` -------------------------------- ### Ready! Macro Usage Example Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/futures-core.md Demonstrates how the ready! macro can be used to automatically propagate Poll::Pending within a future's poll method. ```rust use futures::future::Future; use futures::ready; use std::pin::Pin; use std::task::{Context, Poll}; fn my_future_poll( future: Pin<&mut F>, cx: &mut Context<'_>, ) -> Poll { // ready! propagates Poll::Pending automatically Poll::Ready(ready!(future.poll(cx))) } ``` -------------------------------- ### Boxed Future Creation Example Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/futures-core.md Shows how to create a `BoxFuture` using the `boxed()` method from the `FutureExt` trait. This example creates a simple future that resolves to the integer 42. ```rust use futures::future::{BoxFuture, FutureExt}; fn create_boxed_future() -> BoxFuture<'static, i32> { async { 42 }.boxed() } ``` -------------------------------- ### Local Boxed Future Creation Example Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/futures-core.md Demonstrates creating a `BoxFuture` which can be used for local futures (non-`Send`). Similar to `create_boxed_future`, this example uses `boxed()` to create a future that resolves to 42. ```rust use futures::future::{BoxFuture, FutureExt}; fn create_local_boxed_future() -> BoxFuture<'static, i32> { async { 42 }.boxed() } ``` -------------------------------- ### StreamExt Integration for Channel Receivers Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/channel.md Shows how to use StreamExt combinators with channel receivers. This example uses unbounded channels and demonstrates mapping and filtering operations. ```rust use futures::channel::mpsc; use futures::stream::StreamExt; use futures::executor::block_on; async fn example() { let (tx, rx) = mpsc::unbounded::(); let (tx2, rx2) = mpsc::unbounded::(); // Use StreamExt combinators let mapped = rx.map(|x| x * 2); let filtered = rx2.filter(|x| *x > 5); } ``` -------------------------------- ### Send with Error Handling Example Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/sink.md Illustrates how to handle potential errors during an asynchronous send operation to an MPSC channel. ```rust use futures::sink::SinkExt; use futures::channel::mpsc; use futures::executor::block_on; async fn example() { let (mut tx, rx) = mpsc::channel::(10); match tx.send(42).await { Ok(()) => println!("Sent successfully"), Err(e) => println!("Send error: {:?}", e), } } ``` -------------------------------- ### Context Usage Example Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/futures-core.md Demonstrates how to use the `Context` and `Poll` types within a polling function. This example shows a generic `my_poll` function that takes a future and a context, then polls the future. ```rust use std::task::{Context, Poll, Waker}; use std::pin::Pin; fn my_poll( future: Pin<&mut T>, cx: &mut Context<'_> ) -> Poll { future.poll(cx) } ``` -------------------------------- ### Future Usage Example Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/futures-core.md An example demonstrating the usage of an `async fn`, which implicitly implements the `Future` trait. Futures are typically polled by executors or resolved using `.await`. ```rust use futures::future::Future; use std::task::{Context, Poll}; use std::pin::Pin; async fn my_async_value() -> i32 { 42 } // The async block creates a Future implementation let future = my_async_value(); // futures are polled by executors or via .await ``` -------------------------------- ### Example Usage of Either Enum Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/types.md Demonstrates how to create an instance of the Either enum, specifying a value for either the Left or Right variant. This is useful for representing choices between two types. ```rust use futures::future::Either; let value: Either = Either::Left(42); ``` -------------------------------- ### Handle Errors in Futures with Try Futures Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/README.md Employ `TryFutureExt` for chaining operations on futures that return `Result`. This example demonstrates mapping both successful outcomes (`map_ok`) and errors (`map_err`). ```rust use futures::future::TryFutureExt; async fn example() -> Result { let future: Result = Ok(5); future .map_ok(|x| x * 2) .map_err(|e| format!("Error: {}", e)) .await } ``` -------------------------------- ### Create and Use an Unbounded MPSC Channel Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/channel.md Use `mpsc::unbounded` to create an MPSC channel without a capacity limit. This example shows sending a value and receiving it asynchronously from an unbounded channel. ```rust use futures::channel::mpsc; use futures::executor::block_on; use futures::stream::StreamExt; fn example() { let (tx, mut rx) = mpsc::unbounded(); block_on(async { tx.unbounded_send(42).ok(); if let Some(val) = rx.next().await { println!("Received: {}", val); } }); } ``` -------------------------------- ### Build Documentation with All Features Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Command to build complete documentation for the crate, including all unstable features. The `--open` flag automatically opens the documentation in a web browser. ```bash cargo doc --all-features --open ``` -------------------------------- ### Build with All Features Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/README.md Use this command to build the project with all available features enabled. This is useful for development or when you need the full functionality of the library. ```bash cargo build --all-features ``` -------------------------------- ### Minimal no-std Futures Configuration Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Use this configuration for minimal no-std environments. It includes core Future and Stream traits and the ready! macro, without any allocations or threading. ```toml [dependencies] futures = { version = "0.3", default-features = false } ``` -------------------------------- ### ready() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/future-combinators.md Creates a future that is immediately ready with the given value. ```APIDOC ## ready() ### Description Creates a future that is immediately ready with the given value. ### Signature ```rust pub fn ready(t: T) -> Ready ``` ### Parameters #### Path Parameters - **t** (T) - Required - The value to return ### Returns `Ready` — An immediately ready future ### Example ```rust use futures::future::ready; async fn example() { let value = ready(42).await; assert_eq!(value, 42); } ``` ``` -------------------------------- ### start_send() Method Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/sink.md Begins sending a value to the sink. Must only be called after poll_ready returns Ready. It takes the value to be sent as a parameter. ```rust fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> ``` -------------------------------- ### SeekFrom Enum Definition Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/io.md Defines the possible seek positions relative to the start, end, or current position of a stream. ```rust pub enum SeekFrom { Start(u64), End(i64), Current(i64), } ``` -------------------------------- ### Enable Async/Await Macros Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Enable this feature to use the `join!`, `select!`, and `try_join!` macros, which are essential for writing asynchronous code with async/await syntax. This is almost always recommended. ```toml [dependencies] futures = { version = "0.3", features = ["async-await"] } ``` -------------------------------- ### fold() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/stream-combinators.md Reduces a stream to a single accumulated value by applying a closure to each item and an accumulator. The process starts with an initial value. ```APIDOC ## fold() ### Description Reduces the stream to a single value by repeatedly applying a closure. ### Method `fold` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use futures::stream::{iter, StreamExt}; async fn example() { let stream = iter(vec![1, 2, 3, 4]); let sum = stream.fold(0, |acc, x| async move { acc + x }).await; assert_eq!(sum, 10); } ``` ### Response #### Success Response `Fold` — A future producing the final accumulated value ``` -------------------------------- ### SeekFrom Enum Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/io.md Specifies a seek position relative to the start, end, or current position of a stream. This enum is used with asynchronous seeking operations. ```APIDOC ## SeekFrom Enum ### Description Specifies a seek position relative to the stream. ### Definition ```rust pub enum SeekFrom { Start(u64), End(i64), Current(i64), } ``` ### Variants - `Start(u64)` — Bytes from start - `End(i64)` — Bytes from end (can be negative) - `Current(i64)` — Bytes from current position ``` -------------------------------- ### ThreadPoolBuilder::new Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Creates a new `ThreadPoolBuilder` with default settings to configure a thread pool. ```APIDOC ## ThreadPoolBuilder::new ### Description Initializes a new `ThreadPoolBuilder` with default configuration values. This builder allows for customization of thread pool parameters before creation. ### Signature ```rust pub fn new() -> Self ``` ### Returns - `ThreadPoolBuilder` - A new instance of the builder. ``` -------------------------------- ### Transforming the success value of a future Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/try-future-combinators.md Use `map_ok` to transform the success value of a future. Errors are left unchanged. This example parses a string into an i32. ```rust use futures::future::{TryFutureExt, FutureExt}; use std::num::ParseIntError; async fn example() -> Result { let future: Result = Ok("42".to_string()); let parsed = async { future } .map_ok(|s| s.parse::()) .await?; } ``` -------------------------------- ### Ready! Macro Equivalent Pattern Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/futures-core.md Shows the equivalent pattern to the ready! macro for propagating Poll::Pending, useful for understanding its behavior. ```rust let Poll::Ready(val) = some_future.poll(cx) else { return Poll::Pending; }; // Use val here ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Command to execute the entire test suite for the crate, ensuring all features are tested. This is useful for verifying the correctness of the library across all its functionalities. ```bash cargo test --all-features ``` -------------------------------- ### Transforming the error value of a future Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/try-future-combinators.md Use `map_err` to transform the error value of a future. Success values are left unchanged. This example formats an integer error into a string. ```rust use futures::future::TryFutureExt; async fn example() -> Result { let future: Result = Err(42); future .map_err(|e| format!("Error code: {}", e)) .await } ``` -------------------------------- ### Get Next Item from a Stream Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/stream-combinators.md Retrieves the next item from a stream. This method requires the stream to be Unpin. It returns an Option containing the item or None if the stream is exhausted. ```rust use futures::stream::{iter, StreamExt}; async fn example() { let mut stream = iter(vec![1, 2, 3]); assert_eq!(stream.next().await, Some(1)); assert_eq!(stream.next().await, Some(2)); } ``` -------------------------------- ### Build No-std Minimal Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/README.md Build the project with default features disabled for a minimal, no-standard-library environment. This is suitable for embedded systems or environments where `std` is not available. ```bash cargo build --no-default-features ``` -------------------------------- ### Minimal Future Execution in Rust Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/README.md Demonstrates the most basic usage of `futures::executor::block_on` to run a simple async block. ```rust use futures::executor::block_on; fn main() { let result = block_on(async { 42 }); println!("Result: {}", result); } ``` -------------------------------- ### start_send() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/sink.md Begins sending a value to the sink. This method should only be called after `poll_ready` has returned `Ready`. ```APIDOC ## start_send() ### Description Begins sending a value to the sink. Must only be called after `poll_ready` returns Ready. ### Signature: ```rust fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> ``` ### Parameters: | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | item | Item | Yes | Value to send | ### Returns: `Result<(), Error>` — Ok if send initiated, Err on error --- ``` -------------------------------- ### Configure and create ThreadPool with ThreadPoolBuilder Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Use `ThreadPoolBuilder` to customize thread pool settings like the number of threads, stack size, and thread name prefix before creating the pool. ```rust use futures::executor::ThreadPoolBuilder; fn main() { let pool = ThreadPoolBuilder::new() .pool_size(4) .name_prefix("worker") .create() .expect("Failed to create pool"); } ``` -------------------------------- ### Pin Type Alias for Pinned References Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/types.md A type alias for `core::pin::Pin

`, commonly used in async Rust to prevent futures and streams from being moved after they have started. ```rust pub type Pin

= core::pin::Pin

``` -------------------------------- ### Handle Async Read I/O Errors Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/errors.md Demonstrates how to handle potential I/O errors when reading from an async source, specifically checking for `UnexpectedEof`. ```rust use futures::io::AsyncReadExt; use std::io; async fn example(mut reader: impl futures::io::AsyncRead + Unpin) { match reader.read_exact(&mut vec![0u8; 1024]).await { Ok(()) => println!("Read successfully"), Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => { println!("EOF reached unexpectedly") } Err(e) => println!("I/O error: {}", e), } } ``` -------------------------------- ### Chaining recovery futures after error Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/try-future-combinators.md Use `or_else` to chain a recovery future after an error. If the initial future is successful, its value is used. This example provides a default value when an error occurs. ```rust use futures::future::TryFutureExt; async fn example() -> Result { let f1: Result = Err("failed".to_string()); f1 .or_else(|_| async { Ok(0) // Default value on error }) .await } ``` -------------------------------- ### Chaining futures after success Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/try-future-combinators.md Use `and_then` to chain another try-future after a successful result. If the initial future returns an error, it short-circuits. This example doubles a positive number or returns an error. ```rust use futures::future::TryFutureExt; async fn example() -> Result { let f1: Result = Ok(5); f1 .and_then(|x| async move { if x > 0 { Ok(x * 2) } else { Err("negative".to_string()) } }) .await } ``` -------------------------------- ### Complete Futures Configuration Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Includes all available features for futures-rs, such as std, async/await, executor, thread-pool, channel, io, sink, and compat. This provides the most comprehensive set of capabilities. ```toml [dependencies] futures = { version = "0.3", features = [ "std", "async-await", "executor", "thread-pool", "channel", "io", "sink", "compat" ] } ``` -------------------------------- ### Handling RecvError in Oneshot Channels Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/errors.md Demonstrates awaiting a oneshot receiver and handling the RecvError that occurs when the sender is dropped before sending a value. This example uses block_on to run the async operation. ```rust use futures::channel::oneshot; use futures::executor::block_on; fn example() { let (_tx, rx) = oneshot::channel::(); block_on(async { match rx.await { Ok(val) => println!("Received: {}", val), Err(_) => println!("RecvError: sender dropped"), } }); } ``` -------------------------------- ### Enable Default Features Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Use this configuration to enable the default feature set, which includes standard library support, async/await macros, and built-in executors. ```toml [dependencies] futures = "0.3" ``` -------------------------------- ### Sink Trait Definition Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/sink.md The Sink trait defines the interface for asynchronous data sinks. It includes methods for checking readiness, starting a send operation, flushing buffered data, and closing the sink. ```APIDOC ## Sink Trait ### Description The `Sink` trait represents a target that can asynchronously receive values. ### Definition **Signature:** ```rust pub trait Sink { type Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>; fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error>; fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>; fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>; } ``` **Associated Types:** | Type | |------| | `Error` | The error type returned by sink operations --- ``` -------------------------------- ### Enable Standard Library Support Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Enable this feature for environments that use the standard library, providing mutexes, synchronization primitives, I/O traits, and threading support. Omit for no-std environments. ```toml [dependencies] futures = { version = "0.3", features = ["std"] } ``` -------------------------------- ### Handling TrySendError for Full or Disconnected MPSC Channels Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/errors.md Illustrates how to use try_send and handle TrySendError, which can occur if the MPSC channel's buffer is full or if the receiver has been dropped. The example shows extracting the unsent value. ```rust use futures::channel::mpsc; fn example() { let (mut tx, _rx) = mpsc::channel::(2); // First two sends succeed tx.try_send(1).ok(); tx.try_send(2).ok(); // Third send fails match tx.try_send(3) { Ok(()) => println!("Sent"), Err(e) => { let val = e.into_inner(); println!("Buffer full, failed to send: {}", val); } } } ``` -------------------------------- ### Enable I/O Compatibility for Futures 0.1 and 0.3 Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Enable compatibility for I/O traits between futures 0.1 and 0.3. Use this when migrating I/O code from futures 0.1. Requires the 'compat' and 'io' features. ```toml [dependencies] futures = { version = "0.3", features = ["compat", "io-compat"] } ``` -------------------------------- ### Concurrent Task Execution with ThreadPool in Rust Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/README.md Shows how to create a thread pool and spawn multiple asynchronous tasks onto it for concurrent execution. ```rust use futures::executor::ThreadPool; use futures::task::SpawnExt; fn main() { let pool = ThreadPool::new().expect("Failed to create pool"); for i in 0..5 { let pool_clone = pool.clone(); pool.spawn(async move { println!("Task {}", i); }).ok(); } } ``` -------------------------------- ### Enable Allocator Support (No-Std) Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Use this feature for no_std environments that have an allocator. It enables boxed futures, channels, stream combinators, and collections like Vec and HashMap. ```toml [dependencies] futures = { version = "0.3", default-features = false, features = ["alloc"] } ``` -------------------------------- ### Spawn a Simple Async Task Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/README.md Use `block_on` from `futures::executor` to run an async function to completion on the current thread. ```rust use futures::executor::block_on; async fn main_async() { // Your async code here } fn main() { block_on(main_async()); } ``` -------------------------------- ### Initialize and use a LocalPool executor Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Create a new `LocalPool` to manage tasks on a single thread. Obtain a `LocalSpawner` from the pool to spawn new asynchronous tasks. The pool can then be used to run futures until completion or until all spawned tasks are finished. ```rust use futures::executor::LocalPool; use futures::stream::StreamExt; fn main() { let mut pool = LocalPool::new(); let spawner = pool.spawner(); pool.run_until(async { // Run async code }); } ``` -------------------------------- ### join() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/future-combinators.md Combines two futures, returning both outputs when both complete. ```APIDOC ## join() ### Description Combines two futures, returning both outputs when both complete. ### Signature ```rust pub fn join(f1: F1, f2: F2) -> Join where F1: Future, F2: Future, ``` ### Parameters #### Path Parameters - **f1** (F1) - Required - First future - **f2** (F2) - Required - Second future ### Returns `Join` — A future producing `(F1::Output, F2::Output)` ### Example ```rust use futures::future::join; async fn example() { let f1 = async { 1 }; let f2 = async { 2 }; let (a, b) = join(f1, f2).await; assert_eq!((a, b), (1, 2)); } ``` ``` -------------------------------- ### Server/Networking Futures Configuration Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md This configuration is suitable for server and networking applications. It includes std, async/await, executor, io, sink, and channel features. ```toml [dependencies] futures = { version = "0.3", features = [ "std", "async-await", "executor", "io", "sink", "channel" ] } ``` -------------------------------- ### Spawn Task with ThreadPool Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Demonstrates spawning an async task onto a `ThreadPool`. Handles potential `SpawnError` if the executor is shut down. ```rust use futures::executor::ThreadPool; use futures::task::SpawnExt; fn main() { let pool = ThreadPool::new().unwrap(); match pool.spawn(async { 42 }) { Ok(()) => println!("Spawned successfully"), Err(e) => println!("Spawn error: {:?}", e), } } ``` -------------------------------- ### Try sending a value with mpsc channel Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/channel.md Demonstrates how to attempt sending a value to an mpsc channel and handle potential errors, including extracting the unsent value if the send fails. ```rust use futures::channel::mpsc; let (mut tx, _rx) = mpsc::channel::(1); match tx.try_send(42) { Ok(()) => println!("Sent"), Err(e) => { let val = e.into_inner(); println!("Failed to send: {}", val); } } ``` -------------------------------- ### Test No-std Build Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Command to test a no-standard-library build of the crate, specifically enabling the 'alloc' feature. This is crucial for testing environments where the standard library is not available. ```bash cargo test --no-default-features --features alloc ``` -------------------------------- ### Enter Executor Context Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Use the `enter` function to gain access to the current executor context, enabling task spawning without explicitly passing an executor instance. This is typically used internally by functions like `block_on`. ```rust pub fn enter() -> Result ``` -------------------------------- ### Asynchronous Communication with Channels in Rust Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/README.md Demonstrates sending a value through a multi-producer, single-consumer channel and receiving it asynchronously. ```rust use futures::channel::mpsc; use futures::sink::SinkExt; use futures::stream::StreamExt; use futures::executor::block_on; fn main() { block_on(async { let (mut tx, mut rx) = mpsc::channel(10); tx.send(42).await.ok(); if let Some(val) = rx.next().await { println!("Received: {}", val); } }); } ``` -------------------------------- ### map_ok() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/try-future-combinators.md Transforms each success item from a TryStream using a provided closure. It returns a new TryStream with the transformed success values. ```APIDOC ## map_ok() ### Description Transforms each success item from the stream using a closure. ### Signature ```rust fn map_ok(self, f: F) -> MapOk where F: FnMut(Self::Ok) -> T, Self: Sized, ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **f** (FnMut(Self::Ok) -> T) - Required - Closure to transform each item ### Returns `MapOk` — A new try-stream ### Source `futures-util/src/stream/try_stream.rs` ``` -------------------------------- ### Enter Executor Context Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Use `enter()` to obtain a guard that maintains executor context. This is necessary before spawning tasks. ```rust use futures::executor::enter; fn main() { let _guard = enter().expect("Unable to enter executor context"); // Can now spawn tasks } ``` -------------------------------- ### Chaining Operations on Futures in Rust Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/README.md Shows how to chain operations like `map` onto a future and then `await` its result. ```rust use futures::future::FutureExt; use futures::executor::block_on; async fn async_fn() -> i32 { 5 } fn main() { let result = block_on(async { async_fn() .map(|x| x * 2) .await }); assert_eq!(result, 10); } ``` -------------------------------- ### SinkExt Integration for Channel Senders Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/channel.md Demonstrates using SinkExt combinators with a channel sender. Ensure the necessary futures and channel modules are imported. ```rust use futures::channel::mpsc; use futures::sink::SinkExt; use futures::executor::block_on; async fn example() { let (mut tx, mut rx) = mpsc::channel(10); // Use SinkExt methods tx.send(1).await.ok(); tx.send(2).await.ok(); tx.flush().await.ok(); // Receive values let _val = rx.next().await; } ``` -------------------------------- ### ThreadPoolBuilder::create Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Builds and returns a new `ThreadPool` instance based on the configurations set in the builder. ```APIDOC ## ThreadPoolBuilder::create ### Description Constructs and returns a `ThreadPool` instance using the parameters previously configured via the `ThreadPoolBuilder`. This is the final step in creating a customized thread pool. ### Signature ```rust pub fn create(self) -> Result ``` ### Returns - `Result` - A `Result` containing the newly created `ThreadPool` on success, or an `io::Error` if the pool could not be created. ### Example ```rust use futures::executor::ThreadPoolBuilder; let pool = ThreadPoolBuilder::new() .pool_size(4) .name_prefix("worker") .create() .expect("Failed to create pool"); ``` ``` -------------------------------- ### enter() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Enters the executor context, allowing task spawning without an explicit executor. Used internally by `block_on`. ```APIDOC ## enter() ### Description Enters the executor context, allowing task spawning without an explicit executor. Used internally by `block_on`. ### Signature ```rust pub fn enter() -> Result ``` ### Returns `Result` - Guard for the executor context ``` -------------------------------- ### Create and Use Oneshot Channel Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/channel.md Demonstrates creating a oneshot channel, sending a value, and receiving it asynchronously. Ensure the sender is dropped after sending or the receiver will not complete. ```rust use futures::channel::oneshot; use futures::executor::block_on; fn example() { let (tx, rx) = oneshot::channel::(); block_on(async { tx.send(42).ok(); if let Ok(val) = rx.await { println!("Received: {}", val); } }); } ``` -------------------------------- ### Create Immediately Ready Ok/Err Future Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/future-combinators.md Creates a future that is immediately ready with either an `Ok` or `Err` variant of a `Result`. This is useful for futures that represent a known success or failure. ```rust use futures::future::ok; use futures::future::err; // Example of creating an Ok future // let ok_future = ok::(10); // Example of creating an Err future // let err_future = err::("an error"); ``` -------------------------------- ### Add futures-channel to Cargo.toml Source: https://github.com/rust-lang/futures-rs/blob/master/futures-channel/README.md Add the futures-channel crate as a dependency in your Cargo.toml file to include it in your project. ```toml [dependencies] futures-channel = "0.3" ``` -------------------------------- ### ThreadPool::new Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Creates a new thread pool with default configuration. The number of threads defaults to the CPU count. ```APIDOC ## ThreadPool::new ### Description Creates a new thread pool with default configuration. The number of worker threads is automatically set to the number of CPU cores available. ### Signature ```rust pub fn new() -> Result ``` ### Returns - `Result` - A new `ThreadPool` instance or an `io::Error` if creation fails. ### Example ```rust use futures::executor::ThreadPool; use futures::task::SpawnExt; let pool = ThreadPool::new().expect("Failed to create pool"); pool.spawn(async { println!("Task running on thread pool"); }).ok(); ``` ``` -------------------------------- ### Enable Asynchronous I/O Traits Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Enable this feature, which requires `std` and `alloc` features, to use asynchronous I/O traits like `AsyncRead`, `AsyncWrite`, and their associated extension traits. This is essential for building I/O-bound applications. ```toml [dependencies] futures = { version = "0.3", features = ["io"] } ``` -------------------------------- ### Enable Vectored Write-All Operations Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Enable the unstable 'write-all-vectored' feature to add the 'write_all_vectored()' method to 'AsyncWriteExt'. Requires the 'unstable' and 'io' features. ```toml [dependencies] futures = { version = "0.3", features = ["unstable", "io", "write-all-vectored"] } ``` -------------------------------- ### Ready! Macro Definition Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/futures-core.md The ready! macro simplifies propagating Poll::Pending in custom future and stream implementations. ```rust macro_rules! ready { ($e:expr) => { ... } } ``` -------------------------------- ### ok() and err() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/future-combinators.md Creates a future that is immediately ready with Ok or Err. ```APIDOC ## ok() and err() ### Description Creates a future that is immediately ready with `Ok` or `Err`. ### Signatures ```rust pub fn ok(t: T) -> Ready> pub fn err(e: E) -> Ready> ``` ### Returns `Ready>` ``` -------------------------------- ### Enable Channels Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Enable this feature, which requires the `alloc` feature, to use MPSC and oneshot channels for inter-task communication. This is useful for implementing pub/sub patterns and coordinating async tasks. ```toml [dependencies] futures = { version = "0.3", features = ["channel"] } ``` -------------------------------- ### select() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/future-combinators.md Races two futures, returning the output of whichever completes first. It takes two futures as input and returns a new future that resolves with the output of the first future to complete. ```APIDOC ## select() ### Description Races two futures, returning the output of whichever completes first. ### Signature ```rust pub fn select(f1: F1, f2: F2) -> Select where F1: Future + Unpin, F2: Future + Unpin, ``` ### Parameters #### Path Parameters - **f1** (F1) - Required - First future - **f2** (F2) - Required - Second future ### Returns `Select` — A future producing `Either<(F1::Output, F2), (F1, F2::Output)>` ``` -------------------------------- ### Enable Futures 0.1 and 0.3 Compatibility Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Enable compatibility shims for interoperability between futures 0.1 and 0.3. Useful for migrating from futures 0.1 or using libraries that depend on futures 0.1. Requires the 'std' feature. ```toml [dependencies] futures = { version = "0.3", features = ["compat"] } ``` -------------------------------- ### join_all() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/future-combinators.md Joins multiple futures from an iterator, returning all outputs as a vector. ```APIDOC ## join_all() ### Description Joins multiple futures from an iterator, returning all outputs as a vector. ### Signature (requires alloc feature) ```rust pub fn join_all(iter: I) -> JoinAll where I: IntoIterator, I::Item: Future, ``` ### Parameters #### Path Parameters - **iter** (I) - Required - Iterator of futures ### Returns `JoinAll` — A future producing `Vec` ### Example ```rust use futures::future::join_all; async fn example() { let futures = vec![async { 1 }, async { 2 }, async { 3 }]; let results = join_all(futures).await; assert_eq!(results, vec![1, 2, 3]); } ``` ``` -------------------------------- ### Embedded Futures with Allocator Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md This configuration is for embedded systems with an allocator. It includes no-std, alloc, async-await, and spin features. ```toml [dependencies] futures = { version = "0.3", default-features = false, features = [ "alloc", "async-await", "spin" ] } ``` -------------------------------- ### Async Seek and Read Operation Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/io.md Demonstrates seeking to a specific position in a file and then reading a fixed number of bytes from that position. ```rust use futures::io::{AsyncSeekExt, AsyncReadExt}; async fn example(mut file: impl futures::io::AsyncSeek + futures::io::AsyncRead + Unpin) { // Seek to position file.seek(std::io::SeekFrom::Start(100)).await.ok(); // Read from that position let mut buf = [0u8; 64]; file.read_exact(&mut buf).await.ok(); } ``` -------------------------------- ### channel() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/channel.md Creates a oneshot channel, returning a sender and receiver pair. ```APIDOC ## channel() ### Description Creates a oneshot channel for sending exactly one message from a sender to a receiver. ### Signature ```rust pub fn channel() -> (Sender, Receiver) ``` ### Returns - `(Sender, Receiver)` — A tuple containing the sender and receiver ends of the channel. ``` -------------------------------- ### ready! Macro Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/futures-core.md A convenience macro for propagating `Poll::Pending` in custom future or stream implementations. It simplifies the pattern of checking for `Poll::Ready` and returning `Poll::Pending` early. ```APIDOC ## ready! Macro ### Definition ```rust macro_rules! ready { ($e:expr) => { ... } } ``` Convenience macro for propagating `Poll::Pending` in custom future/stream implementations. ```rust let Poll::Ready(val) = some_future.poll(cx) else { return Poll::Pending; }; // Use val here ``` Can be replaced by the equivalent pattern: ```rust let val = ready!(some_future.poll(cx)); ``` **Source:** `futures-core/src/ready.rs` ### Usage Example ```rust use futures::future::Future; use futures::ready; use std::pin::Pin; use std::task::{Context, Poll}; fn my_future_poll( future: Pin<&mut F>, cx: &mut Context<'_>, ) -> Poll { // ready! propagates Poll::Pending automatically Poll::Ready(ready!(future.poll(cx))) } ``` ``` -------------------------------- ### poll_ready() Method Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/sink.md Checks if the sink is ready to accept a value. Must be called before start_send and must return Ready before each send. ```rust fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> ``` -------------------------------- ### Spawn future with ThreadPool Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Use `ThreadPool::new()` to create a multi-threaded executor and `spawn` to submit futures for execution. The pool size defaults to the CPU count. ```rust use futures::executor::ThreadPool; use futures::task::SpawnExt; fn main() { let pool = ThreadPool::new().expect("Failed to create pool"); pool.spawn(async { println!("Task running on thread pool"); }).ok(); } ``` -------------------------------- ### Transform Success and Error Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/try-future-combinators.md Shows how to use `map_ok` and `map_err` to transform the success and error values of a `TryFuture` independently. ```APIDOC ## Transform Success and Error ### Description This example illustrates how to transform both the success and error types of a `TryFuture` using `map_ok` and `map_err` combinators. ### Code Example ```rust use futures::future::TryFutureExt; async fn example() -> Result { let future: Result = Ok(42); let result = future .map_ok(|x| format!("Value: {{}}", x)) .map_err(|e| e.len() as i32) .await?; Ok(result) } ``` ``` -------------------------------- ### repeat_with() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/stream-combinators.md Creates an infinite stream by repeatedly calling a closure. Each call to the closure generates the next item in the stream. ```APIDOC ## repeat_with() ### Description Creates an infinite stream by repeatedly calling a closure. ### Signature ```rust pub fn repeat_with(f: F) -> RepeatWith where F: FnMut() -> T, ``` ### Parameters #### Path Parameters - **f** (FnMut() -> T) - Required - Closure to generate values ### Returns `RepeatWith` — An infinite stream ``` -------------------------------- ### enter Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/executor.md Creates a guard that maintains executor context while it's held. This is necessary before spawning tasks within the executor context. ```APIDOC ## enter ### Description A guard that maintains executor context while it's held. This function should be called before spawning tasks. ### Usage ```rust use futures::executor::enter; let _guard = enter().expect("Unable to enter executor context"); // Can now spawn tasks ``` ``` -------------------------------- ### Send Data with MPSC Channel Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/README.md Demonstrates sending data through a multi-producer, single-consumer (MPSC) channel and handling potential send errors. ```rust use futures::sink::SinkExt; async fn example() { let (mut tx, _rx) = futures::channel::mpsc::channel::(10); match tx.send(42).await { Ok(()) => println!("Sent"), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### AsyncSeekExt::seek and AsyncReadExt::read_exact Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/io.md Demonstrates a common I/O pattern: seeking to a specific position in a file or stream and then reading a fixed number of bytes from that position. This is often used for random access to data. ```APIDOC ## AsyncSeekExt::seek and AsyncReadExt::read_exact ### Description Seeks to a position and then reads a specific number of bytes. ### Usage Pattern This pattern combines seeking to a desired offset and then reading a precise amount of data, useful for random access operations. ### Example ```rust use futures::io::{AsyncSeekExt, AsyncReadExt}; async fn example(mut file: impl futures::io::AsyncSeek + futures::io::AsyncRead + Unpin) { // Seek to position 100 from the start file.seek(std::io::SeekFrom::Start(100)).await.ok(); // Read exactly 64 bytes from the current position let mut buf = [0u8; 64]; file.read_exact(&mut buf).await.ok(); } ``` ``` -------------------------------- ### Create and Use a Bounded MPSC Channel Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/channel.md Use `mpsc::channel` to create a bounded channel with a specified buffer capacity. This snippet demonstrates sending a value and then receiving it asynchronously. ```rust use futures::channel::mpsc; use futures::executor::block_on; use futures::sink::SinkExt; use futures::stream::StreamExt; fn example() { let (mut tx, mut rx) = mpsc::channel(10); block_on(async { tx.send(42).await.ok(); if let Some(val) = rx.next().await { println!("Received: {}", val); } }); } ``` -------------------------------- ### Use Spin Locks for No_std Environments Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/configuration.md Enable the use of spin locks instead of std mutexes for no_std environments. This is useful for building no_std applications that need shared futures or for real-time systems where std locks are unavailable. Requires the 'alloc' feature. ```toml [dependencies] futures = { version = "0.3", default-features = false, features = ["alloc", "spin"] } ``` -------------------------------- ### with() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/sink.md Transforms items before they are sent through the sink using a provided closure. This allows for modifying each item individually. ```APIDOC ## with() ### Description Transforms items before sending them through the sink. ### Signature ```rust fn with(self, f: F) -> With where F: FnMut(U) -> Fut, Fut: Future>, Self: Sized, ``` ### Parameters #### Path Parameters - **f** (FnMut(U) -> Fut) - Required - Closure to transform items ### Returns `With` — A new sink that transforms items ``` -------------------------------- ### poll_ready() Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/api-reference/sink.md Checks if the sink is ready to accept a value. This method must be called before `start_send` and should return `Ready` before initiating a send operation. ```APIDOC ## poll_ready() ### Description Checks if the sink is ready to accept a value. ### Signature: ```rust fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> ``` ### Returns: `Poll>` - `Ready(Ok(()))` — Ready to send - `Ready(Err(e))` — Error, sink unusable - `Pending` — Not ready, will be woken ### Usage: Must be called before `start_send` and must return Ready before each send. --- ``` -------------------------------- ### ThreadPoolBuilder Source: https://github.com/rust-lang/futures-rs/blob/master/_autodocs/types.md A builder pattern for creating and configuring a `ThreadPool`. It allows customization of pool size, stack size, and thread name prefixes before creating the thread pool. ```APIDOC ## ThreadPoolBuilder ### Description Configurable thread pool builder. ### Methods - `new() -> Self` — New builder - `pool_size(&mut self, size: usize) -> &mut Self` — Set thread count - `stack_size(&mut self, size: usize) -> &mut Self` — Set stack size - `name_prefix(&mut self, prefix: S) -> &mut Self` — Set thread name prefix - `create(self) -> Result` — Build pool ```