webbluetooth_core/
timer.rs1use futures_channel::oneshot;
10use futures_util::future::{select, Either};
11use std::cmp::Reverse;
12use std::collections::BinaryHeap;
13use std::future::Future;
14use std::sync::{mpsc, OnceLock};
15use std::time::{Duration, Instant};
16
17struct Entry {
18 deadline: Instant,
19 waker: oneshot::Sender<()>,
20}
21
22impl PartialEq for Entry {
23 fn eq(&self, other: &Self) -> bool {
24 self.deadline == other.deadline
25 }
26}
27impl Eq for Entry {}
28impl PartialOrd for Entry {
29 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
30 Some(self.cmp(other))
31 }
32}
33impl Ord for Entry {
34 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
35 self.deadline.cmp(&other.deadline)
36 }
37}
38
39fn timer() -> &'static mpsc::Sender<Entry> {
40 static TIMER: OnceLock<mpsc::Sender<Entry>> = OnceLock::new();
41 TIMER.get_or_init(|| {
42 let (tx, rx) = mpsc::channel::<Entry>();
43 std::thread::Builder::new()
44 .name("webbluetooth-timer".into())
45 .spawn(move || {
46 let mut heap: BinaryHeap<Reverse<Entry>> = BinaryHeap::new();
47 loop {
48 let now = Instant::now();
50 while heap.peek().is_some_and(|Reverse(e)| e.deadline <= now) {
51 if let Some(Reverse(e)) = heap.pop() {
52 let _ = e.waker.send(());
53 }
54 }
55 let next = heap
57 .peek()
58 .map(|Reverse(e)| e.deadline.saturating_duration_since(now));
59 let received = match next {
60 Some(d) => match rx.recv_timeout(d) {
61 Ok(e) => Some(e),
62 Err(mpsc::RecvTimeoutError::Timeout) => None,
63 Err(mpsc::RecvTimeoutError::Disconnected) => return,
64 },
65 None => match rx.recv() {
66 Ok(e) => Some(e),
67 Err(_) => return,
68 },
69 };
70 if let Some(e) = received {
71 heap.push(Reverse(e));
72 }
73 }
74 })
75 .expect("could not start the webbluetooth timer thread");
76 tx
77 })
78}
79
80pub fn sleep(duration: Duration) -> impl Future<Output = ()> {
82 let (tx, rx) = oneshot::channel();
83 let _ = timer().send(Entry {
84 deadline: Instant::now() + duration,
85 waker: tx,
86 });
87 async move {
88 let _ = rx.await;
89 }
90}
91
92pub async fn timeout<F: Future>(duration: Duration, future: F) -> Result<F::Output, ()> {
96 let future = std::pin::pin!(future);
97 let delay = std::pin::pin!(sleep(duration));
98 match select(future, delay).await {
99 Either::Left((value, _)) => Ok(value),
100 Either::Right(((), _)) => Err(()),
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107 use futures_executor::block_on;
108
109 #[test]
110 fn sleep_actually_waits() {
111 let start = Instant::now();
112 block_on(sleep(Duration::from_millis(120)));
113 assert!(
114 start.elapsed() >= Duration::from_millis(100),
115 "returned too early"
116 );
117 }
118
119 #[test]
120 fn timeout_returns_the_value_when_fast_enough() {
121 let got = block_on(timeout(Duration::from_secs(5), async { 42 }));
122 assert_eq!(got, Ok(42));
123 }
124
125 #[test]
126 fn timeout_gives_up_on_a_future_that_never_finishes() {
127 let got = block_on(timeout(
128 Duration::from_millis(80),
129 std::future::pending::<()>(),
130 ));
131 assert_eq!(got, Err(()));
132 }
133
134 #[test]
135 fn deadlines_fire_in_order_not_submission_order() {
136 let out = block_on(async {
138 let long = sleep(Duration::from_millis(400));
139 let short = sleep(Duration::from_millis(60));
140 match select(std::pin::pin!(long), std::pin::pin!(short)).await {
141 Either::Left(_) => "long",
142 Either::Right(_) => "short",
143 }
144 });
145 assert_eq!(out, "short");
146 }
147}