Created
November 10, 2019 03:28
-
-
Save sjolsen/560184b86dee032bf41e9cd3de139c12 to your computer and use it in GitHub Desktop.
Zero-cost futures?
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
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