Skip to content

Instantly share code, notes, and snippets.

@benmkw
Created March 28, 2020 10:24
Show Gist options
  • Save benmkw/acd171318738cccb1318d1216ae6afa4 to your computer and use it in GitHub Desktop.
Save benmkw/acd171318738cccb1318d1216ae6afa4 to your computer and use it in GitHub Desktop.
basic_rust_executor
// https://gcc.godbolt.org/z/dT6sd5
use std::{
future::Future,
pin::Pin,
task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};
fn foo() {}
// executor based on https://github.com/spacejam/extreme
static VTABLE: RawWakerVTable = RawWakerVTable::new(
|_clone_me| RawWaker::new(foo as *const (), &VTABLE),
|_wake_me| {},
|_wake_by_ref_me| {},
|_drop_me| {},
);
/// Run a `Future`.
pub fn run<F: Future>(mut f: F) -> F::Output {
let raw_waker = RawWaker::new(foo as *const (), &VTABLE);
let waker = unsafe { Waker::from_raw(raw_waker) };
let mut cx = Context::from_waker(&waker);
loop {
let pin = unsafe { Pin::new_unchecked(&mut f) };
match F::poll(pin, &mut cx) {
Poll::Pending => {}
Poll::Ready(val) => return val,
}
}
}
pub struct MyFuture {
int: u8,
}
impl Future for MyFuture {
type Output = u8;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
println!("futures poll method got called {:?}", self.int);
let max = 5;
if self.int == max {
Poll::Ready(max)
} else {
cx.waker().wake_by_ref();
unsafe {
self.get_unchecked_mut().int += 1;
}
Poll::Pending
}
}
}
pub async fn hello_world() -> u8 {
MyFuture { int: 0 }.await
}
fn main() {
let future = hello_world();
let res = run(future);
dbg!(&res);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment