### TakeUntil Example Source: https://docs.rs/futures/latest/futures/prelude/stream/struct.TakeUntil.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E An example demonstrating the usage of `take_until` and `take_result`. ```APIDOC ## Example Usage of `take_result` ```rust use futures::future; use futures::stream::{self, StreamExt}; use futures::task::Poll; let stream = stream::iter(1..=10); let mut i = 0; let stop_fut = future::poll_fn(|_cx| { i += 1; if i <= 5 { Poll::Pending } else { Poll::Ready("reason") } }); let mut stream = stream.take_until(stop_fut); let _ = stream.by_ref().collect::>().await; let result = stream.take_result().unwrap(); assert_eq!(result, "reason"); ``` ``` -------------------------------- ### Async Task System Example Source: https://docs.rs/futures/latest/src/futures/lib.rs.html?search= Demonstrates setting up an executor, creating asynchronous tasks using async blocks, and executing them. This example shows how to use a thread pool to spawn futures and process data asynchronously. ```rust # use futures::channel::mpsc; # use futures::executor; # use futures::executor::ThreadPool; # use futures::StreamExt; # fn main() { # { let pool = ThreadPool::new().expect("Failed to build pool"); let (tx, rx) = mpsc::unbounded::(); let fut_values = async { let fut_tx_result = async move { (0..100).for_each(|v| { tx.unbounded_send(v).expect("Failed to send"); }) }; pool.spawn_ok(fut_tx_result); let fut_values = rx .map(|v| v * 2) .collect(); fut_values.await }; let values: Vec = executor::block_on(fut_values); println!("Values={{:?}}", values); # } # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371 } ``` -------------------------------- ### OptionFuture Example Source: https://docs.rs/futures/latest/futures/future/struct.OptionFuture.html?search= Demonstrates creating and awaiting an OptionFuture with both Some and None values. ```rust use futures::future::OptionFuture; let mut a: OptionFuture<_> = Some(async { 123 }).into(); assert_eq!(a.await, Some(123)); a = None.into(); assert_eq!(a.await, None); ``` -------------------------------- ### Async Task System Example Source: https://docs.rs/futures/latest/futures/index.html?search= Demonstrates the creation and execution of asynchronous tasks using async/await, futures, streams, and executors. This example shows how to set up a thread pool, send data asynchronously via a channel, process it with a stream, and collect the results. ```Rust fn main() { let pool = ThreadPool::new().expect("Failed to build pool"); let (tx, rx) = mpsc::unbounded::(); // Create a future by an async block, where async is responsible for an // implementation of Future. At this point no executor has been provided // to this future, so it will not be running. let fut_values = async { // Create another async block, again where the Future implementation // is generated by async. Since this is inside of a parent async block, // it will be provided with the executor of the parent block when the parent // block is executed. // // This executor chaining is done by Future::poll whose second argument // is a std::task::Context. This represents our executor, and the Future // implemented by this async block can be polled using the parent async // block's executor. let fut_tx_result = async move { (0..100).for_each(|v| { tx.unbounded_send(v).expect("Failed to send"); }) }; // Use the provided thread pool to spawn the generated future // responsible for transmission pool.spawn_ok(fut_tx_result); let fut_values = rx .map(|v| v * 2) .collect(); // Use the executor provided to this async block to wait for the // future to complete. fut_values.await }; // Actually execute the above future, which will invoke Future::poll and // subsequently chain appropriate Future::poll and methods needing executors // to drive all futures. Eventually fut_values will be driven to completion. let values: Vec = executor::block_on(fut_values); println!("Values={{:?}}", values); } ``` -------------------------------- ### AtomicWaker::new() Example Source: https://docs.rs/futures/latest/futures/task/struct.AtomicWaker.html?search= Creates a new AtomicWaker instance. This is the starting point for using AtomicWaker. ```rust pub const fn new() -> AtomicWaker ``` -------------------------------- ### Async Task System Example Source: https://docs.rs/futures/latest/futures/index.html Demonstrates the creation and execution of futures using async blocks, task spawning, and executor chaining. This example shows how to send and receive data asynchronously using channels and collect results. ```Rust fn main() { let pool = ThreadPool::new().expect("Failed to build pool"); let (tx, rx) = mpsc::unbounded::(); // Create a future by an async block, where async is responsible for an // implementation of Future. At this point no executor has been provided // to this future, so it will not be running. let fut_values = async { // Create another async block, again where the Future implementation // is generated by async. Since this is inside of a parent async block, // it will be provided with the executor of the parent block when the parent // block is executed. // // This executor chaining is done by Future::poll whose second argument // is a std::task::Context. This represents our executor, and the Future // implemented by this async block can be polled using the parent async // block's executor. let fut_tx_result = async move { (0..100).for_each(|v| { tx.unbounded_send(v).expect("Failed to send"); }) }; // Use the provided thread pool to spawn the generated future // responsible for transmission pool.spawn_ok(fut_tx_result); let fut_values = rx .map(|v| v * 2) .collect(); // Use the executor provided to this async block to wait for the // future to complete. fut_values.await }; // Actually execute the above future, which will invoke Future::poll and // subsequently chain appropriate Future::poll and methods needing executors // to drive all futures. Eventually fut_values will be driven to completion. let values: Vec = executor::block_on(fut_values); println!("Values={:?}", values); } ``` -------------------------------- ### Example: Round Robin Selection Source: https://docs.rs/futures/latest/futures/prelude/stream/fn.select_with_strategy.html Shows how to implement a round-robin strategy using `select_with_strategy` to alternate between two streams. This example uses a closure with state to toggle between streams. ```rust use futures::stream::{ repeat, select_with_strategy, PollNext, StreamExt }; let left = repeat(1); let right = repeat(2); let rrobin = |last: &mut PollNext| last.toggle(); let mut out = select_with_strategy(left, right, rrobin); for _ in 0..100 { // We should be alternating now. assert_eq!(1, out.select_next_some().await); assert_eq!(2, out.select_next_some().await); } ``` -------------------------------- ### try_next() - Example Source: https://docs.rs/futures/latest/futures/prelude/stream/trait.TryStreamExt.html?search= Demonstrates using `try_next` to get the next item from a stream, handling both `Ok` and `Err` values. ```rust use futures::stream::{self, TryStreamExt}; let mut stream = stream::iter(vec![Ok(()), Err(())]); assert_eq!(stream.try_next().await, Ok(Some(()))); assert_eq!(stream.try_next().await, Err(())); ``` -------------------------------- ### Async Task System Execution Example Source: https://docs.rs/futures/latest/src/futures/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates building an asynchronous task system using futures, streams, and executors. It shows how to create futures with async blocks, spawn tasks onto a thread pool, and collect results from a stream. This example requires the futures crate and its executor module. ```rust # use futures::channel::mpsc; # use futures::executor; ///standard executors to provide a context for futures and streams # use futures::executor::ThreadPool; # use futures::StreamExt; # fn main() { # { let pool = ThreadPool::new().expect("Failed to build pool"); let (tx, rx) = mpsc::unbounded::(); // Create a future by an async block, where async is responsible for an // implementation of Future. At this point no executor has been provided // to this future, so it will not be running. let fut_values = async { // Create another async block, again where the Future implementation // is generated by async. Since this is inside of a parent async block, // it will be provided with the executor of the parent block when the parent // block is executed. // // This executor chaining is done by Future::poll whose second argument // is a std::task::Context. This represents our executor, and the Future // implemented by this async block can be polled using the parent async // block's executor. let fut_tx_result = async move { (0..100).for_each(|v| { tx.unbounded_send(v).expect("Failed to send"); }) }; // Use the provided thread pool to spawn the generated future // responsible for transmission pool.spawn_ok(fut_tx_result); let fut_values = rx .map(|v| v * 2) .collect(); // Use the executor provided to this async block to wait for the // future to complete. fut_values.await }; // Actually execute the above future, which will invoke Future::poll and // subsequently chain appropriate Future::poll and methods needing executors // to drive all futures. Eventually fut_values will be driven to completion. let values: Vec = executor::block_on(fut_values); println!("Values={{:?}}", values); # } # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371 } ``` -------------------------------- ### Async Executor and Task System Example Source: https://docs.rs/futures/latest/src/futures/lib.rs.html?search=u32+-%3E+bool Demonstrates setting up a thread pool executor and using async/await syntax to manage asynchronous tasks, including sending and receiving data through an unbounded channel. ```rust # use futures::channel::mpsc; # use futures::executor; # use futures::executor::ThreadPool; # use futures::StreamExt; # fn main() { # { let pool = ThreadPool::new().expect("Failed to build pool"); let (tx, rx) = mpsc::unbounded::(); // Create a future by an async block, where async is responsible for an // implementation of Future. At this point no executor has been provided // to this future, so it will not be running. let fut_values = async { // Create another async block, again where the Future implementation // is generated by async. Since this is inside of a parent async block, // it will be provided with the executor of the parent block when the parent // block is executed. // // This executor chaining is done by Future::poll whose second argument // is a std::task::Context. This represents our executor, and the Future // implemented by this async block can be polled using the parent async // block's executor. let fut_tx_result = async move { (0..100).for_each(|v| { tx.unbounded_send(v).expect("Failed to send"); }) }; // Use the provided thread pool to spawn the generated future // responsible for transmission pool.spawn_ok(fut_tx_result); let fut_values = rx .map(|v| v * 2) .collect(); // Use the executor provided to this async block to wait for the // future to complete. fut_values.await }; // Actually execute the above future, which will invoke Future::poll and // subsequently chain appropriate Future::poll and methods needing executors // to drive all futures. Eventually fut_values will be driven to completion. let values: Vec = executor::block_on(fut_values); println!("Values={{:?}}", values); # } # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371 } ``` -------------------------------- ### Example: Consuming a Mutex Source: https://docs.rs/futures/latest/futures/lock/struct.Mutex.html?search= Demonstrates how to create a Mutex and then consume it to retrieve the inner value. ```rust use futures::lock::Mutex; let mutex = Mutex::new(0); assert_eq!(mutex.into_inner(), 0); ``` -------------------------------- ### AtomicWaker Example: Signalling a Flag Source: https://docs.rs/futures/latest/futures/task/struct.AtomicWaker.html This example demonstrates how to use AtomicWaker to create a Flag that can be signalled manually. It shows the typical pattern of registering a waker before checking a condition and waking the waker when the condition is met. ```rust use futures::future::Future; use futures::task::{Context, Poll, AtomicWaker}; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::Relaxed; use std::pin::Pin; struct Inner { waker: AtomicWaker, set: AtomicBool, } #[derive(Clone)] struct Flag(Arc); impl Flag { pub fn new() -> Self { Self(Arc::new(Inner { waker: AtomicWaker::new(), set: AtomicBool::new(false), })) } pub fn signal(&self) { self.0.set.store(true, Relaxed); self.0.waker.wake(); } } impl Future for Flag { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { // quick check to avoid registration if already done. if self.0.set.load(Relaxed) { return Poll::Ready(()); } self.0.waker.register(cx.waker()); // Need to check condition **after** `register` to avoid a race // condition that would result in lost notifications. if self.0.set.load(Relaxed) { Poll::Ready(()) } else { Poll::Pending } } } ``` -------------------------------- ### Get Window Start Index Source: https://docs.rs/futures/latest/futures/io/struct.Window.html Returns the starting index of the current window within the underlying buffer. ```rust pub fn start(&self) -> usize ``` -------------------------------- ### TakeUntil Example Source: https://docs.rs/futures/latest/futures/stream/struct.TakeUntil.html Demonstrates how to use `take_until` to create a stream that stops yielding elements after a certain condition is met by a future. It shows how to collect the stream's elements and then retrieve the result from the stopping future. ```rust use futures::future; use futures::stream::{self, StreamExt}; use futures::task::Poll; let stream = stream::iter(1..=10); let mut i = 0; let stop_fut = future::poll_fn(|_cx| { i += 1; if i <= 5 { Poll::Pending } else { Poll::Ready("reason") } }); let mut stream = stream.take_until(stop_fut); let _ = stream.by_ref().collect::>().await; let result = stream.take_result().unwrap(); assert_eq!(result, "reason"); ``` -------------------------------- ### Stream Position Source: https://docs.rs/futures/latest/futures/io/struct.AllowStdIo.html?search=std%3A%3Avec Gets the current position within the stream, measured in bytes from the start. ```APIDOC ## fn stream_position(&mut self) -> Result ### Description Returns the current seek position from the start of the stream. ### Method `stream_position` ### Response #### Success Response - **u64** - The current position in bytes. #### Error Response - **Error** - An error if the current position cannot be determined. ``` -------------------------------- ### AtomicWaker::register Example: Implementing a Flag Source: https://docs.rs/futures/latest/futures/task/struct.AtomicWaker.html This example shows how to use `AtomicWaker::register` within the `poll` method of a Future to implement a flag. It emphasizes registering the waker before checking the flag's state to prevent lost notifications. ```rust use futures::future::Future; use futures::task::{Context, Poll, AtomicWaker}; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::Relaxed; use std::pin::Pin; struct Flag { waker: AtomicWaker, set: AtomicBool, } impl Future for Flag { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { // Register **before** checking `set` to avoid a race condition // that would result in lost notifications. self.waker.register(cx.waker()); if self.set.load(Relaxed) { Poll::Ready(()) } else { Poll::Pending } } } ``` -------------------------------- ### StreamExt::enumerate Example Source: https://docs.rs/futures/latest/futures/stream/struct.Chain.html?search=std%3A%3Avec Adds an index to each item yielded by the stream. The index starts at 0. ```rust async fn example(stream: S) { let _ = stream.enumerate().collect::>().await; } ``` -------------------------------- ### Rust rchunks example Source: https://docs.rs/futures/latest/futures/io/struct.IoSliceMut.html Demonstrates the usage of the `rchunks` method to iterate over a slice in chunks starting from the end. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` -------------------------------- ### take Source: https://docs.rs/futures/latest/futures/compat/struct.Compat.html Creates an adapter that reads at most a specified limit of bytes. ```APIDOC ## fn take(self, limit: u64) -> Take ### Description Creates an adapter which will read at most `limit` bytes from it. ### Parameters #### Path Parameters - `limit` (u64) - Required - The maximum number of bytes to read. ### Returns - `Take` - An adapter that reads at most `limit` bytes. ``` -------------------------------- ### ThreadPool::builder() Example Source: https://docs.rs/futures/latest/futures/executor/struct.ThreadPool.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initiates the creation of a ThreadPool with a customizable configuration. Refer to ThreadPoolBuilder documentation for detailed options. ```rust use futures::executor::ThreadPool; let pool = ThreadPool::builder() .pool_size(4) .create() .unwrap(); ``` -------------------------------- ### StreamExt::next Example Source: https://docs.rs/futures/latest/futures/prelude/stream/struct.Chain.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to get the next item from a stream using the `next` method from the `StreamExt` trait. Requires the stream to be `Unpin`. ```rust async fn next( mut stream: S, ) -> Option { stream.next().await } ``` -------------------------------- ### Get current cursor position Source: https://docs.rs/futures/latest/futures/io/struct.Cursor.html Retrieves the current position of the cursor within the buffer. This example demonstrates seeking relative to the current position. ```rust use futures::io::{AsyncSeekExt, Cursor, SeekFrom}; let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); assert_eq!(buff.position(), 0); buff.seek(SeekFrom::Current(2)).await?; assert_eq!(buff.position(), 2); buff.seek(SeekFrom::Current(-1)).await?; assert_eq!(buff.position(), 1); ``` -------------------------------- ### Getting Stream Position Source: https://docs.rs/futures/latest/futures/io/struct.Cursor.html?search=std%3A%3Avec Creates a future that returns the current seek position from the start of the stream. Useful for tracking progress or resuming operations. ```rust fn stream_position(&mut self) -> Seek<'_, Self> where Self: Unpin, ``` -------------------------------- ### Simple Example of `select` Source: https://docs.rs/futures/latest/futures/prelude/future/fn.select.html?search= Demonstrates how to use `select` to wait for one of two futures to complete. It shows how to handle the `Either` enum to extract the resolved value and the remaining future. Requires `Future + Unpin` bounds. ```rust use core::pin::pin; use futures::future; use futures::future::Either; // These two futures have different types even though their outputs have the same type. let future1 = async { future::pending::<()>().await; // will never finish 1 }; let future2 = async { future::ready(2).await }; // 'select' requires Future + Unpin bounds let future1 = pin!(future1); let future2 = pin!(future2); let value = match future::select(future1, future2).await { Either::Left((value1, _)) => value1, // `value1` is resolved from `future1` // `_` represents `future2` Either::Right((value2, _)) => value2, // `value2` is resolved from `future2` // `_` represents `future1` }; assert!(value == 2); ``` -------------------------------- ### AsyncBufReadExt fill_buf Example Source: https://docs.rs/futures/latest/futures/io/trait.AsyncBufReadExt.html Demonstrates using fill_buf to get available data from an async read stream and consume it. Requires the `std` and `io` features. ```rust use futures::{io::AsyncBufReadExt as _, stream::{iter, TryStreamExt as _}}; let mut stream = iter(vec![Ok(vec![1, 2, 3]), Ok(vec![4, 5, 6])]).into_async_read(); assert_eq!(stream.fill_buf().await?, vec![1, 2, 3]); stream.consume_unpin(2); assert_eq!(stream.fill_buf().await?, vec![3]); stream.consume_unpin(1); assert_eq!(stream.fill_buf().await?, vec![4, 5, 6]); stream.consume_unpin(3); assert_eq!(stream.fill_buf().await?, vec![]); ``` -------------------------------- ### Example of using select_next_some with select macro Source: https://docs.rs/futures/latest/futures/prelude/stream/trait.StreamExt.html?search= Demonstrates how to use `select_next_some` with the `select!` macro to concurrently process items from a future and a stream, and handle stream completion. ```rust use futures::{future, select}; use futures::stream::{StreamExt, FuturesUnordered}; let mut fut = future::ready(1); let mut async_tasks = FuturesUnordered::new(); let mut total = 0; loop { select! { num = fut => { // First, the `ready` future completes. total += num; // Then we spawn a new task onto `async_tasks`, async_tasks.push(async { 5 }); }, // On the next iteration of the loop, the task we spawned // completes. num = async_tasks.select_next_some() => { total += num; } // Finally, both the `ready` future and `async_tasks` have // finished, so we enter the `complete` branch. complete => break, } } assert_eq!(total, 6); ``` -------------------------------- ### Rust rsplit_mut example Source: https://docs.rs/futures/latest/futures/io/struct.IoSliceMut.html?search= Shows how to use `rsplit_mut` to get mutable subslices separated by elements matching a predicate, working backwards. The matched element is excluded. ```rust let mut v = [100, 400, 300, 200, 600, 500]; let mut count = 0; for group in v.rsplit_mut(|num| *num % 3 == 0) { count += 1; group[0] = count; } assert_eq!(v, [3, 400, 300, 2, 600, 1]); ``` -------------------------------- ### Example: Using TakeUntil and take_result Source: https://docs.rs/futures/latest/futures/prelude/stream/struct.TakeUntil.html?search=u32+-%3E+bool Demonstrates how to use TakeUntil to limit a stream's output until a future resolves, and then retrieve the future's result. ```rust use futures::future; use futures::stream::{self, StreamExt}; use futures::task::Poll; let stream = stream::iter(1..=10); let mut i = 0; let stop_fut = future::poll_fn(|_cx| { i += 1; if i <= 5 { Poll::Pending } else { Poll::Ready("reason") } }); let mut stream = stream.take_until(stop_fut); let _ = stream.by_ref().collect::>().await; let result = stream.take_result().unwrap(); assert_eq!(result, "reason"); ``` -------------------------------- ### Mutably Iterating Over Slice Elements Source: https://docs.rs/futures/latest/futures/io/struct.IoSliceMut.html?search= Use `iter_mut()` to get a mutable iterator over the elements of a slice, allowing modification. The iterator yields elements from start to end. ```Rust let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` -------------------------------- ### Create and run tasks with LocalPool Source: https://docs.rs/futures/latest/futures/executor/struct.LocalPool.html Demonstrates creating a new LocalPool, spawning initial tasks, and then running all tasks to completion. The `run()` method blocks until all tasks, including newly spawned ones, are finished. ```rust use futures::executor::LocalPool; let mut pool = LocalPool::new(); // ... spawn some initial tasks using `spawn.spawn()` or `spawn.spawn_local()` // run *all* tasks in the pool to completion, including any newly-spawned ones. pool.run(); ``` -------------------------------- ### Rust rsplit_mut Example Source: https://docs.rs/futures/latest/futures/io/struct.IoSliceMut.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use `rsplit_mut` to get mutable subslices and modify them. The predicate matches numbers divisible by 3, and the first element of each mutable subslice is updated. ```rust let mut v = [100, 400, 300, 200, 600, 500]; let mut count = 0; for group in v.rsplit_mut(|num| *num % 3 == 0) { count += 1; group[0] = count; } assert_eq!(v, [3, 400, 300, 200, 600, 1]); ``` -------------------------------- ### Removing a prefix from a slice Source: https://docs.rs/futures/latest/futures/io/struct.IoSlice.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use `strip_prefix` to get a subslice with the specified prefix removed. Returns `None` if the slice does not start with the prefix. An empty prefix results in the original slice. ```rust let v = [10, 40, 30]; assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[10, 50]), None); assert_eq!(v.strip_prefix(&[]), Some(&[10, 40, 30][..])); ``` -------------------------------- ### Removing a prefix from a slice Source: https://docs.rs/futures/latest/futures/io/struct.IoSlice.html?search=std%3A%3Avec Use `strip_prefix` to get a subslice with the specified prefix removed. Returns `None` if the slice does not start with the prefix. An empty prefix results in the original slice. ```rust let slice = &[1, 2, 3, 4, 5]; assert_eq!(slice.strip_prefix(&[1, 2]), Some(&[3, 4, 5][..])); assert_eq!(slice.strip_prefix(&[1, 2, 3, 4, 5]), Some(&[][..])); assert_eq!(slice.strip_prefix(&[]), Some(&[1, 2, 3, 4, 5][..])); assert_eq!(slice.strip_prefix(&[1, 3]), None); ``` -------------------------------- ### Limiting Bytes Read with Take Adapter Source: https://docs.rs/futures/latest/futures/io/trait.AsyncReadExt.html Demonstrates using the `take` method to create an adapter that reads at most a specified number of bytes from an `AsyncRead` source. The example shows reading fewer bytes than available and asserting the number of bytes read and the buffer content. ```rust use futures::io::{AsyncReadExt, Cursor}; let reader = Cursor::new(&b"12345678"[..]); let mut buffer = [0; 5]; let mut take = reader.take(4); let n = take.read(&mut buffer).await?; assert_eq!(n, 4); assert_eq!(&buffer, b"1234\0"); ``` -------------------------------- ### Getting Metadata with and_then Source: https://docs.rs/futures/latest/futures/io/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use `and_then` to chain fallible operations, specifically for retrieving file metadata and its modification time. This example highlights handling potential errors like 'NotFound'. ```Rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### MutexGuard Map Example Source: https://docs.rs/futures/latest/futures/lock/struct.MutexGuard.html Demonstrates how to use `MutexGuard::map` to get a locked view over a portion of the data. This is useful for accessing nested data structures within a Mutex without needing to lock the entire MutexGuard. ```rust use futures::lock::{Mutex, MutexGuard}; let data = Mutex::new(Some("value".to_string())); { let locked_str = MutexGuard::map(data.lock().await, |opt| opt.as_mut().unwrap()); assert_eq!(&*locked_str, "value"); } ``` -------------------------------- ### Stream Forwarding to Sink Example Source: https://docs.rs/futures/latest/futures/prelude/stream/trait.StreamExt.html Demonstrates how to forward all items from a stream to a sink and then flush and close the sink. This is useful for processing stream data into a destination. ```rust use futures::future::FutureExt; use futures::sink::SinkExt; use futures::stream::{self, StreamExt}; let mut stream = stream::iter(vec![1, 2, 3]); let mut sink = Vec::new(); let fut = stream.forward(&mut sink); futures::executor::block_on(fut); assert_eq!(sink, vec![1, 2, 3]); ``` -------------------------------- ### Consuming Error to Get Inner Value with into_inner Source: https://docs.rs/futures/latest/futures/io/struct.Error.html Demonstrates consuming an `io::Error` to extract its inner error using `into_inner`. This is useful when you want to take ownership of the underlying error, for example, to inspect or process it further. ```rust use std::io::{Error, ErrorKind}; fn print_error(err: Error) { if let Some(inner_err) = err.into_inner() { println!("Inner error: {inner_err}"); } else { println!("No inner error"); } } fn main() { // Will print "No inner error". print_error(Error::last_os_error()); // Will print "Inner error: ...". print_error(Error::new(ErrorKind::Other, "oh no!")); } ``` -------------------------------- ### Peekable Stream Example Source: https://docs.rs/futures/latest/futures/stream/struct.Peekable.html Demonstrates how to use the `peekable()` adapter to create a Peekable stream and conditionally consume elements using `next_if_eq`. ```APIDOC ## Peekable Stream Example This example shows how to create a `Peekable` stream and use its methods to conditionally consume elements. ### Method This example primarily uses the `next_if_eq` method available on `Peekable` streams. ### Endpoint N/A (This is an SDK example, not an HTTP endpoint) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```rust use core::pin::pin; use futures::stream; use futures::stream::StreamExt; let stream = stream::iter(0..5).peekable(); let mut stream = pin!(stream); // The first item of the stream is 0; consume it. assert_eq!(stream.as_mut().next_if_eq(&0).await, Some(0)); // The next item returned is now 1, so `consume` will return `false`. assert_eq!(stream.as_mut().next_if_eq(&0).await, None); // `next_if_eq` saves the value of the next item if it was not equal to `expected`. assert_eq!(stream.next().await, Some(1)); ``` ### Response #### Success Response (200) N/A (This is an SDK example, not an HTTP endpoint) #### Response Example N/A ``` -------------------------------- ### TryFold Example: Summing Ok values Source: https://docs.rs/futures/latest/futures/stream/trait.TryStreamExt.html Demonstrates using try_fold to sum Ok values from a stream. The accumulation stops if an error is encountered. ```rust use futures::stream::{self, TryStreamExt}; let number_stream = stream::iter(vec![Ok::(1), Ok(2)]); let sum = number_stream.try_fold(0, |acc, x| async move { Ok(acc + x) }); assert_eq!(sum.await, Ok(3)); ``` -------------------------------- ### Using always_ready to create an immediate future Source: https://docs.rs/futures/latest/futures/future/fn.always_ready.html?search= This example demonstrates how to use `always_ready` to create a future that is immediately ready. It asserts that the size of the future is 0, indicating no heap allocation, and then awaits its value twice. ```rust use std::mem::size_of_val; use futures::future; let a = future::always_ready(|| 1); assert_eq!(size_of_val(&a), 0); assert_eq!(a.await, 1); assert_eq!(a.await, 1); ``` -------------------------------- ### StreamExt::map Example Source: https://docs.rs/futures/latest/futures/stream/struct.Unfold.html?search=std%3A%3Avec Demonstrates mapping items of a stream to a new type using an asynchronous closure. The original stream is consumed. ```rust async fn example(stream: S) -> impl Stream where S: Stream, F: FnMut(S::Item) -> T, { stream.map(f) } ``` -------------------------------- ### From::from Example Source: https://docs.rs/futures/latest/futures/io/struct.CopyBuf.html?search=std%3A%3Avec Example of the `from` method from the `From` trait, used for type conversion. ```rust fn from(t: T) -> T { // ... implementation details ... } ``` -------------------------------- ### fn take(self, limit: u64) -> Take Source: https://docs.rs/futures/latest/futures/io/trait.AsyncReadExt.html?search= Creates an adaptor which will read at most `limit` bytes from the underlying stream. ```APIDOC ## fn take(self, limit: u64) -> Take ### Description Creates an adaptor which will read at most `limit` bytes from the underlying stream. ``` -------------------------------- ### select! with complete and default branches Source: https://docs.rs/futures/latest/futures/macro.select.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use `complete` and `default` branches in `select!`, particularly useful within a loop. ```rust use futures::future; use futures::select; let mut a_fut = future::ready(4); let mut b_fut = future::ready(6); let mut total = 0; loop { select! { a = a_fut => total += a, b = b_fut => total += b, complete => break, default => panic!(), // never runs (futures run first, then complete) } } assert_eq!(total, 10); ``` -------------------------------- ### ForEach Search Examples Source: https://docs.rs/futures/latest/futures/stream/struct.ForEach.html?search= Provides examples of how to perform searches within futures streams using the ForEach operation. These examples demonstrate common search patterns and type conversions. ```APIDOC ## ForEach Search Examples ### Description Demonstrates various search queries that can be performed on futures streams, including searching for specific types, type transformations, and nested types. ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### Start Send for Unpin Sinks Source: https://docs.rs/futures/latest/futures/stream/struct.TryBuffered.html?search=u32+-%3E+bool A convenience method for calling `Sink::start_send` on `Unpin` sink types. ```rust fn start_send_unpin(&mut self, item: Item) -> Result<(), Self::Error> where Self: Unpin, ``` -------------------------------- ### Getting the Length of a Slice Source: https://docs.rs/futures/latest/futures/io/struct.IoSlice.html Illustrates how to get the number of elements in a slice using the `len()` method. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### fn compat(self) -> Compat Source: https://docs.rs/futures/latest/futures/task/trait.SpawnExt.html?search=std%3A%3Avec Wraps a `Spawn` implementor to make it usable as a futures 0.1 `Executor`. This method requires the `compat` feature to be enabled. ```APIDOC ## fn compat(self) -> Compat ### Description Wraps a `Spawn` and makes it usable as a futures 0.1 `Executor`. Requires the `compat` feature to enable. ### Method `compat` ### Parameters - **self**: `Self` - The `Spawn` implementor to wrap. ### Return Value - `Compat`: A `Compat` struct that implements the futures 0.1 `Executor` trait. ### Note This method is available only when the `compat` crate feature is enabled. ``` -------------------------------- ### start_send Method Source: https://docs.rs/futures/latest/futures/prelude/sink/trait.Sink.html Begins sending an item to the Sink. Must be preceded by a successful poll_ready call. Guarantees completion only after poll_flush or poll_close. ```rust fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> ``` -------------------------------- ### Get a reference to the inner buffer Source: https://docs.rs/futures/latest/futures/io/struct.Cursor.html Gets an immutable reference to the underlying Vec within the Cursor. ```rust use futures::io::Cursor; let buff = Cursor::new(Vec::new()); let reference = buff.get_ref(); ``` -------------------------------- ### Create and use a drain sink Source: https://docs.rs/futures/latest/futures/prelude/sink/fn.drain.html Demonstrates how to create a drain sink and send an item to it. The item will be discarded. ```rust use futures::sink::{self, SinkExt}; let mut drain = sink::drain(); drain.send(5).await?; ``` -------------------------------- ### Fanout Implementations: Get References Source: https://docs.rs/futures/latest/futures/prelude/sink/struct.Fanout.html?search=u32+-%3E+bool Provides methods to get shared or mutable references to the inner sinks of a Fanout combinator. ```rust pub fn get_ref(&self) -> (&Si1, &Si2) ``` ```rust pub fn get_mut(&mut self) -> (&mut Si1, &mut Si2) ``` ```rust pub fn get_pin_mut( self: Pin<&mut Fanout>, ) -> (Pin<&mut Si1>, Pin<&mut Si2>) ``` -------------------------------- ### Polling a Future with a Waker Source: https://docs.rs/futures/latest/futures/task/struct.Waker.html?search= This example demonstrates how to poll a future using a Waker. It initializes a no-op Waker and a simple async future, then polls the future to check its readiness. ```rust use std::future::Future; use std::task; let mut cx = task::Context::from_waker(task::Waker::noop()); let mut future = Box::pin(async { 10 }); assert_eq!(future.as_mut().poll(&mut cx), task::Poll::Ready(10)); ``` -------------------------------- ### Implementing try_join using try_select Source: https://docs.rs/futures/latest/futures/future/fn.try_select.html This example demonstrates how to implement a `try_join` functionality using `try_select`. It shows how to handle the results from either the left or right future completing first, and how to combine their successful outcomes or propagate errors. ```rust use futures::future::{self, Either, Future, FutureExt, TryFuture, TryFutureExt}; // A poor-man's try_join implemented on top of select fn try_join(a: A, b: B) -> impl TryFuture where A: TryFuture + Unpin + 'static, B: TryFuture + Unpin + 'static, E: 'static, { future::try_select(a, b).then(|res| -> Box> + Unpin> { match res { Ok(Either::Left((x, b))) => Box::new(b.map_ok(move |y| (x, y))), Ok(Either::Right((y, a))) => Box::new(a.map_ok(move |x| (x, y))), Err(Either::Left((e, _))) => Box::new(future::err(e)), Err(Either::Right((e, _))) => Box::new(future::err(e)), } }) } ``` -------------------------------- ### Execute Hook After Thread Start Source: https://docs.rs/futures/latest/futures/executor/struct.ThreadPoolBuilder.html Registers a closure to be executed immediately after each worker thread starts. The closure receives the thread's index. ```rust pub fn after_start(&mut self, f: F) -> &mut ThreadPoolBuilder where F: Fn(usize) + Send + Sync + 'static, ``` -------------------------------- ### Using try_join5 with five futures Source: https://docs.rs/futures/latest/futures/future/fn.try_join5.html Demonstrates how to use `try_join5` to concurrently run five futures that all resolve to `Ok` values. This example uses `future::ready` to create futures that immediately return a successful result. ```rust use futures::future; let a = future::ready(Ok::(1)); let b = future::ready(Ok::(2)); let c = future::ready(Ok::(3)); let d = future::ready(Ok::(4)); let e = future::ready(Ok::(5)); let tuple = future::try_join5(a, b, c, d, e); assert_eq!(tuple.await, Ok((1, 2, 3, 4, 5))); ``` -------------------------------- ### Get Underlying Bytes with IoSlice::as_slice Source: https://docs.rs/futures/latest/futures/io/struct.IoSlice.html Illustrates using the nightly-only `as_slice` method to get the underlying bytes of an IoSlice without borrowing it, allowing for re-assignment. ```rust #![feature(io_slice_as_bytes)] use std::io::IoSlice; let data = b"abcdef"; let mut io_slice = IoSlice::new(data); let tail = &io_slice.as_slice()[3..]; // This works because `tail` doesn't borrow `io_slice` io_slice = IoSlice::new(tail); assert_eq!(io_slice.as_slice(), b"def"); ``` -------------------------------- ### Ready Implementations Source: https://docs.rs/futures/latest/futures/prelude/future/struct.Ready.html?search= Provides details on the trait implementations for the `Ready` struct, showcasing its behavior with standard Rust and asynchronous programming patterns. ```APIDOC ## Implementations ### `impl Clone for Ready` #### `clone` ```rust fn clone(&self) -> Ready ``` Returns a duplicate of the value. #### `clone_from` ```rust fn clone_from(&mut self, source: &Self) ``` Performs copy-assignment from `source`. ### `impl Debug for Ready` #### `fmt` ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> ``` Formats the value using the given formatter. ### `impl FusedFuture for Ready` #### `is_terminated` ```rust fn is_terminated(&self) -> bool ``` Returns `true` if the underlying future should no longer be polled. ### `impl Future for Ready` #### `Output` ```rust type Output = T ``` The type of value produced on completion. #### `poll` ```rust fn poll(self: Pin<&mut Ready>, _cx: &mut Context<'_>) -> Poll ``` Attempts to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. ### `impl Unpin for Ready` ``` -------------------------------- ### MapOkOrElse Example Source: https://docs.rs/futures/latest/futures/future/struct.MapOkOrElse.html Demonstrates how to use map_ok_or_else to handle both success and error cases of a TryFuture, mapping them to a common type. ```rust use futures::future::{self, FutureExt}; let future = future::ok::<_, _>(10); let mapped = future.map_ok_or_else(|e| panic!("unexpected error: {}", e), |v| v * 2); // To run this example, you would typically poll the future or use it in an async context. // For demonstration, let's assume it's polled and resolves to Ok(20). // assert_eq!(future::poll_fn(|cx| mapped.poll(cx)).await, Poll::Ready(Ok(20))); let future_err = future::err::<_, _>(10); let mapped_err = future_err.map_ok_or_else(|e| e * 2, |v| panic!("unexpected success: {}", v)); // For demonstration, let's assume it's polled and resolves to Err(20). // assert_eq!(future::poll_fn(|cx| mapped_err.poll(cx)).await, Poll::Ready(Err(20))); ``` -------------------------------- ### Accessing Elements and Sub-slices with `get` Source: https://docs.rs/futures/latest/futures/io/struct.IoSlice.html Shows how to safely access individual elements or sub-slices by index or range using the `get()` method. Returns `None` for out-of-bounds access. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Get Extension Data from Context (Nightly) Source: https://docs.rs/futures/latest/futures/task/struct.Context.html Retrieves a mutable reference to the extension data for the current task. This is a nightly-only experimental API. ```rust pub const fn ext(&mut self) -> &mut (dyn Any + 'static) ``` -------------------------------- ### Starting Send Operation for Unpin Sinks with `start_send_unpin` Source: https://docs.rs/futures/latest/futures/stream/struct.TryChunks.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E A convenience method for calling `Sink::start_send` on `Unpin` sink types. It attempts to send an item without blocking the current task. ```rust fn start_send_unpin(&mut self, item: Item) -> Result<(), Self::Error> where Self: Unpin, A convenience method for calling `Sink::start_send` on `Unpin` sink types. Read more ``` -------------------------------- ### Split Off Slice Starting with Third Element (Rust) Source: https://docs.rs/futures/latest/futures/io/struct.IoSliceMut.html?search= Removes a subslice starting from the third element and returns it. The original slice is modified to contain elements before the split point. ```Rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.split_off(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` -------------------------------- ### Buffer Sink start_send Method Source: https://docs.rs/futures/latest/futures/prelude/sink/struct.Buffer.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Begins the process of sending an item to the sink. Must be preceded by a successful poll_ready call. ```rust fn start_send( self: Pin<&mut Buffer>, item: Item, ) -> Result<(), as Sink>::Error> ``` -------------------------------- ### try_for_each() - Example Source: https://docs.rs/futures/latest/futures/prelude/stream/trait.TryStreamExt.html?search= Shows how to use `try_for_each` to process each item of a stream until an error occurs or the stream completes. ```rust use futures::future; use futures::stream::{self, TryStreamExt}; let mut x = 0i32; { let fut = stream::repeat(Ok(1)).try_for_each(|item| { x += item; future::ready(if x == 3 { Err(()) } else { Ok(()) }) }); assert_eq!(fut.await, Err(())); } assert_eq!(x, 3); ```