Module futures

Source
Expand description

Async programming primitives and utilities.


futures provides fundamental traits and utilities for asynchronous programming in Rust. It defines the core Future trait and provides essential async utilities that work with both the standard library and async runtimes like Tokio.

The crate includes several key modules: future for working with individual futures, stream for handling asynchronous streams of data, sink for asynchronous data consumption, executor for running futures to completion, and channel for async communication primitives.

Key traits include Future for asynchronous computations, Stream for asynchronous iterators, and Sink for asynchronous data receivers. The library also provides combinators for chaining and transforming futures.

The channel module provides essential async communication building blocks: mpsc channels for multiple-producer, single-consumer communication, and oneshot channels for one-time value passing between tasks. These are runtime-agnostic and work across different async executors.

This crate serves as the foundation for async Rust, providing compatibility between different async runtimes and offering low-level building blocks for async applications.

§Examples

Working with futures and combinators:

use futures::{future, executor::block_on};

// Create simple futures
let fut1 = future::ready(42);
let fut2 = future::ready("hello");

// Combine futures
let combined = future::join(fut1, fut2);

// Execute the future
let (num, text) = block_on(combined);
assert_eq!(num, 42);
assert_eq!(text, "hello");

Using async streams:

use futures::{stream, StreamExt, executor::block_on};

// Create a stream of numbers
let stream = stream::iter(0..5);

// Transform the stream
let doubled_stream = stream.map(|x| x * 2);
let doubled: Vec<_> = block_on(doubled_stream.collect());

assert_eq!(doubled, vec![0, 2, 4, 6, 8]);

Using mpsc channels for async communication:

use futures::{channel::mpsc, SinkExt, StreamExt, executor::block_on};

let (mut sender, mut receiver) = mpsc::channel::<i32>(10);

// Send some values
block_on(async {
    sender.send(1).await.unwrap();
    sender.send(2).await.unwrap();
    sender.send(3).await.unwrap();
    drop(sender); // Close the channel
});

// Receive values
let received: Vec<i32> = block_on(receiver.collect());
assert_eq!(received, vec![1, 2, 3]);

Using oneshot channels for single-value communication:

use futures::{channel::oneshot, executor::block_on};

let (sender, receiver) = oneshot::channel::<String>();

// Send a value
sender.send("Hello from oneshot!".to_string()).unwrap();

// Receive the value
let message = block_on(receiver).unwrap();
assert_eq!(message, "Hello from oneshot!");

Modules§

channel
Asynchronous channels.
executor
Built-in executors and related tools.
io
Asynchronous I/O.
lock
Futures-powered synchronization primitives.
never
This module contains the Never type.
prelude
A “prelude” for crates using the futures crate.
task
Tools for working with tasks.

Macros§

join
Polls multiple futures simultaneously, returning a tuple of all results once complete.
pending
A macro which yields to the event loop once.
pin_mut
Pins a value on the stack.
poll
A macro which returns the result of polling a future once within the current async context.
ready
Extracts the successful type of a Poll<T>.
select
Polls multiple futures and streams simultaneously, executing the branch for the future that finishes first. If multiple futures are ready, one will be pseudo-randomly selected at runtime. Futures directly passed to select! must be Unpin and implement FusedFuture.
select_biased
Polls multiple futures and streams simultaneously, executing the branch for the future that finishes first. Unlike select!, if multiple futures are ready, one will be selected in order of declaration. Futures directly passed to select_biased! must be Unpin and implement FusedFuture.
stream_select
Combines several streams, all producing the same Item type, into one stream. This is similar to select_all but does not require the streams to all be the same type. It also keeps the streams inline, and does not require Box<dyn Stream>s to be allocated. Streams passed to this macro must be Unpin.
try_join
Polls multiple futures simultaneously, resolving to a Result containing either a tuple of the successful outputs or an error.

Traits§

AsyncBufRead
Read bytes asynchronously.
AsyncBufReadExt
An extension trait which adds utility methods to AsyncBufRead types.
AsyncRead
Read bytes asynchronously.
AsyncReadExt
An extension trait which adds utility methods to AsyncRead types.
AsyncSeek
Seek bytes asynchronously.
AsyncSeekExt
An extension trait which adds utility methods to AsyncSeek types.
AsyncWrite
Write bytes asynchronously.
AsyncWriteExt
An extension trait which adds utility methods to AsyncWrite types.
Future
A future represents an asynchronous computation obtained by use of async.
FutureExt
An extension trait for Futures that provides a variety of convenient adapters.
Sink
A Sink is a value into which other values can be sent, asynchronously.
SinkExt
An extension trait for Sinks that provides a variety of convenient combinator functions.
Stream
A stream of values produced asynchronously.
StreamExt
An extension trait for Streams that provides a variety of convenient combinator functions.
TryFuture
A convenience for futures that return Result values that includes a variety of adapters tailored to such futures.
TryFutureExt
Adapters specific to Result-returning futures
TryStream
A convenience for streams that return Result values that includes a variety of adapters tailored to such futures.
TryStreamExt
Adapters specific to Result-returning streams