Skip to content

Commit

Permalink
Add simple blocking async executor (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
clabby authored Feb 24, 2024
1 parent e13eea0 commit e10418f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
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

0 comments on commit e10418f

Please sign in to comment.