|
| 1 | +// Copyright 2025 Shift Crypto AG |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +use alloc::boxed::Box; |
| 16 | +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 | + |
| 47 | +/// Waits for an option to contain a value and returns that value, leaving `None` in its place. |
| 48 | +/// E.g. `assert_eq!(option(&Some(42)).await, 42)`. |
| 49 | +pub fn option<O>(option: &RefCell<Option<O>>) -> AsyncOption<'_, O> { |
| 50 | + AsyncOption(option) |
| 51 | +} |
| 52 | + |
| 53 | +/// Polls a future until the result is available. |
| 54 | +#[cfg(feature = "testing")] |
| 55 | +pub fn block_on<O>(task: impl core::future::Future<Output = O>) -> O { |
| 56 | + let mut task: crate::bb02_async::Task<O> = alloc::boxed::Box::pin(task); |
| 57 | + loop { |
| 58 | + if let Poll::Ready(result) = spin(&mut task) { |
| 59 | + return result; |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments