1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#[cfg(feature = "async-io")]
pub use asyncio::*;
#[cfg(any(feature = "async-io", feature = "docs"))]
mod asyncio {
use async_io::Timer;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use crate::IntoDeadline;
use pin_project_lite::pin_project;
pin_project! {
#[must_use = "Futures do nothing unless polled or .awaited"]
#[derive(Debug)]
pub struct Deadline {
#[pin]
delay: Timer,
}
}
impl Future for Deadline {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
match this.delay.poll(cx) {
Poll::Ready(_) => Poll::Ready(()),
Poll::Pending => Poll::Pending,
}
}
}
impl IntoDeadline for std::time::Duration {
type Deadline = Deadline;
fn into_deadline(self) -> Self::Deadline {
Deadline {
delay: Timer::after(self),
}
}
}
impl IntoDeadline for std::time::Instant {
type Deadline = Deadline;
fn into_deadline(self) -> Self::Deadline {
Deadline {
delay: Timer::at(self),
}
}
}
}
#[cfg(feature = "tokio")]
pub use tokiooo::*;
#[cfg(feature = "tokio")]
mod tokiooo {
use std::future::{pending, Future, Pending};
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::time::{timeout, timeout_at, Instant as TokioInstant, Timeout};
use crate::IntoDeadline;
#[must_use = "Futures do nothing unless polled or .awaited"]
#[derive(Debug)]
pub struct Deadline {
delay: Pin<Box<Timeout<Pending<()>>>>,
}
impl Future for Deadline {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match Pin::new(&mut self.delay).poll(cx) {
Poll::Ready(_) => Poll::Ready(()),
Poll::Pending => Poll::Pending,
}
}
}
impl IntoDeadline for std::time::Duration {
type Deadline = Deadline;
fn into_deadline(self) -> Self::Deadline {
Deadline {
delay: Box::pin(timeout(self, pending())),
}
}
}
impl IntoDeadline for std::time::Instant {
type Deadline = Deadline;
fn into_deadline(self) -> Self::Deadline {
let instant = TokioInstant::from(self);
Deadline {
delay: Box::pin(timeout_at(instant, pending())),
}
}
}
}