Skip to content

Instantly share code, notes, and snippets.

@panicbit
Created July 30, 2020 18:20
Show Gist options
  • Save panicbit/21b45a5ddb8691e3765845a01a03c01e to your computer and use it in GitHub Desktop.
Save panicbit/21b45a5ddb8691e3765845a01a03c01e to your computer and use it in GitHub Desktop.
fn main() {
let counter1 = Counter { name: "C1", counter: 3 };
let counter2 = Counter { name: "C2", counter: 5 };
let joined = join(counter1, counter2);
block_on(joined);
}
fn block_on(mut future: impl Future) {
loop {
println!("Polling a future in the runtime");
if future.poll() == Poll::Ready {
return;
}
}
}
trait Future {
fn poll(&mut self) -> Poll;
}
#[derive(PartialEq)]
enum Poll {
Ready,
NotReady,
}
struct Counter {
name: &'static str,
counter: i32,
}
impl Future for Counter {
fn poll(&mut self) -> Poll {
if self.counter < 0 {
return Poll::Ready
}
println!("[{}] Counter is {}", self.name, self.counter);
self.counter -= 1;
Poll::NotReady
}
}
struct Join<F1, F2> {
future1: Option<F1>,
future2: Option<F2>,
}
impl<F1: Future, F2: Future> Future for Join<F1, F2> {
fn poll(&mut self) -> Poll {
if let Some(future1) = &mut self.future1 {
println!("Polling select future 1");
if future1.poll() == Poll::Ready {
self.future1.take();
}
}
if let Some(future2) = &mut self.future2 {
println!("Polling select future 2");
if future2.poll() == Poll::Ready {
self.future2.take();
}
}
if self.future1.is_none() && self.future2.is_none() {
Poll::Ready
} else {
Poll::NotReady
}
}
}
fn join<F1: Future, F2: Future>(future1: F1, future2: F2) -> Join<F1, F2> {
Join {
future1: Some(future1),
future2: Some(future2),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment