-
Notifications
You must be signed in to change notification settings - Fork 53
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add simple blocking async executor (#38)
- Loading branch information
Showing
2 changed files
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters