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
//! Helper library support for `async` wai functions, used for both
use std::cell::RefCell;
use std::future::Future;
use std::mem;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;
use std::task::*;
#[cfg(target_arch = "wasm32")]
#[link(wasm_import_module = "canonical_abi")]
extern "C" {
pub fn async_export_done(ctx: i32, ptr: i32);
}
#[cfg(not(target_arch = "wasm32"))]
pub unsafe extern "C" fn async_export_done(_ctx: i32, _ptr: i32) {
panic!("only supported on wasm");
}
struct PollingWaker {
state: RefCell<State>,
}
enum State {
Waiting(Pin<Box<dyn Future<Output = ()>>>),
Polling,
Woken,
}
// These are valid for single-threaded WebAssembly because everything is
// single-threaded and send/sync don't matter much. This module will need
// an alternative implementation for threaded WebAssembly when that comes about
// to host runtimes off-the-web.
#[cfg(not(target_feature = "atomics"))]
unsafe impl Send for PollingWaker {}
#[cfg(not(target_feature = "atomics"))]
unsafe impl Sync for PollingWaker {}
/// Runs the `future` provided to completion, polling the future whenever its
/// waker receives a call to `wake`.
pub fn execute(future: impl Future<Output = ()> + 'static) {
let waker = Arc::new(PollingWaker {
state: RefCell::new(State::Waiting(Box::pin(future))),
});
waker.wake()
}
impl Wake for PollingWaker {
fn wake(self: Arc<Self>) {
let mut state = self.state.borrow_mut();
let mut future = match mem::replace(&mut *state, State::Polling) {
// We are the first wake to come in to wake-up this future. This
// means that we need to actually poll the future, so leave the
// `Polling` state in place.
State::Waiting(future) => future,
// Otherwise the future is either already polling or it was already
// woken while it was being polled, in both instances we reset the
// state back to `Woken` and then we return. This means that the
// future is owned by some previous stack frame and will drive the
// future as necessary.
State::Polling | State::Woken => {
*state = State::Woken;
return;
}
};
drop(state);
// Create the futures waker/context from ourselves, used for polling.
let waker = self.clone().into();
let mut cx = Context::from_waker(&waker);
loop {
match future.as_mut().poll(&mut cx) {
// The future is finished! By returning here we destroy the
// future and release all of its resources.
Poll::Ready(()) => break,
// The future has work yet-to-do, so continue below.
Poll::Pending => {}
}
let mut state = self.state.borrow_mut();
match *state {
// This means that we were not woken while we were polling and
// the state is as it was when we took out the future before. By
// `Pending` being returned at this point we're guaranteed that
// our waker will be woken up at some point in the future, which
// will come look at this future again. This means that we
// simply store our future and return, since this call to `wake`
// is now finished.
State::Polling => {
*state = State::Waiting(future);
break;
}
// This means that we received a call to `wake` while we were
// polling. Ideally we'd enqueue some sort of microtask-tick
// here or something like that but for now we just loop around
// and poll again.
State::Woken => {}
// This shouldn't be possible since we own the future, and no
// one else should insert another future here.
State::Waiting(_) => unreachable!(),
}
}
}
}
pub struct Oneshot<T> {
inner: Rc<OneshotInner<T>>,
}
pub struct Sender<T> {
inner: Rc<OneshotInner<T>>,
}
struct OneshotInner<T> {
state: RefCell<OneshotState<T>>,
}
enum OneshotState<T> {
Start,
Waiting(Waker),
Done(T),
}
impl<T> Oneshot<T> {
/// Returns a new "oneshot" channel as well as a completion callback.
pub fn new() -> (Oneshot<T>, Sender<T>) {
let inner = Rc::new(OneshotInner {
state: RefCell::new(OneshotState::Start),
});
(
Oneshot {
inner: Rc::clone(&inner),
},
Sender { inner },
)
}
}
impl<T> Future for Oneshot<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
let mut state = self.inner.state.borrow_mut();
match mem::replace(&mut *state, OneshotState::Start) {
OneshotState::Done(t) => Poll::Ready(t),
OneshotState::Waiting(_) | OneshotState::Start => {
*state = OneshotState::Waiting(cx.waker().clone());
Poll::Pending
}
}
}
}
impl<T> Sender<T> {
pub fn into_usize(self) -> usize {
Rc::into_raw(self.inner) as usize
}
pub unsafe fn from_usize(ptr: usize) -> Sender<T> {
Sender {
inner: Rc::from_raw(ptr as *const _),
}
}
pub fn send(self, val: T) {
let mut state = self.inner.state.borrow_mut();
let prev = mem::replace(&mut *state, OneshotState::Done(val));
// Must `drop` before the `wake` below because waking may induce
// polling which would induce another `borrow_mut` which would
// conflict with this `borrow_mut` otherwise.
drop(state);
match prev {
// nothing has polled the returned future just yet, so we just
// filled in the result of the computation. Presumably this will
// get picked up at some point in the future.
OneshotState::Start => {}
// Something was waiting for the result, so we wake the waker
// here which, for wasm, will likely induce polling immediately.
OneshotState::Waiting(waker) => waker.wake(),
// Shouldn't be possible, this is the only closure that writes
// `Done` and this can only be invoked once.
OneshotState::Done(_) => unreachable!(),
}
}
}
impl<T> Drop for OneshotInner<T> {
fn drop(&mut self) {
if let OneshotState::Waiting(waker) = &*self.state.borrow() {
waker.wake_by_ref();
}
}
}