Skip to content

Instantly share code, notes, and snippets.

@little-dude
Created August 17, 2019 12:11
Show Gist options
  • Save little-dude/c6719be8b533c1797503b51a7113e8ff to your computer and use it in GitHub Desktop.
Save little-dude/c6719be8b533c1797503b51a7113e8ff to your computer and use it in GitHub Desktop.
use futures::{
stream::Stream,
task::{Context, Poll},
Future,
};
use std::pin::Pin;
use tokio::sync::mpsc::{Receiver, Sender};
/// Dummy structure that represent some state we update when we
/// receive data or events.
struct State;
impl State {
fn update(&mut self, _data: Vec<u8>) {
println!("updated state");
}
fn handle_event(&mut self, _event: u32) {
println!("handled event");
}
}
/// The future I want to implement.
struct MyFuture {
state: State,
data: Receiver<Vec<u8>>,
events: Receiver<Vec<u8>>,
}
impl MyFuture {
fn poll_data(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
use Poll::*;
let MyFuture {
ref mut data,
ref mut state,
..
} = self.get_mut();
loop {
// this breaks, because Pin::new consume the mutable
// reference on the first iteration of the loop.
match Pin::new(data).poll_next(cx) {
Ready(Some(vec)) => state.update(vec),
Ready(None) => return Ready(()),
Pending => return Pending,
}
}
}
// unimplemented, but we basically have the same problem than with
// `poll_data()`
fn poll_events(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
unimplemented!()
}
}
impl Future for MyFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
use Poll::*;
if let Ready(_) = self.poll_data(cx) {
return Ready(());
}
// This does not work because self was consumed when
// self.poll_data() was called.
if let Ready(_) = self.poll_events(cx) {
return Ready(());
}
return Pending;
}
}
fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment