|
12 | 12 | // See the License for the specific language governing permissions and |
13 | 13 | // limitations under the License. |
14 | 14 |
|
15 | | -use alloc::boxed::Box; |
16 | 15 | use core::cell::RefCell; |
17 | | -use core::pin::Pin; |
18 | | -use core::task::{Context, Poll}; |
19 | | - |
20 | | -/// Task is the top-level future which can be polled by an executor. |
21 | | -/// Note that other futures awaited inside do not have to be pinned. |
22 | | -/// The 'a lifetime allows to spin a boxed/pinned future that is not |
23 | | -/// 'static, or a future with non-'static input param references. |
24 | | -pub type Task<'a, O> = Pin<Box<dyn core::future::Future<Output = O> + 'a>>; |
25 | | - |
26 | | -/// A primitive poll invocation for a task, with no waking functionality. |
27 | | -pub fn spin<O>(task: &mut Task<O>) -> Poll<O> { |
28 | | - // TODO: statically allocate the context. |
29 | | - let waker = crate::waker_fn::waker_fn(|| {}); |
30 | | - let context = &mut Context::from_waker(&waker); |
31 | | - task.as_mut().poll(context) |
32 | | -} |
33 | | - |
34 | | -/// Implements the Option future, see `option()`. |
35 | | -pub struct AsyncOption<'a, O>(&'a RefCell<Option<O>>); |
36 | | - |
37 | | -impl<O> core::future::Future for AsyncOption<'_, O> { |
38 | | - type Output = O; |
39 | | - fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> { |
40 | | - match self.0.borrow_mut().take() { |
41 | | - None => Poll::Pending, |
42 | | - Some(output) => Poll::Ready(output), |
43 | | - } |
44 | | - } |
45 | | -} |
46 | 16 |
|
47 | 17 | /// Disables the screensaver while waiting for an option to contain a value. Afterwards, it returns that value |
48 | 18 | pub async fn option_no_screensaver<O>(opt: &RefCell<Option<O>>) -> O { |
49 | 19 | bitbox02::screen_saver::screen_saver_disable(); |
50 | | - let result = option(opt).await; |
| 20 | + let result = util::bb02_async::option(opt).await; |
51 | 21 | bitbox02::screen_saver::screen_saver_enable(); |
52 | 22 | result |
53 | 23 | } |
54 | | - |
55 | | -/// Waits for an option to contain a value and returns that value, leaving `None` in its place. |
56 | | -/// E.g. `assert_eq!(option(&Some(42)).await, 42)`. |
57 | | -pub fn option<O>(option: &RefCell<Option<O>>) -> AsyncOption<'_, O> { |
58 | | - AsyncOption(option) |
59 | | -} |
60 | | - |
61 | | -/// Polls a future until the result is available. |
62 | | -pub fn block_on<O>(task: impl core::future::Future<Output = O>) -> O { |
63 | | - let mut task: crate::bb02_async::Task<O> = alloc::boxed::Box::pin(task); |
64 | | - loop { |
65 | | - bitbox02::ui::screen_process(); |
66 | | - if let Poll::Ready(result) = spin(&mut task) { |
67 | | - return result; |
68 | | - } |
69 | | - } |
70 | | -} |
0 commit comments