use std::time::Duration;
const MAX_CHUNK: Duration = Duration::from_millis(2_147_483_647);
fn chunks(duration: Duration) -> impl Iterator<Item = Duration> {
let mut remaining = duration;
let mut first = true;
std::iter::from_fn(move || {
if remaining.is_zero() && !first {
return None;
}
first = false;
let step = remaining.min(MAX_CHUNK);
remaining -= step;
Some(step)
})
}
pub async fn sleep(duration: Duration) {
for step in chunks(duration) {
#[cfg(not(target_family = "wasm"))]
tokio::time::sleep(step).await;
#[cfg(target_family = "wasm")]
gloo_timers::future::sleep(step).await;
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::{MAX_CHUNK, chunks};
#[test]
fn long_waits_split_below_the_browser_timer_limit() {
let steps: Vec<Duration> = chunks(MAX_CHUNK * 2 + Duration::from_millis(5)).collect();
assert_eq!(steps, vec![MAX_CHUNK, MAX_CHUNK, Duration::from_millis(5)]);
assert_eq!(
chunks(Duration::ZERO).collect::<Vec<_>>(),
vec![Duration::ZERO]
);
assert_eq!(
chunks(Duration::from_millis(250)).collect::<Vec<_>>(),
vec![Duration::from_millis(250)]
);
}
#[test]
fn the_longest_duration_stays_within_the_chunk_limit() {
assert!(
chunks(Duration::MAX)
.take(1_000)
.all(|step| step == MAX_CHUNK)
);
}
}