Skip to content

Instantly share code, notes, and snippets.

@Mathspy
Created May 10, 2020 12:48
Show Gist options
  • Save Mathspy/6c718974ac7b8cc835bd46215b36dc15 to your computer and use it in GitHub Desktop.
Save Mathspy/6c718974ac7b8cc835bd46215b36dc15 to your computer and use it in GitHub Desktop.
Detect if a reader is ready to be read from
async fn is_reader_ready<R>(reader: &mut R) -> bool where R: AsyncRead + Unpin {
let mut me = &mut *reader;
poll_fn(|cx| {
let mut v = [];
Poll::Ready(Pin::new(&mut me).poll_read(cx, &mut v[..]).is_ready())
}).await
}
@Mathspy
Copy link
Author

Mathspy commented May 10, 2020

Don't actually use this. I originally wrote it for testing purposes before realising

  1. it tests implementation details
  2. reading into a 0 sized buffer is not always going to do what you expect it to. Some futures might even shortcut this and say they are always ready to read because they kind of are, you asked them for no data they can definitely serve you that lol
  3. Majority of futures make no guarantee how many times you will need to poll them before they are actually ready. So even if you're testing your own future, if it calls other futures you have no guarantee this will return what you expect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment