Async IO

Async byte interfaces, descriptor wrappers, and exact-fill helpers in std.aio.

std.aio defines async byte-oriented interfaces, descriptor-backed async wrappers, and exact-fill/write-all helpers. It re-exports std.io.IOError, so sync and async I/O report the same error cases.

Async methods return std.future.Future values.

Interfaces

interface Reader {
    fn read(self, buffer: [u8]) -> future.Future<usize throws(io.IOError)>;
}

interface Writer {
    fn write(self, data: bytes.Bytes) -> future.Future<void throws(io.IOError)>;
}

interface Stream: Reader, Writer;

aio.Reader.read(buffer) is one async read operation. It may complete with fewer bytes than requested, and 0 means EOF for stream-shaped handles. aio.Writer.write(data) writes all supplied bytes or returns an error. Writer APIs use canonical bytes.Bytes inputs; callers can pass string literals, String, existing byte views, or [u8] slices directly.

TCP streams from std.net implement aio.Stream.

Helpers

aio.write writes byte-view data, and aio.read(reader, buffer) fills the requested buffer exactly or returns IOError.UnexpectedEofError.

import std.aio;
import std.mem;
import std.os;

async fn main() {
    let fds = [0, 0];
    unsafe {
        assert os.pipe(fds.ptr) == 0;
    }

    let reader = try aio.DescriptorReader(fds[0] as usize);
    let writer = try aio.DescriptorWriter(fds[1] as usize);

    try await aio.write(&writer, "z");

    let buffer = [0 as u8];
    try await aio.read(&reader, mem.slice_of<u8>(buffer.ptr, buffer.length));
    assert buffer[0] == 122 as u8;

    unsafe {
        _ = os.close(fds[0] as usize);
        _ = os.close(fds[1] as usize);
    }
}

Descriptor Wrappers

aio.DescriptorReader, aio.DescriptorWriter, and aio.DescriptorStream borrow operating-system descriptors. They do not close those descriptors when dropped.

Constructors such as DescriptorReader(descriptor) set the descriptor to nonblocking mode and may throw IOError if that setup fails.

import std.aio;

async fn main() {
    let out = try aio.stdout();
    try await out.write("hello\n");
}

Async standard handles are functions: aio.stdin(), aio.stdout(), and aio.stderr().

API Reference

ItemPurpose
aio.IOErrorRe-export of std.io.IOError.
aio.ReaderAsync byte reader capability.
aio.WriterAsync byte writer capability.
aio.StreamAsync ordered byte stream capability.
aio.read(reader, buffer)Fill a byte buffer exactly.
aio.write(writer, data)Write byte-view data completely.
DescriptorReader(descriptor)Borrowed async descriptor reader; sets nonblocking mode.
DescriptorWriter(descriptor)Borrowed async descriptor writer; sets nonblocking mode.
DescriptorStream(descriptor)Borrowed async descriptor stream; sets nonblocking mode.
stdin(), stdout(), stderr()Create borrowed async wrappers for standard descriptors.