async_io

Struct Async

Source
pub struct Async<T> { /* private fields */ }
Expand description

Async adapter for I/O types.

This type puts an I/O handle into non-blocking mode, registers it in epoll/kqueue/event ports/IOCP, and then provides an async interface for it.

§Caveats

Async is a low-level primitive, and as such it comes with some caveats.

For higher-level primitives built on top of Async, look into async-net or async-process (on Unix).

The most notable caveat is that it is unsafe to access the inner I/O source mutably using this primitive. Traits likes AsyncRead and AsyncWrite are not implemented by default unless it is guaranteed that the resource won’t be invalidated by reading or writing. See the IoSafe trait for more information.

§Supported types

Async supports all networking types, as well as some OS-specific file descriptors like timerfd and inotify.

However, do not use Async with types like File, Stdin, Stdout, or Stderr because all operating systems have issues with them when put in non-blocking mode.

§Concurrent I/O

Note that &Async<T> implements AsyncRead and AsyncWrite if &T implements those traits, which means tasks can concurrently read and write using shared references.

But there is a catch: only one task can read a time, and only one task can write at a time. It is okay to have two tasks where one is reading and the other is writing at the same time, but it is not okay to have two tasks reading at the same time or writing at the same time. If you try to do that, conflicting tasks will just keep waking each other in turn, thus wasting CPU time.

Besides AsyncRead and AsyncWrite, this caveat also applies to poll_readable() and poll_writable().

However, any number of tasks can be concurrently calling other methods like readable() or read_with().

§Closing

Closing the write side of Async with [close()][futures_lite::AsyncWriteExt::close()] simply flushes. If you want to shutdown a TCP or Unix socket, use Shutdown.

§Examples

Connect to a server and echo incoming messages back to the server:

use async_io::Async;
use futures_lite::io;
use std::net::TcpStream;

// Connect to a local server.
let stream = Async::<TcpStream>::connect(([127, 0, 0, 1], 8000)).await?;

// Echo all messages from the read side of the stream into the write side.
io::copy(&stream, &stream).await?;

You can use either predefined async methods or wrap blocking I/O operations in Async::read_with(), Async::read_with_mut(), Async::write_with(), and Async::write_with_mut():

use async_io::Async;
use std::net::TcpListener;

let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;

// These two lines are equivalent:
let (stream, addr) = listener.accept().await?;
let (stream, addr) = listener.read_with(|inner| inner.accept()).await?;

Implementations§

Source§

impl<T: AsSocket> Async<T>

Source

pub fn new(io: T) -> Result<Async<T>>

Creates an async I/O handle.

This method will put the handle in non-blocking mode and register it in epoll/kqueue/event ports/IOCP.

On Unix systems, the handle must implement AsFd, while on Windows it must implement AsSocket.

§Examples
use async_io::Async;
use std::net::{SocketAddr, TcpListener};

let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))?;
let listener = Async::new(listener)?;
Source

pub fn new_nonblocking(io: T) -> Result<Async<T>>

Creates an async I/O handle without setting it to non-blocking mode.

This method will register the handle in epoll/kqueue/event ports/IOCP.

On Unix systems, the handle must implement AsFd, while on Windows it must implement AsSocket.

§Caveats

The caller should ensure that the handle is set to non-blocking mode or that it is okay if it is not set. If not set to non-blocking mode, I/O operations may block the current thread and cause a deadlock in an asynchronous context.

Source§

impl<T> Async<T>

Source

pub fn get_ref(&self) -> &T

Gets a reference to the inner I/O handle.

§Examples
use async_io::Async;
use std::net::TcpListener;

let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
let inner = listener.get_ref();
Source

pub unsafe fn get_mut(&mut self) -> &mut T

Gets a mutable reference to the inner I/O handle.

§Safety

The underlying I/O source must not be dropped using this function.

§Examples
use async_io::Async;
use std::net::TcpListener;

let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
let inner = unsafe { listener.get_mut() };
Source

pub fn into_inner(self) -> Result<T>

Unwraps the inner I/O handle.

This method will not put the I/O handle back into blocking mode.

§Examples
use async_io::Async;
use std::net::TcpListener;

let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
let inner = listener.into_inner()?;

// Put the listener back into blocking mode.
inner.set_nonblocking(false)?;
Source

pub fn readable(&self) -> Readable<'_, T>

Waits until the I/O handle is readable.

This method completes when a read operation on this I/O handle wouldn’t block.

§Examples
use async_io::Async;
use std::net::TcpListener;

let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;

// Wait until a client can be accepted.
listener.readable().await?;
Source

pub fn readable_owned(self: Arc<Self>) -> ReadableOwned<T>

Waits until the I/O handle is readable.

This method completes when a read operation on this I/O handle wouldn’t block.

Source

pub fn writable(&self) -> Writable<'_, T>

Waits until the I/O handle is writable.

This method completes when a write operation on this I/O handle wouldn’t block.

§Examples
use async_io::Async;
use std::net::{TcpStream, ToSocketAddrs};

let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
let stream = Async::<TcpStream>::connect(addr).await?;

// Wait until the stream is writable.
stream.writable().await?;
Source

pub fn writable_owned(self: Arc<Self>) -> WritableOwned<T>

Waits until the I/O handle is writable.

This method completes when a write operation on this I/O handle wouldn’t block.

Source

pub fn poll_readable(&self, cx: &mut Context<'_>) -> Poll<Result<()>>

Polls the I/O handle for readability.

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.

§Caveats

Two different tasks should not call this method concurrently. Otherwise, conflicting tasks will just keep waking each other in turn, thus wasting CPU time.

Note that the AsyncRead implementation for Async also uses this method.

§Examples
use async_io::Async;
use futures_lite::future;
use std::net::TcpListener;

let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;

// Wait until a client can be accepted.
future::poll_fn(|cx| listener.poll_readable(cx)).await?;
Source

pub fn poll_writable(&self, cx: &mut Context<'_>) -> Poll<Result<()>>

Polls the I/O handle for writability.

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.

§Caveats

Two different tasks should not call this method concurrently. Otherwise, conflicting tasks will just keep waking each other in turn, thus wasting CPU time.

Note that the AsyncWrite implementation for Async also uses this method.

§Examples
use async_io::Async;
use futures_lite::future;
use std::net::{TcpStream, ToSocketAddrs};

let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
let stream = Async::<TcpStream>::connect(addr).await?;

// Wait until the stream is writable.
future::poll_fn(|cx| stream.poll_writable(cx)).await?;
Source

pub async fn read_with<R>(&self, op: impl FnMut(&T) -> Result<R>) -> Result<R>

Performs a read operation asynchronously.

The I/O handle is registered in the reactor and put in non-blocking mode. This method invokes the op closure in a loop until it succeeds or returns an error other than io::ErrorKind::WouldBlock. In between iterations of the loop, it waits until the OS sends a notification that the I/O handle is readable.

The closure receives a shared reference to the I/O handle.

§Examples
use async_io::Async;
use std::net::TcpListener;

let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;

// Accept a new client asynchronously.
let (stream, addr) = listener.read_with(|l| l.accept()).await?;
Source

pub async unsafe fn read_with_mut<R>( &mut self, op: impl FnMut(&mut T) -> Result<R>, ) -> Result<R>

Performs a read operation asynchronously.

The I/O handle is registered in the reactor and put in non-blocking mode. This method invokes the op closure in a loop until it succeeds or returns an error other than io::ErrorKind::WouldBlock. In between iterations of the loop, it waits until the OS sends a notification that the I/O handle is readable.

The closure receives a mutable reference to the I/O handle.

§Safety

In the closure, the underlying I/O source must not be dropped.

§Examples
use async_io::Async;
use std::net::TcpListener;

let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;

// Accept a new client asynchronously.
let (stream, addr) = unsafe { listener.read_with_mut(|l| l.accept()).await? };
Source

pub async fn write_with<R>(&self, op: impl FnMut(&T) -> Result<R>) -> Result<R>

Performs a write operation asynchronously.

The I/O handle is registered in the reactor and put in non-blocking mode. This method invokes the op closure in a loop until it succeeds or returns an error other than io::ErrorKind::WouldBlock. In between iterations of the loop, it waits until the OS sends a notification that the I/O handle is writable.

The closure receives a shared reference to the I/O handle.

§Examples
use async_io::Async;
use std::net::UdpSocket;

let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
socket.get_ref().connect("127.0.0.1:9000")?;

let msg = b"hello";
let len = socket.write_with(|s| s.send(msg)).await?;
Source

pub async unsafe fn write_with_mut<R>( &mut self, op: impl FnMut(&mut T) -> Result<R>, ) -> Result<R>

Performs a write operation asynchronously.

The I/O handle is registered in the reactor and put in non-blocking mode. This method invokes the op closure in a loop until it succeeds or returns an error other than io::ErrorKind::WouldBlock. In between iterations of the loop, it waits until the OS sends a notification that the I/O handle is writable.

§Safety

The closure receives a mutable reference to the I/O handle. In the closure, the underlying I/O source must not be dropped.

§Examples
use async_io::Async;
use std::net::UdpSocket;

let mut socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
socket.get_ref().connect("127.0.0.1:9000")?;

let msg = b"hello";
let len = unsafe { socket.write_with_mut(|s| s.send(msg)).await? };
Source§

impl Async<TcpListener>

Source

pub fn bind<A: Into<SocketAddr>>(addr: A) -> Result<Async<TcpListener>>

Creates a TCP listener bound to the specified address.

Binding with port number 0 will request an available port from the OS.

§Examples
use async_io::Async;
use std::net::TcpListener;

let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
println!("Listening on {}", listener.get_ref().local_addr()?);
Source

pub async fn accept(&self) -> Result<(Async<TcpStream>, SocketAddr)>

Accepts a new incoming TCP connection.

When a connection is established, it will be returned as a TCP stream together with its remote address.

§Examples
use async_io::Async;
use std::net::TcpListener;

let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?;
let (stream, addr) = listener.accept().await?;
println!("Accepted client: {}", addr);
Source

pub fn incoming( &self, ) -> impl Stream<Item = Result<Async<TcpStream>>> + Send + '_

Returns a stream of incoming TCP connections.

The stream is infinite, i.e. it never stops with a None.

§Examples
use async_io::Async;
use futures_lite::{pin, stream::StreamExt};
use std::net::TcpListener;

let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?;
let incoming = listener.incoming();
pin!(incoming);

while let Some(stream) = incoming.next().await {
    let stream = stream?;
    println!("Accepted client: {}", stream.get_ref().peer_addr()?);
}
Source§

impl Async<TcpStream>

Source

pub async fn connect<A: Into<SocketAddr>>(addr: A) -> Result<Async<TcpStream>>

Creates a TCP connection to the specified address.

§Examples
use async_io::Async;
use std::net::{TcpStream, ToSocketAddrs};

let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
let stream = Async::<TcpStream>::connect(addr).await?;
Source

pub async fn peek(&self, buf: &mut [u8]) -> Result<usize>

Reads data from the stream without removing it from the buffer.

Returns the number of bytes read. Successive calls of this method read the same data.

§Examples
use async_io::Async;
use futures_lite::{io::AsyncWriteExt, stream::StreamExt};
use std::net::{TcpStream, ToSocketAddrs};

let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
let mut stream = Async::<TcpStream>::connect(addr).await?;

stream
    .write_all(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
    .await?;

let mut buf = [0u8; 1024];
let len = stream.peek(&mut buf).await?;
Source§

impl Async<UdpSocket>

Source

pub fn bind<A: Into<SocketAddr>>(addr: A) -> Result<Async<UdpSocket>>

Creates a UDP socket bound to the specified address.

Binding with port number 0 will request an available port from the OS.

§Examples
use async_io::Async;
use std::net::UdpSocket;

let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 0))?;
println!("Bound to {}", socket.get_ref().local_addr()?);
Source

pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>

Receives a single datagram message.

Returns the number of bytes read and the address the message came from.

This method must be called with a valid byte slice of sufficient size to hold the message. If the message is too long to fit, excess bytes may get discarded.

§Examples
use async_io::Async;
use std::net::UdpSocket;

let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;

let mut buf = [0u8; 1024];
let (len, addr) = socket.recv_from(&mut buf).await?;
Source

pub async fn peek_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>

Receives a single datagram message without removing it from the queue.

Returns the number of bytes read and the address the message came from.

This method must be called with a valid byte slice of sufficient size to hold the message. If the message is too long to fit, excess bytes may get discarded.

§Examples
use async_io::Async;
use std::net::UdpSocket;

let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;

let mut buf = [0u8; 1024];
let (len, addr) = socket.peek_from(&mut buf).await?;
Source

pub async fn send_to<A: Into<SocketAddr>>( &self, buf: &[u8], addr: A, ) -> Result<usize>

Sends data to the specified address.

Returns the number of bytes written.

§Examples
use async_io::Async;
use std::net::UdpSocket;

let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 0))?;
let addr = socket.get_ref().local_addr()?;

let msg = b"hello";
let len = socket.send_to(msg, addr).await?;
Source

pub async fn recv(&self, buf: &mut [u8]) -> Result<usize>

Receives a single datagram message from the connected peer.

Returns the number of bytes read.

This method must be called with a valid byte slice of sufficient size to hold the message. If the message is too long to fit, excess bytes may get discarded.

The connect method connects this socket to a remote address. This method will fail if the socket is not connected.

§Examples
use async_io::Async;
use std::net::UdpSocket;

let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
socket.get_ref().connect("127.0.0.1:9000")?;

let mut buf = [0u8; 1024];
let len = socket.recv(&mut buf).await?;
Source

pub async fn peek(&self, buf: &mut [u8]) -> Result<usize>

Receives a single datagram message from the connected peer without removing it from the queue.

Returns the number of bytes read and the address the message came from.

This method must be called with a valid byte slice of sufficient size to hold the message. If the message is too long to fit, excess bytes may get discarded.

The connect method connects this socket to a remote address. This method will fail if the socket is not connected.

§Examples
use async_io::Async;
use std::net::UdpSocket;

let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
socket.get_ref().connect("127.0.0.1:9000")?;

let mut buf = [0u8; 1024];
let len = socket.peek(&mut buf).await?;
Source

pub async fn send(&self, buf: &[u8]) -> Result<usize>

Sends data to the connected peer.

Returns the number of bytes written.

The connect method connects this socket to a remote address. This method will fail if the socket is not connected.

§Examples
use async_io::Async;
use std::net::UdpSocket;

let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
socket.get_ref().connect("127.0.0.1:9000")?;

let msg = b"hello";
let len = socket.send(msg).await?;

Trait Implementations§

Source§

impl<T: AsRawSocket> AsRawSocket for Async<T>

Source§

fn as_raw_socket(&self) -> RawSocket

Extracts the raw socket. Read more
Source§

impl<T> AsRef<T> for Async<T>

Source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<T: AsSocket> AsSocket for Async<T>

Source§

fn as_socket(&self) -> BorrowedSocket<'_>

Borrows the socket.
Source§

impl<T> AsyncRead for &Async<T>
where for<'a> &'a T: Read,

Source§

fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize>>

Attempt to read from the AsyncRead into buf. Read more
Source§

fn poll_read_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>], ) -> Poll<Result<usize>>

Attempt to read from the AsyncRead into bufs using vectored IO operations. Read more
Source§

impl<T: IoSafe + Read> AsyncRead for Async<T>

Source§

fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize>>

Attempt to read from the AsyncRead into buf. Read more
Source§

fn poll_read_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>], ) -> Poll<Result<usize>>

Attempt to read from the AsyncRead into bufs using vectored IO operations. Read more
Source§

impl<T> AsyncWrite for &Async<T>
where for<'a> &'a T: Write,

Source§

fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize>>

Attempt to write bytes from buf into the object. Read more
Source§

fn poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>], ) -> Poll<Result<usize>>

Attempt to write bytes from bufs into the object using vectored IO operations. Read more
Source§

fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Attempt to flush the object, ensuring that any buffered data reach their destination. Read more
Source§

fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Attempt to close the object. Read more
Source§

impl<T: IoSafe + Write> AsyncWrite for Async<T>

Source§

fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize>>

Attempt to write bytes from buf into the object. Read more
Source§

fn poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>], ) -> Poll<Result<usize>>

Attempt to write bytes from bufs into the object using vectored IO operations. Read more
Source§

fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Attempt to flush the object, ensuring that any buffered data reach their destination. Read more
Source§

fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Attempt to close the object. Read more
Source§

impl<T: Debug> Debug for Async<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Drop for Async<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<T: Into<OwnedSocket>> TryFrom<Async<T>> for OwnedSocket

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: Async<T>) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<T: AsSocket + From<OwnedSocket>> TryFrom<OwnedSocket> for Async<T>

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: OwnedSocket) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<TcpListener> for Async<TcpListener>

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(listener: TcpListener) -> Result<Self>

Performs the conversion.
Source§

impl TryFrom<TcpStream> for Async<TcpStream>

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(stream: TcpStream) -> Result<Self>

Performs the conversion.
Source§

impl TryFrom<UdpSocket> for Async<UdpSocket>

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(socket: UdpSocket) -> Result<Self>

Performs the conversion.
Source§

impl<T> Unpin for Async<T>

Auto Trait Implementations§

§

impl<T> Freeze for Async<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Async<T>
where T: RefUnwindSafe,

§

impl<T> Send for Async<T>
where T: Send,

§

impl<T> Sync for Async<T>
where T: Sync,

§

impl<T> UnwindSafe for Async<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AsFd for T
where T: AsSocket,

Source§

fn as_fd(&self) -> BorrowedSocket<'_>

An as_fd function for Winsock, where an Fd is a Socket.
Source§

impl<T> AsRawFd for T
where T: AsRawSocket,

Source§

fn as_raw_fd(&self) -> u64

A version of as_raw_fd for use with Winsock API.
Source§

impl<T> AsSource for T
where T: AsSocket,

Source§

fn source(&self) -> BorrowedSocket<'_>

Returns the borrowed socket.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more