Skip to main content

waft_foundation/
completer.rs

1//! Flutter counterpart: `dart:async` `Completer`, the `Future` it completes, and `Future.wait`.
2//!
3//! A future's listeners run on the microtask queue, as Dart's do: [`CompleterFuture::then`]
4//! queues its callback through the [`App`] and [`Completer::complete`] queues the pending ones.
5//! An `await` resumes its task at the checkpoint instead; the shell runs both.
6
7use std::cell::{Cell, OnceCell};
8use std::future::Future;
9use std::pin::Pin;
10use std::rc::Rc;
11use std::task::{Context, Poll, Waker};
12
13use crate::app::App;
14use crate::change_notifier::Listener;
15
16type Callback<T> = Box<dyn FnOnce(&mut App, T)>;
17
18/// The state a completer and its futures share. The value is written once, so it is a
19/// `OnceCell`; the lists are only ever taken out whole and put back, so they are `Cell`s —
20/// nothing here can hit a runtime borrow conflict.
21struct Shared<T> {
22    value: OnceCell<T>,
23    wakers: Cell<Vec<Waker>>,
24    callbacks: Cell<Vec<Callback<T>>>,
25}
26
27impl<T> Shared<T> {
28    fn new(value: Option<T>) -> Rc<Shared<T>> {
29        let shared = Shared {
30            value: OnceCell::new(),
31            wakers: Cell::new(Vec::new()),
32            callbacks: Cell::new(Vec::new()),
33        };
34        if let Some(value) = value {
35            let _ = shared.value.set(value);
36        }
37        Rc::new(shared)
38    }
39}
40
41/// A way to produce `Future` objects and to complete them later with a value.
42///
43/// The resolving half; [`future`](Self::future) hands out the listening half any number of
44/// times. A completer dropped before [`complete`](Self::complete) leaves its futures pending
45/// forever, as a Dart future nobody completes.
46pub struct Completer<T> {
47    shared: Rc<Shared<T>>,
48}
49
50impl<T> Completer<T> {
51    pub fn new() -> Completer<T> {
52        Completer {
53            shared: Shared::new(None),
54        }
55    }
56
57    /// A completer that has already completed with `value`.
58    pub fn completed(value: T) -> Completer<T> {
59        Completer {
60            shared: Shared::new(Some(value)),
61        }
62    }
63
64    /// Whether the future has been completed.
65    pub fn is_completed(&self) -> bool {
66        self.shared.value.get().is_some()
67    }
68
69    /// The future that is completed by this completer.
70    pub fn future(&self) -> CompleterFuture<T> {
71        CompleterFuture {
72            shared: Rc::clone(&self.shared),
73        }
74    }
75}
76
77impl<T: Clone + 'static> Completer<T> {
78    /// Completes the future with the supplied value. Registered callbacks run on the
79    /// microtask queue and awaiting tasks resume at the checkpoint — never inline.
80    ///
81    /// # Panics
82    ///
83    /// On a second call, where Dart's throws a `StateError`.
84    pub fn complete(&self, app: &mut App, value: T) {
85        assert!(
86            self.shared.value.set(value.clone()).is_ok(),
87            "Completer.complete called twice (Dart's StateError)"
88        );
89        for waker in self.shared.wakers.take() {
90            waker.wake();
91        }
92        for callback in self.shared.callbacks.take() {
93            schedule(app, callback, value.clone());
94        }
95    }
96}
97
98impl<T> Default for Completer<T> {
99    fn default() -> Completer<T> {
100        Completer::new()
101    }
102}
103
104/// Another reference to the same completion, as a Dart completer is one shared object: what
105/// lets a completer held in arena data be completed with the `App` borrowed mutably.
106impl<T> Clone for Completer<T> {
107    fn clone(&self) -> Completer<T> {
108        Completer {
109            shared: Rc::clone(&self.shared),
110        }
111    }
112}
113
114/// Queues `callback` with `value` on the microtask queue.
115fn schedule<T: 'static>(app: &mut App, callback: Callback<T>, value: T) {
116    let pending = Cell::new(Some((callback, value)));
117    app.schedule_microtask(Listener::new(move |app| {
118        if let Some((callback, value)) = pending.take() {
119            callback(app, value);
120        }
121    }));
122}
123
124/// A [`Completer`]'s future. Every clone resolves with its own clone of the value, as every
125/// `await` of one Dart future sees the same result.
126pub struct CompleterFuture<T> {
127    shared: Rc<Shared<T>>,
128}
129
130impl<T> CompleterFuture<T> {
131    /// A future that is already complete: Dart's `Future.value` and `SynchronousFuture`.
132    pub fn ready(value: T) -> CompleterFuture<T> {
133        Completer::completed(value).future()
134    }
135
136    /// Whether the value is known yet — what Dart learns by handing `then` a callback and
137    /// seeing whether it ran synchronously.
138    pub fn is_completed(&self) -> bool {
139        self.shared.value.get().is_some()
140    }
141}
142
143impl<T: Clone + 'static> CompleterFuture<T> {
144    /// Runs `future` as a task and hands out its result as a completer's future: the future
145    /// of a Dart `async` function whose body awaits, for a method that returns a nameable,
146    /// shareable future over an awaited chain.
147    pub fn spawn(app: &App, future: impl Future<Output = T> + 'static) -> CompleterFuture<T> {
148        let completer = Completer::new();
149        let result = completer.future();
150        app.spawn(async move |cx| {
151            let value = future.await;
152            cx.update(|app| completer.complete(app, value));
153        });
154        result
155    }
156
157    /// The value, if the completer has completed.
158    pub fn peek(&self) -> Option<T> {
159        self.shared.value.get().cloned()
160    }
161
162    /// Dart's `then`: runs `callback` with the value on the microtask queue once the future
163    /// has completed — never inline, even on an already resolved future.
164    pub fn then(self, app: &mut App, callback: impl FnOnce(&mut App, T) + 'static) {
165        match self.shared.value.get() {
166            Some(value) => schedule(app, Box::new(callback), value.clone()),
167            None => {
168                let mut callbacks = self.shared.callbacks.take();
169                callbacks.push(Box::new(callback));
170                self.shared.callbacks.set(callbacks);
171            }
172        }
173    }
174}
175
176impl<T> Clone for CompleterFuture<T> {
177    fn clone(&self) -> CompleterFuture<T> {
178        CompleterFuture {
179            shared: Rc::clone(&self.shared),
180        }
181    }
182}
183
184impl<T: Clone> Future for CompleterFuture<T> {
185    type Output = T;
186
187    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
188        if let Some(value) = self.shared.value.get() {
189            return Poll::Ready(value.clone());
190        }
191        let waker = cx.waker();
192        let mut wakers = self.shared.wakers.take();
193        if !wakers.iter().any(|known| known.will_wake(waker)) {
194            wakers.push(waker.clone());
195        }
196        self.shared.wakers.set(wakers);
197        Poll::Pending
198    }
199}
200
201/// Dart's `Future.wait`: resolves with every value once the last future has resolved.
202pub async fn wait_all<T>(futures: impl IntoIterator<Item = impl Future<Output = T>>) -> Vec<T> {
203    let mut values = Vec::new();
204    for future in futures {
205        values.push(future.await);
206    }
207    values
208}