futures_time/
lib.rs

1//! # Async time operators.
2//!
3//! This crate provides ergonomic, async time-based operations. It serves as an
4//! experimental playground to experiment with how we could potentially add
5//! time-based operations to `async-std`, and subsequently the stdlib.
6//!
7//! The goal is to make working with time and other events feel natural. A major
8//! source of inspiration for this has been RxJS, which uses events (including
9//! time) to trigger operations. This crate takes that principle, inverts the
10//! model to make it evaluate lazily, and wraps it in an ergnomic Rust
11//! interface.
12//!
13//! # Examples
14//!
15//! __Delay a future's execution by 100ms__
16//!
17//! ```
18//! use futures_time::prelude::*;
19//! use futures_time::time::Duration;
20//!
21//! async_io::block_on(async {
22//!     let res = async { "meow" }
23//!         .delay(Duration::from_millis(100))
24//!         .await;
25//!     assert_eq!(res, "meow");
26//! })
27//! ```
28//!
29//! __Error if a future takes longer than 200ms__
30//!
31//! ```
32//! use futures_time::prelude::*;
33//! use futures_time::time::Duration;
34//!
35//! async_io::block_on(async {
36//!     let res = async { "meow" }
37//!         .delay(Duration::from_millis(100))
38//!         .timeout(Duration::from_millis(200))
39//!         .await;
40//!     assert_eq!(res.unwrap(), "meow");
41//! })
42//! ```
43//!
44//! __Throttle a stream__
45//!
46//! This lets two items through in total: one `100ms` after the program has
47//! started, and one `300ms` after the program has started.
48//!
49//! ```
50//! use futures_lite::prelude::*;
51//! use futures_time::prelude::*;
52//! use futures_time::time::Duration;
53//! use futures_time::stream;
54//!
55//! async_io::block_on(async {
56//!     let mut counter = 0;
57//!     stream::interval(Duration::from_millis(100))  // Yield an item every 100ms
58//!         .take(4)                                  // Stop after 4 items
59//!         .throttle(Duration::from_millis(300))     // Only let an item through every 300ms
60//!         .for_each(|_| counter += 1)               // Increment a counter for each item
61//!         .await;
62//!
63//!     assert_eq!(counter, 2);
64//! })
65//! ```
66//!
67//! # The `Timer` trait
68//!
69//! The future returned by [`task::sleep`] implements the [`future::Timer`]
70//! trait. This represents a future whose deadline can be moved forward into the
71//! future.
72//!
73//! For example, say we have a deadline of `Duration::from_secs(10)`. By calling
74//! `Timer::reset_timer` the timer can be reschedule to trigger at a later time.
75//! This functionality is required for methods such as `debounce` and
76//! `Stream::timeout`, which will regularly want to reschedule their timers to trigger
77//! the future.
78//!
79//! Currently the only type implementing the `Timer` trait is
80//! [`task::Sleep`], which is created from a `Duration.` This is in contrast
81//! with [`task::sleep_until`], which takes an `Instant`, and cannot be reset.
82//!
83//! # Cancellation
84//!
85//! You can use [`channel::bounded`] to create a [`channel::Sender`] and [`channel::Receiver`] pair.
86//! When the "sender" sends a message, all "receivers" will halt execution of the future the next time they are
87//! `.await`ed. This will cause the future to stop executing, and all
88//! destructors to be run.
89//!
90//! ```
91//! use futures_lite::prelude::*;
92//! use futures_time::prelude::*;
93//! use futures_time::channel;
94//! use futures_time::time::Duration;
95//!
96//! async_io::block_on(async {
97//!     let (send, mut recv) = channel::bounded::<()>(1); // create a new send/receive pair
98//!     let mut counter = 0;
99//!     let value = async { "meow" }
100//!         .delay(Duration::from_millis(100))
101//!         .timeout(recv.next()) // time-out when the sender emits a message
102//!         .await;
103//!
104//!     assert_eq!(value.unwrap(), "meow");
105//! })
106//! ```
107//!
108//! # Futures
109//!
110//! - [`Future::delay`](`future::FutureExt::delay`) Delay execution for a specified time.
111//! - [`Future::timeout`](`future::FutureExt::timeout`) Cancel the future if the execution takes longer than the specified time.
112//! - [`Future::park`](`future::FutureExt::park`) Suspend or resume the execution of a future.
113//!
114//! # Tasks
115//!
116//! - [`task::sleep_until`] Sleeps until the specified deadline.
117//! - [`task::sleep`] Sleeps for the specified amount of time.
118//!
119//! # Streams
120//!
121//! - [`Stream::buffer`](`stream::StreamExt::buffer`) Returns a stream which buffers items and flushes them at each interval.
122//! - [`Stream::debounce`](`stream::StreamExt::debounce`) Returns a stream that debounces for the given duration.
123//! - [`Stream::delay`](`stream::StreamExt::delay`) Delay execution for a specified time.
124//! - [`Stream::park`](`stream::StreamExt::park`) Suspend or resume the execution of a stream.
125//! - [`Stream::sample`](`stream::StreamExt::sample`) Yield the last value received, if any, at each interval.
126//! - [`Stream::throttle`](`stream::StreamExt::throttle`) Filter out all items after the first for a specified time.
127//! - [`Stream::timeout`](`stream::StreamExt::timeout`) Cancel the stream if the execution takes longer than the specified time.
128//! - [`stream::interval`](`stream::interval`) Creates a new stream that yields at a set interval.
129//!
130//! # Re-exports
131//!
132//! - `channel` is a re-export of the [`async-channel`] crate, exposed for convenience
133//!
134//! [`async-channel`]: https://docs.rs/async-channel/latest/async_channel
135
136#![forbid(unsafe_code)]
137#![deny(missing_debug_implementations)]
138#![warn(missing_docs, future_incompatible, unreachable_pub)]
139#![forbid(rustdoc::missing_doc_code_examples)]
140
141pub(crate) mod utils;
142
143pub mod future;
144pub mod stream;
145pub mod task;
146pub mod time;
147
148/// An async multi-producer multi-consumer channel.
149pub mod channel {
150    /// Suspend or resume execution of a future.
151    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
152    pub enum Parker {
153        /// Put the future into a suspended state.
154        Park,
155        /// Put the future into an active state.
156        Unpark,
157    }
158    #[doc(inline)]
159    pub use async_channel::*;
160}
161
162/// The `futures-time` prelude.
163pub mod prelude {
164    pub use super::future::FutureExt as _;
165    pub use super::future::IntoFuture as _;
166    pub use super::future::Timer as _;
167    pub use super::stream::IntoStream as _;
168    pub use super::stream::StreamExt as _;
169}