### join3 usage example Source: https://docs.rs/futures/latest/futures/future/fn.join3.html Example showing how to use join3 to await three async blocks and get a tuple of their results. ```rust use futures::future; let a = async { 1 }; let b = async { 2 }; let c = async { 3 }; let tuple = future::join3(a, b, c); assert_eq!(tuple.await, (1, 2, 3)); ``` -------------------------------- ### Example: using Mutex::into_inner Source: https://docs.rs/futures/latest/futures/lock/struct.Mutex.html Example from the documentation for the into_inner method, showing how to create a Mutex and consume it to get the inner value. ```rust use futures::lock::Mutex; let mutex = Mutex::new(0); assert_eq!(mutex.into_inner(), 0); ``` -------------------------------- ### Example: Using noop_waker Source: https://docs.rs/futures/latest/futures/task/fn.noop_waker.html Example usage of `noop_waker` from the documentation. It creates a waker and calls `wake()` on it. ```rust use futures::task::noop_waker; let waker = noop_waker(); waker.wake(); ``` -------------------------------- ### Example usage of join_all Source: https://docs.rs/futures/latest/futures/future/fn.join_all.html Example that creates three async functions and uses `join_all` to await them, asserting the collected results are in order. ```rust use futures::future::join_all; async fn foo(i: u32) -> u32 { i } let futures = vec![foo(1), foo(2), foo(3)]; assert_eq!(join_all(futures).await, [1, 2, 3]); ``` -------------------------------- ### Example: using always_ready Source: https://docs.rs/futures/latest/futures/future/fn.always_ready.html Example usage of `always_ready` with a closure returning 1, demonstrating that the future is zero-sized and can be awaited multiple times. ```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); ``` -------------------------------- ### join5 usage example Source: https://docs.rs/futures/latest/futures/future/fn.join5.html Example showing how to use `future::join5` to await five async blocks and assert that the resulting tuple matches the expected values. ```rust use futures::future; let a = async { 1 }; let b = async { 2 }; let c = async { 3 }; let d = async { 4 }; let e = async { 5 }; let tuple = future::join5(a, b, c, d, e); assert_eq!(tuple.await, (1, 2, 3, 4, 5)); ``` -------------------------------- ### Example: using stream_select! with endless integer streams Source: https://docs.rs/futures/latest/futures/macro.stream_select.html Example showing how to use `stream_select!` to combine three endless integer streams. The macro requires streams to be `Unpin` and pseudo-randomly selects among ready streams. The example matches the first yielded value and prints a message. ```rust use futures::{stream, StreamExt, stream_select}; let endless_ints = |i| stream::iter(vec![i].into_iter().cycle()).fuse(); let mut endless_numbers = stream_select!(endless_ints(1i32), endless_ints(2), endless_ints(3)); match endless_numbers.next().await { Some(1) => println!("Got a 1"), Some(2) => println!("Got a 2"), Some(3) => println!("Got a 3"), _ => unreachable!(), } ``` -------------------------------- ### take example Source: https://docs.rs/futures/latest/futures/prelude/self/trait.StreamExt.html Creates a stream of at most n items from the underlying stream. After n items are yielded, the stream is done. The example collects the first three items from a range. ```rust use futures::stream::{self, StreamExt}; let stream = stream::iter(1..=10).take(3); assert_eq!(vec![1, 2, 3], stream.collect::>().await); ``` -------------------------------- ### OptionFuture usage example Source: https://docs.rs/futures/latest/futures/future/struct.OptionFuture.html Shows how to create an `OptionFuture` from `Some` and `None` using `.into()` and await it, expecting `Some(123)` and `None` respectively. ```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); ``` -------------------------------- ### Using StreamExt::into_future to get next item and tail Source: https://docs.rs/futures/latest/futures/prelude/self/trait.StreamExt.html Converts the stream into a future of (next_item, tail_of_stream). The stream must be Unpin. The example shows repeatedly awaiting into_future to get the next item and the remaining stream. ```rust use futures::stream::{self, StreamExt}; let stream = stream::iter(1..=3); let (item, stream) = stream.into_future().await; assert_eq!(Some(1), item); let (item, stream) = stream.into_future().await; assert_eq!(Some(2), item); ``` -------------------------------- ### Get current position with position Source: https://docs.rs/futures/latest/futures/io/struct.Cursor.html Returns the current position of the cursor. The example shows seeking with AsyncSeekExt and checking the position after each seek. ```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); ``` -------------------------------- ### try_next example: asynchronously retrieving the next item Source: https://docs.rs/futures/latest/futures/prelude/self/trait.TryStreamExt.html Demonstrates using try_next to get the next item from a TryStream, returning a Result, E> that works with the ? operator. ```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(())); ``` -------------------------------- ### Example: Using io::sink with AsyncWriteExt Source: https://docs.rs/futures/latest/futures/io/fn.sink.html Example showing how to create a sink writer and write a buffer to it. The write returns the number of bytes written, which equals the buffer length. ```rust use futures::io::{self, AsyncWriteExt}; let buffer = vec![1, 2, 3, 5, 8]; let mut writer = io::sink(); let num_bytes = writer.write(&buffer).await?; assert_eq!(num_bytes, 5); ``` -------------------------------- ### Using noop_waker_ref to get a no-op Waker Source: https://docs.rs/futures/latest/futures/task/fn.noop_waker_ref.html This example imports `noop_waker_ref` from `futures::task`, obtains a static reference to a no-op `Waker`, and calls `wake_by_ref()` on it. The `Waker` does nothing when woken, which is useful for testing or when no actual wake-up is needed. ```rust use futures::task::noop_waker_ref; let waker = noop_waker_ref(); waker.wake_by_ref(); ``` -------------------------------- ### Flush example using AsyncWriteExt Source: https://docs.rs/futures/latest/futures/io/trait.AsyncWriteExt.html Example showing how to use write_all and flush on a buffered writer. It writes bytes to a cursor and flushes to ensure all data is written. The output is asserted to be [1, 2, 3, 4, 0]. ```rust use futures::io::{AllowStdIo, AsyncWriteExt}; use std::io::{BufWriter, Cursor}; let mut output = vec![0u8; 5]; { let writer = Cursor::new(&mut output); let mut buffered = AllowStdIo::new(BufWriter::new(writer)); buffered.write_all(&[1, 2]).await?; buffered.write_all(&[3, 4]).await?; buffered.flush().await?; } assert_eq!(output, [1, 2, 3, 4, 0]); ``` -------------------------------- ### Extract stopping future result with take_result Source: https://docs.rs/futures/latest/futures/prelude/self/struct.TakeUntil.html Shows how to use take_result to retrieve the value returned by the stopping future after it resolves. The example creates a stream, a poll_fn future that resolves after 5 polls, and then calls take_result to get the reason. Requires the StreamExt trait. ```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"); ``` -------------------------------- ### Example: Using future::ok to create a ready future Source: https://docs.rs/futures/latest/futures/future/fn.ok.html Creates a future with `future::ok::(1)` and asserts that awaiting it yields `Ok(1)`. This demonstrates the basic usage of the `ok` function. ```rust use futures::future; let a = future::ok::(1); assert_eq!(a.await, Ok(1)); ``` -------------------------------- ### Using peek_mut to modify the next stream item Source: https://docs.rs/futures/latest/futures/prelude/self/struct.Peekable.html Example from the peek_mut method documentation. It creates a peekable stream from an iterator, uses peek_mut to get a mutable reference to the next item, modifies it if it equals 2, and then collects the stream to verify the change. Requires the StreamExt trait and pinning the stream. ```rust use core::pin::pin; use futures::stream; use futures::stream::StreamExt; let stream = stream::iter(vec![1, 2, 3]).peekable(); let mut stream = pin!(stream); assert_eq!(stream.as_mut().peek_mut().await, Some(&mut 1)); assert_eq!(stream.as_mut().next().await, Some(1)); // Peek into the stream and modify the value which will be returned next if let Some(p) = stream.as_mut().peek_mut().await { if *p == 2 { *p = 5; } } assert_eq!(stream.collect::>().await, vec![5, 3]); ``` -------------------------------- ### Get immutable reference with get_ref Source: https://docs.rs/futures/latest/futures/io/struct.Cursor.html Gets an immutable reference to the underlying value in the cursor. ```rust use futures::io::Cursor; let buff = Cursor::new(Vec::new()); let reference = buff.get_ref(); ``` -------------------------------- ### spawn_local_with_handle usage example Source: https://docs.rs/futures/latest/futures/task/trait.LocalSpawnExt.html Example of using spawn_local_with_handle to spawn a future and obtain a RemoteHandle that resolves to the future's output. Requires the 'channel' and 'std' crate features. The example asserts that run_until returns the future's output (1). ```rust use futures::executor::LocalPool; use futures::task::LocalSpawnExt; let mut executor = LocalPool::new(); let spawner = executor.spawner(); let future = async { 1 }; let join_handle_fut = spawner.spawn_local_with_handle(future).unwrap(); assert_eq!(executor.run_until(join_handle_fut), 1); ``` -------------------------------- ### Example: poor-man's try_join using try_select Source: https://docs.rs/futures/latest/futures/future/fn.try_select.html An example implementation of a `try_join` function using `try_select` and `Either::factor_first` to combine the results. It demonstrates handling both success and error cases. ```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)), } }) } ``` -------------------------------- ### map_err example Source: https://docs.rs/futures/latest/futures/prelude/self/trait.TryStreamExt.html Maps the error value of a TryStream using map_err. The example adds 2 to the error value and asserts the result. ```rust use futures::stream::{self, TryStreamExt}; let mut stream = stream::iter(vec![Ok(5), Err(0)]) .map_err(|x| x + 2); assert_eq!(stream.try_next().await, Ok(Some(5))); assert_eq!(stream.try_next().await, Err(2)); ```