1use std::time::Duration;
24
25pub const UNBOUNDED_SLEEP: Duration = Duration::from_secs(4_294_967_295);
27
28#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
30pub enum TimerError {
31 #[error("no JavaScript global scope owns setTimeout")]
33 NoGlobalScope,
34 #[error("JavaScript timer rejected: {0}")]
36 Rejected(String),
37}
38
39#[cfg(not(all(feature = "browser", target_family = "wasm")))]
41pub async fn sleep(duration: Duration) -> Result<(), TimerError> {
42 if duration >= UNBOUNDED_SLEEP {
43 return std::future::pending().await;
44 }
45 futures_timer::Delay::new(duration).await;
46 Ok(())
47}
48
49#[cfg(all(feature = "browser", target_family = "wasm"))]
51pub async fn sleep(duration: Duration) -> Result<(), TimerError> {
52 if duration >= UNBOUNDED_SLEEP {
53 return std::future::pending().await;
54 }
55 for millis in TimeoutSegments::new(duration) {
56 browser::set_timeout(millis).await?;
57 }
58 Ok(())
59}
60
61#[cfg(any(test, all(feature = "browser", target_family = "wasm")))]
69struct TimeoutSegments {
70 remaining_ms: u128,
72 fresh: bool,
74}
75
76#[cfg(any(test, all(feature = "browser", target_family = "wasm")))]
77impl TimeoutSegments {
78 fn new(duration: Duration) -> Self {
80 Self {
81 remaining_ms: duration.as_nanos().div_ceil(1_000_000),
82 fresh: true,
83 }
84 }
85}
86
87#[cfg(any(test, all(feature = "browser", target_family = "wasm")))]
88impl Iterator for TimeoutSegments {
89 type Item = i32;
90
91 fn next(&mut self) -> Option<i32> {
92 if self.remaining_ms == 0 && !self.fresh {
93 return None;
94 }
95 self.fresh = false;
96 let segment = i32::try_from(self.remaining_ms).unwrap_or(i32::MAX);
98 self.remaining_ms -= u128::from(segment.unsigned_abs());
100 Some(segment)
101 }
102}
103
104#[cfg(all(feature = "browser", target_family = "wasm"))]
105mod browser {
106 use std::cell::Cell;
107 use std::cell::RefCell;
108 use std::future::Future;
109 use std::pin::Pin;
110 use std::rc::Rc;
111 use std::task::Context;
112 use std::task::Poll;
113 use std::task::Waker;
114
115 use wasm_bindgen::closure::Closure;
116 use wasm_bindgen::JsCast;
117
118 use super::TimerError;
119 use crate::global::global;
120 use crate::global::Global;
121
122 struct TimeoutShared {
123 fired: Cell<bool>,
124 waker: RefCell<Option<Waker>>,
125 }
126
127 struct BrowserTimeout {
130 scope: Global,
131 millis: i32,
132 handle: Option<i32>,
133 callback: Option<Closure<dyn FnMut()>>,
134 shared: Rc<TimeoutShared>,
135 }
136
137 impl BrowserTimeout {
138 fn new(millis: i32) -> Result<Self, TimerError> {
139 let scope = global().ok_or(TimerError::NoGlobalScope)?;
140 Ok(Self {
141 scope,
142 millis,
143 handle: None,
144 callback: None,
145 shared: Rc::new(TimeoutShared {
146 fired: Cell::new(false),
147 waker: RefCell::new(None),
148 }),
149 })
150 }
151 }
152
153 impl Future for BrowserTimeout {
154 type Output = Result<(), TimerError>;
155
156 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
157 if self.shared.fired.get() {
158 self.handle = None;
159 self.callback = None;
160 return Poll::Ready(Ok(()));
161 }
162 *self.shared.waker.borrow_mut() = Some(cx.waker().clone());
163 if self.handle.is_none() {
164 let shared = Rc::clone(&self.shared);
165 let callback = Closure::wrap(Box::new(move || {
166 shared.fired.set(true);
167 let waker = shared.waker.borrow_mut().take();
168 if let Some(waker) = waker {
169 waker.wake();
170 }
171 }) as Box<dyn FnMut()>);
172 match self
173 .scope
174 .set_timeout_0(callback.as_ref().unchecked_ref(), self.millis)
175 {
176 Ok(handle) => {
177 self.handle = Some(handle);
178 self.callback = Some(callback);
179 }
180 Err(error) => {
181 return Poll::Ready(Err(TimerError::Rejected(format!("{error:?}"))));
182 }
183 }
184 }
185 Poll::Pending
186 }
187 }
188
189 impl Drop for BrowserTimeout {
190 fn drop(&mut self) {
191 if !self.shared.fired.get() {
192 if let Some(handle) = self.handle.take() {
193 self.scope.clear_timeout(handle);
194 }
195 }
196 self.callback = None;
197 }
198 }
199
200 pub(super) async fn set_timeout(millis: i32) -> Result<(), TimerError> {
202 BrowserTimeout::new(millis)?.await
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use std::time::Duration;
209
210 use super::TimeoutSegments;
211
212 fn segments(duration: Duration) -> Vec<i32> {
213 TimeoutSegments::new(duration).collect()
214 }
215
216 #[test]
217 fn test_zero_duration_still_yields_once() {
218 assert_eq!(segments(Duration::ZERO), vec![0]);
219 }
220
221 #[test]
222 fn test_sub_millisecond_rounds_up() {
223 assert_eq!(segments(Duration::from_nanos(1)), vec![1]);
224 assert_eq!(segments(Duration::from_micros(1_500)), vec![2]);
225 assert_eq!(segments(Duration::from_millis(7)), vec![7]);
226 }
227
228 #[test]
229 fn test_ceiling_is_chained_not_clamped() {
230 let max = i32::MAX;
231 let at_ceiling = Duration::from_millis(u64::from(max.unsigned_abs()));
232
233 assert_eq!(segments(at_ceiling), vec![max]);
234 assert_eq!(segments(at_ceiling + Duration::from_millis(1)), vec![
235 max, 1
236 ]);
237 assert_eq!(segments(at_ceiling * 2), vec![max, max]);
238 }
239
240 #[test]
241 fn test_segments_sum_to_the_rounded_duration() {
242 for nanos in [0_u64, 1, 999_999, 1_000_000, 86_400_000_000_000, u64::MAX] {
243 let duration = Duration::from_nanos(nanos);
244 let emitted = segments(duration);
245 let total: u128 = emitted
246 .iter()
247 .map(|&ms| u128::from(ms.unsigned_abs()))
248 .sum();
249
250 assert_eq!(total, duration.as_nanos().div_ceil(1_000_000));
251 assert!(emitted.iter().all(|&ms| ms >= 0));
252 }
253 }
254}
255
256#[cfg(all(test, not(target_family = "wasm")))]
257mod native_tests {
258 use std::time::Duration;
259
260 use futures::FutureExt;
261
262 use super::sleep;
263 use super::UNBOUNDED_SLEEP;
264
265 #[test]
266 fn test_unbounded_sleep_never_resolves_or_overflows() {
267 let mut never = Box::pin(sleep(Duration::MAX));
268 assert!(never.as_mut().now_or_never().is_none());
269 assert!(Box::pin(sleep(UNBOUNDED_SLEEP)).now_or_never().is_none());
270 }
271
272 #[test]
273 fn test_native_sleep_never_fails() {
274 assert_eq!(futures::executor::block_on(sleep(Duration::ZERO)), Ok(()));
275 }
276}
277
278#[cfg(all(test, feature = "browser", target_family = "wasm"))]
279mod browser_tests {
280 use std::time::Duration;
281
282 use wasm_bindgen_test::wasm_bindgen_test;
283 use wasm_bindgen_test::wasm_bindgen_test_configure;
284
285 use super::sleep;
286
287 wasm_bindgen_test_configure!(run_in_browser);
288
289 #[wasm_bindgen_test]
290 async fn test_browser_sleep_resolves_after_its_duration() {
291 let started = js_sys::Date::now();
292 sleep(Duration::from_millis(20)).await.unwrap();
293
294 assert!(js_sys::Date::now() - started >= 19.0);
296 }
297
298 #[wasm_bindgen_test]
299 async fn test_browser_zero_sleep_yields_and_resolves() {
300 sleep(Duration::ZERO).await.unwrap();
301 }
302
303 #[wasm_bindgen_test]
304 async fn test_browser_dropped_sleep_cancels_scheduled_timeout() {
305 use futures::FutureExt;
306
307 for _ in 0..256 {
308 let mut pending_sleep = Box::pin(sleep(Duration::from_secs(60)));
309 assert!(pending_sleep.as_mut().now_or_never().is_none());
310 drop(pending_sleep);
311 }
312 sleep(Duration::from_millis(20)).await.unwrap();
313 }
314}