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
#![no_std]
#![deny(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unstable_features,
unused_import_braces,
unused_qualifications,
clippy::all
)]
use core::future;
use core::task;
pub fn run_spinning<F>(future: F) -> F::Output
where
F: future::Future,
{
run(future, || core::sync::atomic::spin_loop_hint())
}
pub fn run<F>(future: F, wait: impl FnMut()) -> F::Output
where
F: future::Future,
{
run_with_wake(future, wait, || {})
}
pub fn run_with_wake<F>(future: F, mut wait: impl FnMut(), wake: impl Fn()) -> F::Output
where
F: future::Future,
{
pin_utils::pin_mut!(future);
let raw_waker: task::RawWaker = create_raw_waker(&wake);
let waker = unsafe { task::Waker::from_raw(raw_waker) };
let mut context = task::Context::from_waker(&waker);
loop {
if let task::Poll::Ready(result) = future.as_mut().poll(&mut context) {
return result;
}
wait();
}
}
fn create_raw_waker<F>(wake: *const F) -> task::RawWaker
where
F: Fn(),
{
task::RawWaker::new(
wake as *const (),
&task::RawWakerVTable::new(
|wake_ptr| create_raw_waker(wake_ptr as *const F),
|wake_ptr| unsafe {
let wake = (wake_ptr as *const F).as_ref().unwrap();
wake();
},
|wake_ptr| unsafe {
let wake = (wake_ptr as *const F).as_ref().unwrap();
wake();
},
|_| {},
),
)
}