Skip to main content

tilo_lock/
deferred.rs

1//! Code a program fetches after its first frame, through a loader it registers
2//! ([`Deferred::defer`]).
3//!
4//! [`Deferred::get`] is `None` until the code is in, and starts that fetch once;
5//! [`Deferred::wait`] is for code that can wait.
6
7use std::future::Future;
8use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
9use std::sync::{Mutex, OnceLock};
10use std::task::{Poll, Waker};
11
12use crate::MutexRecover as _;
13
14pub struct Deferred<T> {
15    value: OnceLock<T>,
16    load: OnceLock<fn()>,
17    requested: AtomicBool,
18    generation: AtomicU64,
19    /// Bumped by every failed fetch, so a waiter learns its fetch failed.
20    failures: AtomicU64,
21    waiters: Mutex<Vec<Waker>>,
22}
23
24impl<T: Copy> Default for Deferred<T> {
25    fn default() -> Self {
26        Self::new()
27    }
28}
29
30impl<T: Copy> Deferred<T> {
31    #[must_use]
32    pub const fn new() -> Self {
33        Self {
34            value: OnceLock::new(),
35            load: OnceLock::new(),
36            requested: AtomicBool::new(false),
37            generation: AtomicU64::new(0),
38            failures: AtomicU64::new(0),
39            waiters: Mutex::new(Vec::new()),
40        }
41    }
42
43    /// The code once it is in, fetching it if no fetch is running; `None` if that
44    /// fails or no loader is registered.
45    pub fn wait(&self) -> impl Future<Output = Option<T>> + Send + '_
46    where
47        T: Send + Sync,
48    {
49        let failures = self.failures.load(Ordering::Acquire);
50        std::future::poll_fn(move |cx| {
51            if let Some(value) = self.get() {
52                return Poll::Ready(Some(value));
53            }
54            if self.load.get().is_none() || self.failures.load(Ordering::Acquire) != failures {
55                return Poll::Ready(None);
56            }
57            self.waiters.lock_recover().push(cx.waker().clone());
58            // The code may have arrived, or the fetch failed, between the
59            // checks above and the registration.
60            if self.value.get().is_some() || self.failures.load(Ordering::Acquire) != failures {
61                cx.waker().wake_by_ref();
62            }
63            Poll::Pending
64        })
65    }
66
67    // Wake `waker` once the code is in or its fetch failed, so work polled once a frame runs again then.
68    pub fn wake_on_arrival(&self, waker: Waker) {
69        if self.value.get().is_some() {
70            waker.wake();
71            return;
72        }
73        self.waiters.lock_recover().push(waker);
74        // The code may have arrived between the check and the registration.
75        if self.value.get().is_some() {
76            self.wake_waiters();
77        }
78    }
79
80    fn wake_waiters(&self) {
81        let waiters = std::mem::take(&mut *self.waiters.lock_recover());
82        for waiter in waiters {
83            waiter.wake();
84        }
85    }
86
87    /// The code, or `None` while it is still to come; a miss starts a fetch.
88    #[must_use]
89    pub fn get(&self) -> Option<T> {
90        let value = self.value.get().copied();
91        if value.is_none() && !self.requested.swap(true, Ordering::AcqRel) {
92            match self.load.get() {
93                Some(load) => load(),
94                None => self.requested.store(false, Ordering::Release),
95            }
96        }
97        value
98    }
99
100    pub fn fetching(&self) -> bool {
101        self.value.get().is_none() && self.requested.load(Ordering::Acquire)
102    }
103
104    /// Bumped when the code arrives, so what was made without it is made again.
105    pub fn generation(&self) -> u64 {
106        self.generation.load(Ordering::Acquire)
107    }
108
109    /// How the program fetches the code: `load` starts the fetch, then calls
110    /// [`Self::install`] or [`Self::load_failed`].
111    pub fn defer(&self, load: fn()) {
112        let _ = self.load.set(load);
113    }
114
115    pub fn install(&self, value: T) {
116        if self.value.set(value).is_ok() {
117            self.generation.fetch_add(1, Ordering::AcqRel);
118        }
119        self.wake_waiters();
120    }
121
122    /// The fetch failed: the next use fetches again.
123    pub fn load_failed(&self) {
124        self.requested.store(false, Ordering::Release);
125        self.failures.fetch_add(1, Ordering::AcqRel);
126        self.wake_waiters();
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use std::sync::atomic::{AtomicUsize, Ordering};
133
134    use super::Deferred;
135
136    static LOADS: AtomicUsize = AtomicUsize::new(0);
137    static CODE: Deferred<u32> = Deferred::new();
138
139    fn load() {
140        LOADS.fetch_add(1, Ordering::SeqCst);
141    }
142
143    #[test]
144    fn fetches_once_until_it_fails_and_serves_what_arrived() {
145        assert_eq!(CODE.get(), None, "nothing to fetch with yet");
146        CODE.defer(load);
147        assert_eq!(CODE.get(), None);
148        assert_eq!(CODE.get(), None);
149        assert_eq!(LOADS.load(Ordering::SeqCst), 1, "one fetch at a time");
150        CODE.load_failed();
151        assert_eq!(CODE.get(), None);
152        assert_eq!(LOADS.load(Ordering::SeqCst), 2, "a failed fetch is retried");
153        assert_eq!(CODE.generation(), 0);
154        CODE.install(7);
155        assert_eq!(CODE.get(), Some(7));
156        assert_eq!(CODE.generation(), 1);
157        assert_eq!(LOADS.load(Ordering::SeqCst), 2);
158    }
159
160    static WAITED: Deferred<u32> = Deferred::new();
161
162    fn load_waited() {}
163
164    #[test]
165    fn a_waiter_gets_the_code_once_it_arrives_and_none_when_its_fetch_fails() {
166        use std::future::Future as _;
167        use std::pin::pin;
168        use std::task::{Context, Poll, Waker};
169
170        let mut cx = Context::from_waker(Waker::noop());
171        assert_eq!(
172            pin!(WAITED.wait()).poll(&mut cx),
173            Poll::Ready(None),
174            "no loader"
175        );
176        WAITED.defer(load_waited);
177        let mut failing = pin!(WAITED.wait());
178        assert!(failing.as_mut().poll(&mut cx).is_pending());
179        WAITED.load_failed();
180        assert_eq!(failing.as_mut().poll(&mut cx), Poll::Ready(None));
181        let mut arriving = pin!(WAITED.wait());
182        assert!(arriving.as_mut().poll(&mut cx).is_pending());
183        WAITED.install(9);
184        assert_eq!(arriving.as_mut().poll(&mut cx), Poll::Ready(Some(9)));
185    }
186
187    static ARRIVING: Deferred<u32> = Deferred::new();
188
189    struct Count(AtomicUsize);
190
191    impl std::task::Wake for Count {
192        fn wake(self: std::sync::Arc<Self>) {
193            self.0.fetch_add(1, Ordering::SeqCst);
194        }
195    }
196
197    #[test]
198    fn work_that_found_the_code_missing_is_woken_once_it_arrives() {
199        ARRIVING.defer(load_waited);
200        let woken = std::sync::Arc::new(Count(AtomicUsize::new(0)));
201        assert_eq!(ARRIVING.get(), None);
202        ARRIVING.wake_on_arrival(std::task::Waker::from(std::sync::Arc::clone(&woken)));
203        assert_eq!(woken.0.load(Ordering::SeqCst), 0, "nothing arrived yet");
204        ARRIVING.install(3);
205        assert_eq!(woken.0.load(Ordering::SeqCst), 1);
206        ARRIVING.wake_on_arrival(std::task::Waker::from(std::sync::Arc::clone(&woken)));
207        assert_eq!(
208            woken.0.load(Ordering::SeqCst),
209            2,
210            "code already in wakes at once"
211        );
212    }
213}