Skip to content

Commit

Permalink
Merge pull request #51 from expenses/wasm-support
Browse files Browse the repository at this point in the history
Support for `wasm32-unknown-unknown`
  • Loading branch information
yoshuawuyts committed Jan 27, 2020
2 parents 4586461 + 9f620d7 commit 799ed3b
Show file tree
Hide file tree
Showing 10 changed files with 98 additions and 33 deletions.
2 changes: 2 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions .idea/futures-timer.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,15 @@ Timeouts for futures.
"""

[dependencies]
gloo-timers = { version = "0.2.0", features = ["futures"], optional = true }
send_wrapper = { version = "0.4.0", optional = true }

[dev-dependencies]
async-std = { version = "1.0.1", features = ["attributes"] }
futures = "0.3.1"

[features]
wasm-bindgen = [
"gloo-timers",
"send_wrapper"
]
35 changes: 8 additions & 27 deletions src/delay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ use crate::{ScheduledTimer, TimerHandle};
/// at.
pub struct Delay {
state: Option<Arc<Node<ScheduledTimer>>>,
when: Instant,
}

impl Delay {
Expand All @@ -38,25 +37,14 @@ impl Delay {
Delay::new_handle(Instant::now() + dur, Default::default())
}

/// Return the `Instant` when this delay will fire.
#[inline]
pub fn when(&self) -> Instant {
self.when
}

/// Creates a new future which will fire at the time specified by `at`.
///
/// The returned instance of `Delay` will be bound to the timer specified by
/// the `handle` argument.
pub(crate) fn new_handle(at: Instant, handle: TimerHandle) -> Delay {
let inner = match handle.inner.upgrade() {
Some(i) => i,
None => {
return Delay {
state: None,
when: at,
}
}
None => return Delay { state: None },
};
let state = Arc::new(Node::new(ScheduledTimer {
at: Mutex::new(Some(at)),
Expand All @@ -70,30 +58,23 @@ impl Delay {
// timer, meaning that we'll want to immediately return an error from
// `poll`.
if inner.list.push(&state).is_err() {
return Delay {
state: None,
when: at,
};
return Delay { state: None };
}

inner.waker.wake();
Delay {
state: Some(state),
when: at,
}
Delay { state: Some(state) }
}

/// Resets this timeout to an new timeout which will fire at the time
/// specified by `at`.
#[inline]
pub fn reset(&mut self, at: Instant) {
self.when = at;
if self._reset(self.when).is_err() {
pub fn reset(&mut self, dur: Duration) {
if self._reset(dur).is_err() {
self.state = None
}
}

fn _reset(&mut self, at: Instant) -> Result<(), ()> {
fn _reset(&mut self, dur: Duration) -> Result<(), ()> {
let state = match self.state {
Some(ref state) => state,
None => return Err(()),
Expand All @@ -111,7 +92,7 @@ impl Delay {
Err(s) => bits = s,
}
}
*state.at.lock().unwrap() = Some(at);
*state.at.lock().unwrap() = Some(Instant::now() + dur);
// If we fail to push our node then we've become an inert timer, so
// we'll want to clear our `state` field accordingly
timeouts.list.push(state)?;
Expand Down Expand Up @@ -165,6 +146,6 @@ impl Drop for Delay {

impl fmt::Debug for Delay {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.debug_struct("Delay").field("when", &self.when).finish()
f.debug_struct("Delay").finish()
}
}
36 changes: 36 additions & 0 deletions src/delay_wasm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//! A version of `Delay` that works on wasm.

use gloo_timers::future::TimeoutFuture;
use send_wrapper::SendWrapper;
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
time::Duration,
};

/// A version of `Delay` that works on wasm.
#[derive(Debug)]
pub struct Delay(SendWrapper<TimeoutFuture>);

impl Delay {
/// Creates a new future which will fire at `dur` time into the future.
#[inline]
pub fn new(dur: Duration) -> Delay {
Self(SendWrapper::new(TimeoutFuture::new(dur.as_millis() as u32)))
}

/// Resets the timeout.
#[inline]
pub fn reset(&mut self, dur: Duration) {
*self = Delay::new(at);
}
}

impl Future for Delay {
type Output = ();

fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
Pin::new(&mut *Pin::into_inner(self).0).poll(cx)
}
}
14 changes: 9 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,24 @@
//!
//! # Examples
//!
//! ```no_run
//! # #[async_std::main]
//! # async fn main() {
//! ```
//! use std::time::Duration;
//! use futures_timer::Delay;
//! use futures::executor::block_on;
//!
//! let now = Delay::new(Duration::from_secs(3)).await;
//! let now = block_on(Delay::new(Duration::from_secs(3)));
//! println!("waited for 3 secs");
//! # }
//! ```

#![deny(missing_docs)]
#![warn(missing_debug_implementations)]

mod arc_list;
mod atomic_waker;
#[cfg(not(all(target_arch = "wasm32", feature = "wasm-bindgen")))]
mod delay;
#[cfg(all(target_arch = "wasm32", feature = "wasm-bindgen"))]
mod delay_wasm;
mod global;
mod heap;
mod heap_timer;
Expand All @@ -30,4 +31,7 @@ use heap::{Heap, Slot};
use heap_timer::HeapTimer;
use timer::{ScheduledTimer, Timer, TimerHandle};

#[cfg(not(all(target_arch = "wasm32", feature = "wasm-bindgen")))]
pub use self::delay::Delay;
#[cfg(all(target_arch = "wasm32", feature = "wasm-bindgen"))]
pub use self::delay_wasm::Delay;
2 changes: 1 addition & 1 deletion tests/smoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ async fn reset() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
assert!(i.elapsed() > dur);

let i = Instant::now();
d.reset(Instant::now() + dur);
d.reset(dur);
d.await;
assert!(i.elapsed() > dur);
Ok(())
Expand Down

0 comments on commit 799ed3b

Please sign in to comment.