|
| 1 | +//! Timers for web targets. |
| 2 | +//! |
| 3 | +//! These use the `setTimeout` function on the web to handle timing. |
| 4 | +
|
| 5 | +use std::convert::TryInto; |
| 6 | +use std::sync::atomic::{AtomicUsize, Ordering}; |
| 7 | +use std::sync::Arc; |
| 8 | +use std::task::{Context, Poll}; |
| 9 | +use std::time::Duration; |
| 10 | + |
| 11 | +use atomic_waker::AtomicWaker; |
| 12 | +use wasm_bindgen::closure::Closure; |
| 13 | +use wasm_bindgen::JsCast; |
| 14 | + |
| 15 | +/// A timer for non-Web platforms. |
| 16 | +/// |
| 17 | +/// self registers a timeout in the global reactor, which in turn sets a timeout in the poll call. |
| 18 | +#[derive(Debug)] |
| 19 | +pub(super) struct Timer { |
| 20 | + /// The waker to wake when the timer fires. |
| 21 | + waker: Arc<State>, |
| 22 | + |
| 23 | + /// The ongoing timeout or interval. |
| 24 | + ongoing_timeout: TimerId, |
| 25 | + |
| 26 | + /// Keep the closure alive so we don't drop it. |
| 27 | + closure: Option<Closure<dyn FnMut()>>, |
| 28 | +} |
| 29 | + |
| 30 | +#[derive(Debug)] |
| 31 | +struct State { |
| 32 | + /// The number of times this timer has been woken. |
| 33 | + woken: AtomicUsize, |
| 34 | + |
| 35 | + /// The waker to wake when the timer fires. |
| 36 | + waker: AtomicWaker, |
| 37 | +} |
| 38 | + |
| 39 | +#[derive(Debug)] |
| 40 | +enum TimerId { |
| 41 | + NoTimer, |
| 42 | + Timeout(i32), |
| 43 | + Interval(i32), |
| 44 | +} |
| 45 | + |
| 46 | +impl Timer { |
| 47 | + /// Create a timer that will never fire. |
| 48 | + #[inline] |
| 49 | + pub(super) fn never() -> Self { |
| 50 | + Self { |
| 51 | + waker: Arc::new(State { |
| 52 | + woken: AtomicUsize::new(0), |
| 53 | + waker: AtomicWaker::new(), |
| 54 | + }), |
| 55 | + ongoing_timeout: TimerId::NoTimer, |
| 56 | + closure: None, |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + /// Create a timer that will fire at the given instant. |
| 61 | + #[inline] |
| 62 | + pub(super) fn after(duration: Duration) -> Timer { |
| 63 | + let mut this = Self::never(); |
| 64 | + this.set_after(duration); |
| 65 | + this |
| 66 | + } |
| 67 | + |
| 68 | + /// Create a timer that will fire at the given instant. |
| 69 | + #[inline] |
| 70 | + pub(super) fn interval(period: Duration) -> Timer { |
| 71 | + let mut this = Self::never(); |
| 72 | + this.set_interval(period); |
| 73 | + this |
| 74 | + } |
| 75 | + |
| 76 | + /// Returns `true` if self timer will fire at some point. |
| 77 | + #[inline] |
| 78 | + pub(super) fn will_fire(&self) -> bool { |
| 79 | + matches!( |
| 80 | + self.ongoing_timeout, |
| 81 | + TimerId::Timeout(_) | TimerId::Interval(_) |
| 82 | + ) |
| 83 | + } |
| 84 | + |
| 85 | + /// Set the timer to fire after the given duration. |
| 86 | + #[inline] |
| 87 | + pub(super) fn set_after(&mut self, duration: Duration) { |
| 88 | + // Set the timeout. |
| 89 | + let id = { |
| 90 | + let waker = self.waker.clone(); |
| 91 | + let closure: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || { |
| 92 | + waker.wake(); |
| 93 | + })); |
| 94 | + |
| 95 | + let result = web_sys::window() |
| 96 | + .unwrap() |
| 97 | + .set_timeout_with_callback_and_timeout_and_arguments_0( |
| 98 | + closure.as_ref().unchecked_ref(), |
| 99 | + duration.as_millis().try_into().expect("timeout too long"), |
| 100 | + ); |
| 101 | + |
| 102 | + // Make sure we don't drop the closure before it's called. |
| 103 | + self.closure = Some(closure); |
| 104 | + |
| 105 | + match result { |
| 106 | + Ok(id) => id, |
| 107 | + Err(_) => { |
| 108 | + panic!("failed to set timeout") |
| 109 | + } |
| 110 | + } |
| 111 | + }; |
| 112 | + |
| 113 | + // Set our ID. |
| 114 | + self.ongoing_timeout = TimerId::Timeout(id); |
| 115 | + } |
| 116 | + |
| 117 | + /// Set the timer to emit events periodically. |
| 118 | + #[inline] |
| 119 | + pub(super) fn set_interval(&mut self, period: Duration) { |
| 120 | + // Set the timeout. |
| 121 | + let id = { |
| 122 | + let waker = self.waker.clone(); |
| 123 | + let closure: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || { |
| 124 | + waker.wake(); |
| 125 | + })); |
| 126 | + |
| 127 | + let result = web_sys::window() |
| 128 | + .unwrap() |
| 129 | + .set_interval_with_callback_and_timeout_and_arguments_0( |
| 130 | + closure.as_ref().unchecked_ref(), |
| 131 | + period.as_millis().try_into().expect("timeout too long"), |
| 132 | + ); |
| 133 | + |
| 134 | + // Make sure we don't drop the closure before it's called. |
| 135 | + self.closure = Some(closure); |
| 136 | + |
| 137 | + match result { |
| 138 | + Ok(id) => id, |
| 139 | + Err(_) => { |
| 140 | + panic!("failed to set interval") |
| 141 | + } |
| 142 | + } |
| 143 | + }; |
| 144 | + |
| 145 | + // Set our ID. |
| 146 | + self.ongoing_timeout = TimerId::Interval(id); |
| 147 | + } |
| 148 | + |
| 149 | + /// Poll for the next timer event. |
| 150 | + #[inline] |
| 151 | + pub(super) fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<()>> { |
| 152 | + let mut registered = false; |
| 153 | + let mut woken = self.waker.woken.load(Ordering::Acquire); |
| 154 | + |
| 155 | + loop { |
| 156 | + if woken > 0 { |
| 157 | + // Try to decrement the number of woken events. |
| 158 | + if let Err(new_woken) = self.waker.woken.compare_exchange( |
| 159 | + woken, |
| 160 | + woken - 1, |
| 161 | + Ordering::SeqCst, |
| 162 | + Ordering::Acquire, |
| 163 | + ) { |
| 164 | + woken = new_woken; |
| 165 | + continue; |
| 166 | + } |
| 167 | + |
| 168 | + // If we are using a one-shot timer, clear it. |
| 169 | + if let TimerId::Timeout(_) = self.ongoing_timeout { |
| 170 | + self.clear(); |
| 171 | + } |
| 172 | + |
| 173 | + return Poll::Ready(Some(())); |
| 174 | + } |
| 175 | + |
| 176 | + if !registered { |
| 177 | + // Register the waker. |
| 178 | + self.waker.waker.register(cx.waker()); |
| 179 | + registered = true; |
| 180 | + } else { |
| 181 | + // We've already registered, so we can just return pending. |
| 182 | + return Poll::Pending; |
| 183 | + } |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + /// Clear the current timeout. |
| 188 | + fn clear(&mut self) { |
| 189 | + match self.ongoing_timeout { |
| 190 | + TimerId::NoTimer => {} |
| 191 | + TimerId::Timeout(id) => { |
| 192 | + web_sys::window().unwrap().clear_timeout_with_handle(id); |
| 193 | + } |
| 194 | + TimerId::Interval(id) => { |
| 195 | + web_sys::window().unwrap().clear_interval_with_handle(id); |
| 196 | + } |
| 197 | + } |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | +impl State { |
| 202 | + fn wake(&self) { |
| 203 | + self.woken.fetch_add(1, Ordering::SeqCst); |
| 204 | + self.waker.wake(); |
| 205 | + } |
| 206 | +} |
| 207 | + |
| 208 | +impl Drop for Timer { |
| 209 | + fn drop(&mut self) { |
| 210 | + self.clear(); |
| 211 | + } |
| 212 | +} |
0 commit comments