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_cyclic(|id| {
46//!             rx.map(move |item| (id.clone(), item))
47//!         });
48//!         (tx, id)
49//!     })
50//!     .collect::<Vec<_>>();
51//! for (mut tx, saved_id) in txs {
52//!    tx.send(()).await.unwrap();
53//!    let (received_id, ()) = selector.next().await.unwrap();
54//!    assert_eq!(received_id, saved_id);
55//! }
56//! # }
57//! ```
58//!
59//! More examples live [here](https://github.com/Razz4780/async-selector/tree/main/examples).
60
61#![deny(missing_docs, unused_crate_dependencies)]
62
63use crate::{
64    pollable::{PollAsFuture, PollAsStream},
65    selector::Selector,
66};
67
68mod list;
69mod mpsc;
70pub mod pollable;
71pub mod selector;
72mod task;
73
74/// [`Selector`] specialized for polling [`Future`]s.
75///
76/// Behaves much like [`FuturesUnordered`](futures::stream::FuturesUnordered).
77pub type FutureSelector<F> = Selector<PollAsFuture<F>>;
78/// [`Selector`] specialized for polling [`Stream`](futures::stream::Stream)s.
79///
80/// Behaves much like [`SelectAll`](futures::stream::SelectAll).
81pub type StreamSelector<S> = Selector<PollAsStream<S>>;