use core::{
future::Future,
pin::Pin,
task::{Context, Poll},
task::{RawWaker, RawWakerVTable, Waker},
};
pub trait Interrupt: Send + Sync + Sized {
fn new() -> Self;
fn interrupt(&self);
fn wait_for(&self);
#[allow(unsafe_code)]
fn block_on<F: Future>(mut f: F) -> <F as Future>::Output {
let task: Self = Interrupt::new();
let mut f = unsafe { Pin::new_unchecked(&mut f) };
'executor: loop {
let waker = waker(&task);
let context = &mut Context::from_waker(&waker);
match f.as_mut().poll(context) {
Poll::Pending => task.wait_for(),
Poll::Ready(ret) => break 'executor ret,
}
}
}
}
#[inline(always)]
#[allow(unsafe_code)]
fn waker<I: Interrupt>(interrupt: *const I) -> Waker {
unsafe fn clone<I: Interrupt>(data: *const ()) -> RawWaker {
RawWaker::new(data, vtable::<I>())
}
unsafe fn wake<I: Interrupt>(data: *const ()) {
ref_wake::<I>(data)
}
unsafe fn ref_wake<I: Interrupt>(data: *const ()) {
I::interrupt(&*(data as *const I));
}
unsafe fn drop<I: Interrupt>(_data: *const ()) {}
unsafe fn vtable<I: Interrupt>() -> &'static RawWakerVTable {
&RawWakerVTable::new(clone::<I>, wake::<I>, ref_wake::<I>, drop::<I>)
}
unsafe {
Waker::from_raw(RawWaker::new(interrupt as *const (), vtable::<I>()))
}
}