Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(common): Add simple blocking async executor #38

Merged
merged 1 commit into from
Feb 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions crates/common/src/executor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//! This module contains utilities for handling async functions in the no_std environment. This allows for usage of
//! async/await syntax for futures in a single thread.

use alloc::boxed::Box;
use core::{
future::Future,
task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};

/// This function busy waits on a future until it is ready. It uses a no-op waker to poll the future in a
/// thread-blocking loop.
pub fn block_on<T>(f: impl Future<Output = T>) -> T {
let mut f = Box::pin(f);

// Construct a no-op waker.
fn noop_clone(_: *const ()) -> RawWaker {
noop_raw_waker()
}
fn noop(_: *const ()) {}
fn noop_raw_waker() -> RawWaker {
let vtable = &RawWakerVTable::new(noop_clone, noop, noop, noop);
RawWaker::new(core::ptr::null(), vtable)
}
let waker = unsafe { Waker::from_raw(noop_raw_waker()) };
let mut context = Context::from_waker(&waker);

loop {
// Safety: This is safe because we only poll the future once per loop iteration,
// and we do not move the future after pinning it.
if let Poll::Ready(v) = f.as_mut().poll(&mut context) {
return v;
}
}
}
5 changes: 5 additions & 0 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
#![cfg_attr(target_arch = "mips", feature(asm_experimental_arch))]
#![no_std]

extern crate alloc;

pub mod io;

pub mod malloc;
Expand All @@ -20,6 +22,9 @@ pub use traits::BasicKernelInterface;
mod types;
pub use types::{FileDescriptor, RegisterSize};

mod executor;
pub use executor::block_on;

#[cfg(target_arch = "mips")]
pub(crate) mod cannon;

Expand Down
Loading