-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathlib.rs
More file actions
215 lines (187 loc) · 5.75 KB
/
Copy pathlib.rs
File metadata and controls
215 lines (187 loc) · 5.75 KB
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
//! A pollable runtime based on [`compio`]. It is just a compio runtime except
//! Linux, where there is also an eventfd if the driver is io-uring. This crate
//! ensures that the raw fd returned by [`RawFd::as_raw_fd`] is always actively
//! pollable.
#![warn(missing_docs)]
#[cfg(target_os = "linux")]
use std::os::fd::OwnedFd;
use std::{
cell::RefCell,
future::Future,
io,
ops::{Deref, DerefMut},
pin::Pin,
sync::Arc,
task::{Context, Poll, Waker},
time::Duration,
};
use compio::{
driver::{AsRawFd, RawFd},
runtime::OptWaker,
};
use futures_util::FutureExt;
/// See [`Runtime`]
///
/// [`Runtime`]: compio::runtime::Runtime
pub struct Runtime {
runtime: compio::runtime::Runtime,
#[cfg(target_os = "linux")]
efd: Option<OwnedFd>,
}
#[cfg(target_os = "linux")]
impl Runtime {
/// Create [`Runtime`].
pub fn new() -> io::Result<Self> {
use rustix::event::{EventfdFlags, eventfd};
let efd = eventfd(0, EventfdFlags::CLOEXEC | EventfdFlags::NONBLOCK)?;
let mut builder = compio::driver::ProactorBuilder::new();
builder.register_eventfd(efd.as_raw_fd());
let runtime = compio::runtime::RuntimeBuilder::new()
.with_proactor(builder)
.build()?;
let efd = if runtime.driver_type().is_iouring() {
Some(efd)
} else {
None
};
Ok(Self { runtime, efd })
}
/// Clear the eventfd, if possible.
pub(crate) fn clear(&self) -> io::Result<()> {
if let Some(efd) = &self.efd {
let mut buf = [0u8; 8];
rustix::io::read(efd, &mut buf)?;
}
Ok(())
}
}
#[cfg(not(target_os = "linux"))]
impl Runtime {
/// Create [`Runtime`].
pub fn new() -> io::Result<Self> {
Ok(Self {
runtime: compio::runtime::Runtime::new()?,
})
}
/// Clear the eventfd, if possible.
pub(crate) fn clear(&self) -> io::Result<()> {
Ok(())
}
}
impl Runtime {
/// Run the scheduled tasks.
pub fn run(&self) -> bool {
let main_task_remaining = if MAIN_TASK.is_set() {
MAIN_TASK.with(|task| task.poll())
} else {
false
};
self.runtime.run() | main_task_remaining
}
/// Poll the runtime. Returns the next timeout.
pub fn poll_and_run(&self) -> Option<Duration> {
self.runtime.poll_with(Some(Duration::ZERO));
let remaining_tasks = self.run();
if remaining_tasks {
Some(Duration::ZERO)
} else {
self.runtime.current_timeout()
}
}
/// Set the current main task and wait for its completion.
pub fn enter_block_on<F: Future<Output = ()>, T>(&self, future: F, f: impl FnOnce() -> T) -> T {
let opt_waker = self.runtime.opt_waker();
let task = unsafe { MainTask::new(future, opt_waker) };
MAIN_TASK.set(&task, f)
}
/// Block on the future till it completes. Users should enter the runtime
/// before calling this function, and poll the runtime themselves.
pub fn block_on<F: Future>(&self, future: F, poll: impl Fn(Option<Duration>)) -> F::Output {
let result = RefCell::new(None);
self.enter_block_on(
async {
let res = Some(future.await);
result.replace(res);
},
|| {
loop {
let timeout = self.poll_and_run();
if let Some(result) = result.take() {
break result;
}
poll(timeout);
self.clear().ok();
}
},
)
}
}
impl Deref for Runtime {
type Target = compio::runtime::Runtime;
fn deref(&self) -> &Self::Target {
&self.runtime
}
}
impl DerefMut for Runtime {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.runtime
}
}
impl AsRawFd for Runtime {
fn as_raw_fd(&self) -> RawFd {
#[cfg(target_os = "linux")]
{
self.efd
.as_ref()
.map(|f| f.as_raw_fd())
.unwrap_or_else(|| self.runtime.as_raw_fd())
}
#[cfg(not(target_os = "linux"))]
{
self.runtime.as_raw_fd()
}
}
}
struct MainTask {
future: RefCell<Pin<Box<dyn Future<Output = ()>>>>,
opt_waker: Arc<OptWaker>,
waker: Waker,
}
unsafe fn reduce_lifetime<'a>(
future: impl Future<Output = ()> + 'a,
) -> Pin<Box<dyn Future<Output = ()> + 'static>> {
let future = Box::pin(future) as Pin<Box<dyn Future<Output = ()> + 'a>>;
unsafe {
std::mem::transmute::<
Pin<Box<dyn Future<Output = ()> + 'a>>,
Pin<Box<dyn Future<Output = ()> + 'static>>,
>(future)
}
}
impl MainTask {
pub unsafe fn new(future: impl Future<Output = ()>, opt_waker: Arc<OptWaker>) -> Self {
let waker = Waker::from(opt_waker.clone());
Self {
// SAFETY: the future will only be polled within the scope of `enter_block_on`, which
// guarantees that the future will not outlive the main task.
future: RefCell::new(unsafe { reduce_lifetime(future.fuse()) }),
opt_waker,
waker,
}
}
pub fn poll(&self) -> bool {
let mut cx = Context::from_waker(&self.waker);
if let Ok(mut fut) = self.future.try_borrow_mut() {
if let Poll::Ready(()) = fut.as_mut().poll(&mut cx) {
// The future has completed, so we should not wait for the driver to wake us up
// anymore.
true
} else {
self.opt_waker.reset()
}
} else {
false
}
}
}
scoped_tls::scoped_thread_local!(static MAIN_TASK: MainTask);