stop_token/
async_io.rs

1//! Create deadlines from `Instant`.
2//!
3//! # Features
4//!
5//! This module is empty when no features are enabled. To implement deadlines
6//! for `Instant` you can enable one of the following features:
7//!
8//! - `async-io`: use this when using the `async-std` or `smol` runtimes.
9//! - `tokio`: use this when using the `tokio` runtime.
10//!
11//! # Examples
12//!
13//! ```
14//! use std::time::Instant;
15//! use async_std::prelude::*;
16//! use stop_token::prelude::*;
17//! use stop_token::StopToken;
18//!
19//! struct Event;
20//!
21//! async fn do_work(work: impl Stream<Item = Event> + Unpin, deadline: Instant) {
22//!     let mut work = work.timeout_at(deadline);
23//!     while let Some(Ok(event)) = work.next().await {
24//!         process_event(event).await
25//!     }
26//! }
27//!
28//! async fn process_event(_event: Event) {
29//! }
30//! ```
31
32use async_io::Timer;
33use std::future::Future;
34use std::pin::Pin;
35use std::task::{Context, Poll};
36use std::time::Instant;
37
38use pin_project_lite::pin_project;
39
40pin_project! {
41    /// A future that times out after a duration of time.
42    #[must_use = "Futures do nothing unless polled or .awaited"]
43    #[derive(Debug)]
44    pub(crate) struct Deadline {
45        instant: Instant,
46        #[pin]
47        delay: Timer,
48    }
49}
50
51impl Clone for Deadline {
52    fn clone(&self) -> Self {
53        Self {
54            instant: self.instant,
55            delay: Timer::at(self.instant),
56        }
57    }
58}
59
60impl Future for Deadline {
61    type Output = ();
62
63    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
64        let this = self.project();
65        match this.delay.poll(cx) {
66            Poll::Ready(_) => Poll::Ready(()),
67            Poll::Pending => Poll::Pending,
68        }
69    }
70}
71
72impl Into<crate::Deadline> for std::time::Instant {
73    fn into(self) -> crate::Deadline {
74        let deadline = Deadline {
75            instant: self,
76            delay: Timer::at(self),
77        };
78        crate::Deadline {
79            kind: crate::deadline::DeadlineKind::AsyncIo { t: deadline },
80        }
81    }
82}