Skip to content

Instantly share code, notes, and snippets.

@sjolsen
Created November 10, 2019 03:28
Show Gist options
  • Save sjolsen/560184b86dee032bf41e9cd3de139c12 to your computer and use it in GitHub Desktop.
Save sjolsen/560184b86dee032bf41e9cd3de139c12 to your computer and use it in GitHub Desktop.
Zero-cost futures?
use futures::executor::*;
use futures::future::*;
use futures::task::*;
use futures_util::pin_mut;
use std::pin::*;
async fn use_me(i: i32) -> i32 {
i
}
struct UseMeManually(i32);
impl Future for UseMeManually {
type Output = i32;
fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> {
Poll::Ready(self.0)
}
}
fn use_me_manually(i: i32) -> impl Future<Output = i32> {
UseMeManually(i)
}
fn block_busy<F: Future>(f: F) -> <F as Future>::Output {
pin_mut!(f);
loop {
let w = noop_waker();
let mut ctx = Context::from_waker(&w);
match f.as_mut().poll(&mut ctx) {
Poll::Ready(t) => return t,
Poll::Pending => (),
}
}
}
pub fn use_them(i: i32) -> i32 {
block_on(use_me(i))
}
pub fn use_them_manually(i: i32) -> i32 {
block_busy(use_me_manually(i))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment