rtx 0.1.0

RTx is a zero-cost runtime-abstraction intended for use by Rust libraries to enable the Freedom of Choice between asynchronous runtimes.
//! Common traits and types for I/O.

use std::io;
use std::task::{Context, Poll};

// We could have created our own I/O traits, but the ones from `futures-io` are extended
// in `futures-util` with all the nice helper methods that return `Future`s which can be awaited.
// That saves us a lot of duplicated work.
//
// Tokio's I/O traits are technically more flexible, but there's no way to get them by themselves.
// Even with all its optional features disabled, Tokio still has a lot more to compile than just
// its I/O traits, which limits its utility as a building block here.

#[cfg(any(feature = "async", doc))]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use futures_io::AsyncRead;

#[cfg(any(feature = "async", doc))]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use futures_io::AsyncWrite;

#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use futures_util::AsyncWriteExt;

#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use futures_util::AsyncReadExt;

pub trait Ready {
    /// Polls for read readiness of the I/O handle.
    ///
    /// When this method returns Poll::Ready, that means the OS has delivered an event indicating
    /// readability since the last time this task has called the method and
    /// received Poll::Pending.
    ///
    fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;

    /// Polls for write readiness of the I/O handle.
    ///
    /// When this method returns Poll::Ready, that means the OS has delivered an event indicating
    /// writability since the last time this task has called the method and
    /// received Poll::Pending.
    ///
    fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;

    /// Polls for either read or write readiness of the I/O handle.
    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        if self.poll_read_ready(cx)?.is_ready() {
            return Poll::Ready(Ok(()));
        }

        if self.poll_write_ready(cx)?.is_ready() {
            return Poll::Ready(Ok(()));
        }

        Poll::Pending
    }
}