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
use std::future::Future;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::thread::{self, Thread};
use std::time::Duration;
use tokio::time::Instant;
pub(crate) fn timeout<F, I, E>(fut: F, timeout: Option<Duration>) -> Result<I, Waited<E>>
where
F: Future<Output = Result<I, E>>,
{
enter();
let deadline = timeout.map(|d| {
log::trace!("wait at most {:?}", d);
Instant::now() + d
});
let thread = ThreadWaker(thread::current());
let waker = futures_util::task::waker(Arc::new(thread));
let mut cx = Context::from_waker(&waker);
futures_util::pin_mut!(fut);
loop {
match fut.as_mut().poll(&mut cx) {
Poll::Ready(Ok(val)) => return Ok(val),
Poll::Ready(Err(err)) => return Err(Waited::Inner(err)),
Poll::Pending => (),
}
if let Some(deadline) = deadline {
let now = Instant::now();
if now >= deadline {
log::trace!("wait timeout exceeded");
return Err(Waited::TimedOut(crate::error::TimedOut));
}
log::trace!("({:?}) park timeout {:?}", thread::current().id(), deadline - now);
thread::park_timeout(deadline - now);
} else {
log::trace!("({:?}) park without timeout", thread::current().id());
thread::park();
}
}
}
#[derive(Debug)]
pub(crate) enum Waited<E> {
TimedOut(crate::error::TimedOut),
Inner(E),
}
struct ThreadWaker(Thread);
impl futures_util::task::ArcWake for ThreadWaker {
fn wake_by_ref(arc_self: &Arc<Self>) {
arc_self.0.unpark();
}
}
fn enter() {
#[cfg(debug_assertions)]
{
tokio::runtime::Builder::new()
.core_threads(1)
.build()
.expect("build shell runtime")
.enter(|| {});
}
}