Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ wasm-bindgen = "0.2.58"

[target.'cfg(all(target_arch = "wasm32", not(target_os="wasi"), not(cargo_web)))'.dev-dependencies]
wasm-bindgen-test = "0.3.4"
base64 = "0.11.0"
ssri = "5.0.0"

[target.'cfg(target_os = "emscripten")'.dependencies]
ryu = "1.0.2" # 1.0.1 breaks emscripten
Expand Down
68 changes: 68 additions & 0 deletions src/callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,71 @@ impl<IN: 'static> Callback<IN> {
Callback::from(func)
}
}

#[cfg(test)]
pub(crate) mod test_util {
use super::*;
use std::cell::RefCell;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};

struct CallbackHandle<T> {
waker: Option<Waker>,
output: Option<T>,
}

impl<T> Default for CallbackHandle<T> {
fn default() -> Self {
CallbackHandle {
waker: None,
output: None,
}
}
}

pub(crate) struct CallbackFuture<T>(Rc<RefCell<CallbackHandle<T>>>);

impl<T> Clone for CallbackFuture<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}

impl<T> Default for CallbackFuture<T> {
fn default() -> Self {
Self(Rc::default())
}
}

impl<T: 'static> Into<Callback<T>> for CallbackFuture<T> {
fn into(self) -> Callback<T> {
Callback::from(move |r| self.finish(r))
}
}

impl<T> Future for CallbackFuture<T> {
type Output = T;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(output) = self.ready() {
Poll::Ready(output)
} else {
self.0.borrow_mut().waker = Some(cx.waker().clone());
Poll::Pending
}
}
}

impl<T> CallbackFuture<T> {
fn ready(&self) -> Option<T> {
self.0.borrow_mut().output.take()
}

fn finish(&self, output: T) {
self.0.borrow_mut().output = Some(output);
if let Some(waker) = self.0.borrow_mut().waker.take() {
waker.wake();
}
}
}
}
Loading