Skip to main content

alpha2_host_core/
request_watch.rs

1//! A heartbeat from the long loops a request's own thread runs, for the host's request watch.
2
3thread_local! {
4    static REQUEST_WATCH: std::cell::RefCell<Option<Box<dyn Fn()>>> =
5        const { std::cell::RefCell::new(None) };
6}
7
8/// Calls `beat` on this thread each time a loop of this crate that runs on a request's thread
9/// takes a step (an audio decoder block, a seek), until the guard drops.
10#[must_use = "the watch ends when the guard drops"]
11pub fn watch_request(beat: impl Fn() + 'static) -> RequestWatchGuard {
12    let previous = REQUEST_WATCH.with(|watch| watch.replace(Some(Box::new(beat))));
13    RequestWatchGuard {
14        previous,
15        thread: std::marker::PhantomData,
16    }
17}
18
19/// Ends a [`watch_request`] watch, restoring the one before it.
20pub struct RequestWatchGuard {
21    previous: Option<Box<dyn Fn()>>,
22    thread: std::marker::PhantomData<*const ()>,
23}
24
25impl Drop for RequestWatchGuard {
26    fn drop(&mut self) {
27        let previous = self.previous.take();
28        REQUEST_WATCH.with(|watch| {
29            watch.replace(previous);
30        });
31    }
32}
33
34/// Tells this thread's [`watch_request`] watch, if any, that a step starts.
35pub fn beat_request() {
36    REQUEST_WATCH.with(|watch| {
37        if let Some(beat) = watch.borrow().as_ref() {
38            beat();
39        }
40    });
41}