Skip to content

Instantly share code, notes, and snippets.

@carllerche
Last active August 31, 2022 17:11
Show Gist options
  • Save carllerche/5d7037bd55dac1cb72891529a4ff1540 to your computer and use it in GitHub Desktop.
Save carllerche/5d7037bd55dac1cb72891529a4ff1540 to your computer and use it in GitHub Desktop.
pub struct Interest(...);
pub struct Ready(...);
impl Interest {
pub const READ = ...;
pub const WRITE = ...;
}
pub trait AsyncIo {
/// Wait for any of the requested input, returns the actual readiness.
///
/// # Examples
///
/// ```
/// async fn main() -> Result<(), Box<dyn Error>> {
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// loop {
/// let ready = stream.ready(Interest::READABLE | Interest::WRITABLE).await?;
///
/// if ready.is_readable() {
/// let mut data = vec![0; 1024];
/// // Try to read data, this may still fail with `WouldBlock`
/// // if the readiness event is a false positive.
/// match stream.try_read(&mut data) {
/// Ok(n) => {
/// println!("read {} bytes", n);
/// }
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// continue;
/// }
/// Err(e) => {
/// return Err(e.into());
/// }
/// }
///
/// }
///
/// if ready.is_writable() {
/// // Try to write data, this may still fail with `WouldBlock`
/// // if the readiness event is a false positive.
/// match stream.try_write(b"hello world") {
/// Ok(n) => {
/// println!("write {} bytes", n);
/// }
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// continue
/// }
/// Err(e) => {
/// return Err(e.into());
/// }
/// }
/// }
/// }
/// }
/// ```
async fn ready(&mut self, interest: Interest) -> io::Result<Ready>;
}
pub trait AsyncRead: AsyncIo {
fn try_read(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()>;
}
pub trait AsyncWrite: AsyncIo {
fn try_write(&mut self, buf: &[u8]) -> io::Result<usize>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment