Skip to main content

async_selector/
lib.rs

1//! Fast and flexible [`Future`]/[`Stream`](futures::Stream)/task selector.
2//!
3//! Designed for optimal performance when polling a large number of tasks
4//! (see [example](https://github.com/Razz4780/async-selector/blob/main/examples/speed.rs)).
5//!
6//! Allows for:
7//! 1. Polling multiple tasks concurrently on the same thread
8//! 2. Safely injecting shared state into polling logic (see [`PollWith`](crate::pollable::PollWith))
9//! 3. Accessing and removing the tasks by automatically assigned unique ids
10//!
11//! # Examples
12//!
13//! Simply flatten a set of streams:
14//!
15//! ```
16//! # use async_selector::StreamSelector;
17//! # use futures::{StreamExt, channel::mpsc};
18//! # #[tokio::main(flavor = "current_thread")]
19//! # async fn main() {
20//! let mut selector = StreamSelector::default();
21//! (0..5).for_each(|i| {
22//!     let (tx, rx) = mpsc::unbounded();
23//!     selector.push(rx);
24//!     tx.unbounded_send(i).unwrap();
25//! });
26//! let collected = selector.collect::<Vec<_>>().await;
27//! assert_eq!(
28//!     collected,
29//!     vec![0, 1, 2, 3, 4],
30//! );
31//! # }
32//! ```
33//!
34//! Use as a map of streams:
35//!
36//! ```
37//! # use async_selector::StreamSelector;
38//! # use futures::{SinkExt, StreamExt, channel::mpsc};
39//! # #[tokio::main(flavor = "current_thread")]
40//! # async fn main() {
41//! let mut selector = StreamSelector::default();
42//! let txs = (0..10)
43//!     .map(|_| {
44//!         let (tx, rx) = mpsc::channel::<()>(8);
45//!         let id = selector.push_with_id(rx);
46//!         (tx, id)
47//!     })
48//!     .collect::<Vec<_>>();
49//! for (mut tx, saved_id) in txs {
50//!     tx.send(()).await.unwrap();
51//!     let ((), received_id) = selector.with_id().next().await.unwrap();
52//!     assert_eq!(received_id, saved_id);
53//! }
54//! # }
55//! ```
56//!
57//! More examples live [here](https://github.com/Razz4780/async-selector/tree/main/examples).
58
59#![deny(missing_docs, unused_crate_dependencies)]
60
61use crate::{
62    pollable::{PollAsFuture, PollAsStream},
63    selector::Selector,
64};
65
66mod list;
67mod mpsc;
68pub mod pollable;
69pub mod selector;
70mod task;
71
72/// [`Selector`] specialized for polling [`Future`]s.
73///
74/// Behaves much like [`FuturesUnordered`](futures::stream::FuturesUnordered).
75pub type FutureSelector<F> = Selector<PollAsFuture<F>>;
76/// [`Selector`] specialized for polling [`Stream`](futures::stream::Stream)s.
77///
78/// Behaves much like [`SelectAll`](futures::stream::SelectAll).
79pub type StreamSelector<S> = Selector<PollAsStream<S>>;