Skip to content
Standard libraryZig 0.17.1Official documentation
Sourcestd/Io.zig

Source line 1

A cross-platform interface that abstracts all I/O operations and concurrency. It includes:

  • file system
  • networking
  • processes
  • time and sleeping
  • randomness
  • async, await, concurrent, and cancel
  • concurrent queues
  • wait groups and select
  • mutexes, futexes, events, and conditions
  • memory mapped files This interface allows programmers to write optimal, reusable code while participating in these operations.

Fields

userdata: ?*anyopaque
vtable: *const VTable

std.Io.Alignment

alias

Source line 23

Alias of std.mem.Alignment

std.Io.Allocator

alias

Source line 22

Alias of std.mem.Allocator

std.Io.AnyFuture

container

Source line 1294

std.Io.assert

alias

Source line 21

Alias of std.debug.assert

std.Io.async

function

Source line 2532

Calls function with args, such that the return value of the function is not guaranteed to be available until await is called.

function may be called immediately, before async returns. This has weaker guarantees than concurrent, making more portable and reusable.

When this function returns, it is guaranteed that function has already been called and completed, or it has successfully been assigned a unit of concurrency.

See also:

pub fn async( io: Io, function: anytype, args: std.meta.ArgsTuple(@TypeOf(function)), ) Future(@typeInfo(@TypeOf(function)).@"fn".return_type.?)

Parameters

io: Io
args: std.meta.ArgsTuple(@TypeOf(function))

std.Io.async.start

function

Source line 2540

fn start(context: *const anyopaque, result: *anyopaque) void

Parameters

context: *const anyopaque
result: *anyopaque

std.Io.Batch

container

Source line 578

Submits many operations together without waiting for all of them to complete.

This is a low-level abstraction based on Operation. For a higher level API that operates on Future, see Select and Group.

Fields

storage: []Operation.Storage
unused: Operation.List
submitted: Operation.List
pending: Operation.List
completed: Operation.List
userdata: ?*anyopaque align(@max(@alignOf(?*anyopaque), 4))

std.Io.Batch.add

function

Source line 613

Adds an operation to be performed at the next await call. Returns the index that will be returned by next after the operation completes. Asserts that no more than storage.len operations are active at a time.

pub fn add(batch: *Batch, operation: Operation) u32

Parameters

batch: *Batch
operation: Operation

std.Io.Batch.addAt

function

Source line 622

Adds an operation to be performed at the next await call. After the operation completes, next will return index. Asserts that the operation at index is not active.

pub fn addAt(batch: *Batch, index: u32, operation: Operation) void

Parameters

batch: *Batch
index: u32
operation: Operation

std.Io.Batch.awaitAsync

function

Source line 682

Waits for at least one of the submitted operations to complete. After this function returns the completed operations can be iterated with next.

This function provides opportunity for the implementation to introduce concurrency into the batched operations, but unlike awaitConcurrent, does not require it, and therefore cannot fail with error.ConcurrencyUnavailable.

pub fn awaitAsync(batch: *Batch, io: Io) Cancelable!void

Parameters

batch: *Batch
io: Io

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.Batch.awaitConcurrent

function

Source line 695

Waits for at least one of the submitted operations to complete. After this function returns the completed operations can be iterated with next.

Unlike awaitAsync, this function requires the implementation to perform the operations concurrently and therefore can fail with error.ConcurrencyUnavailable.

pub fn awaitConcurrent(batch: *Batch, io: Io, timeout: Timeout) AwaitConcurrentError!void

Parameters

batch: *Batch
io: Io
timeout: Timeout

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

ConcurrencyUnavailable ConcurrentError

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

Timeout Error

std.Io.Batch.AwaitConcurrentError

error-set

Source line 686

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

ConcurrencyUnavailable ConcurrentError

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

Timeout Error

std.Io.Batch.cancel

function

Source line 705

Requests all pending operations to be interrupted, then waits for all pending operations to complete. After this returns, the Batch is in a well-defined state, ready to be iterated with next. Successfully canceled operations will be absent from the iteration. Some operations may have successfully completed regardless of the cancel request and will appear in the iteration.

pub fn cancel(batch: *Batch, io: Io) void

Parameters

batch: *Batch
io: Io

std.Io.Batch.Completion

container

Source line 642

Fields

index: u32

The element within the provided operation storage that completed. addAt can be used to re-arm the Batch using this index.

result: Operation.Result

The return value of the operation.

std.Io.Batch.init

function

Source line 590

After calling this, it is safe to unconditionally defer a call to cancel. storage is a pre-allocated buffer of undefined memory that determines the maximum number of active operations that can be submitted via add and addAt.

pub fn init(storage: []Operation.Storage) Batch

Parameters

storage: []Operation.Storage

std.Io.Batch.next

function

Source line 655

After calling awaitAsync, awaitConcurrent, or cancel, this function iterates over the completed operations.

Each completion returned from this function dequeues from the Batch. It is not required to dequeue all completions before awaiting again.

pub fn next(batch: *Batch) ?Completion

Parameters

batch: *Batch

std.Io.builtin

constant

Source line 17

std.Io.Cancelable

error-set

Source line 815

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.CancelProtection

container

Source line 1451

In rare cases, it is desirable to completely block cancelation notification, so that a region of code can run uninterrupted before error.Canceled is potentially observed. Therefore, every task has a "cancel protection" state which indicates whether or not Io functions can introduce cancelation points.

To modify a task's cancel protection state, see swapCancelProtection.

For a description of cancelation and cancelation points, see Future.cancel.

Fields

unblocked = 0

Any call to an Io function with error.Canceled in its error set is a cancelation point.

This is the default state, which all tasks are created in.

blocked = 1

No Io function introduces a cancelation point (error.Canceled will never be returned).

std.Io.checkCancel

function

Source line 1485

This function acts as a pure cancelation point (subject to protection; see CancelProtection) and does nothing else. In other words, it returns error.Canceled if there is an outstanding non-blocked cancelation request, but otherwise is a no-op.

It is rarely necessary to call this function. The primary use case is in long-running CPU-bound tasks which may need to respond to cancelation before completing. Short tasks, or those which perform other Io operations (and hence have other cancelation points), will typically already respond quickly to cancelation requests.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn checkCancel(io: Io) Cancelable!void

Parameters

io: Io

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.Clock

container

Source line 836

Fields

real

A settable system-wide clock that measures real (i.e. wall-clock) time. This clock is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), and by frequency adjustments performed by NTP and similar applications.

This clock normally counts the number of seconds since 1970-01-01 00:00:00 Coordinated Universal Time (UTC) except that it ignores leap seconds; near a leap second it is typically adjusted by NTP to stay roughly in sync with UTC.

Timestamps returned by implementations of this clock represent time elapsed since 1970-01-01T00:00:00Z, the POSIX/Unix epoch, ignoring leap seconds. This is colloquially known as "Unix time". If the underlying OS uses a different epoch for native timestamps (e.g., Windows, which uses 1601-01-01) they are translated accordingly.

awake

A nonsettable system-wide clock that represents time since some unspecified point in the past.

Monotonic: Guarantees that the time returned by consecutive calls will not go backwards, but successive calls may return identical (not-increased) time values.

Not affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), but may be affected by frequency adjustments.

This clock expresses intent to exclude time that the system is suspended. However, implementations may be unable to satisify this, and may include that time.

  • On Linux, corresponds CLOCK_MONOTONIC.
  • On macOS, corresponds to CLOCK_UPTIME_RAW.
boot

Identical to awake except it expresses intent to include time that the system is suspended, however, due to limitations it may behave identically to awake.

  • On Linux, corresponds CLOCK_BOOTTIME.
  • On macOS, corresponds to CLOCK_MONOTONIC_RAW.
cpu_process

Tracks the amount of CPU time in user or kernel mode used by the calling process.

cpu_thread

Tracks the amount of CPU time in user or kernel mode used by the calling thread.

std.Io.Clock.Duration

container

Source line 1005

Fields

raw: Io.Duration
clock: Clock

std.Io.Clock.Duration.sleep

function

Source line 1015

Waits until a specified amount of time has passed on clock.

See also:

  • Io.sleep
  • Clock.Timestamp.wait
  • Timeout.sleep
pub fn sleep(duration: Clock.Duration, io: Io) Cancelable!void

Parameters

duration: Clock.Duration
io: Io

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.Clock.now

function

Source line 893

This function is not cancelable because it does not block.

Resolution is determined by resolution which may be 0 if the clock is unsupported.

See also:

  • Clock.Timestamp.now
pub fn now(clock: Clock, io: Io) Io.Timestamp

Parameters

clock: Clock
io: Io

std.Io.Clock.resolution

function

Source line 904

Reveals the granularity of clock. May be zero, indicating unsupported clock.

pub fn resolution(clock: Clock, io: Io) ResolutionError!Io.Duration

Parameters

clock: Clock
io: Io

Errors

ClockUnavailable
Unexpected

std.Io.Clock.ResolutionError

error-set

Source line 897

Errors

ClockUnavailable
Unexpected

std.Io.Clock.Timestamp

container

Source line 908

Fields

raw: Io.Timestamp
clock: Clock

std.Io.Clock.Timestamp.addDuration

function

Source line 944

pub fn addDuration(from: Clock.Timestamp, duration: Clock.Duration) Clock.Timestamp

Parameters

from: Clock.Timestamp
duration: Clock.Duration

std.Io.Clock.Timestamp.compare

function

Source line 999

pub fn compare(lhs: Clock.Timestamp, op: math.CompareOperator, rhs: Clock.Timestamp) bool

Parameters

std.Io.Clock.Timestamp.durationFromNow

function

Source line 978

Resolution is determined by resolution which may be 0 if the clock is unsupported.

pub fn durationFromNow(timestamp: Clock.Timestamp, io: Io) Clock.Duration

Parameters

timestamp: Clock.Timestamp
io: Io

std.Io.Clock.Timestamp.durationTo

function

Source line 936

pub fn durationTo(from: Clock.Timestamp, to: Clock.Timestamp) Clock.Duration

Parameters

std.Io.Clock.Timestamp.fromNow

function

Source line 962

Resolution is determined by resolution which may be 0 if the clock is unsupported.

pub fn fromNow(io: Io, duration: Clock.Duration) Clock.Timestamp

Parameters

io: Io
duration: Clock.Duration

std.Io.Clock.Timestamp.now

function

Source line 919

This function is not cancelable because it does not block.

Resolution is determined by resolution which may be 0 if the clock is unsupported.

See also:

  • Clock.now
pub fn now(io: Io, clock: Clock) Clock.Timestamp

Parameters

io: Io
clock: Clock

std.Io.Clock.Timestamp.subDuration

function

Source line 952

pub fn subDuration(from: Clock.Timestamp, duration: Clock.Duration) Clock.Timestamp

Parameters

from: Clock.Timestamp
duration: Clock.Duration

std.Io.Clock.Timestamp.toClock

function

Source line 988

Resolution is determined by resolution which may be 0 if the clock is unsupported.

pub fn toClock(t: Clock.Timestamp, io: Io, clock: Clock) Clock.Timestamp

Parameters

t: Clock.Timestamp
io: Io
clock: Clock

std.Io.Clock.Timestamp.untilNow

function

Source line 971

Resolution is determined by resolution which may be 0 if the clock is unsupported.

pub fn untilNow(timestamp: Clock.Timestamp, io: Io) Clock.Duration

Parameters

timestamp: Clock.Timestamp
io: Io

std.Io.Clock.Timestamp.wait

function

Source line 932

Sleeps until the timestamp arrives.

See also:

  • Io.sleep
  • Clock.Duration.sleep
  • Timeout.sleep
pub fn wait(t: Clock.Timestamp, io: Io) Cancelable!void

Parameters

t: Clock.Timestamp
io: Io

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.concurrent

function

Source line 2571

Calls function with args, such that the return value of the function is not guaranteed to be available until await is called, allowing the caller to progress while waiting for any Io operations.

This has stronger guarantee than async, placing restrictions on what kind of Io implementations are supported. By calling async instead, one allows, for example, stackful single-threaded blocking I/O.

pub fn concurrent( io: Io, function: anytype, args: std.meta.ArgsTuple(@TypeOf(function)), ) ConcurrentError!Future(@typeInfo(@TypeOf(function)).@"fn".return_type.?)

Parameters

io: Io
args: std.meta.ArgsTuple(@TypeOf(function))

Errors

ConcurrencyUnavailable

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

std.Io.concurrent.start

function

Source line 2579

fn start(context: *const anyopaque, result: *anyopaque) void

Parameters

context: *const anyopaque
result: *anyopaque

std.Io.ConcurrentError

error-set

Source line 2558

Errors

ConcurrencyUnavailable

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

std.Io.Condition

container

Source line 1782

Fields

state: std.atomic.Value(State)
epoch: std.atomic.Value(u32)

Incremented whenever the condition is signaled

std.Io.Condition.broadcast

function

Source line 1945

pub fn broadcast(cond: *Condition, io: Io) void

Parameters

cond: *Condition
io: Io

std.Io.Condition.deregister

function

Source line 1908

fn deregister(cond: *Condition, io: Io) void

Parameters

cond: *Condition
io: Io

std.Io.Condition.init

constant

Source line 1792

Condition

std.Io.Condition.signal

function

Source line 1926

pub fn signal(cond: *Condition, io: Io) void

Parameters

cond: *Condition
io: Io

std.Io.Condition.State

container

Source line 1787

Fields

waiters: u16
signals: u16

std.Io.Condition.wait

function

Source line 1802

Blocks until the condition is signaled or canceled.

See also:

  • waitUncancelable
  • waitTimeout
pub fn wait(cond: *Condition, io: Io, mutex: *Mutex) Cancelable!void

Parameters

cond: *Condition
io: Io
mutex: *Mutex

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.Condition.waitTimeout

function

Source line 1817

Blocks until the condition is signaled, canceled, or the provided timeout expires.

See also:

  • wait
  • waitUncancelable
pub fn waitTimeout(cond: *Condition, io: Io, mutex: *Mutex, timeout: Timeout) WaitTimeoutError!void

Parameters

cond: *Condition
io: Io
mutex: *Mutex
timeout: Timeout

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

Timeout Error

std.Io.Condition.WaitTimeoutError

error-set

Source line 1809

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

Timeout Error

std.Io.Condition.waitUncancelable

function

Source line 1872

Same as wait, except does not introduce a cancelation point.

See Future.cancel for a description of cancelation points.

pub fn waitUncancelable(cond: *Condition, io: Io, mutex: *Mutex) void

Parameters

cond: *Condition
io: Io
mutex: *Mutex

std.Io.Dir

alias

Source line 44

Alias of std.Io.Dir

std.Io.Dispatch

alias

Source line 37

Alias of std.Io.Dispatch

std.Io.doOp

function

Source line 3631

fn doOp() void

std.Io.Duration

container

Source line 1087

Fields

nanoseconds: i96

std.Io.Duration.format

function

Source line 1127

Write number of nanoseconds according to its signed magnitude: [#y][#w][#d][#h][#m]#[.###][n|u|m]s

pub fn format(duration: Duration, w: *Writer) Writer.Error!void

Parameters

duration: Duration
w: *Writer

Errors

WriteFailed

See the Writer implementation for detailed diagnostics.

Example usage

test format {
    try testFormat("0ns", 0);
    try testFormat("1ns", 1);
    try testFormat("-1ns", -(1));
    try testFormat("999ns", std.time.ns_per_us - 1);
    try testFormat("-999ns", -(std.time.ns_per_us - 1));
    try testFormat("1us", std.time.ns_per_us);
    try testFormat("-1us", -(std.time.ns_per_us));
    try testFormat("1.45us", 1450);
    try testFormat("-1.45us", -(1450));
    try testFormat("1.5us", 3 * std.time.ns_per_us / 2);
    try testFormat("-1.5us", -(3 * std.time.ns_per_us / 2));
    try testFormat("14.5us", 14500);
    try testFormat("-14.5us", -(14500));
    try testFormat("145us", 145000);
    try testFormat("-145us", -(145000));
    try testFormat("999.999us", std.time.ns_per_ms - 1);
    try testFormat("-999.999us", -(std.time.ns_per_ms - 1));
    try testFormat("1ms", std.time.ns_per_ms + 1);
    try testFormat("-1ms", -(std.time.ns_per_ms + 1));
    try testFormat("1.5ms", 3 * std.time.ns_per_ms / 2);
    try testFormat("-1.5ms", -(3 * std.time.ns_per_ms / 2));
    try testFormat("1.11ms", 1110000);
    try testFormat("-1.11ms", -(1110000));
    try testFormat("1.111ms", 1111000);
    try testFormat("-1.111ms", -(1111000));
    try testFormat("1.111ms", 1111100);
    try testFormat("-1.111ms", -(1111100));
    try testFormat("999.999ms", std.time.ns_per_s - 1);
    try testFormat("-999.999ms", -(std.time.ns_per_s - 1));
    try testFormat("1s", std.time.ns_per_s);
    try testFormat("-1s", -(std.time.ns_per_s));
    try testFormat("59.999s", std.time.ns_per_min - 1);
    try testFormat("-59.999s", -(std.time.ns_per_min - 1));
    try testFormat("1m", std.time.ns_per_min);
    try testFormat("-1m", -(std.time.ns_per_min));
    try testFormat("1h", std.time.ns_per_hour);
    try testFormat("-1h", -(std.time.ns_per_hour));
    try testFormat("1d", std.time.ns_per_day);
    try testFormat("-1d", -(std.time.ns_per_day));
    try testFormat("1w", std.time.ns_per_week);
    try testFormat("-1w", -(std.time.ns_per_week));
    try testFormat("1y", 365 * std.time.ns_per_day);
    try testFormat("-1y", -(365 * std.time.ns_per_day));
    try testFormat("1y52w23h59m59.999s", 730 * std.time.ns_per_day - 1); // 365d = 52w1d
    try testFormat("-1y52w23h59m59.999s", -(730 * std.time.ns_per_day - 1)); // 365d = 52w1d
    try testFormat("1y1h1.001s", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + std.time.ns_per_ms);
    try testFormat("-1y1h1.001s", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + std.time.ns_per_ms));
    try testFormat("1y1h1s", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + 999 * std.time.ns_per_us);
    try testFormat("-1y1h1s", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + 999 * std.time.ns_per_us));
    try testFormat("1y1h999.999us", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms - 1);
    try testFormat("-1y1h999.999us", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms - 1));
    try testFormat("1y1h1ms", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms);
    try testFormat("-1y1h1ms", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms));
    try testFormat("1y1h1ms", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms + 1);
    try testFormat("-1y1h1ms", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms + 1));
    try testFormat("1y1m999ns", 365 * std.time.ns_per_day + std.time.ns_per_min + 999);
    try testFormat("-1y1m999ns", -(365 * std.time.ns_per_day + std.time.ns_per_min + 999));
    try testFormat("292y24w3d23h47m16.854s", std.math.maxInt(i64));
    try testFormat("-292y24w3d23h47m16.854s", std.math.minInt(i64) + 1);
    try testFormat("-292y24w3d23h47m16.854s", std.math.minInt(i64));
}

std.Io.Duration.formatUnsigned

function

Source line 1132

fn formatUnsigned(w: *Writer, ns: u96) Writer.Error!void

Parameters

w: *Writer
ns: u96

Errors

WriteFailed

See the Writer implementation for detailed diagnostics.

std.Io.Duration.fromMicroseconds

function

Source line 1097

pub fn fromMicroseconds(x: i64) Duration

Parameters

x: i64

std.Io.Duration.fromMilliseconds

function

Source line 1101

pub fn fromMilliseconds(x: i64) Duration

Parameters

x: i64

std.Io.Duration.fromNanoseconds

function

Source line 1093

pub fn fromNanoseconds(x: i96) Duration

Parameters

x: i96

std.Io.Duration.fromSeconds

function

Source line 1105

pub fn fromSeconds(x: i64) Duration

Parameters

x: i64

std.Io.Duration.max

constant

Source line 1091

Duration

std.Io.Duration.testFormat

function

Source line 1241

fn testFormat(expected: []const u8, input: i96) !void

Parameters

expected: []const u8
input: i96

std.Io.Duration.toMicroseconds

function

Source line 1109

pub fn toMicroseconds(d: Duration) i64

Parameters

std.Io.Duration.toMilliseconds

function

Source line 1113

pub fn toMilliseconds(d: Duration) i64

Parameters

std.Io.Duration.toNanoseconds

function

Source line 1121

pub fn toNanoseconds(d: Duration) i96

Parameters

std.Io.Duration.toSeconds

function

Source line 1117

pub fn toSeconds(d: Duration) i64

Parameters

std.Io.Duration.zero

constant

Source line 1090

Duration

std.Io.Event

container

Source line 1966

Logical boolean flag which can be set and unset and supports a "wait until set" operation.

Fields

unset
waiting
is_set

std.Io.Event.isSet

function

Source line 1972

Returns whether the logical boolean is true.

pub fn isSet(event: *const Event) bool

Parameters

event: *const Event

std.Io.Event.reset

function

Source line 2073

Sets the logical boolean to false.

Assumes that there is no pending call to wait or waitUncancelable.

However, concurrent calls to isSet, set, and reset are allowed.

pub fn reset(e: *Event) void

Parameters

e: *Event

std.Io.Event.set

function

Source line 2061

Sets the logical boolean to true, and hence unblocks any pending calls to wait. The logical boolean remains true until reset is called, so future calls to set have no semantic effect.

Any memory accesses prior to a set call are "released", so that if this set call causes isSet to return true or a wait to finish, those tasks will be able to observe those memory accesses.

pub fn set(e: *Event, io: Io) void

Parameters

e: *Event
io: Io

std.Io.Event.wait

function

Source line 1980

Blocks until the logical boolean is true.

pub fn wait(event: *Event, io: Io) Cancelable!void

Parameters

event: *Event
io: Io

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.Event.waitTimeout

function

Source line 2025

Blocks the calling thread until either the logical boolean is set or the timeout expires.

pub fn waitTimeout(event: *Event, io: Io, timeout: Timeout) WaitTimeoutError!void

Parameters

event: *Event
io: Io
timeout: Timeout

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

Timeout

std.Io.Event.WaitTimeoutError

error-set

Source line 2022

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

Timeout

std.Io.Event.waitUncancelable

function

Source line 2006

Same as wait, except does not introduce a cancelation point.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn waitUncancelable(event: *Event, io: Io) void

Parameters

event: *Event
io: Io

std.Io.Evented

type

Source line 31

std.Io.failing

constant

Source line 2718

An implementation of Io which simulates a system supporting no Io operations.

This system has the following properties:

  • Concurrency is unavailable.
  • The stdio handles are pipes whose remote ends are already closed.
  • The filesystem is entirely empty, including that the cwd is no longer present.
  • The filesystem is full, so attempting to create entries always returns error.NoSpaceLeft.
  • No entropy source is supported, so randomSecure always returns error.EntropyUnavailable, and random always returns (fills the buffer) with 0.
  • No clocks are supported, so now and sleep always return error.UnsupportedClock.
  • No network is connected, so network operations always return error.NetworkDown.
std.Io

std.Io.failingClockResolution

function

Source line 3519

pub fn failingClockResolution(userdata: ?*anyopaque, clock: Clock) Clock.ResolutionError!Duration

Parameters

userdata: ?*anyopaque
clock: Clock

Errors

ClockUnavailable
Unexpected

std.Io.failingConcurrent

function

Source line 2855

pub fn failingConcurrent( userdata: ?*anyopaque, result_len: usize, result_alignment: std.mem.Alignment, context: []const u8, context_alignment: std.mem.Alignment, start: *const fn (context: *const anyopaque, result: *anyopaque) void, ) ConcurrentError!*AnyFuture

Parameters

userdata: ?*anyopaque
result_len: usize
result_alignment: std.mem.Alignment
context: []const u8
context_alignment: std.mem.Alignment
start: *const fn (context: *const anyopaque, result: *anyopaque) void

Errors

ConcurrencyUnavailable

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

std.Io.failingDirAccess

function

Source line 3052

pub fn failingDirAccess(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.AccessOptions) Dir.AccessError!void

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
options: Dir.AccessOptions

Errors

AccessDenied

The requested AccessOptions would be denied to the file, or search permission is denied for one of the directories in the path prefix.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

FileBusy
FileNotFound
InputOutput
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

PermissionDenied

Write permission was requested but the file is immutable.

ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirCreateDir

function

Source line 3005

pub fn failingDirCreateDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!void

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
permissions: Dir.Permissions

Errors

AccessDenied

In WASI, this error may occur when the file descriptor does not hold the required rights to create a new directory relative to it.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DiskQuota
FileNotFound
LinkQuotaExceeded
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NoDevice
NoSpaceLeft
NotDir
PathAlreadyExists
PermissionDenied
ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirCreateDirPath

function

Source line 3013

pub fn failingDirCreateDirPath(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirPathError!Dir.CreatePathStatus

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
permissions: Dir.Permissions

Errors

AccessDenied CreateDirError

In WASI, this error may occur when the file descriptor does not hold the required rights to create a new directory relative to it.

AntivirusInterference OpenError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy OpenError
DiskQuota CreateDirError
FileBusy OpenError

One of these three things:

  • pathname refers to an executable image which is currently being executed and write access was requested.
  • pathname refers to a file that is currently in use as a swap file, and the O_TRUNC flag was specified.
  • pathname refers to a file that is currently being read by the kernel (e.g., for module/firmware loading), and write access was requested.
FileLocksUnsupported OpenError
FileNotFound OpenError

Either:

  • One of the path components does not exist.
  • Cwd was used, but cwd has been deleted.
  • The path associated with the open directory handle has been deleted.
  • On macOS, multiple processes or threads raced to create the same file with O.EXCL set to false.
FileTooBig OpenError

The file is too large to be opened. This error is unreachable for 64-bit targets, as well as when opening directories.

IsDir OpenError

Either:

  • The path refers to a directory and write permissions were requested.
  • The path refers to a directory and allow_directory was set to false.
LinkQuotaExceeded CreateDirError
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound CreateDirError

On Windows, \\server or \\server\share was not found.

NoDevice CreateDirError
NoSpaceLeft OpenError

A new path cannot be created because the device has no room for the new file. This error is only reachable when the CREAT flag is provided.

NotDir OpenError

A component used as a directory in the path was not, in fact, a directory, or DIRECTORY was specified and the path was not a directory.

PathAlreadyExists OpenError

The path already exists and the CREAT and EXCL flags were provided.

PermissionDenied CreateDirError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ReadOnlyFileSystem CreateDirError
Streaming StatError

Attempted to stat a non-file stream.

SymLinkLoop CreateDirError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

The path exceeded max_path_bytes bytes. Insufficient kernel memory was available, or the named file is a FIFO and per-user hard limit on memory allocation for pipes has been reached.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock OpenError

Non-blocking was requested and the operation cannot return immediately.

std.Io.failingDirCreateDirPathOpen

function

Source line 3021

pub fn failingDirCreateDirPathOpen(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions, options: Dir.OpenOptions) Dir.CreateDirPathOpenError!Dir

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
permissions: Dir.Permissions
options: Dir.OpenOptions

Errors

AccessDenied CreateDirError

In WASI, this error may occur when the file descriptor does not hold the required rights to create a new directory relative to it.

AntivirusInterference OpenError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy OpenError
DiskQuota CreateDirError
FileBusy OpenError

One of these three things:

  • pathname refers to an executable image which is currently being executed and write access was requested.
  • pathname refers to a file that is currently in use as a swap file, and the O_TRUNC flag was specified.
  • pathname refers to a file that is currently being read by the kernel (e.g., for module/firmware loading), and write access was requested.
FileLocksUnsupported OpenError
FileNotFound OpenError

Either:

  • One of the path components does not exist.
  • Cwd was used, but cwd has been deleted.
  • The path associated with the open directory handle has been deleted.
  • On macOS, multiple processes or threads raced to create the same file with O.EXCL set to false.
FileTooBig OpenError

The file is too large to be opened. This error is unreachable for 64-bit targets, as well as when opening directories.

IsDir OpenError

Either:

  • The path refers to a directory and write permissions were requested.
  • The path refers to a directory and allow_directory was set to false.
LinkQuotaExceeded CreateDirError
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound CreateDirError

On Windows, \\server or \\server\share was not found.

NoDevice CreateDirError
NoSpaceLeft OpenError

A new path cannot be created because the device has no room for the new file. This error is only reachable when the CREAT flag is provided.

NotDir OpenError

A component used as a directory in the path was not, in fact, a directory, or DIRECTORY was specified and the path was not a directory.

PathAlreadyExists OpenError

The path already exists and the CREAT and EXCL flags were provided.

PermissionDenied CreateDirError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ReadOnlyFileSystem CreateDirError
Streaming StatError

Attempted to stat a non-file stream.

SymLinkLoop CreateDirError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

The path exceeded max_path_bytes bytes. Insufficient kernel memory was available, or the named file is a FIFO and per-user hard limit on memory allocation for pipes has been reached.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock OpenError

Non-blocking was requested and the operation cannot return immediately.

std.Io.failingDirCreateFile

function

Source line 3060

pub fn failingDirCreateFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.CreateFileOptions) File.OpenError!File

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
options: Dir.CreateFileOptions

Errors

AccessDenied

In WASI, this error may occur when the file descriptor does not hold the required rights to open a new resource relative to it.

AntivirusInterference

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy
FileBusy

One of these three things:

  • pathname refers to an executable image which is currently being executed and write access was requested.
  • pathname refers to a file that is currently in use as a swap file, and the O_TRUNC flag was specified.
  • pathname refers to a file that is currently being read by the kernel (e.g., for module/firmware loading), and write access was requested.
FileLocksUnsupported
FileNotFound

Either:

  • One of the path components does not exist.
  • Cwd was used, but cwd has been deleted.
  • The path associated with the open directory handle has been deleted.
  • On macOS, multiple processes or threads raced to create the same file with O.EXCL set to false.
FileTooBig

The file is too large to be opened. This error is unreachable for 64-bit targets, as well as when opening directories.

IsDir

Either:

  • The path refers to a directory and write permissions were requested.
  • The path refers to a directory and allow_directory was set to false.
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NoDevice
NoSpaceLeft

A new path cannot be created because the device has no room for the new file. This error is only reachable when the CREAT flag is provided.

NotDir

A component used as a directory in the path was not, in fact, a directory, or DIRECTORY was specified and the path was not a directory.

PathAlreadyExists

The path already exists and the CREAT and EXCL flags were provided.

PermissionDenied
PipeBusy
ProcessFdQuotaExceeded
ReadOnlyFileSystem
SymLinkLoop
SystemFdQuotaExceeded
SystemResources

The path exceeded max_path_bytes bytes. Insufficient kernel memory was available, or the named file is a FIFO and per-user hard limit on memory allocation for pipes has been reached.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock

Non-blocking was requested and the operation cannot return immediately.

std.Io.failingDirCreateFileAtomic

function

Source line 3068

pub fn failingDirCreateFileAtomic(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.CreateFileAtomicOptions) Dir.CreateFileAtomicError!File.Atomic

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
options: Dir.CreateFileAtomicOptions

Errors

AccessDenied

In WASI, this error may occur when the file descriptor does not hold the required rights to open a new resource relative to it.

AntivirusInterference

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

FileBusy

The file attempted to be created is a running executable.

FileNotFound

Either:

  • One of the path components does not exist.
  • Cwd was used, but cwd has been deleted.
  • The path associated with the open directory handle has been deleted.
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NoDevice
NoSpaceLeft

A new path cannot be created because the device has no room for the new file.

NotDir

A component used as a directory in the path was not, in fact, a directory.

PermissionDenied
ProcessFdQuotaExceeded
ReadOnlyFileSystem
SymLinkLoop
SystemFdQuotaExceeded
SystemResources

Insufficient kernel memory was available.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock

std.Io.failingDirDeleteDir

function

Source line 3119

pub fn failingDirDeleteDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteDirError!void

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8

Errors

AccessDenied
BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DirNotEmpty
FileBusy
FileNotFound
FileSystem
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NotDir
PermissionDenied
ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirDeleteFile

function

Source line 3112

pub fn failingDirDeleteFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteFileError!void

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8

Errors

AccessDenied

In WASI, this error may occur when the file descriptor does not hold the required rights to unlink a resource by path relative to it.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

FileBusy
FileNotFound
FileSystem
IsDir
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NotDir
PermissionDenied
ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirHardLink

function

Source line 3203

pub fn failingDirHardLink(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8, options: Dir.HardLinkOptions) Dir.HardLinkError!void

Parameters

userdata: ?*anyopaque
old_dir: Dir
old_sub_path: []const u8
new_dir: Dir
new_sub_path: []const u8
options: Dir.HardLinkOptions

Errors

AccessDenied HardLinkError
BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

CrossDevice HardLinkError
DiskQuota HardLinkError
FileNotFound HardLinkError
HardwareFailure HardLinkError
LinkQuotaExceeded HardLinkError
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NoSpaceLeft HardLinkError
NotDir HardLinkError
OperationUnsupported HardLinkError

Either the OS or the filesystem does not support hard links.

PathAlreadyExists HardLinkError
PermissionDenied HardLinkError
ReadOnlyFileSystem HardLinkError
SymLinkLoop HardLinkError
SystemResources HardLinkError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirOpenDir

function

Source line 3030

pub fn failingDirOpenDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.OpenOptions) Dir.OpenError!Dir

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
options: Dir.OpenOptions

Errors

AccessDenied
BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

FileNotFound
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NoDevice
NotDir
PermissionDenied
ProcessFdQuotaExceeded
SymLinkLoop
SystemFdQuotaExceeded
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirOpenFile

function

Source line 3076

pub fn failingDirOpenFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.OpenFileOptions) File.OpenError!File

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
flags: Dir.OpenFileOptions

Errors

AccessDenied

In WASI, this error may occur when the file descriptor does not hold the required rights to open a new resource relative to it.

AntivirusInterference

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy
FileBusy

One of these three things:

  • pathname refers to an executable image which is currently being executed and write access was requested.
  • pathname refers to a file that is currently in use as a swap file, and the O_TRUNC flag was specified.
  • pathname refers to a file that is currently being read by the kernel (e.g., for module/firmware loading), and write access was requested.
FileLocksUnsupported
FileNotFound

Either:

  • One of the path components does not exist.
  • Cwd was used, but cwd has been deleted.
  • The path associated with the open directory handle has been deleted.
  • On macOS, multiple processes or threads raced to create the same file with O.EXCL set to false.
FileTooBig

The file is too large to be opened. This error is unreachable for 64-bit targets, as well as when opening directories.

IsDir

Either:

  • The path refers to a directory and write permissions were requested.
  • The path refers to a directory and allow_directory was set to false.
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NoDevice
NoSpaceLeft

A new path cannot be created because the device has no room for the new file. This error is only reachable when the CREAT flag is provided.

NotDir

A component used as a directory in the path was not, in fact, a directory, or DIRECTORY was specified and the path was not a directory.

PathAlreadyExists

The path already exists and the CREAT and EXCL flags were provided.

PermissionDenied
PipeBusy
ProcessFdQuotaExceeded
ReadOnlyFileSystem
SymLinkLoop
SystemFdQuotaExceeded
SystemResources

The path exceeded max_path_bytes bytes. Insufficient kernel memory was available, or the named file is a FIFO and per-user hard limit on memory allocation for pipes has been reached.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock

Non-blocking was requested and the operation cannot return immediately.

std.Io.failingDirReadLink

function

Source line 3153

pub fn failingDirReadLink(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usize

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
buffer: []u8

Errors

AccessDenied

In WASI, this error may occur when the file descriptor does not hold the required rights to read value of a symbolic link relative to it.

AntivirusInterference

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

FileBusy

File attempted to be opened is a running executable.

FileNotFound
FileSystem
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NotDir
NotLink
PermissionDenied
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnsupportedReparsePointType

Windows-only. This error may occur if the opened reparse point is of unsupported type.

std.Io.failingDirRealPath

function

Source line 3097

pub fn failingDirRealPath(userdata: ?*anyopaque, dir: Dir, out_buffer: []u8) Dir.RealPathError!usize

Parameters

userdata: ?*anyopaque
dir: Dir
out_buffer: []u8

Errors

AccessDenied RealPathError
AntivirusInterference RealPathError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy RealPathError
FileBusy RealPathError
FileNotFound RealPathError
FileSystem RealPathError
FileTooBig RealPathError
InputOutput RealPathError
IsDir RealPathError
NameTooLong RealPathError

The full file system path could not fit into the provided buffer, or due to its length could not be obtained via realpath functions no matter the buffer size provided.

NetworkNotFound RealPathError

On Windows, \\server or \\server\share was not found.

NoDevice RealPathError
NoSpaceLeft RealPathError
NotDir RealPathError
OperationUnsupported RealPathError

This operating system, file system, or Io implementation does not support realpath operations.

PathAlreadyExists RealPathError
PermissionDenied RealPathError
PipeBusy RealPathError
ProcessFdQuotaExceeded RealPathError
SymLinkLoop RealPathError
SystemFdQuotaExceeded RealPathError
SystemResources RealPathError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnrecognizedVolume RealPathError

On Windows, the volume does not contain a recognized file system. File system drivers might not be loaded, or the volume may be corrupt.

std.Io.failingDirRealPathFile

function

Source line 3104

pub fn failingDirRealPathFile(userdata: ?*anyopaque, dir: Dir, path_name: []const u8, out_buffer: []u8) Dir.RealPathFileError!usize

Parameters

userdata: ?*anyopaque
dir: Dir
path_name: []const u8
out_buffer: []u8

Errors

AccessDenied RealPathError
AntivirusInterference RealPathError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy RealPathError
FileBusy RealPathError
FileNotFound RealPathError
FileSystem RealPathError
FileTooBig RealPathError
InputOutput RealPathError
IsDir RealPathError
NameTooLong RealPathError

The full file system path could not fit into the provided buffer, or due to its length could not be obtained via realpath functions no matter the buffer size provided.

NetworkNotFound RealPathError

On Windows, \\server or \\server\share was not found.

NoDevice RealPathError
NoSpaceLeft RealPathError
NotDir RealPathError
OperationUnsupported RealPathError

This operating system, file system, or Io implementation does not support realpath operations.

PathAlreadyExists RealPathError
PermissionDenied RealPathError
PipeBusy RealPathError
ProcessFdQuotaExceeded RealPathError
SymLinkLoop RealPathError
SystemFdQuotaExceeded RealPathError
SystemResources RealPathError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnrecognizedVolume RealPathError

On Windows, the volume does not contain a recognized file system. File system drivers might not be loaded, or the volume may be corrupt.

std.Io.failingDirRename

function

Source line 3126

pub fn failingDirRename(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenameError!void

Parameters

userdata: ?*anyopaque
old_dir: Dir
old_sub_path: []const u8
new_dir: Dir
new_sub_path: []const u8

Errors

AccessDenied

In WASI, this error may occur when the file descriptor does not hold the required rights to rename a resource by path relative to it.

AntivirusInterference

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

CrossDevice
DirNotEmpty

Attempted to replace a nonempty directory.

DiskQuota
FileBusy

The file attempted to be moved or replaced is a running executable.

FileNotFound
HardwareFailure
IsDir
LinkQuotaExceeded
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NoDevice
NoSpaceLeft
NotDir
PermissionDenied
PipeBusy
ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirRenamePreserve

function

Source line 3135

pub fn failingDirRenamePreserve(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenamePreserveError!void

Parameters

userdata: ?*anyopaque
old_dir: Dir
old_sub_path: []const u8
new_dir: Dir
new_sub_path: []const u8

Errors

AccessDenied

In WASI, this error may occur when the file descriptor does not hold the required rights to rename a resource by path relative to it.

On Windows, this error may be returned instead of PathAlreadyExists when renaming a directory over an existing directory.

On Darwin, this error may be returned when a component of either pathname refers to a "dataless" directory that requires materialization, and the I/O policy of the current thread or process disallows dataless directory materialization.

AntivirusInterference RenameError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

CrossDevice RenameError
DirNotEmpty RenameError

Attempted to replace a nonempty directory.

DiskQuota RenameError
FileBusy RenameError

The file attempted to be moved or replaced is a running executable.

FileNotFound RenameError
HardwareFailure RenameError
IsDir RenameError
LinkQuotaExceeded RenameError
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound RenameError

On Windows, \\server or \\server\share was not found.

NoDevice RenameError
NoSpaceLeft RenameError
NotDir RenameError
OperationUnsupported

Operating system or file system does not support atomic nonreplacing rename.

PathAlreadyExists
PermissionDenied RenameError
PipeBusy RenameError
ReadOnlyFileSystem RenameError
SymLinkLoop RenameError
SystemResources RenameError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirSetFileOwner

function

Source line 3169

pub fn failingDirSetFileOwner(userdata: ?*anyopaque, dir: std.Io.Dir, sub_path: []const u8, owner: ?File.Uid, group: ?File.Gid, options: Dir.SetFileOwnerOptions) Dir.SetFileOwnerError!void

Parameters

userdata: ?*anyopaque
dir: std.Io.Dir
sub_path: []const u8
owner: ?File.Uid
group: ?File.Gid
options: Dir.SetFileOwnerOptions

Errors

AccessDenied SetOwnerError
BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

FileNotFound SetOwnerError
InputOutput SetOwnerError
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

PermissionDenied SetOwnerError
ReadOnlyFileSystem SetOwnerError
SymLinkLoop SetOwnerError
SystemResources SetOwnerError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirSetFilePermissions

function

Source line 3186

pub fn failingDirSetFilePermissions(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: File.Permissions, options: Dir.SetFilePermissionsOptions) Dir.SetFilePermissionsError!void

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
permissions: File.Permissions
options: Dir.SetFilePermissionsOptions

Errors

AccessDenied SetPermissionsError
BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

FileNotFound SetPermissionsError
InputOutput SetPermissionsError
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

OperationUnsupported

SetFilePermissionsOptions.follow_symlinks was set to false, which is not allowed by the file system or operating system.

PermissionDenied SetPermissionsError
ProcessFdQuotaExceeded
ReadOnlyFileSystem SetPermissionsError
SymLinkLoop SetPermissionsError
SystemFdQuotaExceeded
SystemResources SetPermissionsError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirSetOwner

function

Source line 3161

pub fn failingDirSetOwner(userdata: ?*anyopaque, dir: Dir, owner: ?File.Uid, group: ?File.Gid) Dir.SetOwnerError!void

Parameters

userdata: ?*anyopaque
dir: Dir
owner: ?File.Uid
group: ?File.Gid

Errors

AccessDenied SetOwnerError
Canceled Cancelable

Caller has requested the async operation to stop.

FileNotFound SetOwnerError
InputOutput SetOwnerError
PermissionDenied SetOwnerError
ReadOnlyFileSystem SetOwnerError
SymLinkLoop SetOwnerError
SystemResources SetOwnerError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirSetPermissions

function

Source line 3179

pub fn failingDirSetPermissions(userdata: ?*anyopaque, dir: Dir, permissions: Dir.Permissions) Dir.SetPermissionsError!void

Parameters

userdata: ?*anyopaque
dir: Dir
permissions: Dir.Permissions

Errors

AccessDenied SetPermissionsError
Canceled Cancelable

Caller has requested the async operation to stop.

FileNotFound SetPermissionsError
InputOutput SetPermissionsError
PermissionDenied SetPermissionsError
ReadOnlyFileSystem SetPermissionsError
SymLinkLoop SetPermissionsError
SystemResources SetPermissionsError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirStat

function

Source line 3038

pub fn failingDirStat(userdata: ?*anyopaque, dir: Dir) Dir.StatError!Dir.Stat

Parameters

userdata: ?*anyopaque
dir: Dir

Errors

AccessDenied StatError

In WASI, this error may occur when the file descriptor does not hold the required rights to get its filestat information.

Canceled Cancelable

Caller has requested the async operation to stop.

PermissionDenied StatError
Streaming StatError

Attempted to stat a non-file stream.

SystemResources StatError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingDirStatFile

function

Source line 3044

pub fn failingDirStatFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.StatFileOptions) Dir.StatFileError!File.Stat

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
options: Dir.StatFileOptions

Errors

AccessDenied OpenError

In WASI, this error may occur when the file descriptor does not hold the required rights to open a new resource relative to it.

AntivirusInterference OpenError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy OpenError
FileBusy OpenError

One of these three things:

  • pathname refers to an executable image which is currently being executed and write access was requested.
  • pathname refers to a file that is currently in use as a swap file, and the O_TRUNC flag was specified.
  • pathname refers to a file that is currently being read by the kernel (e.g., for module/firmware loading), and write access was requested.
FileLocksUnsupported OpenError
FileNotFound OpenError

Either:

  • One of the path components does not exist.
  • Cwd was used, but cwd has been deleted.
  • The path associated with the open directory handle has been deleted.
  • On macOS, multiple processes or threads raced to create the same file with O.EXCL set to false.
FileTooBig OpenError

The file is too large to be opened. This error is unreachable for 64-bit targets, as well as when opening directories.

IsDir OpenError

Either:

  • The path refers to a directory and write permissions were requested.
  • The path refers to a directory and allow_directory was set to false.
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound OpenError

On Windows, \\server or \\server\share was not found.

NoDevice OpenError
NoSpaceLeft OpenError

A new path cannot be created because the device has no room for the new file. This error is only reachable when the CREAT flag is provided.

NotDir OpenError

A component used as a directory in the path was not, in fact, a directory, or DIRECTORY was specified and the path was not a directory.

PathAlreadyExists OpenError

The path already exists and the CREAT and EXCL flags were provided.

PermissionDenied OpenError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ReadOnlyFileSystem OpenError
Streaming StatError

Attempted to stat a non-file stream.

SymLinkLoop OpenError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

The path exceeded max_path_bytes bytes. Insufficient kernel memory was available, or the named file is a FIFO and per-user hard limit on memory allocation for pipes has been reached.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock OpenError

Non-blocking was requested and the operation cannot return immediately.

std.Io.failingDirSymLink

function

Source line 3144

pub fn failingDirSymLink(userdata: ?*anyopaque, dir: Dir, target_path: []const u8, sym_link_path: []const u8, flags: Dir.SymLinkFlags) Dir.SymLinkError!void

Parameters

userdata: ?*anyopaque
dir: Dir
target_path: []const u8
sym_link_path: []const u8
flags: Dir.SymLinkFlags

Errors

AccessDenied

In WASI, this error may occur when the file descriptor does not hold the required rights to create a new symbolic link relative to it.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DiskQuota
FileNotFound
FileSystem
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NoSpaceLeft
NotDir
PathAlreadyExists
PermissionDenied
ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileDowngradeLock

function

Source line 3359

pub fn failingFileDowngradeLock(userdata: ?*anyopaque, file: File) File.DowngradeLockError!void

Parameters

userdata: ?*anyopaque
file: File

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileHardLink

function

Source line 3372

pub fn failingFileHardLink(userdata: ?*anyopaque, file: File, new_dir: Dir, new_sub_path: []const u8, options: File.HardLinkOptions) File.HardLinkError!void

Parameters

userdata: ?*anyopaque
file: File
new_dir: Dir
new_sub_path: []const u8
options: File.HardLinkOptions

Errors

AccessDenied
BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

CrossDevice
DiskQuota
FileNotFound
HardwareFailure
LinkQuotaExceeded
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NoSpaceLeft
NotDir
OperationUnsupported

Either the OS or the filesystem does not support hard links.

PathAlreadyExists
PermissionDenied
ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileLength

function

Source line 3219

pub fn failingFileLength(userdata: ?*anyopaque, file: File) File.LengthError!u64

Parameters

userdata: ?*anyopaque
file: File

Errors

AccessDenied StatError

In WASI, this error may occur when the file descriptor does not hold the required rights to get its filestat information.

Canceled Cancelable

Caller has requested the async operation to stop.

PermissionDenied StatError
Streaming StatError

Attempted to stat a non-file stream.

SystemResources StatError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileLock

function

Source line 3339

pub fn failingFileLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!void

Parameters

userdata: ?*anyopaque
file: File
lock: File.Lock

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

FileLocksUnsupported
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileMemoryMapCreate

function

Source line 3381

pub fn failingFileMemoryMapCreate(userdata: ?*anyopaque, file: File, options: File.MemoryMap.CreateOptions) File.MemoryMap.CreateError!File.MemoryMap

Parameters

userdata: ?*anyopaque
file: File
options: File.MemoryMap.CreateOptions

Errors

AccessDenied

One of the following:

  • The File.Kind is not file.
  • The file is not open for reading and read access protections enabled.
  • The file is not open for writing and write access protections enabled.
Canceled Cancelable

Caller has requested the async operation to stop.

InputOutput ReadPositionalError
IsDir ReadPositionalError

Trying to read a directory file descriptor as if it were a file.

LockViolation ReadPositionalError

Unable to read file due to lock. Depending on the Io implementation, reading from a locked file may return this error, or may ignore the lock.

LockedMemoryLimitExceeded
NotOpenForReading ReadPositionalError

File was not opened with read capability.

OutOfMemory Error
PermissionDenied

The prot argument asks for PROT_EXEC but the mapped area belongs to a file on a filesystem that was mounted no-exec.

ProcessFdQuotaExceeded
SystemFdQuotaExceeded
SystemResources ReadPositionalError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unseekable ReadPositionalError

This file cannot be read positionally.

WouldBlock ReadPositionalError

Non-blocking has been enabled, and reading from the file descriptor would block.

std.Io.failingFileReadPositional

function

Source line 3262

pub fn failingFileReadPositional(userdata: ?*anyopaque, file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usize

Parameters

userdata: ?*anyopaque
file: File
data: []const []u8
offset: u64

Errors

AccessDenied

In WASI, this error occurs when the file descriptor does not hold the required rights to read from it.

Canceled Cancelable

Caller has requested the async operation to stop.

InputOutput
IsDir

Trying to read a directory file descriptor as if it were a file.

LockViolation

Unable to read file due to lock. Depending on the Io implementation, reading from a locked file may return this error, or may ignore the lock.

NotOpenForReading

File was not opened with read capability.

SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unseekable

This file cannot be read positionally.

WouldBlock

Non-blocking has been enabled, and reading from the file descriptor would block.

std.Io.failingFileRealPath

function

Source line 3365

pub fn failingFileRealPath(userdata: ?*anyopaque, file: File, out_buffer: []u8) File.RealPathError!usize

Parameters

userdata: ?*anyopaque
file: File
out_buffer: []u8

Errors

AccessDenied
AntivirusInterference

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy
FileBusy
FileNotFound
FileSystem
FileTooBig
InputOutput
IsDir
NameTooLong

The full file system path could not fit into the provided buffer, or due to its length could not be obtained via realpath functions no matter the buffer size provided.

NetworkNotFound

On Windows, \\server or \\server\share was not found.

NoDevice
NoSpaceLeft
NotDir
OperationUnsupported

This operating system, file system, or Io implementation does not support realpath operations.

PathAlreadyExists
PermissionDenied
PipeBusy
ProcessFdQuotaExceeded
SymLinkLoop
SystemFdQuotaExceeded
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnrecognizedVolume

On Windows, the volume does not contain a recognized file system. File system drivers might not be loaded, or the volume may be corrupt.

std.Io.failingFileSeekBy

function

Source line 3272

pub fn failingFileSeekBy(userdata: ?*anyopaque, file: File, relative_offset: i64) File.SeekError!void

Parameters

userdata: ?*anyopaque
file: File
relative_offset: i64

Errors

AccessDenied

The file descriptor does not hold the required rights to seek on it.

Canceled Cancelable

Caller has requested the async operation to stop.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unseekable

std.Io.failingFileSeekTo

function

Source line 3279

pub fn failingFileSeekTo(userdata: ?*anyopaque, file: File, absolute_offset: u64) File.SeekError!void

Parameters

userdata: ?*anyopaque
file: File
absolute_offset: u64

Errors

AccessDenied

The file descriptor does not hold the required rights to seek on it.

Canceled Cancelable

Caller has requested the async operation to stop.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unseekable

std.Io.failingFileSetLength

function

Source line 3310

pub fn failingFileSetLength(userdata: ?*anyopaque, file: File, length: u64) File.SetLengthError!void

Parameters

userdata: ?*anyopaque
file: File
length: u64

Errors

AccessDenied
Canceled Cancelable

Caller has requested the async operation to stop.

FileBusy
FileTooBig
InputOutput
NonResizable
PermissionDenied
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileSetOwner

function

Source line 3317

pub fn failingFileSetOwner(userdata: ?*anyopaque, file: File, owner: ?File.Uid, group: ?File.Gid) File.SetOwnerError!void

Parameters

userdata: ?*anyopaque
file: File
owner: ?File.Uid
group: ?File.Gid

Errors

AccessDenied
Canceled Cancelable

Caller has requested the async operation to stop.

FileNotFound
InputOutput
PermissionDenied
ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileSetPermissions

function

Source line 3325

pub fn failingFileSetPermissions(userdata: ?*anyopaque, file: File, permissions: File.Permissions) File.SetPermissionsError!void

Parameters

userdata: ?*anyopaque
file: File
permissions: File.Permissions

Errors

AccessDenied
Canceled Cancelable

Caller has requested the async operation to stop.

FileNotFound
InputOutput
PermissionDenied
ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileStat

function

Source line 3213

pub fn failingFileStat(userdata: ?*anyopaque, file: File) File.StatError!File.Stat

Parameters

userdata: ?*anyopaque
file: File

Errors

AccessDenied

In WASI, this error may occur when the file descriptor does not hold the required rights to get its filestat information.

Canceled Cancelable

Caller has requested the async operation to stop.

PermissionDenied
Streaming

Attempted to stat a non-file stream.

SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileSync

function

Source line 3286

pub fn failingFileSync(userdata: ?*anyopaque, file: File) File.SyncError!void

Parameters

userdata: ?*anyopaque
file: File

Errors

AccessDenied
Canceled Cancelable

Caller has requested the async operation to stop.

DiskQuota
InputOutput
NoSpaceLeft
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileTryLock

function

Source line 3346

pub fn failingFileTryLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!bool

Parameters

userdata: ?*anyopaque
file: File
lock: File.Lock

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

FileLocksUnsupported
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingFileWritePositional

function

Source line 3231

pub fn failingFileWritePositional(userdata: ?*anyopaque, file: File, header: []const u8, data: []const []const u8, splat: usize, offset: u64) File.WritePositionalError!usize

Parameters

userdata: ?*anyopaque
file: File
header: []const u8
data: []const []const u8
splat: usize
offset: u64

Errors

AccessDenied

File descriptor does not hold the required rights to write to it.

BrokenPipe

File is an unconnected socket, or closed its read end.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy
DiskQuota
FileBusy
FileTooBig
InputOutput
LockViolation

The process cannot access the file because another process has locked a portion of the file. Windows-only.

NoDevice

This error occurs when a device gets disconnected before or mid-flush while it's being written to - errno(6): No such device or address.

NoSpaceLeft
NotOpenForWriting

File was not opened with write capability.

PermissionDenied
SystemResources

Insufficient kernel memory to read from in_fd.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unseekable

This file cannot be written positionally.

WouldBlock

Non-blocking has been enabled and this operation would block.

std.Io.failingGroupConcurrent

function

Source line 2911

pub fn failingGroupConcurrent( userdata: ?*anyopaque, group: *Group, context: []const u8, context_alignment: std.mem.Alignment, start: *const fn (context: *const anyopaque) void, ) ConcurrentError!void

Parameters

userdata: ?*anyopaque
group: *Group
context: []const u8
context_alignment: std.mem.Alignment
start: *const fn (context: *const anyopaque) void

Errors

ConcurrencyUnavailable

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

std.Io.failingInheritParentDir

function

Source line 3489

pub fn failingInheritParentDir(userdata: ?*anyopaque, handle: Dir.Handle) InheritParentHandleError!Dir

Parameters

userdata: ?*anyopaque
handle: Dir.Handle

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnsupportedOperation

std.Io.failingInheritParentFile

function

Source line 3495

pub fn failingInheritParentFile(userdata: ?*anyopaque, handle: File.Handle, flags: File.Flags) InheritParentHandleError!File

Parameters

userdata: ?*anyopaque
handle: File.Handle
flags: File.Flags

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnsupportedOperation

std.Io.failingNetAccept

function

Source line 3537

pub fn failingNetAccept(userdata: ?*anyopaque, listen_fd: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socket

Parameters

userdata: ?*anyopaque
listen_fd: net.Socket.Handle
options: net.Server.AcceptOptions

Errors

BlockedByFirewall

Firewall rules forbid connection.

Canceled Cancelable

Caller has requested the async operation to stop.

ConnectionAborted

An incoming connection was indicated, but was subsequently terminated by the remote peer prior to accepting the call.

NetworkDown

The network subsystem has failed.

ProcessFdQuotaExceeded

The per-process limit on the number of open file descriptors has been reached.

ProtocolFailure
SocketNotListening

Either listen was never called, or shutdown was called (possibly while this call was blocking). This allows shutdown to be used as a concurrent cancellation mechanism.

SystemFdQuotaExceeded

The system-wide limit on the total number of open files has been reached.

SystemResources

Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock

No connection is already queued and ready to be accepted, and the socket is configured as non-blocking.

std.Io.failingNetBindIp

function

Source line 3544

pub fn failingNetBindIp(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.BindOptions) net.IpAddress.BindError!net.Socket

Parameters

userdata: ?*anyopaque
address: *const net.IpAddress
options: net.IpAddress.BindOptions

Errors

AccessDenied

The address is protected and the current user does not have permission to bind it.

AddressFamilyUnsupported

The address is not valid for the address family of socket.

AddressInUse

The address is already taken. Can occur when bound port is 0 but all ephemeral ports are already in use.

AddressUnavailable

A nonexistent interface was requested or the requested address was not local.

Canceled Cancelable

Caller has requested the async operation to stop.

NetworkDown

The local network interface used to reach the destination is offline.

OptionUnsupported

One of the BindOptions is not supported by the Io implementation.

ProcessFdQuotaExceeded

Per-process limit on the number of open file descriptors has been reached.

ProtocolUnsupportedByAddressFamily
ProtocolUnsupportedBySystem
SocketModeUnsupported
SystemFdQuotaExceeded

System-wide limit on the total number of open files has been reached.

SystemResources

Insufficient memory or other resource internal to the operating system.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingNetConnectIp

function

Source line 3551

pub fn failingNetConnectIp(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ConnectOptions) net.IpAddress.ConnectError!net.Socket

Parameters

userdata: ?*anyopaque
address: *const net.IpAddress
options: net.IpAddress.ConnectOptions

Errors

AccessDenied

The user tried to connect to a broadcast address without having the socket broadcast flag enabled or the connection request failed because of a local firewall rule.

AddressFamilyUnsupported
AddressUnavailable
Canceled Cancelable

Caller has requested the async operation to stop.

ConnectionPending
ConnectionRefused
ConnectionResetByPeer
HostUnreachable
NetworkDown
NetworkUnreachable
OptionUnsupported

One of the ConnectOptions is not supported by the Io implementation.

ProcessFdQuotaExceeded

Per-process limit on the number of open file descriptors has been reached.

ProtocolUnsupportedByAddressFamily
ProtocolUnsupportedBySystem
SocketModeUnsupported
SystemFdQuotaExceeded

System-wide limit on the total number of open files has been reached.

SystemResources

Insufficient memory or other resource internal to the operating system.

Timeout
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock

Non-blocking was requested and the operation cannot return immediately.

std.Io.failingNetConnectUnix

function

Source line 3565

pub fn failingNetConnectUnix(userdata: ?*anyopaque, address: *const net.UnixAddress) net.UnixAddress.ConnectError!net.Socket.Handle

Parameters

userdata: ?*anyopaque
address: *const net.UnixAddress

Errors

AccessDenied
AddressFamilyUnsupported
Canceled Cancelable

Caller has requested the async operation to stop.

ConnectionRefused
FileNotFound
NetworkDown
NotDir
PermissionDenied
ProcessFdQuotaExceeded
ProtocolUnsupportedBySystem
ReadOnlyFileSystem
SocketModeUnsupported
SymLinkLoop
SystemFdQuotaExceeded
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock

std.Io.failingNetInterfaceNameResolve

function

Source line 3599

pub fn failingNetInterfaceNameResolve(userdata: ?*anyopaque, name: *const net.Interface.Name) net.Interface.Name.ResolveError!net.Interface

Parameters

userdata: ?*anyopaque
name: *const net.Interface.Name

Errors

AccessDenied
Canceled Cancelable

Caller has requested the async operation to stop.

InterfaceNotFound
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingNetListenIp

function

Source line 3530

pub fn failingNetListenIp(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ListenOptions) net.IpAddress.ListenError!net.Socket

Parameters

userdata: ?*anyopaque
address: *const net.IpAddress
options: net.IpAddress.ListenOptions

Errors

AccessDenied

The address is protected and the current user does not have permission to bind it.

AddressFamilyUnsupported

The requested address family (IPv4 or IPv6) is not supported by the operating system.

AddressInUse

The address is already taken. Can occur when bound port is 0 but all ephemeral ports are already in use.

AddressUnavailable

A nonexistent interface was requested or the requested address was not local.

Canceled Cancelable

Caller has requested the async operation to stop.

NetworkDown

The local network interface used to reach the destination is offline.

OptionUnsupported

One of the ListenOptions is not supported by the Io implementation.

ProcessFdQuotaExceeded

Per-process limit on the number of open file descriptors has been reached.

ProtocolUnsupportedByAddressFamily
ProtocolUnsupportedBySystem
SocketModeUnsupported
SystemFdQuotaExceeded

System-wide limit on the total number of open files has been reached.

SystemResources

Insufficient memory or other resource internal to the operating system.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingNetListenUnix

function

Source line 3558

pub fn failingNetListenUnix(userdata: ?*anyopaque, address: *const net.UnixAddress, options: net.UnixAddress.ListenOptions) net.UnixAddress.ListenError!net.Socket.Handle

Parameters

userdata: ?*anyopaque
address: *const net.UnixAddress
options: net.UnixAddress.ListenOptions

Errors

AccessDenied
AddressFamilyUnsupported
AddressInUse
AddressUnavailable
Canceled Cancelable

Caller has requested the async operation to stop.

FileNotFound
NetworkDown
NotDir
PermissionDenied
ProcessFdQuotaExceeded
ReadOnlyFileSystem
SymLinkLoop
SystemFdQuotaExceeded
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingNetLookup

function

Source line 3611

pub fn failingNetLookup(userdata: ?*anyopaque, host_name: net.HostName, resolved: *Queue(net.HostName.LookupResult), options: net.HostName.LookupOptions) net.HostName.LookupError!void

Parameters

userdata: ?*anyopaque
host_name: net.HostName
resolved: *Queue(net.HostName.LookupResult)
options: net.HostName.LookupOptions

Errors

AccessDenied BindError

The address is protected and the current user does not have permission to bind it.

AddressFamilyUnsupported BindError

The address is not valid for the address family of socket.

AddressInUse BindError

The address is already taken. Can occur when bound port is 0 but all ephemeral ports are already in use.

AddressUnavailable BindError

A nonexistent interface was requested or the requested address was not local.

Canceled Cancelable

Caller has requested the async operation to stop.

DetectingNetworkConfigurationFailed

Failed to open or read "/etc/hosts" or "/etc/resolv.conf".

InvalidDnsAAAARecord
InvalidDnsARecord
InvalidDnsCnameRecord
NameServerFailure
NetworkDown BindError

The local network interface used to reach the destination is offline.

NoAddressReturned
OptionUnsupported BindError

One of the BindOptions is not supported by the Io implementation.

ProcessFdQuotaExceeded BindError

Per-process limit on the number of open file descriptors has been reached.

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ResolvConfParseFailed
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

System-wide limit on the total number of open files has been reached.

SystemResources BindError

Insufficient memory or other resource internal to the operating system.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnknownHostName

std.Io.failingNetShutdown

function

Source line 3592

pub fn failingNetShutdown(userdata: ?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!void

Parameters

userdata: ?*anyopaque
handle: net.Socket.Handle
how: net.ShutdownHow

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

ConnectionAborted
ConnectionResetByPeer
NetworkDown
SocketUnconnected
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingNetSocketCreatePair

function

Source line 3571

pub fn failingNetSocketCreatePair(userdata: ?*anyopaque, options: net.Socket.CreatePairOptions) net.Socket.CreatePairError![2]net.Socket

Parameters

userdata: ?*anyopaque
options: net.Socket.CreatePairOptions

Errors

AccessDenied
AddressFamilyUnsupported
Canceled Cancelable

Caller has requested the async operation to stop.

OperationUnsupported
ProcessFdQuotaExceeded

The per-process limit on the number of open file descriptors has been reached.

ProtocolUnsupportedByAddressFamily
ProtocolUnsupportedBySystem
SocketModeUnsupported
SystemFdQuotaExceeded

The system-wide limit on the total number of open files has been reached.

SystemResources

Insufficient memory is available. The socket cannot be created until sufficient resources are freed.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingNetWriteFile

function

Source line 3577

pub fn failingNetWriteFile(userdata: ?*anyopaque, handle: net.Socket.Handle, header: []const u8, file_reader: *Io.File.Reader, limit: Io.Limit) net.Stream.Writer.WriteFileError!usize

Parameters

userdata: ?*anyopaque
handle: net.Socket.Handle
header: []const u8
file_reader: *Io.File.Reader
limit: Io.Limit

Errors

AddressFamilyUnsupported Error

The passed address didn't have the correct address family in its sa_family field.

Canceled Cancelable

Caller has requested the async operation to stop.

ConnectionRefused Error

The destination address is not listening.

ConnectionResetByPeer Error

Network session was unexpectedly closed by recipient.

ConnectionTimedOut Error

The remote peer did not respond to ongoing communication, causing the OS to abort the connection.

EndOfStream

Reached the end of the file being read.

FastOpenAlreadyInProgress Error

Another TCP Fast Open is already in progress.

HostUnreachable Error

Network reached but no route to host.

NetworkDown Error

The local network interface used to reach the destination is down.

NetworkUnreachable Error

No route to network.

ReadFailed

The source File.Reader failed; detailed diagnostics are found on that struct.

SocketNotBound Error
SocketUnconnected Error

Local end has been shut down on a connection-oriented socket, or the socket was never connected.

SystemResources Error

The output queue for a network interface was full. This generally indicates that the interface has stopped sending, but may be caused by transient congestion. (Normally, this does not occur in Linux. Packets are just silently dropped when a device queue overflows.)

This is also caused when there is not enough kernel memory available.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unimplemented

The Io implementation cannot offer a more efficient file-to-socket path; the caller should fall back to read-based copying. See Io.Writer.sendFile.

std.Io.failingOperate

function

Source line 2973

pub fn failingOperate(userdata: ?*anyopaque, operation: Operation) Cancelable!Operation.Result

Parameters

userdata: ?*anyopaque
operation: Operation

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.failingProcessCurrentPath

function

Source line 3442

pub fn failingProcessCurrentPath(userdata: ?*anyopaque, buffer: []u8) std.process.CurrentPathError!usize

Parameters

userdata: ?*anyopaque
buffer: []u8

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

CurrentDirUnlinked

Not possible on Windows. Always returned on WASI.

NameTooLong

Buffer is too small to contain the current path.

PathExceedsLimit

The current path cannot be retrieved due to a limitation of the underlying libc or syscall implementation. Retrying with a larger buffer will not succeed.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingProcessExecutableOpen

function

Source line 3413

pub fn failingProcessExecutableOpen(userdata: ?*anyopaque, flags: Dir.OpenFileOptions) std.process.OpenExecutableError!File

Parameters

userdata: ?*anyopaque
flags: Dir.OpenFileOptions

Errors

AccessDenied OpenError

In WASI, this error may occur when the file descriptor does not hold the required rights to open a new resource relative to it.

AntivirusInterference OpenError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy OpenError
FileBusy OpenError

One of these three things:

  • pathname refers to an executable image which is currently being executed and write access was requested.
  • pathname refers to a file that is currently in use as a swap file, and the O_TRUNC flag was specified.
  • pathname refers to a file that is currently being read by the kernel (e.g., for module/firmware loading), and write access was requested.
FileLocksUnsupported OpenError
FileNotFound OpenError

Either:

  • One of the path components does not exist.
  • Cwd was used, but cwd has been deleted.
  • The path associated with the open directory handle has been deleted.
  • On macOS, multiple processes or threads raced to create the same file with O.EXCL set to false.
FileSystem ExecutablePathBaseError
FileTooBig OpenError

The file is too large to be opened. This error is unreachable for 64-bit targets, as well as when opening directories.

InputOutput ExecutablePathBaseError
IsDir OpenError

Either:

  • The path refers to a directory and write permissions were requested.
  • The path refers to a directory and allow_directory was set to false.
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound OpenError

On Windows, \\server or \\server\share was not found.

NoDevice OpenError
NoSpaceLeft OpenError

A new path cannot be created because the device has no room for the new file. This error is only reachable when the CREAT flag is provided.

NotDir OpenError

A component used as a directory in the path was not, in fact, a directory, or DIRECTORY was specified and the path was not a directory.

NotLink ExecutablePathBaseError
OperationUnsupported ExecutablePathBaseError

The operating system does not support an executable learning its own path.

PathAlreadyExists OpenError

The path already exists and the CREAT and EXCL flags were provided.

PermissionDenied OpenError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ProcessNotFound ExecutablePathBaseError
ReadOnlyFileSystem OpenError
SymLinkLoop OpenError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

The path exceeded max_path_bytes bytes. Insufficient kernel memory was available, or the named file is a FIFO and per-user hard limit on memory allocation for pipes has been reached.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnrecognizedVolume ExecutablePathBaseError

On Windows, the volume does not contain a recognized file system. File system drivers might not be loaded, or the volume may be corrupt.

WouldBlock OpenError

Non-blocking was requested and the operation cannot return immediately.

std.Io.failingProcessExecutablePath

function

Source line 3419

pub fn failingProcessExecutablePath(userdata: ?*anyopaque, buffer: []u8) std.process.ExecutablePathError!usize

Parameters

userdata: ?*anyopaque
buffer: []u8

Errors

AccessDenied ExecutablePathBaseError
AntivirusInterference ExecutablePathBaseError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName ExecutablePathBaseError
Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy ExecutablePathBaseError
FileNotFound ExecutablePathBaseError
FileSystem ExecutablePathBaseError
FileTooBig ExecutablePathBaseError
InputOutput ExecutablePathBaseError
IsDir ExecutablePathBaseError
NameTooLong
NetworkNotFound ExecutablePathBaseError

On Windows, \\server or \\server\share was not found.

NoDevice ExecutablePathBaseError
NoSpaceLeft ExecutablePathBaseError
NotDir ExecutablePathBaseError
NotLink ExecutablePathBaseError
OperationUnsupported ExecutablePathBaseError

The operating system does not support an executable learning its own path.

PathAlreadyExists ExecutablePathBaseError
PermissionDenied ExecutablePathBaseError
PipeBusy ExecutablePathBaseError
ProcessFdQuotaExceeded ExecutablePathBaseError
ProcessNotFound ExecutablePathBaseError
SymLinkLoop ExecutablePathBaseError
SystemFdQuotaExceeded ExecutablePathBaseError
SystemResources ExecutablePathBaseError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnrecognizedVolume ExecutablePathBaseError

On Windows, the volume does not contain a recognized file system. File system drivers might not be loaded, or the volume may be corrupt.

std.Io.failingProcessReplace

function

Source line 3460

pub fn failingProcessReplace(userdata: ?*anyopaque, options: std.process.ReplaceOptions) std.process.ReplaceError

Parameters

userdata: ?*anyopaque
options: std.process.ReplaceOptions

std.Io.failingProcessSetCurrentDir

function

Source line 3448

pub fn failingProcessSetCurrentDir(userdata: ?*anyopaque, dir: Dir) std.process.SetCurrentDirError!void

Parameters

userdata: ?*anyopaque
dir: Dir

Errors

AccessDenied
BadPathName
Canceled Cancelable

Caller has requested the async operation to stop.

FileNotFound
FileSystem
NameTooLong
NoDevice
NotDir
OperationUnsupported
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnrecognizedVolume

std.Io.failingProcessSetCurrentPath

function

Source line 3454

pub fn failingProcessSetCurrentPath(userdata: ?*anyopaque, path: []const u8) std.process.SetCurrentPathError!void

Parameters

userdata: ?*anyopaque
path: []const u8

Errors

AccessDenied
BadPathName
Canceled Cancelable

Caller has requested the async operation to stop.

FileNotFound
FileSystem
InvalidWtf8

Windows-only. The path is invalid WTF-8. https://wtf-8.codeberg.page/

NameTooLong
NoDevice
NotDir
OperationUnsupported
SymLinkLoop
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.failingProcessSpawn

function

Source line 3466

pub fn failingProcessSpawn(userdata: ?*anyopaque, options: std.process.SpawnOptions) std.process.SpawnError!std.process.Child

Parameters

userdata: ?*anyopaque
options: std.process.SpawnOptions

Errors

AccessDenied OpenError

In WASI, this error may occur when the file descriptor does not hold the required rights to open a new resource relative to it.

AntivirusInterference OpenError

On Windows, antivirus software is enabled by default. It can be disabled, but Windows Update sometimes ignores the user's preference and re-enables it. When enabled, antivirus software on Windows intercepts file system operations and makes them significantly slower in addition to possibly failing with this error code.

BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy OpenError
FileBusy OpenError

One of these three things:

  • pathname refers to an executable image which is currently being executed and write access was requested.
  • pathname refers to a file that is currently in use as a swap file, and the O_TRUNC flag was specified.
  • pathname refers to a file that is currently being read by the kernel (e.g., for module/firmware loading), and write access was requested.
FileLocksUnsupported OpenError
FileNotFound OpenError

Either:

  • One of the path components does not exist.
  • Cwd was used, but cwd has been deleted.
  • The path associated with the open directory handle has been deleted.
  • On macOS, multiple processes or threads raced to create the same file with O.EXCL set to false.
FileSystem
FileTooBig OpenError

The file is too large to be opened. This error is unreachable for 64-bit targets, as well as when opening directories.

InvalidBatchScriptArg

Windows-only. NUL (U+0000), LF (U+000A), CR (U+000D) are not allowed within arguments when executing a .bat/.cmd script.

  • NUL/LF signifiies end of arguments, so anything afterwards would be lost after execution.
  • CR is stripped by cmd.exe, so any CR codepoints would be lost after execution.
InvalidExe
InvalidName
InvalidProcessGroupId
InvalidUserId
InvalidWtf8

Windows-only. cwd or argv was provided and it was invalid WTF-8. https://wtf-8.codeberg.page/

IsDir OpenError

Either:

  • The path refers to a directory and write permissions were requested.
  • The path refers to a directory and allow_directory was set to false.
NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

NetworkNotFound OpenError

On Windows, \\server or \\server\share was not found.

NoDevice

POSIX-only. StdIo.ignore was selected and opening /dev/null returned ENODEV.

NoSpaceLeft OpenError

A new path cannot be created because the device has no room for the new file. This error is only reachable when the CREAT flag is provided.

NotDir OpenError

A component used as a directory in the path was not, in fact, a directory, or DIRECTORY was specified and the path was not a directory.

OperationUnsupported

The operating system does not support creating child processes.

OutOfMemory
PathAlreadyExists OpenError

The path already exists and the CREAT and EXCL flags were provided.

PermissionDenied
PipeBusy OpenError
ProcessAlreadyExec

An attempt was made to change the process group ID of one of the children of the calling process and the child had already performed an image replacement.

ProcessFdQuotaExceeded
ReadOnlyFileSystem OpenError
ResourceLimitReached
SymLinkLoop
SystemFdQuotaExceeded
SystemResources OpenError

The path exceeded max_path_bytes bytes. Insufficient kernel memory was available, or the named file is a FIFO and per-user hard limit on memory allocation for pipes has been reached.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnrecognizedVolume

On Windows, the volume does not contain a recognized file system. File system drivers might not be loaded, or the volume may be corrupt.

WouldBlock OpenError

Non-blocking was requested and the operation cannot return immediately.

std.Io.failingProgressParentFile

function

Source line 3484

pub fn failingProgressParentFile(userdata: ?*anyopaque) std.Progress.ParentFileError!File

Parameters

userdata: ?*anyopaque

Errors

EnvironmentVariableMissing
UnrecognizedFormat
UnsupportedOperation

std.Io.failingRandomSecure

function

Source line 3507

pub fn failingRandomSecure(userdata: ?*anyopaque, buffer: []u8) RandomSecureError!void

Parameters

userdata: ?*anyopaque
buffer: []u8

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

EntropyUnavailable

std.Io.fiber

alias

Source line 30

Alias of std.Io.fiber

std.Io.File

alias

Source line 45

Alias of std.Io.File

std.Io.foo

variable

Source line 3630

usize

std.Io.futexWait

function

Source line 1681

Atomically checks if the value at ptr equals expected, and if so, blocks until either:

  • a matching (same ptr argument) futexWake call occurs, or
  • a spurious ("random") wakeup occurs.

Typically, futexWake should be called immediately after updating the value at ptr.*, to unblock tasks using futexWait to wait for the value to change from what it previously was.

The caller is responsible for identifying spurious wakeups if necessary, typically by checking the value at ptr.*.

Asserts that T is 4 bytes in length and has a well-defined layout with no padding bits.

pub fn futexWait(io: Io, comptime T: type, ptr: *align(@alignOf(u32)) const T, expected: T) Cancelable!void

Parameters

io: Io
T: type
ptr: *align(@alignOf(u32)) const T
expected: T

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.futexWaitTimeout

function

Source line 1687

Same as futexWait, except also unblocks if timeout expires. As with futexWait, spurious wakeups are possible. It remains the caller's responsibility to differentiate between these three possible wake-up reasons if necessary.

pub fn futexWaitTimeout(io: Io, comptime T: type, ptr: *align(@alignOf(u32)) const T, expected: T, timeout: Timeout) Cancelable!void

Parameters

io: Io
T: type
ptr: *align(@alignOf(u32)) const T
expected: T
timeout: Timeout

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.futexWaitUncancelable

function

Source line 1697

Same as futexWait, except does not introduce a cancelation point.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn futexWaitUncancelable(io: Io, comptime T: type, ptr: *align(@alignOf(u32)) const T, expected: T) void

Parameters

io: Io
T: type
ptr: *align(@alignOf(u32)) const T
expected: T

std.Io.futexWake

function

Source line 1705

Unblocks pending futex waits on ptr, up to a limit of max_waiters calls.

pub fn futexWake(io: Io, comptime T: type, ptr: *align(@alignOf(u32)) const T, max_waiters: u32) void

Parameters

io: Io
T: type
ptr: *align(@alignOf(u32)) const T
max_waiters: u32

std.Io.Future

type-function

Source line 1296

pub fn Future(Result: type) type

Parameters

Result: type

Fields

any_future: ?*AnyFuture
result: Result

std.Io.Future.await

function

Source line 1319

Idempotent. Not threadsafe.

pub fn await(f: *@This(), io: Io) Result

Parameters

f: *@This()
io: Io

std.Io.Future.cancel

function

Source line 1311

Equivalent to await but places a cancelation request. This causes the task to receive error.Canceled from its next "cancelation point" (if any). A cancelation point is a call to a function in Io which can return error.Canceled.

After cancelation of a task is requested, only the next cancelation point in that task will return error.Canceled: future points will not re-signal the cancelation. As such, it is usually a bug to ignore error.Canceled. However, to defer handling cancelation requests, see also recancel and CancelProtection.

Idempotent. Not threadsafe.

pub fn cancel(f: *@This(), io: Io) Result

Parameters

f: *@This()
io: Io

std.Io.Group

container

Source line 1338

An unordered set of tasks which can only be awaited or canceled as a whole. Tasks are spawned in the group with Group.async and Group.concurrent.

The resources associated with each task are guaranteed to be released when the individual task returns, as opposed to when the whole group completes or is awaited. For this reason, it is not a resource leak to have a long-lived group which concurrent tasks are repeatedly added to. However, asynchronous tasks are not guaranteed to run until Group.await or Group.cancel is called, so adding async tasks to a group without ever awaiting it may leak resources.

Fields

token: std.atomic.Value(?*anyopaque)

This value indicates whether or not a group has pending tasks. null means there are no pending tasks, and no resources associated with the group, so await and cancel return immediately without calling the implementation. This means that token must be accessed atomically to avoid racing with the check in await and cancel.

state: usize

This value is available for the implementation to use as it wishes.

std.Io.Group.async

function

Source line 1363

Equivalent to Io.async, except the task is spawned in this Group instead of becoming associated with a Future.

The return type of function must be coercible to Cancelable!void. function returning error.Canceled does nothing because it is an cancelation propagation boundary.

Once this function is called, there are resources associated with the group. To release those resources, await or cancel must eventually be called.

function is not guaranteed to have been called until await or cancel is called.

pub fn async(g: *Group, io: Io, function: anytype, args: std.meta.ArgsTuple(@TypeOf(function))) void

Parameters

g: *Group
io: Io
args: std.meta.ArgsTuple(@TypeOf(function))

std.Io.Group.async.start

function

Source line 1366

fn start(context: *const anyopaque) void

Parameters

context: *const anyopaque

std.Io.Group.await

function

Source line 1408

Blocks until all tasks of the group finish. During this time, cancelation requests propagate to all members of the group, and will also cause error.Canceled to be returned when the group does ultimately finish.

After this function returns, all tasks of the Group created with async or concurrent are guaranteed to have run.

Idempotent. Not threadsafe.

It is safe to call this function concurrently with Group.async or Group.concurrent, provided that the group does not complete until the call to Group.async or Group.concurrent returns.

pub fn await(g: *Group, io: Io) Cancelable!void

Parameters

g: *Group
io: Io

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.Group.cancel

function

Source line 1427

Equivalent to await but immediately requests cancelation on all members of the group.

After this function returns, all tasks of the Group created with async or concurrent are guaranteed to have run.

For a description of cancelation and cancelation points, see Future.cancel.

Idempotent. Not threadsafe.

It is safe to call this function concurrently with Group.async or Group.concurrent, provided that the group does not complete until the call to Group.async or Group.concurrent returns.

pub fn cancel(g: *Group, io: Io) void

Parameters

g: *Group
io: Io

std.Io.Group.concurrent

function

Source line 1384

Equivalent to Io.concurrent, except the task is spawned in this Group instead of becoming associated with a Future.

The return type of function must be coercible to Cancelable!void. function returning error.Canceled does nothing because it is an cancelation propagation boundary.

Once this function is called, there are resources associated with the group. To release those resources, Group.await or Group.cancel must eventually be called.

pub fn concurrent(g: *Group, io: Io, function: anytype, args: std.meta.ArgsTuple(@TypeOf(function))) ConcurrentError!void

Parameters

g: *Group
io: Io
args: std.meta.ArgsTuple(@TypeOf(function))

Errors

ConcurrencyUnavailable

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

std.Io.Group.concurrent.start

function

Source line 1387

fn start(context: *const anyopaque) void

Parameters

context: *const anyopaque

std.Io.Group.init

constant

Source line 1348

Group

std.Io.InheritParentHandleError

error-set

Source line 832

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

UnsupportedOperation

std.Io.Io

alias

Source line 15

Alias of std.Io

std.Io.Kqueue

alias

Source line 38

Alias of std.Io.Kqueue

std.Io.Limit

container

Source line 730

Fields

nothing = 0
unlimited = math.maxInt(usize)
_

std.Io.Limit.countVec

function

Source line 746

pub fn countVec(data: []const []const u8) Limit

Parameters

data: []const []const u8

std.Io.Limit.limited

function

Source line 736

math.maxInt(usize) is interpreted to mean .unlimited.

pub fn limited(n: usize) Limit

Parameters

n: usize

std.Io.Limit.limited64

function

Source line 742

Any value grater than math.maxInt(usize) is interpreted to mean .unlimited.

pub fn limited64(n: u64) Limit

Parameters

n: u64

std.Io.Limit.max

function

Source line 756

pub fn max(a: Limit, b: Limit) Limit

Parameters

a: Limit
b: Limit

std.Io.Limit.min

function

Source line 752

pub fn min(a: Limit, b: Limit) Limit

Parameters

a: Limit
b: Limit

std.Io.Limit.minInt

function

Source line 764

pub fn minInt(l: Limit, n: usize) usize

Parameters

l: Limit
n: usize

std.Io.Limit.minInt64

function

Source line 768

pub fn minInt64(l: Limit, n: u64) usize

Parameters

l: Limit
n: u64

std.Io.Limit.nonzero

function

Source line 802

pub fn nonzero(l: Limit) bool

Parameters

l: Limit

std.Io.Limit.slice

function

Source line 772

pub fn slice(l: Limit, s: []u8) []u8

Parameters

l: Limit
s: []u8

std.Io.Limit.slice1

function

Source line 797

Reduces a slice to account for the limit, leaving room for one extra byte above the limit, allowing for the use case of differentiating between end-of-stream and reaching the limit.

pub fn slice1(l: Limit, non_empty_buffer: []u8) []u8

Parameters

l: Limit
non_empty_buffer: []u8

std.Io.Limit.sliceConst

function

Source line 776

pub fn sliceConst(l: Limit, s: []const u8) []const u8

Parameters

l: Limit
s: []const u8

std.Io.Limit.subtract

function

Source line 808

Return a new limit reduced by amount or return null indicating limit would be exceeded.

pub fn subtract(l: Limit, amount: usize) ?Limit

Parameters

l: Limit
amount: usize

std.Io.Limit.toInt

function

Source line 780

pub fn toInt(l: Limit) ?usize

Parameters

l: Limit

std.Io.Limit.toInt64

function

Source line 787

pub fn toInt64(l: Limit) ?u64

Parameters

l: Limit

std.Io.LockedStderr

container

Source line 2610

Fields

file_writer: *File.Writer
terminal_mode: Terminal.Mode

std.Io.LockedStderr.clear

function

Source line 2621

pub fn clear(ls: LockedStderr, buffer: []u8) Cancelable!void

Parameters

ls: LockedStderr
buffer: []u8

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.LockedStderr.terminal

function

Source line 2614

pub fn terminal(ls: LockedStderr) Terminal

Parameters

std.Io.lockStderr

function

Source line 2645

For doing application-level writes to the standard error stream. Coordinates also with debug-level writes that are ignorant of Io interface and implementations.

See also:

pub fn lockStderr(io: Io, buffer: []u8, terminal_mode: ?Terminal.Mode) Cancelable!LockedStderr

Parameters

io: Io
buffer: []u8
terminal_mode: ?Terminal.Mode

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.math

alias

Source line 20

Alias of std.math

std.Io.Mutex

container

Source line 1716

Mutex is a synchronization primitive which enforces atomic access to a shared region of code known as the "critical section".

Mutex is an extern struct so that it may be used as a field inside another extern struct.

Fields

state: std.atomic.Value(State)

std.Io.Mutex.init

constant

Source line 1719

Mutex

std.Io.Mutex.lock

function

Source line 1731

pub fn lock(m: *Mutex, io: Io) Cancelable!void

Parameters

m: *Mutex
io: Io

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.Mutex.lockUncancelable

function

Source line 1752

Same as lock, except does not introduce a cancelation point.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn lockUncancelable(m: *Mutex, io: Io) void

Parameters

m: *Mutex
io: Io

std.Io.Mutex.State

container

Source line 1721

Fields

unlocked
locked_once
contended

std.Io.Mutex.tryLock

function

Source line 1727

pub fn tryLock(m: *Mutex) bool

Parameters

m: *Mutex

std.Io.Mutex.unlock

function

Source line 1770

pub fn unlock(m: *Mutex, io: Io) void

Parameters

m: *Mutex
io: Io

std.Io.net

alias

Source line 43

Alias of std.Io.net

std.Io.noAsync

function

Source line 2847

pub fn noAsync(userdata: ?*anyopaque, result: []u8, result_alignment: std.mem.Alignment, context: []const u8, context_alignment: std.mem.Alignment, start: *const fn (context: *const anyopaque, result: *anyopaque) void) ?*AnyFuture

Parameters

userdata: ?*anyopaque
result: []u8
result_alignment: std.mem.Alignment
context: []const u8
context_alignment: std.mem.Alignment
start: *const fn (context: *const anyopaque, result: *anyopaque) void

std.Io.noCrashHandler

function

Source line 2843

pub fn noCrashHandler(userdata: ?*anyopaque) void

Parameters

userdata: ?*anyopaque

std.Io.noDirRead

function

Source line 3090

pub fn noDirRead(userdata: ?*anyopaque, dir_reader: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize

Parameters

userdata: ?*anyopaque
dir_reader: *Dir.Reader
buffer: []Dir.Entry

Errors

AccessDenied
Canceled Cancelable

Caller has requested the async operation to stop.

PermissionDenied
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.noDirSetTimestamps

function

Source line 3195

pub fn noDirSetTimestamps(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.SetTimestampsOptions) Dir.SetTimestampsError!void

Parameters

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
options: Dir.SetTimestampsOptions

Errors

AccessDenied SetTimestampsError

times is NULL, or both nsec values are UTIME_NOW, and either:

  • the effective user ID of the caller does not match the owner of the file, the caller does not have write access to the file, and the caller is not privileged (Linux: does not have either the CAP_FOWNER or the CAP_DAC_OVERRIDE capability); or,
  • the file is marked immutable (see chattr(1)).
BadPathName PathNameError

File system cannot encode the requested file name bytes. Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI, invalid characters on Windows, etc. Filesystem and operating specific.

Canceled Cancelable

Caller has requested the async operation to stop.

NameTooLong PathNameError

Returned when an insufficient buffer is provided that cannot fit the path name.

PermissionDenied SetTimestampsError

The caller attempted to change one or both timestamps to a value other than the current time, or to change one of the timestamps to the current time while leaving the other timestamp unchanged, (i.e., times is not NULL, neither nsec field is UTIME_NOW, and neither nsec field is UTIME_OMIT) and either:

  • the caller's effective user ID does not match the owner of file, and the caller is not privileged (Linux: does not have the CAP_FOWNER capability); or,
  • the file is marked append-only or immutable (see chattr(1)).
ReadOnlyFileSystem SetTimestampsError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.noFileSetTimestamps

function

Source line 3332

pub fn noFileSetTimestamps(userdata: ?*anyopaque, file: File, options: File.SetTimestampsOptions) File.SetTimestampsError!void

Parameters

userdata: ?*anyopaque
file: File
options: File.SetTimestampsOptions

Errors

AccessDenied

times is NULL, or both nsec values are UTIME_NOW, and either:

  • the effective user ID of the caller does not match the owner of the file, the caller does not have write access to the file, and the caller is not privileged (Linux: does not have either the CAP_FOWNER or the CAP_DAC_OVERRIDE capability); or,
  • the file is marked immutable (see chattr(1)).
Canceled Cancelable

Caller has requested the async operation to stop.

PermissionDenied

The caller attempted to change one or both timestamps to a value other than the current time, or to change one of the timestamps to the current time while leaving the other timestamp unchanged, (i.e., times is not NULL, neither nsec field is UTIME_NOW, and neither nsec field is UTIME_OMIT) and either:

  • the caller's effective user ID does not match the owner of file, and the caller is not privileged (Linux: does not have the CAP_FOWNER capability); or,
  • the file is marked append-only or immutable (see chattr(1)).
ReadOnlyFileSystem
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.noFileWriteFilePositional

function

Source line 3252

pub fn noFileWriteFilePositional(userdata: ?*anyopaque, file: File, header: []const u8, file_reader: *Io.File.Reader, limit: Io.Limit, offset: u64) File.WriteFilePositionalError!usize

Parameters

userdata: ?*anyopaque
file: File
header: []const u8
file_reader: *Io.File.Reader
limit: Io.Limit
offset: u64

Errors

AccessDenied Error

File descriptor does not hold the required rights to write to it.

BrokenPipe Error

File is an unconnected socket, or closed its read end.

Canceled Cancelable

Caller has requested the async operation to stop.

CorruptedData WriteFileError

Can happen on FreeBSD when using copy_file_range.

DeviceBusy Error
DiskQuota Error
EndOfStream WriteFileError
FileBusy Error
FileTooBig Error
InputOutput Error
LockViolation Error

The process cannot access the file because another process has locked a portion of the file. Windows-only.

NoDevice Error

This error occurs when a device gets disconnected before or mid-flush while it's being written to - errno(6): No such device or address.

NoSpaceLeft Error
NotOpenForWriting Error
PermissionDenied Error
ReadFailed WriteFileError
SystemResources Error

Insufficient kernel memory to read from in_fd.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unimplemented WriteFileError

Descriptor is not valid or locked, or an mmap(2)-like operation is not available for in_fd.

Unseekable
WouldBlock Error

Non-blocking has been enabled and this operation would block.

std.Io.noFileWriteFileStreaming

function

Source line 3243

pub fn noFileWriteFileStreaming(userdata: ?*anyopaque, file: File, header: []const u8, file_reader: *Io.File.Reader, limit: Io.Limit) File.Writer.WriteFileError!usize

Parameters

userdata: ?*anyopaque
file: File
header: []const u8
file_reader: *Io.File.Reader
limit: Io.Limit

Errors

AccessDenied Error

File descriptor does not hold the required rights to write to it.

BrokenPipe Error

File is an unconnected socket, or closed its read end.

Canceled Cancelable

Caller has requested the async operation to stop.

CorruptedData

Can happen on FreeBSD when using copy_file_range.

DeviceBusy Error
DiskQuota Error
EndOfStream
FileBusy Error
FileTooBig Error
InputOutput Error
LockViolation Error

The process cannot access the file because another process has locked a portion of the file. Windows-only.

NoDevice Error

This error occurs when a device gets disconnected before or mid-flush while it's being written to - errno(6): No such device or address.

NoSpaceLeft Error
NotOpenForWriting Error
PermissionDenied Error
ReadFailed
SystemResources Error

Insufficient kernel memory to read from in_fd.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unimplemented

Descriptor is not valid or locked, or an mmap(2)-like operation is not available for in_fd.

WouldBlock Error

Non-blocking has been enabled and this operation would block.

std.Io.noFutexWait

function

Source line 2956

pub fn noFutexWait(userdata: ?*anyopaque, ptr: *const u32, expected: u32, timeout: Timeout) Cancelable!void

Parameters

userdata: ?*anyopaque
ptr: *const u32
expected: u32
timeout: Timeout

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.noFutexWaitUncancelable

function

Source line 2961

pub fn noFutexWaitUncancelable(userdata: ?*anyopaque, ptr: *const u32, expected: u32) void

Parameters

userdata: ?*anyopaque
ptr: *const u32
expected: u32

std.Io.noFutexWake

function

Source line 2966

pub fn noFutexWake(userdata: ?*anyopaque, ptr: *const u32, max_waiters: u32) void

Parameters

userdata: ?*anyopaque
ptr: *const u32
max_waiters: u32

std.Io.noGroupAsync

function

Source line 2898

pub fn noGroupAsync( userdata: ?*anyopaque, group: *Group, context: []const u8, context_alignment: std.mem.Alignment, start: *const fn (context: *const anyopaque) void, ) void

Parameters

userdata: ?*anyopaque
group: *Group
context: []const u8
context_alignment: std.mem.Alignment
start: *const fn (context: *const anyopaque) void

std.Io.noNow

function

Source line 3513

pub fn noNow(userdata: ?*anyopaque, clock: Clock) Timestamp

Parameters

userdata: ?*anyopaque
clock: Clock

std.Io.noRandom

function

Source line 3502

pub fn noRandom(userdata: ?*anyopaque, buffer: []u8) void

Parameters

userdata: ?*anyopaque
buffer: []u8

std.Io.noSleep

function

Source line 3525

pub fn noSleep(userdata: ?*anyopaque, clock: Timeout) Cancelable!void

Parameters

userdata: ?*anyopaque
clock: Timeout

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.noTryLockStderr

function

Source line 3431

pub fn noTryLockStderr(userdata: ?*anyopaque, terminal_mode: ?Terminal.Mode) Cancelable!?LockedStderr

Parameters

userdata: ?*anyopaque
terminal_mode: ?Terminal.Mode

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.operate

function

Source line 555

Performs one Operation.

pub fn operate(io: Io, operation: Operation) Cancelable!Operation.Result

Parameters

io: Io
operation: Operation

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.operateTimeout

function

Source line 562

Performs one Operation with provided timeout.

pub fn operateTimeout(io: Io, operation: Operation, timeout: Timeout) OperateTimeoutError!Operation.Result

Parameters

io: Io
operation: Operation
timeout: Timeout

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

ConcurrencyUnavailable ConcurrentError

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

Timeout Error

std.Io.OperateTimeoutError

error-set

Source line 559

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

ConcurrencyUnavailable ConcurrentError

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

Timeout Error

std.Io.Operation

container

Source line 246

Fields

file_read_streaming: FileReadStreaming
file_write_streaming: FileWriteStreaming
device_io_control: DeviceIoControl

On Windows this is NtDeviceIoControlFile. On POSIX this is ioctl. On other systems this tag is unreachable.

net_receive: NetReceive
net_send: NetSend
net_read: NetRead
net_write: NetWrite

std.Io.Operation.DeviceIoControl

type

Source line 323

std.Io.Operation.DeviceIoControl.Result

alias

Source line 331

Alias of std.os.windows.IO_STATUS_BLOCK

std.Io.Operation.DeviceIoControl.Result

type

Source line 341

Device and operation dependent result. Negative values are negative errno.

std.Io.Operation.FileReadStreaming

container

Source line 260

May return 0 reads which is different than error.EndOfStream.

Fields

file: File
data: []const []u8

std.Io.Operation.FileReadStreaming.Error

error-set

Source line 264

Errors

AccessDenied UnendingError

In WASI, this error occurs when the file descriptor does not hold the required rights to read from it.

ConnectionResetByPeer UnendingError
EndOfStream
InputOutput UnendingError
IsDir UnendingError

Trying to read a directory file descriptor as if it were a file.

LockViolation UnendingError

Unable to read file due to lock. Depending on the Io implementation, reading from a locked file may return this error, or may ignore the lock.

NotOpenForReading UnendingError

File was not opened with read capability.

SocketUnconnected UnendingError
SystemResources UnendingError
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock UnendingError

Non-blocking has been enabled, and reading from the file descriptor would block.

std.Io.Operation.FileReadStreaming.Result

constant

Source line 286

std.Io.Operation.FileReadStreaming.UnendingError

error-set

Source line 265

Errors

AccessDenied

In WASI, this error occurs when the file descriptor does not hold the required rights to read from it.

ConnectionResetByPeer
InputOutput
IsDir

Trying to read a directory file descriptor as if it were a file.

LockViolation

Unable to read file due to lock. Depending on the Io implementation, reading from a locked file may return this error, or may ignore the lock.

NotOpenForReading

File was not opened with read capability.

SocketUnconnected
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock

Non-blocking has been enabled, and reading from the file descriptor would block.

std.Io.Operation.FileWriteStreaming

container

Source line 289

Fields

file: File
header: []const u8 = &.{}
data: []const []const u8
splat: usize = 1

std.Io.Operation.FileWriteStreaming.Error

error-set

Source line 295

Errors

AccessDenied

File descriptor does not hold the required rights to write to it.

BrokenPipe

File is an unconnected socket, or closed its read end.

DeviceBusy
DiskQuota
FileBusy
FileTooBig
InputOutput
LockViolation

The process cannot access the file because another process has locked a portion of the file. Windows-only.

NoDevice

This error occurs when a device gets disconnected before or mid-flush while it's being written to - errno(6): No such device or address.

NoSpaceLeft
NotOpenForWriting
PermissionDenied
SystemResources

Insufficient kernel memory to read from in_fd.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

WouldBlock

Non-blocking has been enabled and this operation would block.

std.Io.Operation.FileWriteStreaming.Result

constant

Source line 320

std.Io.Operation.List

container

Source line 543

Fields

std.Io.Operation.List.DoubleNode

container

Source line 550

Fields

std.Io.Operation.List.empty

constant

Source line 547

List

std.Io.Operation.List.SingleNode

container

Source line 549

Fields

std.Io.Operation.NetRead

container

Source line 430

Fields

socket_handle: net.Socket.Handle
data: [][]u8
control: []u8 = &.{}

std.Io.Operation.NetRead.Error

error-set

Source line 435

Errors

AccessDenied

File descriptor does not hold the required rights to read from it.

ConnectionResetByPeer
ConnectionTimedOut

The remote peer did not respond to ongoing communication, causing the OS to abort the connection.

NetworkDown
SocketUnconnected
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.Operation.NetRead.Result

constant

Source line 447

std.Io.Operation.NetReceive

container

Source line 345

Fields

socket_handle: net.Socket.Handle
message_buffer: []net.IncomingMessage
data_buffer: []u8
flags: net.ReceiveFlags

std.Io.Operation.NetReceive.Error

error-set

Source line 351

Errors

ConnectionResetByPeer

Network connection was unexpectedly closed by sender.

ConnectionTimedOut

The remote peer did not respond to ongoing communication, causing the OS to abort the connection.

MessageOversize

The socket type requires that message be sent atomically, and the size of the message to be sent made this impossible. The message was not transmitted, or was partially transmitted.

NetworkDown

The local network interface used to reach the destination is offline.

PortUnreachable

A connectionless packet was previously sent successfully, however, it was not received because no service is operating at the destination port of the transport on the remote system. This caused an ICMP port unreachable packet to be returned to the OS where it was queued up to be reported at the next call to send or receive on the bound socket.

ProcessFdQuotaExceeded

Per-process limit on the number of open file descriptors has been reached.

SocketUnconnected

Local end has been shut down on a connection-oriented socket, or the socket was never connected.

SystemFdQuotaExceeded

System-wide limit on the total number of open files has been reached.

SystemResources

Insufficient memory or other resource internal to the operating system.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.Operation.NetReceive.Result

container

Source line 381

Fields

std.Io.Operation.NetSend

container

Source line 384

Fields

socket_handle: net.Socket.Handle
messages: []net.OutgoingMessage
flags: net.SendFlags

std.Io.Operation.NetSend.Error

error-set

Source line 389

Errors

AccessDenied

An attempt was made to send to a network/broadcast address as though it was a unicast address.

AddressFamilyUnsupported

Operating system or protocol does not support the address family.

ConnectionRefused

The destination address is not listening. Can still occur for connectionless messages.

ConnectionResetByPeer

Network session was unexpectedly closed by recipient.

ConnectionTimedOut

The remote peer did not respond to ongoing communication, causing the OS to abort the connection.

FastOpenAlreadyInProgress

Another TCP Fast Open is already in progress.

HostUnreachable

Network reached but no route to host.

MessageOversize

The socket type requires that message be sent atomically, and the size of the message to be sent made this impossible. The message was not transmitted, or was partially transmitted.

NetworkDown

The local network interface used to reach the destination is offline.

NetworkUnreachable

No route to network.

SocketUnconnected

Local end has been shut down on a connection-oriented socket, or the socket was never connected.

SystemResources

The output queue for a network interface was full. This generally indicates that the interface has stopped sending, but may be caused by transient congestion. (Normally, this does not occur in Linux. Packets are just silently dropped when a device queue overflows.)

This is also caused when there is not enough kernel memory available.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.Operation.NetSend.Result

container

Source line 427

Fields

std.Io.Operation.NetWrite

container

Source line 450

Fields

socket_handle: net.Socket.Handle
header: []const u8 = &.{}
data: []const []const u8
splat: usize = 1
control: []const u8 = &.{}

std.Io.Operation.NetWrite.Error

error-set

Source line 457

Errors

AddressFamilyUnsupported

The passed address didn't have the correct address family in its sa_family field.

ConnectionRefused

The destination address is not listening.

ConnectionResetByPeer

Network session was unexpectedly closed by recipient.

ConnectionTimedOut

The remote peer did not respond to ongoing communication, causing the OS to abort the connection.

FastOpenAlreadyInProgress

Another TCP Fast Open is already in progress.

HostUnreachable

Network reached but no route to host.

NetworkDown

The local network interface used to reach the destination is down.

NetworkUnreachable

No route to network.

SocketNotBound
SocketUnconnected

Local end has been shut down on a connection-oriented socket, or the socket was never connected.

SystemResources

The output queue for a network interface was full. This generally indicates that the interface has stopped sending, but may be caused by transient congestion. (Normally, this does not occur in Linux. Packets are just silently dropped when a device queue overflows.)

This is also caused when there is not enough kernel memory available.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.Operation.NetWrite.Result

constant

Source line 488

std.Io.Operation.OptionalIndex

container

Source line 528

Fields

none = std.math.maxInt(u32)
_

std.Io.Operation.OptionalIndex.fromIndex

function

Source line 532

pub fn fromIndex(i: usize) OptionalIndex

Parameters

i: usize

std.Io.Operation.OptionalIndex.toIndex

function

Source line 538

pub fn toIndex(oi: OptionalIndex) u32

Parameters

std.Io.Operation.Result

constant

Source line 491

std.Io.Operation.Storage

container

Source line 503

Fields

unused: List.DoubleNode
submission: Submission
pending: Pending
completion: Completion

std.Io.Operation.Storage.Completion

container

Source line 522

Fields

node: List.SingleNode
result: Result

std.Io.Operation.Storage.Pending

container

Source line 514

Fields

node: List.DoubleNode
tag: Tag
userdata: Userdata align(@max(@alignOf(usize), 4))

std.Io.Operation.Storage.Pending.Userdata

type

Source line 519

std.Io.Operation.Storage.Submission

container

Source line 509

Fields

node: List.SingleNode
operation: Operation

std.Io.Operation.Tag

constant

Source line 257

std.Io.Queue

type-function

Source line 2390

Many producer, many consumer, thread-safe, runtime configurable buffer size. When buffer is empty, consumers suspend and are resumed by producers. When buffer is full, producers suspend and are resumed by consumers.

pub fn Queue(Elem: type) type

Parameters

Elem: type

Fields

type_erased: TypeErasedQueue

std.Io.Queue.capacity

function

Source line 2514

Returns buffer length in Elem units.

pub fn capacity(q: *const @This()) usize

Parameters

q: *const @This()

std.Io.Queue.close

function

Source line 2404

After this is called, the queue enters a "closed" state. A closed queue always returns error.Closed for put attempts even when there is space in the buffer. However, existing elements of the queue are retrieved before error.Closed is returned.

Threadsafe.

pub fn close(q: *@This(), io: Io) void

Parameters

q: *@This()
io: Io

std.Io.Queue.get

function

Source line 2486

Receives elements from the beginning of the queue, potentially blocking if there are insufficient elements currently in the queue. Returns when any one of the following conditions is satisfied:

  • At least min elements have been received from the queue
  • The queue is closed and contains no buffered elements
  • The current task is canceled

Returns how many elements of buffer have been populated, if any. If an error is returned, no elements have been populated.

If the queue is closed or the task is canceled, but some items were already received before the closure or cancelation, then get may return a number lower than min, in which case future calls are guaranteed to return error.Canceled or error.Closed.

A return value of 0 is only possible if min is 0, in which case the call is guaranteed to fill as much of buffer as is possible without blocking.

Asserts that buffer.len >= min.

pub fn get(q: *@This(), io: Io, buffer: []Elem, min: usize) (QueueClosedError || Cancelable)!usize

Parameters

q: *@This()
io: Io
buffer: []Elem
min: usize

std.Io.Queue.getOne

function

Source line 2498

Receives one element from the beginning of the queue, blocking if the queue is empty.

pub fn getOne(q: *@This(), io: Io) (QueueClosedError || Cancelable)!Elem

Parameters

q: *@This()
io: Io

std.Io.Queue.getOneUncancelable

function

Source line 2507

Same as getOne, except does not introduce a cancelation point.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn getOneUncancelable(q: *@This(), io: Io) QueueClosedError!Elem

Parameters

q: *@This()
io: Io

Errors

Closed

std.Io.Queue.getUncancelable

function

Source line 2493

Same as get, except does not introduce a cancelation point.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn getUncancelable(q: *@This(), io: Io, buffer: []Elem, min: usize) QueueClosedError!usize

Parameters

q: *@This()
io: Io
buffer: []Elem
min: usize

Errors

Closed

std.Io.Queue.init

function

Source line 2394

pub fn init(buffer: []Elem) @This()

Parameters

buffer: []Elem

std.Io.Queue.put

function

Source line 2429

Appends elements to the end of the queue, potentially blocking if there is insufficient capacity. Returns when any one of the following conditions is satisfied:

  • At least min elements have been added to the queue
  • The queue is closed
  • The current task is canceled

Returns how many of elements have been added to the queue, if any. If an error is returned, no elements have been added.

If the queue is closed or the task is canceled, but some items were already added before the closure or cancelation, then put may return a number lower than min, in which case future calls are guaranteed to return error.Canceled or error.Closed.

A return value of 0 is only possible if min is 0, in which case the call is guaranteed to queue as many of elements as is possible without blocking.

Asserts that elements.len >= min.

pub fn put(q: *@This(), io: Io, elements: []const Elem, min: usize) (QueueClosedError || Cancelable)!usize

Parameters

q: *@This()
io: Io
elements: []const Elem
min: usize

std.Io.Queue.putAll

function

Source line 2438

Same as put but blocks until all elements have been added to the queue.

If the queue is closed or canceled, error.Closed or error.Canceled is returned, and it is unspecified how many, if any, of elements were added to the queue prior to cancelation or closure.

pub fn putAll(q: *@This(), io: Io, elements: []const Elem) (QueueClosedError || Cancelable)!void

Parameters

q: *@This()
io: Io
elements: []const Elem

std.Io.Queue.putOne

function

Source line 2454

Appends item to the end of the queue, blocking if the queue is full.

pub fn putOne(q: *@This(), io: Io, item: Elem) (QueueClosedError || Cancelable)!void

Parameters

q: *@This()
io: Io
item: Elem

std.Io.Queue.putOneUncancelable

function

Source line 2461

Same as putOne, except does not introduce a cancelation point.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn putOneUncancelable(q: *@This(), io: Io, item: Elem) QueueClosedError!void

Parameters

q: *@This()
io: Io
item: Elem

Errors

Closed

std.Io.Queue.putUncancelable

function

Source line 2449

Same as put, except does not introduce a cancelation point.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn putUncancelable(q: *@This(), io: Io, elements: []const Elem, min: usize) QueueClosedError!usize

Parameters

q: *@This()
io: Io
elements: []const Elem
min: usize

Errors

Closed

std.Io.QueueClosedError

error-set

Source line 2078

Errors

Closed

std.Io.random

function

Source line 2674

Obtains entropy from a cryptographically secure pseudo-random number generator.

The implementation may store RNG state in process memory and use it to fill buffer.

The randomness is seeded by randomSecure, or a less secure mechanism upon failure.

Threadsafe.

See also randomSecure.

pub fn random(io: Io, buffer: []u8) void

Parameters

io: Io
buffer: []u8

std.Io.randomSecure

function

Source line 2691

Obtains cryptographically secure entropy from outside the process.

Always makes a syscall, or otherwise avoids dependency on process memory, in order to obtain fresh randomness. Does not rely on stored RNG state.

Does not have any fallback mechanisms; returns error.EntropyUnavailable if any problems occur.

Threadsafe.

See also random.

pub fn randomSecure(io: Io, buffer: []u8) RandomSecureError!void

Parameters

io: Io
buffer: []u8

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

EntropyUnavailable

std.Io.RandomSecureError

error-set

Source line 2678

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

EntropyUnavailable

std.Io.Reader

alias

Source line 41

Alias of std.Io.Reader

std.Io.recancel

function

Source line 1439

Asserts that error.Canceled was returned from a prior cancelation point, and "re-arms" the cancelation request, so that error.Canceled will be returned again from the next cancelation point.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn recancel(io: Io) void

Parameters

io: Io

std.Io.RwLock

alias

Source line 48

Alias of std.Io.RwLock

std.Io.Select

type-function

Source line 1496

Executes tasks together, providing a mechanism to wait until one or more tasks complete. Similar to Batch but operates at the higher level task abstraction layer rather than lower level Operation abstraction layer.

The provided tagged union will be used as the return type of the await function. When calling async or concurrent, one specifies which union field the called function's result will be placed into upon completion.

pub fn Select(comptime U: type) type

Parameters

U: type

Fields

io: Io
group: Group
queue: Queue(U)

std.Io.Select.async

function

Source line 1535

Calls function with args asynchronously. The resource spawned is owned by the select.

function must have return type matching the field field of Union.

function may be called immediately, before async returns.

When this function returns, it is guaranteed that function has already been called and completed, or it has successfully been assigned a unit of concurrency.

After this is called, await or cancel must be called before the select is deinitialized.

Threadsafe.

Related:

  • Io.async
  • Group.async
pub fn async( s: *S, comptime field: Field, function: anytype, args: std.meta.ArgsTuple(@TypeOf(function)), ) void

Parameters

s: *S
field: Field
args: std.meta.ArgsTuple(@TypeOf(function))

std.Io.Select.async.start

function

Source line 1544

fn start(type_erased_context: *const anyopaque) void

Parameters

type_erased_context: *const anyopaque

std.Io.Select.await

function

Source line 1599

Blocks until another task of the select finishes.

It is legal to call async and concurrent after this.

Threadsafe.

pub fn await(s: *S) Cancelable!U

Parameters

s: *S

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.Select.awaitMany

function

Source line 1614

Blocks until at least min number of results have been copied into buffer.

Asserts that buffer.len >= min.

It is legal to call async and concurrent after this.

Threadsafe.

pub fn awaitMany(s: *S, buffer: []U, min: usize) Cancelable!usize

Parameters

s: *S
buffer: []U
min: usize

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.Select.cancel

function

Source line 1638

Requests cancelation on all remaining tasks owned by the select, then blocks until they all finish. If the select was initialized with insufficient buffer space for all remaining tasks to finish, a deadlock occurs.

If any of the select tasks allocate resources, those tasks may have completed, meaning that this function must be called in a loop until null is returned in order to deallocate those resources. If there is no possibility of resource leaks, cancelDiscard is preferable.

It is illegal to call await or awaitMany after this.

It is safe to call this multiple times, even after null is returned.

Threadsafe.

pub fn cancel(s: *S) ?U

Parameters

s: *S

std.Io.Select.cancelDiscard

function

Source line 1659

Requests cancelation on all remaining tasks owned by the select, then blocks until they all finish.

All return values from outstanding tasks are discarded. This function is therefore inappropriate to call when a task can return an allocated resource. For that use case, see cancel.

It is illegal to call await or awaitMany after this.

It is safe to call this multiple times.

Threadsafe.

pub fn cancelDiscard(s: *S) void

Parameters

s: *S

std.Io.Select.concurrent

function

Source line 1572

Calls function with args concurrently. The resource spawned is owned by the select.

function must have return type matching the field field of Union.

After this function returns successfully, it is guaranteed that function has been assigned a unit of concurrency, and await or cancel must be called before the select is deinitialized.

Threadsafe.

Related:

  • Io.concurrent
  • Group.concurrent
pub fn concurrent( s: *S, comptime field: Field, function: anytype, args: std.meta.ArgsTuple(@TypeOf(function)), ) ConcurrentError!void

Parameters

s: *S
field: Field
args: std.meta.ArgsTuple(@TypeOf(function))

Errors

ConcurrencyUnavailable

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

std.Io.Select.concurrent.start

function

Source line 1581

fn start(type_erased_context: *const anyopaque) void

Parameters

type_erased_context: *const anyopaque

std.Io.Select.Field

type

Source line 1506

std.Io.Select.init

function

Source line 1508

pub fn init(io: Io, buffer: []U) S

Parameters

io: Io
buffer: []U

std.Io.Select.S

alias

Source line 1502

Alias of std.Io.Select

std.Io.Select.Union

constant

Source line 1504

std.Io.Semaphore

alias

Source line 49

Alias of std.Io.Semaphore

std.Io.sleep

function

Source line 2603

Waits until a specified amount of time has passed on clock.

See also:

pub fn sleep(io: Io, duration: Duration, clock: Clock) Cancelable!void

Parameters

io: Io
duration: Duration
clock: Clock

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.std

alias

Source line 19

Alias of std

std.Io.swapCancelProtection

function

Source line 1471

Updates the current task's cancel protection state (see CancelProtection).

The typical usage for this function is to protect a block of code from cancelation:

const old_cancel_protect = io.swapCancelProtection(.blocked);
defer _ = io.swapCancelProtection(old_cancel_protect);
doSomeWork() catch |err| switch (err) {
    error.Canceled => unreachable,
};

For a description of cancelation and cancelation points, see Future.cancel.

pub fn swapCancelProtection(io: Io, new: CancelProtection) CancelProtection

Parameters

io: Io
new: CancelProtection

std.Io.Terminal

alias

Source line 46

Alias of std.Io.Terminal

std.Io.Threaded

alias

Source line 28

Alias of std.Io.Threaded

std.Io.Timeout

container

Source line 1251

Declares under what conditions an operation should return error.Timeout.

Fields

none

.none will wait forever

duration: Clock.Duration
deadline: Clock.Timestamp

std.Io.Timeout.Error

error-set

Source line 1257

Errors

Timeout

std.Io.Timeout.sleep

function

Source line 1289

Waits until the timeout has passed.

See also:

  • Io.sleep
  • Clock.Duration.sleep
  • Clock.Timestamp.wait
pub fn sleep(timeout: Timeout, io: Io) Cancelable!void

Parameters

timeout: Timeout
io: Io

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.Timeout.toDeadline

function

Source line 1267

pub fn toDeadline(t: Timeout, io: Io) Timeout

Parameters

t: Timeout
io: Io

std.Io.Timeout.toDurationFromNow

function

Source line 1275

pub fn toDurationFromNow(t: Timeout, io: Io) ?Clock.Duration

Parameters

t: Timeout
io: Io

std.Io.Timeout.toTimestamp

function

Source line 1259

pub fn toTimestamp(t: Timeout, io: Io) ?Clock.Timestamp

Parameters

t: Timeout
io: Io

std.Io.Timestamp

container

Source line 1021

Fields

nanoseconds: i96

std.Io.Timestamp.addDuration

function

Source line 1034

pub fn addDuration(from: Timestamp, duration: Duration) Timestamp

Parameters

from: Timestamp
duration: Duration

std.Io.Timestamp.compare

function

Source line 1082

pub fn compare(lhs: Timestamp, op: math.CompareOperator, rhs: Timestamp) bool

Parameters

std.Io.Timestamp.durationTo

function

Source line 1030

pub fn durationTo(from: Timestamp, to: Timestamp) Duration

Parameters

from: Timestamp
to: Timestamp

std.Io.Timestamp.formatNumber

function

Source line 1066

pub fn formatNumber(t: Timestamp, w: *std.Io.Writer, n: std.fmt.Number) std.Io.Writer.Error!void

Parameters

Errors

WriteFailed

See the Writer implementation for detailed diagnostics.

std.Io.Timestamp.fromNanoseconds

function

Source line 1046

pub fn fromNanoseconds(x: i96) Timestamp

Parameters

x: i96

std.Io.Timestamp.now

function

Source line 1024

pub fn now(io: Io, clock: Clock) Io.Timestamp

Parameters

io: Io
clock: Clock

std.Io.Timestamp.subDuration

function

Source line 1038

pub fn subDuration(from: Timestamp, duration: Duration) Timestamp

Parameters

from: Timestamp
duration: Duration

std.Io.Timestamp.toMicroseconds

function

Source line 1050

pub fn toMicroseconds(t: Timestamp) i64

Parameters

std.Io.Timestamp.toMilliseconds

function

Source line 1054

pub fn toMilliseconds(t: Timestamp) i64

Parameters

std.Io.Timestamp.toNanoseconds

function

Source line 1062

pub fn toNanoseconds(t: Timestamp) i96

Parameters

std.Io.Timestamp.toSeconds

function

Source line 1058

pub fn toSeconds(t: Timestamp) i64

Parameters

std.Io.Timestamp.untilNow

function

Source line 1077

Resolution is determined by Clock.resolution which may be 0 if the clock is unsupported.

pub fn untilNow(t: Timestamp, io: Io, clock: Clock) Duration

Parameters

t: Timestamp
io: Io
clock: Clock

std.Io.Timestamp.withClock

function

Source line 1042

pub fn withClock(t: Timestamp, clock: Clock) Clock.Timestamp

Parameters

t: Timestamp
clock: Clock

std.Io.Timestamp.zero

constant

Source line 1028

Timestamp

std.Io.tryLockStderr

function

Source line 2652

Same as lockStderr but non-blocking.

pub fn tryLockStderr(io: Io, buffer: []u8, terminal_mode: ?Terminal.Mode) Cancelable!?LockedStderr

Parameters

io: Io
buffer: []u8
terminal_mode: ?Terminal.Mode

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.TypeErasedQueue

container

Source line 2080

Fields

mutex: Mutex
closed: bool
buffer: []u8

Ring buffer. This data is logically after queued getters.

start: usize
len: usize
putters: std.DoublyLinkedList
getters: std.DoublyLinkedList

std.Io.TypeErasedQueue.close

function

Source line 2124

After this is called, the queue enters a "closed" state. A closed queue always returns error.Closed for put attempts even when there is space in the buffer. However, existing elements of the queue are retrieved before error.Closed is returned.

Idempotent. Threadsafe.

pub fn close(q: *TypeErasedQueue, io: Io) void

Parameters

std.Io.TypeErasedQueue.fillRingBufferFromPutters

function

Source line 2365

Called when there is nonzero space available in the ring buffer and potentially putters waiting. The mutex is already held and the task is to copy putter data to the ring buffer and signal any putters whose buffers been fully copied.

fn fillRingBufferFromPutters(q: *TypeErasedQueue, io: Io) void

Parameters

std.Io.TypeErasedQueue.get

function

Source line 2248

pub fn get(q: *TypeErasedQueue, io: Io, buffer: []u8, min: usize) (QueueClosedError || Cancelable)!usize

Parameters

q: *TypeErasedQueue
io: Io
buffer: []u8
min: usize

std.Io.TypeErasedQueue.Get

container

Source line 2099

Fields

remaining: []u8
needed: usize
condition: Condition
node: std.DoublyLinkedList.Node

std.Io.TypeErasedQueue.getLocked

function

Source line 2276

fn getLocked(q: *TypeErasedQueue, io: Io, buffer: []u8, min: usize, uncancelable: bool) (QueueClosedError || Cancelable)!usize

Parameters

q: *TypeErasedQueue
io: Io
buffer: []u8
min: usize
uncancelable: bool

std.Io.TypeErasedQueue.gettableSlice

function

Source line 2270

fn gettableSlice(q: *const TypeErasedQueue) ?[]const u8

Parameters

q: *const TypeErasedQueue

std.Io.TypeErasedQueue.getUncancelable

function

Source line 2259

Same as get, except does not introduce a cancelation point.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn getUncancelable(q: *TypeErasedQueue, io: Io, buffer: []u8, min: usize) QueueClosedError!usize

Parameters

q: *TypeErasedQueue
io: Io
buffer: []u8
min: usize

Errors

Closed

std.Io.TypeErasedQueue.init

function

Source line 2106

pub fn init(buffer: []u8) TypeErasedQueue

Parameters

buffer: []u8

std.Io.TypeErasedQueue.put

function

Source line 2144

pub fn put(q: *TypeErasedQueue, io: Io, elements: []const u8, min: usize) (QueueClosedError || Cancelable)!usize

Parameters

q: *TypeErasedQueue
io: Io
elements: []const u8
min: usize

std.Io.TypeErasedQueue.Put

container

Source line 2092

Fields

remaining: []const u8
needed: usize
condition: Condition
node: std.DoublyLinkedList.Node

std.Io.TypeErasedQueue.putLocked

function

Source line 2176

fn putLocked(q: *TypeErasedQueue, io: Io, elements: []const u8, min: usize, uncancelable: bool) (QueueClosedError || Cancelable)!usize

Parameters

q: *TypeErasedQueue
io: Io
elements: []const u8
min: usize
uncancelable: bool

std.Io.TypeErasedQueue.puttableSlice

function

Source line 2166

fn puttableSlice(q: *const TypeErasedQueue) ?[]u8

Parameters

q: *const TypeErasedQueue

std.Io.TypeErasedQueue.putUncancelable

function

Source line 2155

Same as put, except does not introduce a cancelation point.

For a description of cancelation and cancelation points, see Future.cancel.

pub fn putUncancelable(q: *TypeErasedQueue, io: Io, elements: []const u8, min: usize) QueueClosedError!usize

Parameters

q: *TypeErasedQueue
io: Io
elements: []const u8
min: usize

Errors

Closed

std.Io.UnexpectedError

error-set

Source line 820

Errors

Unexpected

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.unlockStderr

function

Source line 2658

pub fn unlockStderr(io: Io) void

Parameters

io: Io

std.Io.unreachableAwait

function

Source line 2872

pub fn unreachableAwait( userdata: ?*anyopaque, any_future: *AnyFuture, result: []u8, result_alignment: std.mem.Alignment, ) void

Parameters

userdata: ?*anyopaque
any_future: *AnyFuture
result: []u8
result_alignment: std.mem.Alignment

std.Io.unreachableBatchAwaitAsync

function

Source line 2986

pub fn unreachableBatchAwaitAsync(userdata: ?*anyopaque, b: *Batch) Cancelable!void

Parameters

userdata: ?*anyopaque
b: *Batch

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.unreachableBatchAwaitConcurrent

function

Source line 2992

pub fn unreachableBatchAwaitConcurrent(userdata: ?*anyopaque, b: *Batch, timeout: Timeout) Batch.AwaitConcurrentError!void

Parameters

userdata: ?*anyopaque
b: *Batch
timeout: Timeout

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

ConcurrencyUnavailable ConcurrentError

May occur due to a temporary condition such as resource exhaustion, or to the Io implementation not supporting concurrency.

Timeout Error

std.Io.unreachableBatchCancel

function

Source line 2999

pub fn unreachableBatchCancel(userdata: ?*anyopaque, b: *Batch) void

Parameters

userdata: ?*anyopaque
b: *Batch

std.Io.unreachableCancel

function

Source line 2885

pub fn unreachableCancel( userdata: ?*anyopaque, any_future: *AnyFuture, result: []u8, result_alignment: std.mem.Alignment, ) void

Parameters

userdata: ?*anyopaque
any_future: *AnyFuture
result: []u8
result_alignment: std.mem.Alignment

std.Io.unreachableCheckCancel

function

Source line 2951

pub fn unreachableCheckCancel(userdata: ?*anyopaque) Cancelable!void

Parameters

userdata: ?*anyopaque

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.unreachableChildKill

function

Source line 3478

pub fn unreachableChildKill(userdata: ?*anyopaque, child: *std.process.Child) void

Parameters

userdata: ?*anyopaque
child: *std.process.Child

std.Io.unreachableChildWait

function

Source line 3472

pub fn unreachableChildWait(userdata: ?*anyopaque, child: *std.process.Child) std.process.Child.WaitError!std.process.Child.Term

Parameters

userdata: ?*anyopaque
child: *std.process.Child

Errors

AccessDenied
Canceled Cancelable

Caller has requested the async operation to stop.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.unreachableDirClose

function

Source line 3084

pub fn unreachableDirClose(userdata: ?*anyopaque, dirs: []const Dir) void

Parameters

userdata: ?*anyopaque
dirs: []const Dir

std.Io.unreachableFileClose

function

Source line 3225

pub fn unreachableFileClose(userdata: ?*anyopaque, files: []const File) void

Parameters

userdata: ?*anyopaque
files: []const File

std.Io.unreachableFileEnableAnsiEscapeCodes

function

Source line 3298

pub fn unreachableFileEnableAnsiEscapeCodes(userdata: ?*anyopaque, file: File) File.EnableAnsiEscapeCodesError!void

Parameters

userdata: ?*anyopaque
file: File

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

NotTerminalDevice
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.unreachableFileIsTty

function

Source line 3292

pub fn unreachableFileIsTty(userdata: ?*anyopaque, file: File) Cancelable!bool

Parameters

userdata: ?*anyopaque
file: File

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.unreachableFileMemoryMapDestroy

function

Source line 3388

pub fn unreachableFileMemoryMapDestroy(userdata: ?*anyopaque, mm: *File.MemoryMap) void

Parameters

userdata: ?*anyopaque
mm: *File.MemoryMap

std.Io.unreachableFileMemoryMapRead

function

Source line 3401

pub fn unreachableFileMemoryMapRead(userdata: ?*anyopaque, mm: *File.MemoryMap) File.ReadPositionalError!void

Parameters

userdata: ?*anyopaque
mm: *File.MemoryMap

Errors

AccessDenied

In WASI, this error occurs when the file descriptor does not hold the required rights to read from it.

Canceled Cancelable

Caller has requested the async operation to stop.

InputOutput
IsDir

Trying to read a directory file descriptor as if it were a file.

LockViolation

Unable to read file due to lock. Depending on the Io implementation, reading from a locked file may return this error, or may ignore the lock.

NotOpenForReading

File was not opened with read capability.

SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unseekable

This file cannot be read positionally.

WouldBlock

Non-blocking has been enabled, and reading from the file descriptor would block.

std.Io.unreachableFileMemoryMapSetLength

function

Source line 3394

pub fn unreachableFileMemoryMapSetLength(userdata: ?*anyopaque, mm: *File.MemoryMap, new_len: usize) File.MemoryMap.SetLengthError!void

Parameters

userdata: ?*anyopaque
mm: *File.MemoryMap
new_len: usize

Errors

AccessDenied

One of the following:

  • The File.Kind is not file.
  • The file is not open for reading and read access protections enabled.
  • The file is not open for writing and write access protections enabled.
Canceled Cancelable

Caller has requested the async operation to stop.

FileBusy SetLengthError
FileTooBig SetLengthError
InputOutput SetLengthError
LockedMemoryLimitExceeded
NonResizable SetLengthError
OperationUnsupported

Changing the mapping length could not be done atomically. Caller must use destroy and create to resize the mapping.

OutOfMemory Error
PermissionDenied

The prot argument asks for PROT_EXEC but the mapped area belongs to a file on a filesystem that was mounted no-exec.

ProcessFdQuotaExceeded
SystemFdQuotaExceeded
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.unreachableFileMemoryMapWrite

function

Source line 3407

pub fn unreachableFileMemoryMapWrite(userdata: ?*anyopaque, mm: *File.MemoryMap) File.WritePositionalError!void

Parameters

userdata: ?*anyopaque
mm: *File.MemoryMap

Errors

AccessDenied

File descriptor does not hold the required rights to write to it.

BrokenPipe

File is an unconnected socket, or closed its read end.

Canceled Cancelable

Caller has requested the async operation to stop.

DeviceBusy
DiskQuota
FileBusy
FileTooBig
InputOutput
LockViolation

The process cannot access the file because another process has locked a portion of the file. Windows-only.

NoDevice

This error occurs when a device gets disconnected before or mid-flush while it's being written to - errno(6): No such device or address.

NoSpaceLeft
NotOpenForWriting

File was not opened with write capability.

PermissionDenied
SystemResources

Insufficient kernel memory to read from in_fd.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Unseekable

This file cannot be written positionally.

WouldBlock

Non-blocking has been enabled and this operation would block.

std.Io.unreachableFileSupportsAnsiEscapeCodes

function

Source line 3304

pub fn unreachableFileSupportsAnsiEscapeCodes(userdata: ?*anyopaque, file: File) Cancelable!bool

Parameters

userdata: ?*anyopaque
file: File

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.unreachableFileUnlock

function

Source line 3353

pub fn unreachableFileUnlock(userdata: ?*anyopaque, file: File) void

Parameters

userdata: ?*anyopaque
file: File

std.Io.unreachableGroupAwait

function

Source line 2926

pub fn unreachableGroupAwait(userdata: ?*anyopaque, group: *Group, token: *anyopaque) Cancelable!void

Parameters

userdata: ?*anyopaque
group: *Group
token: *anyopaque

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.unreachableGroupCancel

function

Source line 2933

pub fn unreachableGroupCancel(userdata: ?*anyopaque, group: *Group, token: *anyopaque) void

Parameters

userdata: ?*anyopaque
group: *Group
token: *anyopaque

std.Io.unreachableLockStderr

function

Source line 3425

pub fn unreachableLockStderr(userdata: ?*anyopaque, terminal_mode: ?Terminal.Mode) Cancelable!LockedStderr

Parameters

userdata: ?*anyopaque
terminal_mode: ?Terminal.Mode

Errors

Canceled

Caller has requested the async operation to stop.

std.Io.unreachableNetClose

function

Source line 3586

pub fn unreachableNetClose(userdata: ?*anyopaque, sockets: []const net.Socket) void

Parameters

userdata: ?*anyopaque
sockets: []const net.Socket

std.Io.unreachableNetInterfaceName

function

Source line 3605

pub fn unreachableNetInterfaceName(userdata: ?*anyopaque, interface: net.Interface) net.Interface.NameError!net.Interface.Name

Parameters

userdata: ?*anyopaque
interface: net.Interface

Errors

Canceled Cancelable

Caller has requested the async operation to stop.

InterfaceNotFound

Out of range index.

NameTooLong

Interface name longer than Name.max_len.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.Io.unreachableRecancel

function

Source line 2940

pub fn unreachableRecancel(userdata: ?*anyopaque) void

Parameters

userdata: ?*anyopaque

std.Io.unreachableSwapCancelProtection

function

Source line 2945

pub fn unreachableSwapCancelProtection(userdata: ?*anyopaque, new: CancelProtection) CancelProtection

Parameters

userdata: ?*anyopaque
new: CancelProtection

std.Io.unreachableUnlockStderr

function

Source line 3437

pub fn unreachableUnlockStderr(userdata: ?*anyopaque) void

Parameters

userdata: ?*anyopaque

std.Io.Uring

alias

Source line 39

Alias of std.Io.Uring

std.Io.VTable

container

Source line 51

Fields

crashHandler: *const fn (?*anyopaque) void
async: *const fn (
    /// Corresponds to `Io.userdata`.
    userdata: ?*anyopaque,
    /// The pointer of this slice is an "eager" result value.
    /// The length is the size in bytes of the result type.
    /// This pointer's lifetime expires directly after the call to this function.
    result: []u8,
    result_alignment: std.mem.Alignment,
    /// Copied and then passed to `start`.
    context: []const u8,
    context_alignment: std.mem.Alignment,
    start: *const fn (context: *const anyopaque, result: *anyopaque) void,
) ?*AnyFuture

If it returns null it means result has been already populated and await will be a no-op.

Thread-safe.

concurrent: *const fn (
    /// Corresponds to `Io.userdata`.
    userdata: ?*anyopaque,
    result_len: usize,
    result_alignment: std.mem.Alignment,
    /// Copied and then passed to `start`.
    context: []const u8,
    context_alignment: std.mem.Alignment,
    start: *const fn (context: *const anyopaque, result: *anyopaque) void,
) ConcurrentError!*AnyFuture

Thread-safe.

await: *const fn (
    /// Corresponds to `Io.userdata`.
    userdata: ?*anyopaque,
    /// The same value that was returned from `async`.
    any_future: *AnyFuture,
    /// Points to a buffer where the result is written.
    /// The length is equal to size in bytes of result type.
    result: []u8,
    result_alignment: std.mem.Alignment,
) void

This function is only called when async returns a non-null value.

Thread-safe.

cancel: *const fn (
    /// Corresponds to `Io.userdata`.
    userdata: ?*anyopaque,
    /// The same value that was returned from `async`.
    any_future: *AnyFuture,
    /// Points to a buffer where the result is written.
    /// The length is equal to size in bytes of result type.
    result: []u8,
    result_alignment: std.mem.Alignment,
) void

Equivalent to await but initiates cancel request.

This function is only called when async returns a non-null value.

Thread-safe.

groupAsync: *const fn (
    /// Corresponds to `Io.userdata`.
    userdata: ?*anyopaque,
    /// Owner of the spawned async task.
    group: *Group,
    /// Copied and then passed to `start`.
    context: []const u8,
    context_alignment: std.mem.Alignment,
    start: *const fn (context: *const anyopaque) void,
) void

Thread-safe.

groupConcurrent: *const fn (
    /// Corresponds to `Io.userdata`.
    userdata: ?*anyopaque,
    /// Owner of the spawned async task.
    group: *Group,
    /// Copied and then passed to `start`.
    context: []const u8,
    context_alignment: std.mem.Alignment,
    start: *const fn (context: *const anyopaque) void,
) ConcurrentError!void

Thread-safe.

groupAwait: *const fn (?*anyopaque, *Group, token: *anyopaque) Cancelable!void
groupCancel: *const fn (?*anyopaque, *Group, token: *anyopaque) void
recancel: *const fn (?*anyopaque) void
swapCancelProtection: *const fn (?*anyopaque, new: CancelProtection) CancelProtection
checkCancel: *const fn (?*anyopaque) Cancelable!void
futexWait: *const fn (?*anyopaque, ptr: *const u32, expected: u32, Timeout) Cancelable!void
futexWaitUncancelable: *const fn (?*anyopaque, ptr: *const u32, expected: u32) void
futexWake: *const fn (?*anyopaque, ptr: *const u32, max_waiters: u32) void
operate: *const fn (?*anyopaque, Operation) Cancelable!Operation.Result
batchAwaitAsync: *const fn (?*anyopaque, *Batch) Cancelable!void
batchAwaitConcurrent: *const fn (?*anyopaque, *Batch, Timeout) Batch.AwaitConcurrentError!void
batchCancel: *const fn (?*anyopaque, *Batch) void
dirCreateDir: *const fn (?*anyopaque, Dir, []const u8, Dir.Permissions) Dir.CreateDirError!void
dirCreateDirPath: *const fn (?*anyopaque, Dir, []const u8, Dir.Permissions) Dir.CreateDirPathError!Dir.CreatePathStatus
dirCreateDirPathOpen: *const fn (?*anyopaque, Dir, []const u8, Dir.Permissions, Dir.OpenOptions) Dir.CreateDirPathOpenError!Dir
dirOpenDir: *const fn (?*anyopaque, Dir, []const u8, Dir.OpenOptions) Dir.OpenError!Dir
dirStat: *const fn (?*anyopaque, Dir) Dir.StatError!Dir.Stat
dirStatFile: *const fn (?*anyopaque, Dir, []const u8, Dir.StatFileOptions) Dir.StatFileError!File.Stat
dirAccess: *const fn (?*anyopaque, Dir, []const u8, Dir.AccessOptions) Dir.AccessError!void
dirCreateFile: *const fn (?*anyopaque, Dir, []const u8, Dir.CreateFileOptions) File.OpenError!File
dirCreateFileAtomic: *const fn (?*anyopaque, Dir, []const u8, Dir.CreateFileAtomicOptions) Dir.CreateFileAtomicError!File.Atomic
dirOpenFile: *const fn (?*anyopaque, Dir, []const u8, Dir.OpenFileOptions) File.OpenError!File
dirClose: *const fn (?*anyopaque, []const Dir) void
dirRead: *const fn (?*anyopaque, *Dir.Reader, []Dir.Entry) Dir.Reader.Error!usize
dirRealPath: *const fn (?*anyopaque, Dir, out_buffer: []u8) Dir.RealPathError!usize
dirRealPathFile: *const fn (?*anyopaque, Dir, path_name: []const u8, out_buffer: []u8) Dir.RealPathFileError!usize
dirDeleteFile: *const fn (?*anyopaque, Dir, []const u8) Dir.DeleteFileError!void
dirDeleteDir: *const fn (?*anyopaque, Dir, []const u8) Dir.DeleteDirError!void
dirRename: *const fn (?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenameError!void
dirRenamePreserve: *const fn (?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenamePreserveError!void
dirSymLink: *const fn (?*anyopaque, Dir, target_path: []const u8, sym_link_path: []const u8, Dir.SymLinkFlags) Dir.SymLinkError!void
dirReadLink: *const fn (?*anyopaque, Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usize
dirSetOwner: *const fn (?*anyopaque, Dir, ?File.Uid, ?File.Gid) Dir.SetOwnerError!void
dirSetFileOwner: *const fn (?*anyopaque, Dir, []const u8, ?File.Uid, ?File.Gid, Dir.SetFileOwnerOptions) Dir.SetFileOwnerError!void
dirSetPermissions: *const fn (?*anyopaque, Dir, Dir.Permissions) Dir.SetPermissionsError!void
dirSetFilePermissions: *const fn (?*anyopaque, Dir, []const u8, File.Permissions, Dir.SetFilePermissionsOptions) Dir.SetFilePermissionsError!void
dirSetTimestamps: *const fn (?*anyopaque, Dir, []const u8, Dir.SetTimestampsOptions) Dir.SetTimestampsError!void
dirHardLink: *const fn (?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8, Dir.HardLinkOptions) Dir.HardLinkError!void
fileStat: *const fn (?*anyopaque, File) File.StatError!File.Stat
fileLength: *const fn (?*anyopaque, File) File.LengthError!u64
fileClose: *const fn (?*anyopaque, []const File) void
fileWritePositional: *const fn (?*anyopaque, File, header: []const u8, data: []const []const u8, splat: usize, offset: u64) File.WritePositionalError!usize
fileWriteFileStreaming: *const fn (?*anyopaque, File, header: []const u8, *Io.File.Reader, Io.Limit) File.Writer.WriteFileError!usize
fileWriteFilePositional: *const fn (?*anyopaque, File, header: []const u8, *Io.File.Reader, Io.Limit, offset: u64) File.WriteFilePositionalError!usize
fileReadPositional: *const fn (?*anyopaque, File, data: []const []u8, offset: u64) File.ReadPositionalError!usize

Returns 0 if reading at or past the end.

fileSeekBy: *const fn (?*anyopaque, File, relative_offset: i64) File.SeekError!void
fileSeekTo: *const fn (?*anyopaque, File, absolute_offset: u64) File.SeekError!void
fileSync: *const fn (?*anyopaque, File) File.SyncError!void
fileIsTty: *const fn (?*anyopaque, File) Cancelable!bool
fileEnableAnsiEscapeCodes: *const fn (?*anyopaque, File) File.EnableAnsiEscapeCodesError!void
fileSupportsAnsiEscapeCodes: *const fn (?*anyopaque, File) Cancelable!bool
fileSetLength: *const fn (?*anyopaque, File, u64) File.SetLengthError!void
fileSetOwner: *const fn (?*anyopaque, File, ?File.Uid, ?File.Gid) File.SetOwnerError!void
fileSetPermissions: *const fn (?*anyopaque, File, File.Permissions) File.SetPermissionsError!void
fileSetTimestamps: *const fn (?*anyopaque, File, File.SetTimestampsOptions) File.SetTimestampsError!void
fileLock: *const fn (?*anyopaque, File, File.Lock) File.LockError!void
fileTryLock: *const fn (?*anyopaque, File, File.Lock) File.LockError!bool
fileUnlock: *const fn (?*anyopaque, File) void
fileDowngradeLock: *const fn (?*anyopaque, File) File.DowngradeLockError!void
fileRealPath: *const fn (?*anyopaque, File, out_buffer: []u8) File.RealPathError!usize
fileHardLink: *const fn (?*anyopaque, File, Dir, []const u8, File.HardLinkOptions) File.HardLinkError!void
fileMemoryMapCreate: *const fn (?*anyopaque, File, File.MemoryMap.CreateOptions) File.MemoryMap.CreateError!File.MemoryMap
fileMemoryMapDestroy: *const fn (?*anyopaque, *File.MemoryMap) void
fileMemoryMapSetLength: *const fn (?*anyopaque, *File.MemoryMap, usize) File.MemoryMap.SetLengthError!void
fileMemoryMapRead: *const fn (?*anyopaque, *File.MemoryMap) File.ReadPositionalError!void
fileMemoryMapWrite: *const fn (?*anyopaque, *File.MemoryMap) File.WritePositionalError!void
processExecutableOpen: *const fn (?*anyopaque, Dir.OpenFileOptions) std.process.OpenExecutableError!File
processExecutablePath: *const fn (?*anyopaque, buffer: []u8) std.process.ExecutablePathError!usize
lockStderr: *const fn (?*anyopaque, ?Terminal.Mode) Cancelable!LockedStderr
tryLockStderr: *const fn (?*anyopaque, ?Terminal.Mode) Cancelable!?LockedStderr
unlockStderr: *const fn (?*anyopaque) void
processCurrentPath: *const fn (?*anyopaque, buffer: []u8) std.process.CurrentPathError!usize
processSetCurrentDir: *const fn (?*anyopaque, Dir) std.process.SetCurrentDirError!void
processSetCurrentPath: *const fn (?*anyopaque, []const u8) std.process.SetCurrentPathError!void
processReplace: *const fn (?*anyopaque, std.process.ReplaceOptions) std.process.ReplaceError
processSpawn: *const fn (?*anyopaque, std.process.SpawnOptions) std.process.SpawnError!std.process.Child
childWait: *const fn (?*anyopaque, *std.process.Child) std.process.Child.WaitError!std.process.Child.Term
childKill: *const fn (?*anyopaque, *std.process.Child) void
progressParentFile: *const fn (?*anyopaque) std.Progress.ParentFileError!File
inheritParentDir: *const fn (?*anyopaque, handle: Dir.Handle) InheritParentHandleError!Dir
inheritParentFile: *const fn (?*anyopaque, handle: File.Handle, flags: File.Flags) InheritParentHandleError!File
now: *const fn (?*anyopaque, Clock) Timestamp
clockResolution: *const fn (?*anyopaque, Clock) Clock.ResolutionError!Duration
sleep: *const fn (?*anyopaque, Timeout) Cancelable!void
random: *const fn (?*anyopaque, buffer: []u8) void
randomSecure: *const fn (?*anyopaque, buffer: []u8) RandomSecureError!void
netListenIp: *const fn (?*anyopaque, address: *const net.IpAddress, net.IpAddress.ListenOptions) net.IpAddress.ListenError!net.Socket
netAccept: *const fn (?*anyopaque, server: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socket
netBindIp: *const fn (?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.BindOptions) net.IpAddress.BindError!net.Socket
netConnectIp: *const fn (?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ConnectOptions) net.IpAddress.ConnectError!net.Socket
netListenUnix: *const fn (?*anyopaque, *const net.UnixAddress, net.UnixAddress.ListenOptions) net.UnixAddress.ListenError!net.Socket.Handle
netConnectUnix: *const fn (?*anyopaque, *const net.UnixAddress) net.UnixAddress.ConnectError!net.Socket.Handle
netSocketCreatePair: *const fn (?*anyopaque, net.Socket.CreatePairOptions) net.Socket.CreatePairError![2]net.Socket
netWriteFile: *const fn (?*anyopaque, net.Socket.Handle, header: []const u8, *Io.File.Reader, Io.Limit) net.Stream.Writer.WriteFileError!usize
netClose: *const fn (?*anyopaque, sockets: []const net.Socket) void
netShutdown: *const fn (?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!void
netInterfaceNameResolve: *const fn (?*anyopaque, *const net.Interface.Name) net.Interface.Name.ResolveError!net.Interface
netInterfaceName: *const fn (?*anyopaque, net.Interface) net.Interface.NameError!net.Interface.Name
netLookup: *const fn (?*anyopaque, net.HostName, *Queue(net.HostName.LookupResult), net.HostName.LookupOptions) net.HostName.LookupError!void

std.Io.Writer

alias

Source line 42

Alias of std.Io.Writer

Source code

std/Io.zig

//! A cross-platform interface that abstracts all I/O operations and
//! concurrency. It includes:
//! * file system
//! * networking
//! * processes
//! * time and sleeping
//! * randomness
//! * async, await, concurrent, and cancel
//! * concurrent queues
//! * wait groups and select
//! * mutexes, futexes, events, and conditions
//! * memory mapped files
//! This interface allows programmers to write optimal, reusable code while
//! participating in these operations.
const Io = @This();

const builtin = @import("builtin");

const std = @import("std.zig");
const math = std.math;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Alignment = std.mem.Alignment;

userdata: ?*anyopaque,
vtable: *const VTable,

pub const Threaded = @import("Io/Threaded.zig");

pub const fiber = @import("Io/fiber.zig");
pub const Evented = if (fiber.supported) switch (builtin.os.tag) {
    .linux => Uring,
    .dragonfly, .freebsd, .netbsd, .openbsd => Kqueue,
    .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => Dispatch,
    else => void,
} else void; // context-switching code not implemented yet
pub const Dispatch = @import("Io/Dispatch.zig");
pub const Kqueue = @import("Io/Kqueue.zig");
pub const Uring = @import("Io/Uring.zig");

pub const Reader = @import("Io/Reader.zig");
pub const Writer = @import("Io/Writer.zig");
pub const net = @import("Io/net.zig");
pub const Dir = @import("Io/Dir.zig");
pub const File = @import("Io/File.zig");
pub const Terminal = @import("Io/Terminal.zig");

pub const RwLock = @import("Io/RwLock.zig");
pub const Semaphore = @import("Io/Semaphore.zig");

pub const VTable = struct {
    crashHandler: *const fn (?*anyopaque) void,

    /// If it returns `null` it means `result` has been already populated and
    /// `await` will be a no-op.
    ///
    /// Thread-safe.
    async: *const fn (
        /// Corresponds to `Io.userdata`.
        userdata: ?*anyopaque,
        /// The pointer of this slice is an "eager" result value.
        /// The length is the size in bytes of the result type.
        /// This pointer's lifetime expires directly after the call to this function.
        result: []u8,
        result_alignment: std.mem.Alignment,
        /// Copied and then passed to `start`.
        context: []const u8,
        context_alignment: std.mem.Alignment,
        start: *const fn (context: *const anyopaque, result: *anyopaque) void,
    ) ?*AnyFuture,
    /// Thread-safe.
    concurrent: *const fn (
        /// Corresponds to `Io.userdata`.
        userdata: ?*anyopaque,
        result_len: usize,
        result_alignment: std.mem.Alignment,
        /// Copied and then passed to `start`.
        context: []const u8,
        context_alignment: std.mem.Alignment,
        start: *const fn (context: *const anyopaque, result: *anyopaque) void,
    ) ConcurrentError!*AnyFuture,
    /// This function is only called when `async` returns a non-null value.
    ///
    /// Thread-safe.
    await: *const fn (
        /// Corresponds to `Io.userdata`.
        userdata: ?*anyopaque,
        /// The same value that was returned from `async`.
        any_future: *AnyFuture,
        /// Points to a buffer where the result is written.
        /// The length is equal to size in bytes of result type.
        result: []u8,
        result_alignment: std.mem.Alignment,
    ) void,
    /// Equivalent to `await` but initiates cancel request.
    ///
    /// This function is only called when `async` returns a non-null value.
    ///
    /// Thread-safe.
    cancel: *const fn (
        /// Corresponds to `Io.userdata`.
        userdata: ?*anyopaque,
        /// The same value that was returned from `async`.
        any_future: *AnyFuture,
        /// Points to a buffer where the result is written.
        /// The length is equal to size in bytes of result type.
        result: []u8,
        result_alignment: std.mem.Alignment,
    ) void,

    /// Thread-safe.
    groupAsync: *const fn (
        /// Corresponds to `Io.userdata`.
        userdata: ?*anyopaque,
        /// Owner of the spawned async task.
        group: *Group,
        /// Copied and then passed to `start`.
        context: []const u8,
        context_alignment: std.mem.Alignment,
        start: *const fn (context: *const anyopaque) void,
    ) void,
    /// Thread-safe.
    groupConcurrent: *const fn (
        /// Corresponds to `Io.userdata`.
        userdata: ?*anyopaque,
        /// Owner of the spawned async task.
        group: *Group,
        /// Copied and then passed to `start`.
        context: []const u8,
        context_alignment: std.mem.Alignment,
        start: *const fn (context: *const anyopaque) void,
    ) ConcurrentError!void,
    groupAwait: *const fn (?*anyopaque, *Group, token: *anyopaque) Cancelable!void,
    groupCancel: *const fn (?*anyopaque, *Group, token: *anyopaque) void,

    recancel: *const fn (?*anyopaque) void,
    swapCancelProtection: *const fn (?*anyopaque, new: CancelProtection) CancelProtection,
    checkCancel: *const fn (?*anyopaque) Cancelable!void,

    futexWait: *const fn (?*anyopaque, ptr: *const u32, expected: u32, Timeout) Cancelable!void,
    futexWaitUncancelable: *const fn (?*anyopaque, ptr: *const u32, expected: u32) void,
    futexWake: *const fn (?*anyopaque, ptr: *const u32, max_waiters: u32) void,

    operate: *const fn (?*anyopaque, Operation) Cancelable!Operation.Result,
    batchAwaitAsync: *const fn (?*anyopaque, *Batch) Cancelable!void,
    batchAwaitConcurrent: *const fn (?*anyopaque, *Batch, Timeout) Batch.AwaitConcurrentError!void,
    batchCancel: *const fn (?*anyopaque, *Batch) void,

    dirCreateDir: *const fn (?*anyopaque, Dir, []const u8, Dir.Permissions) Dir.CreateDirError!void,
    dirCreateDirPath: *const fn (?*anyopaque, Dir, []const u8, Dir.Permissions) Dir.CreateDirPathError!Dir.CreatePathStatus,
    dirCreateDirPathOpen: *const fn (?*anyopaque, Dir, []const u8, Dir.Permissions, Dir.OpenOptions) Dir.CreateDirPathOpenError!Dir,
    dirOpenDir: *const fn (?*anyopaque, Dir, []const u8, Dir.OpenOptions) Dir.OpenError!Dir,
    dirStat: *const fn (?*anyopaque, Dir) Dir.StatError!Dir.Stat,
    dirStatFile: *const fn (?*anyopaque, Dir, []const u8, Dir.StatFileOptions) Dir.StatFileError!File.Stat,
    dirAccess: *const fn (?*anyopaque, Dir, []const u8, Dir.AccessOptions) Dir.AccessError!void,
    dirCreateFile: *const fn (?*anyopaque, Dir, []const u8, Dir.CreateFileOptions) File.OpenError!File,
    dirCreateFileAtomic: *const fn (?*anyopaque, Dir, []const u8, Dir.CreateFileAtomicOptions) Dir.CreateFileAtomicError!File.Atomic,
    dirOpenFile: *const fn (?*anyopaque, Dir, []const u8, Dir.OpenFileOptions) File.OpenError!File,
    dirClose: *const fn (?*anyopaque, []const Dir) void,
    dirRead: *const fn (?*anyopaque, *Dir.Reader, []Dir.Entry) Dir.Reader.Error!usize,
    dirRealPath: *const fn (?*anyopaque, Dir, out_buffer: []u8) Dir.RealPathError!usize,
    dirRealPathFile: *const fn (?*anyopaque, Dir, path_name: []const u8, out_buffer: []u8) Dir.RealPathFileError!usize,
    dirDeleteFile: *const fn (?*anyopaque, Dir, []const u8) Dir.DeleteFileError!void,
    dirDeleteDir: *const fn (?*anyopaque, Dir, []const u8) Dir.DeleteDirError!void,
    dirRename: *const fn (?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenameError!void,
    dirRenamePreserve: *const fn (?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenamePreserveError!void,
    dirSymLink: *const fn (?*anyopaque, Dir, target_path: []const u8, sym_link_path: []const u8, Dir.SymLinkFlags) Dir.SymLinkError!void,
    dirReadLink: *const fn (?*anyopaque, Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usize,
    dirSetOwner: *const fn (?*anyopaque, Dir, ?File.Uid, ?File.Gid) Dir.SetOwnerError!void,
    dirSetFileOwner: *const fn (?*anyopaque, Dir, []const u8, ?File.Uid, ?File.Gid, Dir.SetFileOwnerOptions) Dir.SetFileOwnerError!void,
    dirSetPermissions: *const fn (?*anyopaque, Dir, Dir.Permissions) Dir.SetPermissionsError!void,
    dirSetFilePermissions: *const fn (?*anyopaque, Dir, []const u8, File.Permissions, Dir.SetFilePermissionsOptions) Dir.SetFilePermissionsError!void,
    dirSetTimestamps: *const fn (?*anyopaque, Dir, []const u8, Dir.SetTimestampsOptions) Dir.SetTimestampsError!void,
    dirHardLink: *const fn (?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8, Dir.HardLinkOptions) Dir.HardLinkError!void,

    fileStat: *const fn (?*anyopaque, File) File.StatError!File.Stat,
    fileLength: *const fn (?*anyopaque, File) File.LengthError!u64,
    fileClose: *const fn (?*anyopaque, []const File) void,
    fileWritePositional: *const fn (?*anyopaque, File, header: []const u8, data: []const []const u8, splat: usize, offset: u64) File.WritePositionalError!usize,
    fileWriteFileStreaming: *const fn (?*anyopaque, File, header: []const u8, *Io.File.Reader, Io.Limit) File.Writer.WriteFileError!usize,
    fileWriteFilePositional: *const fn (?*anyopaque, File, header: []const u8, *Io.File.Reader, Io.Limit, offset: u64) File.WriteFilePositionalError!usize,
    /// Returns 0 if reading at or past the end.
    fileReadPositional: *const fn (?*anyopaque, File, data: []const []u8, offset: u64) File.ReadPositionalError!usize,
    fileSeekBy: *const fn (?*anyopaque, File, relative_offset: i64) File.SeekError!void,
    fileSeekTo: *const fn (?*anyopaque, File, absolute_offset: u64) File.SeekError!void,
    fileSync: *const fn (?*anyopaque, File) File.SyncError!void,
    fileIsTty: *const fn (?*anyopaque, File) Cancelable!bool,
    fileEnableAnsiEscapeCodes: *const fn (?*anyopaque, File) File.EnableAnsiEscapeCodesError!void,
    fileSupportsAnsiEscapeCodes: *const fn (?*anyopaque, File) Cancelable!bool,
    fileSetLength: *const fn (?*anyopaque, File, u64) File.SetLengthError!void,
    fileSetOwner: *const fn (?*anyopaque, File, ?File.Uid, ?File.Gid) File.SetOwnerError!void,
    fileSetPermissions: *const fn (?*anyopaque, File, File.Permissions) File.SetPermissionsError!void,
    fileSetTimestamps: *const fn (?*anyopaque, File, File.SetTimestampsOptions) File.SetTimestampsError!void,
    fileLock: *const fn (?*anyopaque, File, File.Lock) File.LockError!void,
    fileTryLock: *const fn (?*anyopaque, File, File.Lock) File.LockError!bool,
    fileUnlock: *const fn (?*anyopaque, File) void,
    fileDowngradeLock: *const fn (?*anyopaque, File) File.DowngradeLockError!void,
    fileRealPath: *const fn (?*anyopaque, File, out_buffer: []u8) File.RealPathError!usize,
    fileHardLink: *const fn (?*anyopaque, File, Dir, []const u8, File.HardLinkOptions) File.HardLinkError!void,

    fileMemoryMapCreate: *const fn (?*anyopaque, File, File.MemoryMap.CreateOptions) File.MemoryMap.CreateError!File.MemoryMap,
    fileMemoryMapDestroy: *const fn (?*anyopaque, *File.MemoryMap) void,
    fileMemoryMapSetLength: *const fn (?*anyopaque, *File.MemoryMap, usize) File.MemoryMap.SetLengthError!void,
    fileMemoryMapRead: *const fn (?*anyopaque, *File.MemoryMap) File.ReadPositionalError!void,
    fileMemoryMapWrite: *const fn (?*anyopaque, *File.MemoryMap) File.WritePositionalError!void,

    processExecutableOpen: *const fn (?*anyopaque, Dir.OpenFileOptions) std.process.OpenExecutableError!File,
    processExecutablePath: *const fn (?*anyopaque, buffer: []u8) std.process.ExecutablePathError!usize,
    lockStderr: *const fn (?*anyopaque, ?Terminal.Mode) Cancelable!LockedStderr,
    tryLockStderr: *const fn (?*anyopaque, ?Terminal.Mode) Cancelable!?LockedStderr,
    unlockStderr: *const fn (?*anyopaque) void,
    processCurrentPath: *const fn (?*anyopaque, buffer: []u8) std.process.CurrentPathError!usize,
    processSetCurrentDir: *const fn (?*anyopaque, Dir) std.process.SetCurrentDirError!void,
    processSetCurrentPath: *const fn (?*anyopaque, []const u8) std.process.SetCurrentPathError!void,
    processReplace: *const fn (?*anyopaque, std.process.ReplaceOptions) std.process.ReplaceError,
    processSpawn: *const fn (?*anyopaque, std.process.SpawnOptions) std.process.SpawnError!std.process.Child,
    childWait: *const fn (?*anyopaque, *std.process.Child) std.process.Child.WaitError!std.process.Child.Term,
    childKill: *const fn (?*anyopaque, *std.process.Child) void,

    progressParentFile: *const fn (?*anyopaque) std.Progress.ParentFileError!File,
    inheritParentDir: *const fn (?*anyopaque, handle: Dir.Handle) InheritParentHandleError!Dir,
    inheritParentFile: *const fn (?*anyopaque, handle: File.Handle, flags: File.Flags) InheritParentHandleError!File,

    now: *const fn (?*anyopaque, Clock) Timestamp,
    clockResolution: *const fn (?*anyopaque, Clock) Clock.ResolutionError!Duration,
    sleep: *const fn (?*anyopaque, Timeout) Cancelable!void,

    random: *const fn (?*anyopaque, buffer: []u8) void,
    randomSecure: *const fn (?*anyopaque, buffer: []u8) RandomSecureError!void,

    netListenIp: *const fn (?*anyopaque, address: *const net.IpAddress, net.IpAddress.ListenOptions) net.IpAddress.ListenError!net.Socket,
    netAccept: *const fn (?*anyopaque, server: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socket,
    netBindIp: *const fn (?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.BindOptions) net.IpAddress.BindError!net.Socket,
    netConnectIp: *const fn (?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ConnectOptions) net.IpAddress.ConnectError!net.Socket,
    netListenUnix: *const fn (?*anyopaque, *const net.UnixAddress, net.UnixAddress.ListenOptions) net.UnixAddress.ListenError!net.Socket.Handle,
    netConnectUnix: *const fn (?*anyopaque, *const net.UnixAddress) net.UnixAddress.ConnectError!net.Socket.Handle,
    netSocketCreatePair: *const fn (?*anyopaque, net.Socket.CreatePairOptions) net.Socket.CreatePairError![2]net.Socket,
    netWriteFile: *const fn (?*anyopaque, net.Socket.Handle, header: []const u8, *Io.File.Reader, Io.Limit) net.Stream.Writer.WriteFileError!usize,
    netClose: *const fn (?*anyopaque, sockets: []const net.Socket) void,
    netShutdown: *const fn (?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!void,
    netInterfaceNameResolve: *const fn (?*anyopaque, *const net.Interface.Name) net.Interface.Name.ResolveError!net.Interface,
    netInterfaceName: *const fn (?*anyopaque, net.Interface) net.Interface.NameError!net.Interface.Name,
    netLookup: *const fn (?*anyopaque, net.HostName, *Queue(net.HostName.LookupResult), net.HostName.LookupOptions) net.HostName.LookupError!void,
};

pub const Operation = union(enum) {
    file_read_streaming: FileReadStreaming,
    file_write_streaming: FileWriteStreaming,
    /// On Windows this is NtDeviceIoControlFile. On POSIX this is ioctl. On
    /// other systems this tag is unreachable.
    device_io_control: DeviceIoControl,
    net_receive: NetReceive,
    net_send: NetSend,
    net_read: NetRead,
    net_write: NetWrite,

    pub const Tag = @typeInfo(Operation).@"union".tag_type.?;

    /// May return 0 reads which is different than `error.EndOfStream`.
    pub const FileReadStreaming = struct {
        file: File,
        data: []const []u8,

        pub const Error = UnendingError || error{EndOfStream};
        pub const UnendingError = error{
            InputOutput,
            SystemResources,
            /// Trying to read a directory file descriptor as if it were a file.
            IsDir,
            ConnectionResetByPeer,
            /// File was not opened with read capability.
            NotOpenForReading,
            SocketUnconnected,
            /// Non-blocking has been enabled, and reading from the file descriptor
            /// would block.
            WouldBlock,
            /// In WASI, this error occurs when the file descriptor does
            /// not hold the required rights to read from it.
            AccessDenied,
            /// Unable to read file due to lock. Depending on the `Io` implementation,
            /// reading from a locked file may return this error, or may ignore the
            /// lock.
            LockViolation,
        } || Io.UnexpectedError;

        pub const Result = Error!usize;
    };

    pub const FileWriteStreaming = struct {
        file: File,
        header: []const u8 = &.{},
        data: []const []const u8,
        splat: usize = 1,

        pub const Error = error{
            DiskQuota,
            FileTooBig,
            InputOutput,
            NoSpaceLeft,
            DeviceBusy,
            /// File descriptor does not hold the required rights to write to it.
            AccessDenied,
            PermissionDenied,
            /// File is an unconnected socket, or closed its read end.
            BrokenPipe,
            /// Insufficient kernel memory to read from in_fd.
            SystemResources,
            NotOpenForWriting,
            /// The process cannot access the file because another process has locked
            /// a portion of the file. Windows-only.
            LockViolation,
            /// Non-blocking has been enabled and this operation would block.
            WouldBlock,
            /// This error occurs when a device gets disconnected before or mid-flush
            /// while it's being written to - errno(6): No such device or address.
            NoDevice,
            FileBusy,
        } || Io.UnexpectedError;

        pub const Result = Error!usize;
    };

    pub const DeviceIoControl = switch (builtin.os.tag) {
        .wasi => noreturn,
        .windows => struct {
            file: File,
            code: std.os.windows.CTL_CODE,
            in: []const u8 = &.{},
            out: []u8 = &.{},

            pub const Result = std.os.windows.IO_STATUS_BLOCK;
        },
        else => struct {
            file: File,
            /// Device-dependent operation code.
            code: u32,
            arg: ?*anyopaque,

            /// Device and operation dependent result. Negative values are
            /// negative errno.
            pub const Result = i32;
        },
    };

    pub const NetReceive = struct {
        socket_handle: net.Socket.Handle,
        message_buffer: []net.IncomingMessage,
        data_buffer: []u8,
        flags: net.ReceiveFlags,

        pub const Error = error{
            /// Insufficient memory or other resource internal to the operating system.
            SystemResources,
            /// Per-process limit on the number of open file descriptors has been reached.
            ProcessFdQuotaExceeded,
            /// System-wide limit on the total number of open files has been reached.
            SystemFdQuotaExceeded,
            /// Local end has been shut down on a connection-oriented socket, or
            /// the socket was never connected.
            SocketUnconnected,
            /// The socket type requires that message be sent atomically, and the
            /// size of the message to be sent made this impossible. The message
            /// was not transmitted, or was partially transmitted.
            MessageOversize,
            /// Network connection was unexpectedly closed by sender.
            ConnectionResetByPeer,
            /// The local network interface used to reach the destination is offline.
            NetworkDown,
            /// A connectionless packet was previously sent successfully,
            /// however, it was not received because no service is operating at
            /// the destination port of the transport on the remote system.
            /// This caused an ICMP port unreachable packet to be returned to
            /// the OS where it was queued up to be reported at the next call
            /// to send or receive on the bound socket.
            PortUnreachable,
            /// The remote peer did not respond to ongoing communication, causing the
            /// OS to abort the connection.
            ConnectionTimedOut,
        } || Io.UnexpectedError;

        pub const Result = struct { ?net.Socket.ReceiveError, usize };
    };

    pub const NetSend = struct {
        socket_handle: net.Socket.Handle,
        messages: []net.OutgoingMessage,
        flags: net.SendFlags,

        pub const Error = error{
            /// The socket type requires that message be sent atomically, and the
            /// size of the message to be sent made this impossible. The message
            /// was not transmitted, or was partially transmitted.
            MessageOversize,
            /// The output queue for a network interface was full. This generally indicates that the
            /// interface has stopped sending, but may be caused by transient congestion. (Normally,
            /// this does not occur in Linux. Packets are just silently dropped when a device queue
            /// overflows.)
            ///
            /// This is also caused when there is not enough kernel memory available.
            SystemResources,
            /// No route to network.
            NetworkUnreachable,
            /// Network reached but no route to host.
            HostUnreachable,
            /// The local network interface used to reach the destination is offline.
            NetworkDown,
            /// The destination address is not listening. Can still occur for
            /// connectionless messages.
            ConnectionRefused,
            /// Operating system or protocol does not support the address family.
            AddressFamilyUnsupported,
            /// Another TCP Fast Open is already in progress.
            FastOpenAlreadyInProgress,
            /// Network session was unexpectedly closed by recipient.
            ConnectionResetByPeer,
            /// Local end has been shut down on a connection-oriented socket, or
            /// the socket was never connected.
            SocketUnconnected,
            /// An attempt was made to send to a network/broadcast address as
            /// though it was a unicast address.
            AccessDenied,
            /// The remote peer did not respond to ongoing communication, causing the
            /// OS to abort the connection.
            ConnectionTimedOut,
        } || Io.UnexpectedError;

        pub const Result = struct { ?net.Socket.SendError, usize };
    };

    pub const NetRead = struct {
        socket_handle: net.Socket.Handle,
        data: [][]u8,
        control: []u8 = &.{},

        pub const Error = error{
            SystemResources,
            ConnectionResetByPeer,
            SocketUnconnected,
            /// File descriptor does not hold the required rights to read from it.
            AccessDenied,
            NetworkDown,
            /// The remote peer did not respond to ongoing communication, causing the
            /// OS to abort the connection.
            ConnectionTimedOut,
        } || Io.UnexpectedError;

        pub const Result = Error!net.Stream.ReadResult;
    };

    pub const NetWrite = struct {
        socket_handle: net.Socket.Handle,
        header: []const u8 = &.{},
        data: []const []const u8,
        splat: usize = 1,
        control: []const u8 = &.{},

        pub const Error = error{
            /// Another TCP Fast Open is already in progress.
            FastOpenAlreadyInProgress,
            /// Network session was unexpectedly closed by recipient.
            ConnectionResetByPeer,
            /// The output queue for a network interface was full. This generally indicates that the
            /// interface has stopped sending, but may be caused by transient congestion. (Normally,
            /// this does not occur in Linux. Packets are just silently dropped when a device queue
            /// overflows.)
            ///
            /// This is also caused when there is not enough kernel memory available.
            SystemResources,
            /// No route to network.
            NetworkUnreachable,
            /// Network reached but no route to host.
            HostUnreachable,
            /// The local network interface used to reach the destination is down.
            NetworkDown,
            /// The destination address is not listening.
            ConnectionRefused,
            /// The passed address didn't have the correct address family in its sa_family field.
            AddressFamilyUnsupported,
            /// Local end has been shut down on a connection-oriented socket, or
            /// the socket was never connected.
            SocketUnconnected,
            /// The remote peer did not respond to ongoing communication, causing the
            /// OS to abort the connection.
            ConnectionTimedOut,
            SocketNotBound,
        } || Io.UnexpectedError;

        pub const Result = Error!usize;
    };

    pub const Result = Result: {
        const operation_info = @typeInfo(Operation).@"union";
        const operation_count = operation_info.field_names.len;
        var field_names: [operation_count][]const u8 = undefined;
        var field_types: [operation_count]type = undefined;
        for (operation_info.field_names, operation_info.field_types, &field_names, &field_types) |f_name, f_type, *field_name, *field_type| {
            field_name.* = f_name;
            field_type.* = if (f_type == noreturn) noreturn else f_type.Result;
        }
        break :Result @Union(.auto, Tag, &field_names, &field_types, &@splat(.{}));
    };

    pub const Storage = union {
        unused: List.DoubleNode,
        submission: Submission,
        pending: Pending,
        completion: Completion,

        pub const Submission = struct {
            node: List.SingleNode,
            operation: Operation,
        };

        pub const Pending = struct {
            node: List.DoubleNode,
            tag: Tag,
            userdata: Userdata align(@max(@alignOf(usize), 4)),

            pub const Userdata = [7]usize;
        };

        pub const Completion = struct {
            node: List.SingleNode,
            result: Result,
        };
    };

    pub const OptionalIndex = enum(u32) {
        none = std.math.maxInt(u32),
        _,

        pub fn fromIndex(i: usize) OptionalIndex {
            const oi: OptionalIndex = @fromBackingInt(@intCast(i));
            assert(oi != .none);
            return oi;
        }

        pub fn toIndex(oi: OptionalIndex) u32 {
            assert(oi != .none);
            return @backingInt(oi);
        }
    };
    pub const List = struct {
        head: OptionalIndex,
        tail: OptionalIndex,

        pub const empty: List = .{ .head = .none, .tail = .none };

        pub const SingleNode = struct { next: OptionalIndex };
        pub const DoubleNode = struct { prev: OptionalIndex, next: OptionalIndex };
    };
};

/// Performs one `Operation`.
pub fn operate(io: Io, operation: Operation) Cancelable!Operation.Result {
    return io.vtable.operate(io.userdata, operation);
}

pub const OperateTimeoutError = Cancelable || Timeout.Error || ConcurrentError;

/// Performs one `Operation` with provided `timeout`.
pub fn operateTimeout(io: Io, operation: Operation, timeout: Timeout) OperateTimeoutError!Operation.Result {
    if (timeout == .none) return io.vtable.operate(io.userdata, operation);
    var storage: [1]Operation.Storage = undefined;
    var batch: Batch = .init(&storage);
    batch.addAt(0, operation);
    try batch.awaitConcurrent(io, timeout);
    const completion = batch.next().?;
    assert(completion.index == 0);
    return completion.result;
}

/// Submits many operations together without waiting for all of them to
/// complete.
///
/// This is a low-level abstraction based on `Operation`. For a higher
/// level API that operates on `Future`, see `Select` and `Group`.
pub const Batch = struct {
    storage: []Operation.Storage,
    unused: Operation.List,
    submitted: Operation.List,
    pending: Operation.List,
    completed: Operation.List,
    userdata: ?*anyopaque align(@max(@alignOf(?*anyopaque), 4)),

    /// After calling this, it is safe to unconditionally defer a call to
    /// `cancel`. `storage` is a pre-allocated buffer of undefined memory that
    /// determines the maximum number of active operations that can be
    /// submitted via `add` and `addAt`.
    pub fn init(storage: []Operation.Storage) Batch {
        var prev: Operation.OptionalIndex = .none;
        for (storage, 0..) |*operation, index| {
            operation.* = .{ .unused = .{ .prev = prev, .next = .fromIndex(index + 1) } };
            prev = .fromIndex(index);
        }
        storage[storage.len - 1].unused.next = .none;
        return .{
            .storage = storage,
            .unused = .{
                .head = .fromIndex(0),
                .tail = .fromIndex(storage.len - 1),
            },
            .submitted = .empty,
            .pending = .empty,
            .completed = .empty,
            .userdata = null,
        };
    }

    /// Adds an operation to be performed at the next await call.
    /// Returns the index that will be returned by `next` after the operation completes.
    /// Asserts that no more than `storage.len` operations are active at a time.
    pub fn add(batch: *Batch, operation: Operation) u32 {
        const index = batch.unused.head.toIndex();
        batch.addAt(index, operation);
        return index;
    }

    /// Adds an operation to be performed at the next await call.
    /// After the operation completes, `next` will return `index`.
    /// Asserts that the operation at `index` is not active.
    pub fn addAt(batch: *Batch, index: u32, operation: Operation) void {
        const storage = &batch.storage[index];
        const unused = storage.unused;
        switch (unused.prev) {
            .none => batch.unused.head = unused.next,
            else => |prev_index| batch.storage[prev_index.toIndex()].unused.next = unused.next,
        }
        switch (unused.next) {
            .none => batch.unused.tail = unused.prev,
            else => |next_index| batch.storage[next_index.toIndex()].unused.prev = unused.prev,
        }

        switch (batch.submitted.tail) {
            .none => batch.submitted.head = .fromIndex(index),
            else => |tail_index| batch.storage[tail_index.toIndex()].submission.node.next = .fromIndex(index),
        }
        storage.* = .{ .submission = .{ .node = .{ .next = .none }, .operation = operation } };
        batch.submitted.tail = .fromIndex(index);
    }

    pub const Completion = struct {
        /// The element within the provided operation storage that completed.
        /// `addAt` can be used to re-arm the `Batch` using this `index`.
        index: u32,
        /// The return value of the operation.
        result: Operation.Result,
    };

    /// After calling `awaitAsync`, `awaitConcurrent`, or `cancel`, this
    /// function iterates over the completed operations.
    ///
    /// Each completion returned from this function dequeues from the `Batch`.
    /// It is not required to dequeue all completions before awaiting again.
    pub fn next(batch: *Batch) ?Completion {
        const index = batch.completed.head;
        if (index == .none) return null;
        const storage = &batch.storage[index.toIndex()];
        const completion = storage.completion;
        const next_index = completion.node.next;
        batch.completed.head = next_index;
        if (next_index == .none) batch.completed.tail = .none;

        const tail_index = batch.unused.tail;
        switch (tail_index) {
            .none => batch.unused.head = index,
            else => batch.storage[tail_index.toIndex()].unused.next = index,
        }
        storage.* = .{ .unused = .{ .prev = tail_index, .next = .none } };
        batch.unused.tail = index;
        return .{ .index = index.toIndex(), .result = completion.result };
    }

    /// Waits for at least one of the submitted operations to complete. After
    /// this function returns the completed operations can be iterated with
    /// `next`.
    ///
    /// This function provides opportunity for the implementation to introduce
    /// concurrency into the batched operations, but unlike `awaitConcurrent`,
    /// does not require it, and therefore cannot fail with
    /// `error.ConcurrencyUnavailable`.
    pub fn awaitAsync(batch: *Batch, io: Io) Cancelable!void {
        return io.vtable.batchAwaitAsync(io.userdata, batch);
    }

    pub const AwaitConcurrentError = ConcurrentError || Cancelable || Timeout.Error;

    /// Waits for at least one of the submitted operations to complete. After
    /// this function returns the completed operations can be iterated with
    /// `next`.
    ///
    /// Unlike `awaitAsync`, this function requires the implementation to
    /// perform the operations concurrently and therefore can fail with
    /// `error.ConcurrencyUnavailable`.
    pub fn awaitConcurrent(batch: *Batch, io: Io, timeout: Timeout) AwaitConcurrentError!void {
        return io.vtable.batchAwaitConcurrent(io.userdata, batch, timeout);
    }

    /// Requests all pending operations to be interrupted, then waits for all
    /// pending operations to complete. After this returns, the `Batch` is in a
    /// well-defined state, ready to be iterated with `next`. Successfully
    /// canceled operations will be absent from the iteration. Some operations
    /// may have successfully completed regardless of the cancel request and
    /// will appear in the iteration.
    pub fn cancel(batch: *Batch, io: Io) void {
        { // abort pending submissions
            var tail_index = batch.unused.tail;
            defer batch.unused.tail = tail_index;
            var index = batch.submitted.head;
            errdefer batch.submissions.head = index;
            while (index != .none) {
                const next_index = batch.storage[index.toIndex()].submission.node.next;
                switch (tail_index) {
                    .none => batch.unused.head = index,
                    else => batch.storage[tail_index.toIndex()].unused.next = index,
                }
                batch.storage[index.toIndex()] = .{ .unused = .{ .prev = tail_index, .next = .none } };
                tail_index = index;
                index = next_index;
            }
            batch.submitted = .{ .head = .none, .tail = .none };
        }
        io.vtable.batchCancel(io.userdata, batch);
        assert(batch.submitted.head == .none and batch.submitted.tail == .none);
        assert(batch.pending.head == .none and batch.pending.tail == .none);
        assert(batch.userdata == null); // that was the last chance to deallocate resources
    }
};

pub const Limit = enum(usize) {
    nothing = 0,
    unlimited = math.maxInt(usize),
    _,

    /// `math.maxInt(usize)` is interpreted to mean `.unlimited`.
    pub fn limited(n: usize) Limit {
        return @fromBackingInt(@intCast(n));
    }

    /// Any value grater than `math.maxInt(usize)` is interpreted to mean
    /// `.unlimited`.
    pub fn limited64(n: u64) Limit {
        return @fromBackingInt(@intCast(@min(n, math.maxInt(usize))));
    }

    pub fn countVec(data: []const []const u8) Limit {
        var total: usize = 0;
        for (data) |d| total += d.len;
        return .limited(total);
    }

    pub fn min(a: Limit, b: Limit) Limit {
        return @fromBackingInt(@intCast(@min(@backingInt(a), @backingInt(b))));
    }

    pub fn max(a: Limit, b: Limit) Limit {
        if (a == .unlimited or b == .unlimited) {
            return .unlimited;
        }

        return @fromBackingInt(@intCast(@max(@backingInt(a), @backingInt(b))));
    }

    pub fn minInt(l: Limit, n: usize) usize {
        return @min(n, @backingInt(l));
    }

    pub fn minInt64(l: Limit, n: u64) usize {
        return @min(n, @backingInt(l));
    }

    pub fn slice(l: Limit, s: []u8) []u8 {
        return s[0..l.minInt(s.len)];
    }

    pub fn sliceConst(l: Limit, s: []const u8) []const u8 {
        return s[0..l.minInt(s.len)];
    }

    pub fn toInt(l: Limit) ?usize {
        return switch (l) {
            else => @backingInt(l),
            .unlimited => null,
        };
    }

    pub fn toInt64(l: Limit) ?u64 {
        return switch (l) {
            else => @backingInt(l),
            .unlimited => null,
        };
    }

    /// Reduces a slice to account for the limit, leaving room for one extra
    /// byte above the limit, allowing for the use case of differentiating
    /// between end-of-stream and reaching the limit.
    pub fn slice1(l: Limit, non_empty_buffer: []u8) []u8 {
        assert(non_empty_buffer.len >= 1);
        return non_empty_buffer[0..@min(@backingInt(l) +| 1, non_empty_buffer.len)];
    }

    pub fn nonzero(l: Limit) bool {
        return l != .nothing;
    }

    /// Return a new limit reduced by `amount` or return `null` indicating
    /// limit would be exceeded.
    pub fn subtract(l: Limit, amount: usize) ?Limit {
        if (l == .unlimited) return .unlimited;
        if (amount > @backingInt(l)) return null;
        return @fromBackingInt(@intCast(@backingInt(l) - amount));
    }
};

pub const Cancelable = error{
    /// Caller has requested the async operation to stop.
    Canceled,
};

pub const UnexpectedError = error{
    /// The Operating System returned an undocumented error code.
    ///
    /// This error is in theory not possible, but it would be better
    /// to handle this error than to invoke undefined behavior.
    ///
    /// When this error code is observed, it usually means the Zig Standard
    /// Library needs a small patch to add the error code to the error set for
    /// the respective function.
    Unexpected,
};

pub const InheritParentHandleError = error{
    UnsupportedOperation,
} || Cancelable || UnexpectedError;

pub const Clock = enum {
    /// A settable system-wide clock that measures real (i.e. wall-clock)
    /// time. This clock is affected by discontinuous jumps in the system
    /// time (e.g., if the system administrator manually changes the
    /// clock), and by frequency adjustments performed by NTP and similar
    /// applications.
    ///
    /// This clock normally counts the number of seconds since 1970-01-01
    /// 00:00:00 Coordinated Universal Time (UTC) except that it ignores
    /// leap seconds; near a leap second it is typically adjusted by NTP to
    /// stay roughly in sync with UTC.
    ///
    /// Timestamps returned by implementations of this clock represent time
    /// elapsed since 1970-01-01T00:00:00Z, the POSIX/Unix epoch, ignoring
    /// leap seconds. This is colloquially known as "Unix time". If the
    /// underlying OS uses a different epoch for native timestamps (e.g.,
    /// Windows, which uses 1601-01-01) they are translated accordingly.
    real,
    /// A nonsettable system-wide clock that represents time since some
    /// unspecified point in the past.
    ///
    /// Monotonic: Guarantees that the time returned by consecutive calls
    /// will not go backwards, but successive calls may return identical
    /// (not-increased) time values.
    ///
    /// Not affected by discontinuous jumps in the system time (e.g., if
    /// the system administrator manually changes the clock), but may be
    /// affected by frequency adjustments.
    ///
    /// This clock expresses intent to **exclude time that the system is
    /// suspended**. However, implementations may be unable to satisify
    /// this, and may include that time.
    ///
    /// * On Linux, corresponds `CLOCK_MONOTONIC`.
    /// * On macOS, corresponds to `CLOCK_UPTIME_RAW`.
    awake,
    /// Identical to `awake` except it expresses intent to **include time
    /// that the system is suspended**, however, due to limitations it may
    /// behave identically to `awake`.
    ///
    /// * On Linux, corresponds `CLOCK_BOOTTIME`.
    /// * On macOS, corresponds to `CLOCK_MONOTONIC_RAW`.
    boot,
    /// Tracks the amount of CPU time in user or kernel mode used by the calling
    /// process.
    cpu_process,
    /// Tracks the amount of CPU time in user or kernel mode used by the calling
    /// thread.
    cpu_thread,

    /// This function is not cancelable because it does not block.
    ///
    /// Resolution is determined by `resolution` which may be 0 if the
    /// clock is unsupported.
    ///
    /// See also:
    /// * `Clock.Timestamp.now`
    pub fn now(clock: Clock, io: Io) Io.Timestamp {
        return io.vtable.now(io.userdata, clock);
    }

    pub const ResolutionError = error{
        ClockUnavailable,
        Unexpected,
    };

    /// Reveals the granularity of `clock`. May be zero, indicating
    /// unsupported clock.
    pub fn resolution(clock: Clock, io: Io) ResolutionError!Io.Duration {
        return io.vtable.clockResolution(io.userdata, clock);
    }

    pub const Timestamp = struct {
        raw: Io.Timestamp,
        clock: Clock,

        /// This function is not cancelable because it does not block.
        ///
        /// Resolution is determined by `resolution` which may be 0 if
        /// the clock is unsupported.
        ///
        /// See also:
        /// * `Clock.now`
        pub fn now(io: Io, clock: Clock) Clock.Timestamp {
            return .{
                .raw = io.vtable.now(io.userdata, clock),
                .clock = clock,
            };
        }

        /// Sleeps until the timestamp arrives.
        ///
        /// See also:
        /// * `Io.sleep`
        /// * `Clock.Duration.sleep`
        /// * `Timeout.sleep`
        pub fn wait(t: Clock.Timestamp, io: Io) Cancelable!void {
            return io.vtable.sleep(io.userdata, .{ .deadline = t });
        }

        pub fn durationTo(from: Clock.Timestamp, to: Clock.Timestamp) Clock.Duration {
            assert(from.clock == to.clock);
            return .{
                .raw = from.raw.durationTo(to.raw),
                .clock = from.clock,
            };
        }

        pub fn addDuration(from: Clock.Timestamp, duration: Clock.Duration) Clock.Timestamp {
            assert(from.clock == duration.clock);
            return .{
                .raw = from.raw.addDuration(duration.raw),
                .clock = from.clock,
            };
        }

        pub fn subDuration(from: Clock.Timestamp, duration: Clock.Duration) Clock.Timestamp {
            assert(from.clock == duration.clock);
            return .{
                .raw = from.raw.subDuration(duration.raw),
                .clock = from.clock,
            };
        }

        /// Resolution is determined by `resolution` which may be 0 if
        /// the clock is unsupported.
        pub fn fromNow(io: Io, duration: Clock.Duration) Clock.Timestamp {
            return .{
                .clock = duration.clock,
                .raw = duration.clock.now(io).addDuration(duration.raw),
            };
        }

        /// Resolution is determined by `resolution` which may be 0 if
        /// the clock is unsupported.
        pub fn untilNow(timestamp: Clock.Timestamp, io: Io) Clock.Duration {
            const now_ts = Clock.Timestamp.now(io, timestamp.clock);
            return timestamp.durationTo(now_ts);
        }

        /// Resolution is determined by `resolution` which may be 0 if
        /// the clock is unsupported.
        pub fn durationFromNow(timestamp: Clock.Timestamp, io: Io) Clock.Duration {
            const now_ts = timestamp.clock.now(io);
            return .{
                .clock = timestamp.clock,
                .raw = now_ts.durationTo(timestamp.raw),
            };
        }

        /// Resolution is determined by `resolution` which may be 0 if
        /// the clock is unsupported.
        pub fn toClock(t: Clock.Timestamp, io: Io, clock: Clock) Clock.Timestamp {
            if (t.clock == clock) return t;
            const now_old = t.clock.now(io);
            const now_new = clock.now(io);
            const duration = now_old.durationTo(t.raw);
            return .{
                .clock = clock,
                .raw = now_new.addDuration(duration),
            };
        }

        pub fn compare(lhs: Clock.Timestamp, op: math.CompareOperator, rhs: Clock.Timestamp) bool {
            assert(lhs.clock == rhs.clock);
            return math.compare(lhs.raw.nanoseconds, op, rhs.raw.nanoseconds);
        }
    };

    pub const Duration = struct {
        raw: Io.Duration,
        clock: Clock,

        /// Waits until a specified amount of time has passed on `clock`.
        ///
        /// See also:
        /// * `Io.sleep`
        /// * `Clock.Timestamp.wait`
        /// * `Timeout.sleep`
        pub fn sleep(duration: Clock.Duration, io: Io) Cancelable!void {
            return io.vtable.sleep(io.userdata, .{ .duration = duration });
        }
    };
};

pub const Timestamp = struct {
    nanoseconds: i96,

    pub fn now(io: Io, clock: Clock) Io.Timestamp {
        return io.vtable.now(io.userdata, clock);
    }

    pub const zero: Timestamp = .{ .nanoseconds = 0 };

    pub fn durationTo(from: Timestamp, to: Timestamp) Duration {
        return .{ .nanoseconds = to.nanoseconds - from.nanoseconds };
    }

    pub fn addDuration(from: Timestamp, duration: Duration) Timestamp {
        return .{ .nanoseconds = from.nanoseconds + duration.nanoseconds };
    }

    pub fn subDuration(from: Timestamp, duration: Duration) Timestamp {
        return .{ .nanoseconds = from.nanoseconds - duration.nanoseconds };
    }

    pub fn withClock(t: Timestamp, clock: Clock) Clock.Timestamp {
        return .{ .raw = t, .clock = clock };
    }

    pub fn fromNanoseconds(x: i96) Timestamp {
        return .{ .nanoseconds = x };
    }

    pub fn toMicroseconds(t: Timestamp) i64 {
        return @intCast(@divTrunc(t.nanoseconds, std.time.ns_per_us));
    }

    pub fn toMilliseconds(t: Timestamp) i64 {
        return @intCast(@divTrunc(t.nanoseconds, std.time.ns_per_ms));
    }

    pub fn toSeconds(t: Timestamp) i64 {
        return @intCast(@divTrunc(t.nanoseconds, std.time.ns_per_s));
    }

    pub fn toNanoseconds(t: Timestamp) i96 {
        return t.nanoseconds;
    }

    pub fn formatNumber(t: Timestamp, w: *std.Io.Writer, n: std.fmt.Number) std.Io.Writer.Error!void {
        return w.printInt(t.nanoseconds, n.mode.base() orelse 10, n.case, .{
            .precision = n.precision,
            .width = n.width,
            .alignment = n.alignment,
            .fill = n.fill,
        });
    }

    /// Resolution is determined by `Clock.resolution` which may be 0 if
    /// the clock is unsupported.
    pub fn untilNow(t: Timestamp, io: Io, clock: Clock) Duration {
        const now_ts = clock.now(io);
        return t.durationTo(now_ts);
    }

    pub fn compare(lhs: Timestamp, op: math.CompareOperator, rhs: Timestamp) bool {
        return math.compare(lhs.nanoseconds, op, rhs.nanoseconds);
    }
};

pub const Duration = struct {
    nanoseconds: i96,

    pub const zero: Duration = .{ .nanoseconds = 0 };
    pub const max: Duration = .{ .nanoseconds = math.maxInt(i96) };

    pub fn fromNanoseconds(x: i96) Duration {
        return .{ .nanoseconds = x };
    }

    pub fn fromMicroseconds(x: i64) Duration {
        return .{ .nanoseconds = @as(i96, x) * std.time.ns_per_us };
    }

    pub fn fromMilliseconds(x: i64) Duration {
        return .{ .nanoseconds = @as(i96, x) * std.time.ns_per_ms };
    }

    pub fn fromSeconds(x: i64) Duration {
        return .{ .nanoseconds = @as(i96, x) * std.time.ns_per_s };
    }

    pub fn toMicroseconds(d: Duration) i64 {
        return @intCast(@divTrunc(d.nanoseconds, std.time.ns_per_us));
    }

    pub fn toMilliseconds(d: Duration) i64 {
        return @intCast(@divTrunc(d.nanoseconds, std.time.ns_per_ms));
    }

    pub fn toSeconds(d: Duration) i64 {
        return @intCast(@divTrunc(d.nanoseconds, std.time.ns_per_s));
    }

    pub fn toNanoseconds(d: Duration) i96 {
        return d.nanoseconds;
    }

    /// Write number of nanoseconds according to its signed magnitude:
    /// `[#y][#w][#d][#h][#m]#[.###][n|u|m]s`
    pub fn format(duration: Duration, w: *Writer) Writer.Error!void {
        if (duration.nanoseconds < 0) try w.writeByte('-');
        return formatUnsigned(w, @abs(duration.nanoseconds));
    }

    fn formatUnsigned(w: *Writer, ns: u96) Writer.Error!void {
        var ns_remaining = ns;
        inline for (.{
            .{ .ns = 365 * std.time.ns_per_day, .sep = 'y' },
            .{ .ns = std.time.ns_per_week, .sep = 'w' },
            .{ .ns = std.time.ns_per_day, .sep = 'd' },
            .{ .ns = std.time.ns_per_hour, .sep = 'h' },
            .{ .ns = std.time.ns_per_min, .sep = 'm' },
        }) |unit| {
            if (ns_remaining >= unit.ns) {
                const units = ns_remaining / unit.ns;
                try w.printInt(units, 10, .lower, .{});
                try w.writeByte(unit.sep);
                ns_remaining -= units * unit.ns;
                if (ns_remaining == 0) return;
            }
        }

        inline for (.{
            .{ .ns = std.time.ns_per_s, .sep = "s" },
            .{ .ns = std.time.ns_per_ms, .sep = "ms" },
            .{ .ns = std.time.ns_per_us, .sep = "us" },
        }) |unit| {
            const kunits = ns_remaining * 1000 / unit.ns;
            if (kunits >= 1000) {
                try w.printInt(kunits / 1000, 10, .lower, .{});
                const frac = kunits % 1000;
                if (frac > 0) {
                    // Write up to 3 decimal places
                    var decimal_buf = [_]u8{ '.', 0, 0, 0 };
                    var inner: Writer = .fixed(decimal_buf[1..]);
                    inner.printInt(frac, 10, .lower, .{ .fill = '0', .width = 3 }) catch unreachable;
                    var end: usize = 4;
                    while (end > 1) : (end -= 1) {
                        if (decimal_buf[end - 1] != '0') break;
                    }
                    try w.writeAll(decimal_buf[0..end]);
                }
                return w.writeAll(unit.sep);
            }
        }

        try w.printInt(ns_remaining, 10, .lower, .{});
        try w.writeAll("ns");
    }

    test format {
        try testFormat("0ns", 0);
        try testFormat("1ns", 1);
        try testFormat("-1ns", -(1));
        try testFormat("999ns", std.time.ns_per_us - 1);
        try testFormat("-999ns", -(std.time.ns_per_us - 1));
        try testFormat("1us", std.time.ns_per_us);
        try testFormat("-1us", -(std.time.ns_per_us));
        try testFormat("1.45us", 1450);
        try testFormat("-1.45us", -(1450));
        try testFormat("1.5us", 3 * std.time.ns_per_us / 2);
        try testFormat("-1.5us", -(3 * std.time.ns_per_us / 2));
        try testFormat("14.5us", 14500);
        try testFormat("-14.5us", -(14500));
        try testFormat("145us", 145000);
        try testFormat("-145us", -(145000));
        try testFormat("999.999us", std.time.ns_per_ms - 1);
        try testFormat("-999.999us", -(std.time.ns_per_ms - 1));
        try testFormat("1ms", std.time.ns_per_ms + 1);
        try testFormat("-1ms", -(std.time.ns_per_ms + 1));
        try testFormat("1.5ms", 3 * std.time.ns_per_ms / 2);
        try testFormat("-1.5ms", -(3 * std.time.ns_per_ms / 2));
        try testFormat("1.11ms", 1110000);
        try testFormat("-1.11ms", -(1110000));
        try testFormat("1.111ms", 1111000);
        try testFormat("-1.111ms", -(1111000));
        try testFormat("1.111ms", 1111100);
        try testFormat("-1.111ms", -(1111100));
        try testFormat("999.999ms", std.time.ns_per_s - 1);
        try testFormat("-999.999ms", -(std.time.ns_per_s - 1));
        try testFormat("1s", std.time.ns_per_s);
        try testFormat("-1s", -(std.time.ns_per_s));
        try testFormat("59.999s", std.time.ns_per_min - 1);
        try testFormat("-59.999s", -(std.time.ns_per_min - 1));
        try testFormat("1m", std.time.ns_per_min);
        try testFormat("-1m", -(std.time.ns_per_min));
        try testFormat("1h", std.time.ns_per_hour);
        try testFormat("-1h", -(std.time.ns_per_hour));
        try testFormat("1d", std.time.ns_per_day);
        try testFormat("-1d", -(std.time.ns_per_day));
        try testFormat("1w", std.time.ns_per_week);
        try testFormat("-1w", -(std.time.ns_per_week));
        try testFormat("1y", 365 * std.time.ns_per_day);
        try testFormat("-1y", -(365 * std.time.ns_per_day));
        try testFormat("1y52w23h59m59.999s", 730 * std.time.ns_per_day - 1); // 365d = 52w1d
        try testFormat("-1y52w23h59m59.999s", -(730 * std.time.ns_per_day - 1)); // 365d = 52w1d
        try testFormat("1y1h1.001s", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + std.time.ns_per_ms);
        try testFormat("-1y1h1.001s", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + std.time.ns_per_ms));
        try testFormat("1y1h1s", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + 999 * std.time.ns_per_us);
        try testFormat("-1y1h1s", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + 999 * std.time.ns_per_us));
        try testFormat("1y1h999.999us", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms - 1);
        try testFormat("-1y1h999.999us", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms - 1));
        try testFormat("1y1h1ms", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms);
        try testFormat("-1y1h1ms", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms));
        try testFormat("1y1h1ms", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms + 1);
        try testFormat("-1y1h1ms", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms + 1));
        try testFormat("1y1m999ns", 365 * std.time.ns_per_day + std.time.ns_per_min + 999);
        try testFormat("-1y1m999ns", -(365 * std.time.ns_per_day + std.time.ns_per_min + 999));
        try testFormat("292y24w3d23h47m16.854s", std.math.maxInt(i64));
        try testFormat("-292y24w3d23h47m16.854s", std.math.minInt(i64) + 1);
        try testFormat("-292y24w3d23h47m16.854s", std.math.minInt(i64));
    }

    fn testFormat(expected: []const u8, input: i96) !void {
        // worst case: "-XXXXXXXXXXXXXyXXwXXdXXhXXmXX.XXXs".len = 34
        var buf: [34]u8 = undefined;
        var w: Writer = .fixed(&buf);
        try w.print("{f}", .{Duration{ .nanoseconds = input }});
        try std.testing.expectEqualStrings(expected, w.buffered());
    }
};

/// Declares under what conditions an operation should return `error.Timeout`.
pub const Timeout = union(enum) {
    /// `.none` will wait forever
    none,
    duration: Clock.Duration,
    deadline: Clock.Timestamp,

    pub const Error = error{Timeout};

    pub fn toTimestamp(t: Timeout, io: Io) ?Clock.Timestamp {
        return switch (t) {
            .none => null,
            .duration => |d| .fromNow(io, d),
            .deadline => |d| d,
        };
    }

    pub fn toDeadline(t: Timeout, io: Io) Timeout {
        return switch (t) {
            .none => .none,
            .duration => |d| .{ .deadline = .fromNow(io, d) },
            .deadline => |d| .{ .deadline = d },
        };
    }

    pub fn toDurationFromNow(t: Timeout, io: Io) ?Clock.Duration {
        return switch (t) {
            .none => null,
            .duration => |d| d,
            .deadline => |d| d.durationFromNow(io),
        };
    }

    /// Waits until the timeout has passed.
    ///
    /// See also:
    /// * `Io.sleep`
    /// * `Clock.Duration.sleep`
    /// * `Clock.Timestamp.wait`
    pub fn sleep(timeout: Timeout, io: Io) Cancelable!void {
        return io.vtable.sleep(io.userdata, timeout);
    }
};

pub const AnyFuture = opaque {};

pub fn Future(Result: type) type {
    return struct {
        any_future: ?*AnyFuture,
        result: Result,

        /// Equivalent to `await` but places a cancelation request. This causes the task to receive
        /// `error.Canceled` from its next "cancelation point" (if any). A cancelation point is a
        /// call to a function in `Io` which can return `error.Canceled`.
        ///
        /// After cancelation of a task is requested, only the next cancelation point in that task
        /// will return `error.Canceled`: future points will not re-signal the cancelation. As such,
        /// it is usually a bug to ignore `error.Canceled`. However, to defer handling cancelation
        /// requests, see also `recancel` and `CancelProtection`.
        ///
        /// Idempotent. Not threadsafe.
        pub fn cancel(f: *@This(), io: Io) Result {
            const any_future = f.any_future orelse return f.result;
            io.vtable.cancel(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
            f.any_future = null;
            return f.result;
        }

        /// Idempotent. Not threadsafe.
        pub fn await(f: *@This(), io: Io) Result {
            const any_future = f.any_future orelse return f.result;
            io.vtable.await(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
            f.any_future = null;
            return f.result;
        }
    };
}

/// An unordered set of tasks which can only be awaited or canceled as a whole.
/// Tasks are spawned in the group with `Group.async` and `Group.concurrent`.
///
/// The resources associated with each task are *guaranteed* to be released when
/// the individual task returns, as opposed to when the whole group completes or
/// is awaited. For this reason, it is not a resource leak to have a long-lived
/// group which concurrent tasks are repeatedly added to. However, asynchronous
/// tasks are not guaranteed to run until `Group.await` or `Group.cancel` is
/// called, so adding async tasks to a group without ever awaiting it may leak
/// resources.
pub const Group = struct {
    /// This value indicates whether or not a group has pending tasks. `null`
    /// means there are no pending tasks, and no resources associated with the
    /// group, so `await` and `cancel` return immediately without calling the
    /// implementation. This means that `token` must be accessed atomically to
    /// avoid racing with the check in `await` and `cancel`.
    token: std.atomic.Value(?*anyopaque),
    /// This value is available for the implementation to use as it wishes.
    state: usize,

    pub const init: Group = .{ .token = .init(null), .state = 0 };

    /// Equivalent to `Io.async`, except the task is spawned in this `Group`
    /// instead of becoming associated with a `Future`.
    ///
    /// The return type of `function` must be coercible to `Cancelable!void`.
    /// `function` returning `error.Canceled` does nothing because it is an
    /// cancelation propagation boundary.
    ///
    /// Once this function is called, there are resources associated with the
    /// group. To release those resources, `await` or `cancel` must eventually
    /// be called.
    ///
    /// `function` is not guaranteed to have been called until `await` or
    /// `cancel` is called.
    pub fn async(g: *Group, io: Io, function: anytype, args: std.meta.ArgsTuple(@TypeOf(function))) void {
        const Args = @TypeOf(args);
        const TypeErased = struct {
            fn start(context: *const anyopaque) void {
                const args_casted: *const Args = @ptrCast(@alignCast(context));
                _ = @as(Cancelable!void, @call(.auto, function, args_casted.*)) catch {};
            }
        };
        io.vtable.groupAsync(io.userdata, g, @ptrCast(&args), .of(Args), TypeErased.start);
    }

    /// Equivalent to `Io.concurrent`, except the task is spawned in this
    /// `Group` instead of becoming associated with a `Future`.
    ///
    /// The return type of `function` must be coercible to `Cancelable!void`.
    /// `function` returning `error.Canceled` does nothing because it is an
    /// cancelation propagation boundary.
    ///
    /// Once this function is called, there are resources associated with the
    /// group. To release those resources, `Group.await` or `Group.cancel` must
    /// eventually be called.
    pub fn concurrent(g: *Group, io: Io, function: anytype, args: std.meta.ArgsTuple(@TypeOf(function))) ConcurrentError!void {
        const Args = @TypeOf(args);
        const TypeErased = struct {
            fn start(context: *const anyopaque) void {
                const args_casted: *const Args = @ptrCast(@alignCast(context));
                _ = @as(Cancelable!void, @call(.auto, function, args_casted.*)) catch {};
            }
        };
        return io.vtable.groupConcurrent(io.userdata, g, @ptrCast(&args), .of(Args), TypeErased.start);
    }

    /// Blocks until all tasks of the group finish. During this time,
    /// cancelation requests propagate to all members of the group, and
    /// will also cause `error.Canceled` to be returned when the group
    /// does ultimately finish.
    ///
    /// After this function returns, all tasks of the `Group` created with
    /// `async` or `concurrent` are guaranteed to have run.
    ///
    /// Idempotent. Not threadsafe.
    ///
    /// It is safe to call this function concurrently with `Group.async` or
    /// `Group.concurrent`, provided that the group does not complete until
    /// the call to `Group.async` or `Group.concurrent` returns.
    pub fn await(g: *Group, io: Io) Cancelable!void {
        const token = g.token.load(.acquire) orelse return;
        try io.vtable.groupAwait(io.userdata, g, token);
        assert(g.token.raw == null);
    }

    /// Equivalent to `await` but immediately requests cancelation on all
    /// members of the group.
    ///
    /// After this function returns, all tasks of the `Group` created with
    /// `async` or `concurrent` are guaranteed to have run.
    ///
    /// For a description of cancelation and cancelation points, see `Future.cancel`.
    ///
    /// Idempotent. Not threadsafe.
    ///
    /// It is safe to call this function concurrently with `Group.async` or
    /// `Group.concurrent`, provided that the group does not complete until
    /// the call to `Group.async` or `Group.concurrent` returns.
    pub fn cancel(g: *Group, io: Io) void {
        const token = g.token.load(.acquire) orelse return;
        io.vtable.groupCancel(io.userdata, g, token);
        assert(g.token.raw == null);
    }
};

/// Asserts that `error.Canceled` was returned from a prior cancelation point, and "re-arms" the
/// cancelation request, so that `error.Canceled` will be returned again from the next cancelation
/// point.
///
/// For a description of cancelation and cancelation points, see `Future.cancel`.
pub fn recancel(io: Io) void {
    io.vtable.recancel(io.userdata);
}

/// In rare cases, it is desirable to completely block cancelation notification, so that a region
/// of code can run uninterrupted before `error.Canceled` is potentially observed. Therefore, every
/// task has a "cancel protection" state which indicates whether or not `Io` functions can introduce
/// cancelation points.
///
/// To modify a task's cancel protection state, see `swapCancelProtection`.
///
/// For a description of cancelation and cancelation points, see `Future.cancel`.
pub const CancelProtection = enum(u1) {
    /// Any call to an `Io` function with `error.Canceled` in its error set is a cancelation point.
    ///
    /// This is the default state, which all tasks are created in.
    unblocked = 0,
    /// No `Io` function introduces a cancelation point (`error.Canceled` will never be returned).
    blocked = 1,
};
/// Updates the current task's cancel protection state (see `CancelProtection`).
///
/// The typical usage for this function is to protect a block of code from cancelation:
/// ```
/// const old_cancel_protect = io.swapCancelProtection(.blocked);
/// defer _ = io.swapCancelProtection(old_cancel_protect);
/// doSomeWork() catch |err| switch (err) {
///     error.Canceled => unreachable,
/// };
/// ```
///
/// For a description of cancelation and cancelation points, see `Future.cancel`.
pub fn swapCancelProtection(io: Io, new: CancelProtection) CancelProtection {
    return io.vtable.swapCancelProtection(io.userdata, new);
}

/// This function acts as a pure cancelation point (subject to protection; see `CancelProtection`)
/// and does nothing else. In other words, it returns `error.Canceled` if there is an outstanding
/// non-blocked cancelation request, but otherwise is a no-op.
///
/// It is rarely necessary to call this function. The primary use case is in long-running CPU-bound
/// tasks which may need to respond to cancelation before completing. Short tasks, or those which
/// perform other `Io` operations (and hence have other cancelation points), will typically already
/// respond quickly to cancelation requests.
///
/// For a description of cancelation and cancelation points, see `Future.cancel`.
pub fn checkCancel(io: Io) Cancelable!void {
    return io.vtable.checkCancel(io.userdata);
}

/// Executes tasks together, providing a mechanism to wait until one or more
/// tasks complete. Similar to `Batch` but operates at the higher level task
/// abstraction layer rather than lower level `Operation` abstraction layer.
///
/// The provided tagged union will be used as the return type of the await
/// function. When calling async or concurrent, one specifies which union field
/// the called function's result will be placed into upon completion.
pub fn Select(comptime U: type) type {
    return struct {
        io: Io,
        group: Group,
        queue: Queue(U),

        const S = @This();

        pub const Union = U;

        pub const Field = std.meta.FieldEnum(U);

        pub fn init(io: Io, buffer: []U) S {
            return .{
                .io = io,
                .queue = .init(buffer),
                .group = .init,
            };
        }

        /// Calls `function` with `args` asynchronously. The resource spawned is
        /// owned by the select.
        ///
        /// `function` must have return type matching the `field` field of `Union`.
        ///
        /// `function` *may* be called immediately, before `async` returns.
        ///
        /// When this function returns, it is guaranteed that `function` has
        /// already been called and completed, or it has successfully been
        /// assigned a unit of concurrency.
        ///
        /// After this is called, `await` or `cancel` must be called before the
        /// select is deinitialized.
        ///
        /// Threadsafe.
        ///
        /// Related:
        /// * `Io.async`
        /// * `Group.async`
        pub fn async(
            s: *S,
            comptime field: Field,
            function: anytype,
            args: std.meta.ArgsTuple(@TypeOf(function)),
        ) void {
            const Context = struct {
                select: *S,
                args: @TypeOf(args),
                fn start(type_erased_context: *const anyopaque) void {
                    const context: *const @This() = @ptrCast(@alignCast(type_erased_context));
                    const result = @call(.auto, function, context.args);
                    const elem = @unionInit(U, @tagName(field), result);
                    context.select.queue.putOneUncancelable(context.select.io, elem) catch |err| switch (err) {
                        error.Closed => {},
                    };
                }
            };
            const context: Context = .{ .select = s, .args = args };
            s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast(&context), .of(Context), Context.start);
        }

        /// Calls `function` with `args` concurrently. The resource spawned is
        /// owned by the select.
        ///
        /// `function` must have return type matching the `field` field of `Union`.
        ///
        /// After this function returns successfully, it is guaranteed that
        /// `function` has been assigned a unit of concurrency, and `await` or
        /// `cancel` must be called before the select is deinitialized.
        ///
        ///
        /// Threadsafe.
        ///
        /// Related:
        /// * `Io.concurrent`
        /// * `Group.concurrent`
        pub fn concurrent(
            s: *S,
            comptime field: Field,
            function: anytype,
            args: std.meta.ArgsTuple(@TypeOf(function)),
        ) ConcurrentError!void {
            const Context = struct {
                select: *S,
                args: @TypeOf(args),
                fn start(type_erased_context: *const anyopaque) void {
                    const context: *const @This() = @ptrCast(@alignCast(type_erased_context));
                    const result = @call(.auto, function, context.args);
                    const elem = @unionInit(U, @tagName(field), result);
                    context.select.queue.putOneUncancelable(context.select.io, elem) catch |err| switch (err) {
                        error.Closed => {},
                    };
                }
            };
            const context: Context = .{ .select = s, .args = args };
            try s.io.vtable.groupConcurrent(s.io.userdata, &s.group, @ptrCast(&context), .of(Context), Context.start);
        }

        /// Blocks until another task of the select finishes.
        ///
        /// It is legal to call `async` and `concurrent` after this.
        ///
        /// Threadsafe.
        pub fn await(s: *S) Cancelable!U {
            return s.queue.getOne(s.io) catch |err| switch (err) {
                error.Canceled => |e| return e,
                error.Closed => unreachable,
            };
        }

        /// Blocks until at least `min` number of results have been copied
        /// into `buffer`.
        ///
        /// Asserts that `buffer.len >= min`.
        ///
        /// It is legal to call `async` and `concurrent` after this.
        ///
        /// Threadsafe.
        pub fn awaitMany(s: *S, buffer: []U, min: usize) Cancelable!usize {
            return s.queue.get(s.io, buffer, min) catch |err| switch (err) {
                error.Canceled => |e| return e,
                error.Closed => unreachable,
            };
        }

        /// Requests cancelation on all remaining tasks owned by the select,
        /// then blocks until they all finish. If the select was initialized
        /// with insufficient buffer space for all remaining tasks to finish, a
        /// deadlock occurs.
        ///
        /// If any of the select tasks allocate resources, those tasks may have
        /// completed, meaning that this function must be called in a loop
        /// until `null` is returned in order to deallocate those resources. If
        /// there is no possibility of resource leaks, `cancelDiscard` is
        /// preferable.
        ///
        /// It is illegal to call `await` or `awaitMany` after this.
        ///
        /// It is safe to call this multiple times, even after `null` is
        /// returned.
        ///
        /// Threadsafe.
        pub fn cancel(s: *S) ?U {
            const io = s.io;
            s.group.cancel(io);
            s.queue.close(io);
            return s.queue.getOneUncancelable(io) catch |err| switch (err) {
                error.Closed => return null,
            };
        }

        /// Requests cancelation on all remaining tasks owned by the select,
        /// then blocks until they all finish.
        ///
        /// All return values from outstanding tasks are discarded. This
        /// function is therefore inappropriate to call when a task can return
        /// an allocated resource. For that use case, see `cancel`.
        ///
        /// It is illegal to call `await` or `awaitMany` after this.
        ///
        /// It is safe to call this multiple times.
        ///
        /// Threadsafe.
        pub fn cancelDiscard(s: *S) void {
            const io = s.io;
            const token = s.group.token.load(.acquire) orelse return;
            s.queue.close(io);
            io.vtable.groupCancel(io.userdata, &s.group, token);
            assert(s.group.token.raw == null);
        }
    };
}

/// Atomically checks if the value at `ptr` equals `expected`, and if so, blocks until either:
///
/// * a matching (same `ptr` argument) `futexWake` call occurs, or
/// * a spurious ("random") wakeup occurs.
///
/// Typically, `futexWake` should be called immediately after updating the value at `ptr.*`, to
/// unblock tasks using `futexWait` to wait for the value to change from what it previously was.
///
/// The caller is responsible for identifying spurious wakeups if necessary, typically by checking
/// the value at `ptr.*`.
///
/// Asserts that `T` is 4 bytes in length and has a well-defined layout with no padding bits.
pub fn futexWait(io: Io, comptime T: type, ptr: *align(@alignOf(u32)) const T, expected: T) Cancelable!void {
    return futexWaitTimeout(io, T, ptr, expected, .none);
}
/// Same as `futexWait`, except also unblocks if `timeout` expires. As with `futexWait`, spurious
/// wakeups are possible. It remains the caller's responsibility to differentiate between these
/// three possible wake-up reasons if necessary.
pub fn futexWaitTimeout(io: Io, comptime T: type, ptr: *align(@alignOf(u32)) const T, expected: T, timeout: Timeout) Cancelable!void {
    const expected_int: u32 = switch (@typeInfo(T)) {
        .@"enum" => @bitCast(@backingInt(expected)),
        else => @bitCast(expected),
    };
    return io.vtable.futexWait(io.userdata, @ptrCast(ptr), expected_int, timeout);
}
/// Same as `futexWait`, except does not introduce a cancelation point.
///
/// For a description of cancelation and cancelation points, see `Future.cancel`.
pub fn futexWaitUncancelable(io: Io, comptime T: type, ptr: *align(@alignOf(u32)) const T, expected: T) void {
    const expected_int: u32 = switch (@typeInfo(T)) {
        .@"enum" => @bitCast(@backingInt(expected)),
        else => @bitCast(expected),
    };
    io.vtable.futexWaitUncancelable(io.userdata, @ptrCast(ptr), expected_int);
}
/// Unblocks pending futex waits on `ptr`, up to a limit of `max_waiters` calls.
pub fn futexWake(io: Io, comptime T: type, ptr: *align(@alignOf(u32)) const T, max_waiters: u32) void {
    comptime assert(@sizeOf(T) == @sizeOf(u32));
    if (max_waiters == 0) return;
    return io.vtable.futexWake(io.userdata, @ptrCast(ptr), max_waiters);
}

/// Mutex is a synchronization primitive which enforces atomic access to a
/// shared region of code known as the "critical section".
///
/// Mutex is an extern struct so that it may be used as a field inside another
/// extern struct.
pub const Mutex = extern struct {
    state: std.atomic.Value(State),

    pub const init: Mutex = .{ .state = .init(.unlocked) };

    pub const State = enum(u32) {
        unlocked,
        locked_once,
        contended,
    };

    pub fn tryLock(m: *Mutex) bool {
        return m.state.cmpxchgStrong(.unlocked, .locked_once, .acquire, .monotonic) == null;
    }

    pub fn lock(m: *Mutex, io: Io) Cancelable!void {
        const initial_state = m.state.cmpxchgStrong(
            .unlocked,
            .locked_once,
            .acquire,
            .monotonic,
        ) orelse {
            @branchHint(.likely);
            return;
        };
        if (initial_state == .contended) {
            try io.futexWait(State, &m.state.raw, .contended);
        }
        while (m.state.swap(.contended, .acquire) != .unlocked) {
            try io.futexWait(State, &m.state.raw, .contended);
        }
    }

    /// Same as `lock`, except does not introduce a cancelation point.
    ///
    /// For a description of cancelation and cancelation points, see `Future.cancel`.
    pub fn lockUncancelable(m: *Mutex, io: Io) void {
        const initial_state = m.state.cmpxchgStrong(
            .unlocked,
            .locked_once,
            .acquire,
            .monotonic,
        ) orelse {
            @branchHint(.likely);
            return;
        };
        if (initial_state == .contended) {
            io.futexWaitUncancelable(State, &m.state.raw, .contended);
        }
        while (m.state.swap(.contended, .acquire) != .unlocked) {
            io.futexWaitUncancelable(State, &m.state.raw, .contended);
        }
    }

    pub fn unlock(m: *Mutex, io: Io) void {
        switch (m.state.swap(.unlocked, .release)) {
            .unlocked => unreachable,
            .locked_once => {},
            .contended => {
                @branchHint(.unlikely);
                io.futexWake(State, &m.state.raw, 1);
            },
        }
    }
};

pub const Condition = struct {
    state: std.atomic.Value(State),
    /// Incremented whenever the condition is signaled
    epoch: std.atomic.Value(u32),

    const State = packed struct(u32) {
        waiters: u16,
        signals: u16,
    };

    pub const init: Condition = .{
        .state = .init(.{ .waiters = 0, .signals = 0 }),
        .epoch = .init(0),
    };

    /// Blocks until the condition is signaled or canceled.
    ///
    /// See also:
    /// * `waitUncancelable`
    /// * `waitTimeout`
    pub fn wait(cond: *Condition, io: Io, mutex: *Mutex) Cancelable!void {
        waitTimeout(cond, io, mutex, .none) catch |err| switch (err) {
            error.Timeout => unreachable,
            error.Canceled => |e| return e,
        };
    }

    pub const WaitTimeoutError = Cancelable || Timeout.Error;

    /// Blocks until the condition is signaled, canceled, or the provided
    /// timeout expires.
    ///
    /// See also:
    /// * `wait`
    /// * `waitUncancelable`
    pub fn waitTimeout(cond: *Condition, io: Io, mutex: *Mutex, timeout: Timeout) WaitTimeoutError!void {
        const deadline = timeout.toDeadline(io);

        var epoch = cond.epoch.load(.acquire); // `.acquire` to ensure ordered before state load

        {
            const prev_state = cond.state.fetchAdd(.{ .waiters = 1, .signals = 0 }, .monotonic);
            assert(prev_state.waiters < math.maxInt(u16)); // overflow caused by too many waiters
        }

        mutex.unlock(io);
        defer mutex.lockUncancelable(io);

        while (true) {
            const result = io.futexWaitTimeout(u32, &cond.epoch.raw, epoch, deadline);

            epoch = cond.epoch.load(.acquire); // `.acquire` to ensure ordered before `state` laod

            // We were woken normally, so try to consume a pending signal. A signal takes
            // priority over an expired deadline, so this is checked before the deadline
            // below. On error we safely remove ourselves as a waiter and propagate the error.
            if (result) |_| {
                var prev_state = cond.state.load(.monotonic);
                while (prev_state.signals > 0) {
                    prev_state = cond.state.cmpxchgWeak(prev_state, .{
                        .waiters = prev_state.waiters - 1,
                        .signals = prev_state.signals - 1,
                    }, .acquire, .monotonic) orelse {
                        // We successfully consumed a signal.
                        return;
                    };
                }
            } else |err| {
                cond.deregister(io);
                return err;
            }

            // There are no signals available and no error; if a timeout was specified and
            // the deadline has passed, remove ourselves as a waiter and return
            // `error.Timeout`. Otherwise, this was a spurious wakeup: loop back to the
            // futex wait.
            switch (deadline) {
                .none => {},
                .deadline => |d| if (d.untilNow(io).raw.nanoseconds >= 0) {
                    cond.deregister(io);
                    return error.Timeout;
                },
                .duration => unreachable,
            }
        }
    }

    /// Same as `wait`, except does not introduce a cancelation point.
    ///
    /// See `Future.cancel` for a description of cancelation points.
    pub fn waitUncancelable(cond: *Condition, io: Io, mutex: *Mutex) void {
        var epoch = cond.epoch.load(.acquire); // `.acquire` to ensure ordered before state load

        {
            const prev_state = cond.state.fetchAdd(.{ .waiters = 1, .signals = 0 }, .monotonic);
            assert(prev_state.waiters < math.maxInt(u16)); // overflow caused by too many waiters
        }

        mutex.unlock(io);
        defer mutex.lockUncancelable(io);

        while (true) {
            io.futexWaitUncancelable(u32, &cond.epoch.raw, epoch);

            epoch = cond.epoch.load(.acquire); // `.acquire` to ensure ordered before `state` laod

            // Even on error, try to consume a pending signal first. Otherwise a race might
            // cause a signal to get stuck in the state with no corresponding waiter.
            {
                var prev_state = cond.state.load(.monotonic);
                while (prev_state.signals > 0) {
                    prev_state = cond.state.cmpxchgWeak(prev_state, .{
                        .waiters = prev_state.waiters - 1,
                        .signals = prev_state.signals - 1,
                    }, .acquire, .monotonic) orelse {
                        // We successfully consumed a signal.
                        return;
                    };
                }
            }

            // There are no more signals available; this was a spurious wakeup,
            // so we'll loop back to the futex wait.
        }
    }

    fn deregister(cond: *Condition, io: Io) void {
        var prev_state = cond.state.load(.monotonic);
        while (true) {
            const new_signals = @min(prev_state.signals, prev_state.waiters - 1);
            prev_state = cond.state.cmpxchgWeak(prev_state, .{
                .waiters = prev_state.waiters - 1,
                .signals = new_signals,
            }, .monotonic, .monotonic) orelse {
                if (prev_state.signals > 0 and prev_state.signals < prev_state.waiters) {
                    // We kept a signal we are not consuming; wake a remaining waiter for it.
                    _ = cond.epoch.fetchAdd(1, .release);
                    io.futexWake(u32, &cond.epoch.raw, 1);
                }
                return;
            };
        }
    }

    pub fn signal(cond: *Condition, io: Io) void {
        var prev_state = cond.state.load(.monotonic);
        while (prev_state.waiters > prev_state.signals) {
            @branchHint(.unlikely);
            prev_state = cond.state.cmpxchgWeak(prev_state, .{
                .waiters = prev_state.waiters,
                .signals = prev_state.signals + 1,
            }, .release, .monotonic) orelse {
                // Update the epoch to tell the waiting threads that there are new signals for them.
                // Note that a waiting thread could miss a take if *exactly* (1<<32)-1 wakes happen
                // between it observing the epoch and sleeping on it, but this is extraordinarily
                // unlikely due to the precise number of calls required.
                _ = cond.epoch.fetchAdd(1, .release); // `.release` to ensure ordered after `state` update
                io.futexWake(u32, &cond.epoch.raw, 1);
                return;
            };
        }
    }

    pub fn broadcast(cond: *Condition, io: Io) void {
        var prev_state = cond.state.load(.monotonic);
        while (prev_state.waiters > prev_state.signals) {
            @branchHint(.unlikely);
            prev_state = cond.state.cmpxchgWeak(prev_state, .{
                .waiters = prev_state.waiters,
                .signals = prev_state.waiters,
            }, .release, .monotonic) orelse {
                // Update the epoch to tell the waiting threads that there are new signals for them.
                // Note that a waiting thread could miss a take if *exactly* (1<<32)-1 wakes happen
                // between it observing the epoch and sleeping on it, but this is extraordinarily
                // unlikely due to the precise number of calls required.
                _ = cond.epoch.fetchAdd(1, .release); // `.release` to ensure ordered after `state` update
                io.futexWake(u32, &cond.epoch.raw, prev_state.waiters - prev_state.signals);
                return;
            };
        }
    }
};

/// Logical boolean flag which can be set and unset and supports a "wait until set" operation.
pub const Event = enum(u32) {
    unset,
    waiting,
    is_set,

    /// Returns whether the logical boolean is `true`.
    pub fn isSet(event: *const Event) bool {
        return switch (@atomicLoad(Event, event, .acquire)) {
            .unset, .waiting => false,
            .is_set => true,
        };
    }

    /// Blocks until the logical boolean is `true`.
    pub fn wait(event: *Event, io: Io) Cancelable!void {
        if (@cmpxchgStrong(Event, event, .unset, .waiting, .acquire, .acquire)) |prev| switch (prev) {
            .unset => unreachable,
            .waiting => {},
            .is_set => return,
        };
        errdefer {
            // Ideally we would restore the event back to `.unset` instead of `.waiting`, but there
            // might be other threads waiting on the event. In theory we could track the *number* of
            // waiting threads in the unused bits of the `Event`, but that has its own problem: the
            // waiters would wake up when a *new waiter* was added. So it's easiest to just leave
            // the state at `.waiting`---at worst it causes one redundant call to `futexWake`.
        }
        while (true) {
            try io.futexWait(Event, event, .waiting);
            switch (@atomicLoad(Event, event, .acquire)) {
                .unset => unreachable, // `reset` called before pending `wait` returned
                .waiting => continue,
                .is_set => return,
            }
        }
    }

    /// Same as `wait`, except does not introduce a cancelation point.
    ///
    /// For a description of cancelation and cancelation points, see `Future.cancel`.
    pub fn waitUncancelable(event: *Event, io: Io) void {
        if (@cmpxchgStrong(Event, event, .unset, .waiting, .acquire, .acquire)) |prev| switch (prev) {
            .unset => unreachable,
            .waiting => {},
            .is_set => return,
        };
        while (true) {
            io.futexWaitUncancelable(Event, event, .waiting);
            switch (@atomicLoad(Event, event, .acquire)) {
                .unset => unreachable, // `reset` called before pending `wait` returned
                .waiting => continue,
                .is_set => return,
            }
        }
    }

    pub const WaitTimeoutError = error{Timeout} || Cancelable;

    /// Blocks the calling thread until either the logical boolean is set or the timeout expires.
    pub fn waitTimeout(event: *Event, io: Io, timeout: Timeout) WaitTimeoutError!void {
        if (@cmpxchgStrong(Event, event, .unset, .waiting, .acquire, .acquire)) |prev| switch (prev) {
            .unset => unreachable,
            .waiting => {},
            .is_set => return,
        };
        errdefer {
            // Ideally we would restore the event back to `.unset` instead of `.waiting`, but there
            // might be other threads waiting on the event. In theory we could track the *number* of
            // waiting threads in the unused bits of the `Event`, but that has its own problem: the
            // waiters would wake up when a *new waiter* was added. So it's easiest to just leave
            // the state at `.waiting`---at worst it causes one redundant call to `futexWake`.
        }

        const deadline = timeout.toDeadline(io);

        while (true) {
            try io.futexWaitTimeout(Event, event, .waiting, timeout);
            switch (@atomicLoad(Event, event, .acquire)) {
                .unset => unreachable, // `reset` called before pending `wait` returned
                .waiting => {
                    const remaining = deadline.toDurationFromNow(io) orelse continue;
                    if (remaining.raw.nanoseconds <= 0) return error.Timeout;
                },
                .is_set => return,
            }
        }
    }

    /// Sets the logical boolean to true, and hence unblocks any pending calls to `wait`. The
    /// logical boolean remains true until `reset` is called, so future calls to `set` have no
    /// semantic effect.
    ///
    /// Any memory accesses prior to a `set` call are "released", so that if this `set` call causes
    /// `isSet` to return `true` or a wait to finish, those tasks will be able to observe those
    /// memory accesses.
    pub fn set(e: *Event, io: Io) void {
        switch (@atomicRmw(Event, e, .Xchg, .is_set, .release)) {
            .unset, .is_set => {},
            .waiting => io.futexWake(Event, e, math.maxInt(u32)),
        }
    }

    /// Sets the logical boolean to false.
    ///
    /// Assumes that there is no pending call to `wait` or `waitUncancelable`.
    ///
    /// However, concurrent calls to `isSet`, `set`, and `reset` are allowed.
    pub fn reset(e: *Event) void {
        @atomicStore(Event, e, .unset, .monotonic);
    }
};

pub const QueueClosedError = error{Closed};

pub const TypeErasedQueue = struct {
    mutex: Mutex,
    closed: bool,

    /// Ring buffer. This data is logically *after* queued getters.
    buffer: []u8,
    start: usize,
    len: usize,

    putters: std.DoublyLinkedList,
    getters: std.DoublyLinkedList,

    const Put = struct {
        remaining: []const u8,
        needed: usize,
        condition: Condition,
        node: std.DoublyLinkedList.Node,
    };

    const Get = struct {
        remaining: []u8,
        needed: usize,
        condition: Condition,
        node: std.DoublyLinkedList.Node,
    };

    pub fn init(buffer: []u8) TypeErasedQueue {
        return .{
            .mutex = .init,
            .closed = false,
            .buffer = buffer,
            .start = 0,
            .len = 0,
            .putters = .{},
            .getters = .{},
        };
    }

    /// After this is called, the queue enters a "closed" state. A closed
    /// queue always returns `error.Closed` for put attempts even when
    /// there is space in the buffer. However, existing elements of the
    /// queue are retrieved before `error.Closed` is returned.
    ///
    /// Idempotent. Threadsafe.
    pub fn close(q: *TypeErasedQueue, io: Io) void {
        q.mutex.lockUncancelable(io);
        defer q.mutex.unlock(io);
        q.closed = true;
        {
            var it = q.getters.first;
            while (it) |node| : (it = node.next) {
                const getter: *Get = @alignCast(@fieldParentPtr("node", node));
                getter.condition.signal(io);
            }
        }
        {
            var it = q.putters.first;
            while (it) |node| : (it = node.next) {
                const putter: *Put = @alignCast(@fieldParentPtr("node", node));
                putter.condition.signal(io);
            }
        }
    }

    pub fn put(q: *TypeErasedQueue, io: Io, elements: []const u8, min: usize) (QueueClosedError || Cancelable)!usize {
        assert(elements.len >= min);
        if (elements.len == 0) return 0;
        try q.mutex.lock(io);
        defer q.mutex.unlock(io);
        return q.putLocked(io, elements, min, false);
    }

    /// Same as `put`, except does not introduce a cancelation point.
    ///
    /// For a description of cancelation and cancelation points, see `Future.cancel`.
    pub fn putUncancelable(q: *TypeErasedQueue, io: Io, elements: []const u8, min: usize) QueueClosedError!usize {
        assert(elements.len >= min);
        if (elements.len == 0) return 0;
        q.mutex.lockUncancelable(io);
        defer q.mutex.unlock(io);
        return q.putLocked(io, elements, min, true) catch |err| switch (err) {
            error.Canceled => unreachable,
            error.Closed => |e| return e,
        };
    }

    fn puttableSlice(q: *const TypeErasedQueue) ?[]u8 {
        const unwrapped_index = q.start + q.len;
        const wrapped_index, const overflow = @subWithOverflow(unwrapped_index, q.buffer.len);
        const slice = switch (overflow) {
            1 => q.buffer[unwrapped_index..],
            0 => q.buffer[wrapped_index..q.start],
        };
        return if (slice.len > 0) slice else null;
    }

    fn putLocked(q: *TypeErasedQueue, io: Io, elements: []const u8, min: usize, uncancelable: bool) (QueueClosedError || Cancelable)!usize {
        // A closed queue cannot be added to, even if there is space in the buffer.
        if (q.closed) return error.Closed;

        // Getters have first priority on the data, and only when the getters
        // queue is empty do we start populating the buffer.

        // The number of elements we add immediately, before possibly blocking.
        var n: usize = 0;

        while (q.getters.popFirst()) |getter_node| {
            const getter: *Get = @alignCast(@fieldParentPtr("node", getter_node));
            const copy_len = @min(getter.remaining.len, elements.len - n);
            assert(copy_len > 0);
            @memcpy(getter.remaining[0..copy_len], elements[n..][0..copy_len]);
            getter.remaining = getter.remaining[copy_len..];
            getter.needed -|= copy_len;
            n += copy_len;
            if (getter.needed == 0) {
                getter.condition.signal(io);
            } else {
                assert(n == elements.len); // we didn't have enough elements for the getter
                q.getters.prepend(getter_node);
            }
            if (n == elements.len) return elements.len;
        }

        while (q.puttableSlice()) |slice| {
            const copy_len = @min(slice.len, elements.len - n);
            assert(copy_len > 0);
            @memcpy(slice[0..copy_len], elements[n..][0..copy_len]);
            q.len += copy_len;
            n += copy_len;
            if (n == elements.len) return elements.len;
        }

        // Don't block if we hit the min.
        if (n >= min) return n;

        var pending: Put = .{
            .remaining = elements[n..],
            .needed = min - n,
            .condition = .init,
            .node = .{},
        };
        q.putters.append(&pending.node);
        defer if (pending.needed > 0) q.putters.remove(&pending.node);

        while (pending.needed > 0 and !q.closed) {
            if (uncancelable) {
                pending.condition.waitUncancelable(io, &q.mutex);
                continue;
            }
            pending.condition.wait(io, &q.mutex) catch |err| switch (err) {
                error.Canceled => if (pending.remaining.len == elements.len) {
                    // Canceled while waiting, and appended no elements.
                    return error.Canceled;
                } else {
                    // Canceled while waiting, but appended some elements, so report those first.
                    io.recancel();
                    return elements.len - pending.remaining.len;
                },
            };
        }
        if (pending.remaining.len == elements.len) {
            // The queue was closed while we were waiting. We appended no elements.
            assert(q.closed);
            return error.Closed;
        }
        return elements.len - pending.remaining.len;
    }

    pub fn get(q: *TypeErasedQueue, io: Io, buffer: []u8, min: usize) (QueueClosedError || Cancelable)!usize {
        assert(buffer.len >= min);
        if (buffer.len == 0) return 0;
        try q.mutex.lock(io);
        defer q.mutex.unlock(io);
        return q.getLocked(io, buffer, min, false);
    }

    /// Same as `get`, except does not introduce a cancelation point.
    ///
    /// For a description of cancelation and cancelation points, see `Future.cancel`.
    pub fn getUncancelable(q: *TypeErasedQueue, io: Io, buffer: []u8, min: usize) QueueClosedError!usize {
        assert(buffer.len >= min);
        if (buffer.len == 0) return 0;
        q.mutex.lockUncancelable(io);
        defer q.mutex.unlock(io);
        return q.getLocked(io, buffer, min, true) catch |err| switch (err) {
            error.Canceled => unreachable,
            error.Closed => |e| return e,
        };
    }

    fn gettableSlice(q: *const TypeErasedQueue) ?[]const u8 {
        const overlong_slice = q.buffer[q.start..];
        const slice = overlong_slice[0..@min(overlong_slice.len, q.len)];
        return if (slice.len > 0) slice else null;
    }

    fn getLocked(q: *TypeErasedQueue, io: Io, buffer: []u8, min: usize, uncancelable: bool) (QueueClosedError || Cancelable)!usize {
        // The ring buffer gets first priority, then data should come from any
        // queued putters, then finally the ring buffer should be filled with
        // data from putters so they can be resumed.

        // The number of elements we received immediately, before possibly blocking.
        var n: usize = 0;

        while (q.gettableSlice()) |slice| {
            const copy_len = @min(slice.len, buffer.len - n);
            assert(copy_len > 0);
            @memcpy(buffer[n..][0..copy_len], slice[0..copy_len]);
            q.start += copy_len;
            if (q.buffer.len - q.start == 0) q.start = 0;
            q.len -= copy_len;
            n += copy_len;
            if (n == buffer.len) {
                q.fillRingBufferFromPutters(io);
                return buffer.len;
            }
        }

        // Copy directly from putters into buffer.
        while (q.putters.popFirst()) |putter_node| {
            const putter: *Put = @alignCast(@fieldParentPtr("node", putter_node));
            const copy_len = @min(putter.remaining.len, buffer.len - n);
            assert(copy_len > 0);
            @memcpy(buffer[n..][0..copy_len], putter.remaining[0..copy_len]);
            putter.remaining = putter.remaining[copy_len..];
            putter.needed -|= copy_len;
            n += copy_len;
            if (putter.needed == 0) {
                putter.condition.signal(io);
            } else {
                assert(n == buffer.len); // we didn't have enough space for the putter
                q.putters.prepend(putter_node);
            }
            if (n == buffer.len) {
                q.fillRingBufferFromPutters(io);
                return buffer.len;
            }
        }

        // No need to call `fillRingBufferFromPutters` from this point onwards,
        // because we emptied the ring buffer *and* the putter queue!

        // Don't block if we hit the min or if the queue is closed. Return how
        // many elements we could get immediately, unless the queue was closed and
        // empty, in which case report `error.Closed`.
        if (n == 0 and q.closed) return error.Closed;
        if (n >= min or q.closed) return n;

        var pending: Get = .{
            .remaining = buffer[n..],
            .needed = min - n,
            .condition = .init,
            .node = .{},
        };
        q.getters.append(&pending.node);
        defer if (pending.needed > 0) q.getters.remove(&pending.node);

        while (pending.needed > 0 and !q.closed) {
            if (uncancelable) {
                pending.condition.waitUncancelable(io, &q.mutex);
                continue;
            }
            pending.condition.wait(io, &q.mutex) catch |err| switch (err) {
                error.Canceled => if (pending.remaining.len == buffer.len) {
                    // Canceled while waiting, and received no elements.
                    return error.Canceled;
                } else {
                    // Canceled while waiting, but received some elements, so report those first.
                    io.recancel();
                    return buffer.len - pending.remaining.len;
                },
            };
        }
        if (pending.remaining.len == buffer.len) {
            // The queue was closed while we were waiting. We received no elements.
            assert(q.closed);
            return error.Closed;
        }
        return buffer.len - pending.remaining.len;
    }

    /// Called when there is nonzero space available in the ring buffer and
    /// potentially putters waiting. The mutex is already held and the task is
    /// to copy putter data to the ring buffer and signal any putters whose
    /// buffers been fully copied.
    fn fillRingBufferFromPutters(q: *TypeErasedQueue, io: Io) void {
        while (q.putters.popFirst()) |putter_node| {
            const putter: *Put = @alignCast(@fieldParentPtr("node", putter_node));
            while (q.puttableSlice()) |slice| {
                const copy_len = @min(slice.len, putter.remaining.len);
                assert(copy_len > 0);
                @memcpy(slice[0..copy_len], putter.remaining[0..copy_len]);
                q.len += copy_len;
                putter.remaining = putter.remaining[copy_len..];
                putter.needed -|= copy_len;
                if (putter.needed == 0) {
                    putter.condition.signal(io);
                    break;
                }
            } else {
                q.putters.prepend(putter_node);
                break;
            }
        }
    }
};

/// Many producer, many consumer, thread-safe, runtime configurable buffer size.
/// When buffer is empty, consumers suspend and are resumed by producers.
/// When buffer is full, producers suspend and are resumed by consumers.
pub fn Queue(Elem: type) type {
    return struct {
        type_erased: TypeErasedQueue,

        pub fn init(buffer: []Elem) @This() {
            return .{ .type_erased = .init(@ptrCast(buffer)) };
        }

        /// After this is called, the queue enters a "closed" state. A closed
        /// queue always returns `error.Closed` for put attempts even when
        /// there is space in the buffer. However, existing elements of the
        /// queue are retrieved before `error.Closed` is returned.
        ///
        /// Threadsafe.
        pub fn close(q: *@This(), io: Io) void {
            q.type_erased.close(io);
        }

        /// Appends elements to the end of the queue, potentially blocking if
        /// there is insufficient capacity. Returns when any one of the
        /// following conditions is satisfied:
        ///
        /// * At least `min` elements have been added to the queue
        /// * The queue is closed
        /// * The current task is canceled
        ///
        /// Returns how many of `elements` have been added to the queue, if any.
        /// If an error is returned, no elements have been added.
        ///
        /// If the queue is closed or the task is canceled, but some items were
        /// already added before the closure or cancelation, then `put` may
        /// return a number lower than `min`, in which case future calls are
        /// guaranteed to return `error.Canceled` or `error.Closed`.
        ///
        /// A return value of 0 is only possible if `min` is 0, in which case
        /// the call is guaranteed to queue as many of `elements` as is possible
        /// *without* blocking.
        ///
        /// Asserts that `elements.len >= min`.
        pub fn put(q: *@This(), io: Io, elements: []const Elem, min: usize) (QueueClosedError || Cancelable)!usize {
            return @divExact(try q.type_erased.put(io, @ptrCast(elements), min * @sizeOf(Elem)), @sizeOf(Elem));
        }

        /// Same as `put` but blocks until all elements have been added to the queue.
        ///
        /// If the queue is closed or canceled, `error.Closed` or `error.Canceled`
        /// is returned, and it is unspecified how many, if any, of `elements` were
        /// added to the queue prior to cancelation or closure.
        pub fn putAll(q: *@This(), io: Io, elements: []const Elem) (QueueClosedError || Cancelable)!void {
            const n = try q.put(io, elements, elements.len);
            if (n != elements.len) {
                _ = try q.put(io, elements[n..], elements.len - n);
                unreachable; // partial `put` implies queue was closed or we were canceled
            }
        }

        /// Same as `put`, except does not introduce a cancelation point.
        ///
        /// For a description of cancelation and cancelation points, see `Future.cancel`.
        pub fn putUncancelable(q: *@This(), io: Io, elements: []const Elem, min: usize) QueueClosedError!usize {
            return @divExact(try q.type_erased.putUncancelable(io, @ptrCast(elements), min * @sizeOf(Elem)), @sizeOf(Elem));
        }

        /// Appends `item` to the end of the queue, blocking if the queue is full.
        pub fn putOne(q: *@This(), io: Io, item: Elem) (QueueClosedError || Cancelable)!void {
            assert(try q.put(io, &.{item}, 1) == 1);
        }

        /// Same as `putOne`, except does not introduce a cancelation point.
        ///
        /// For a description of cancelation and cancelation points, see `Future.cancel`.
        pub fn putOneUncancelable(q: *@This(), io: Io, item: Elem) QueueClosedError!void {
            assert(try q.putUncancelable(io, &.{item}, 1) == 1);
        }

        /// Receives elements from the beginning of the queue, potentially blocking
        /// if there are insufficient elements currently in the queue. Returns when
        /// any one of the following conditions is satisfied:
        ///
        /// * At least `min` elements have been received from the queue
        /// * The queue is closed and contains no buffered elements
        /// * The current task is canceled
        ///
        /// Returns how many elements of `buffer` have been populated, if any.
        /// If an error is returned, no elements have been populated.
        ///
        /// If the queue is closed or the task is canceled, but some items were
        /// already received before the closure or cancelation, then `get` may
        /// return a number lower than `min`, in which case future calls are
        /// guaranteed to return `error.Canceled` or `error.Closed`.
        ///
        /// A return value of 0 is only possible if `min` is 0, in which case
        /// the call is guaranteed to fill as much of `buffer` as is possible
        /// *without* blocking.
        ///
        /// Asserts that `buffer.len >= min`.
        pub fn get(q: *@This(), io: Io, buffer: []Elem, min: usize) (QueueClosedError || Cancelable)!usize {
            return @divExact(try q.type_erased.get(io, @ptrCast(buffer), min * @sizeOf(Elem)), @sizeOf(Elem));
        }

        /// Same as `get`, except does not introduce a cancelation point.
        ///
        /// For a description of cancelation and cancelation points, see `Future.cancel`.
        pub fn getUncancelable(q: *@This(), io: Io, buffer: []Elem, min: usize) QueueClosedError!usize {
            return @divExact(try q.type_erased.getUncancelable(io, @ptrCast(buffer), min * @sizeOf(Elem)), @sizeOf(Elem));
        }

        /// Receives one element from the beginning of the queue, blocking if the queue is empty.
        pub fn getOne(q: *@This(), io: Io) (QueueClosedError || Cancelable)!Elem {
            var buf: [1]Elem = undefined;
            assert(try q.get(io, &buf, 1) == 1);
            return buf[0];
        }

        /// Same as `getOne`, except does not introduce a cancelation point.
        ///
        /// For a description of cancelation and cancelation points, see `Future.cancel`.
        pub fn getOneUncancelable(q: *@This(), io: Io) QueueClosedError!Elem {
            var buf: [1]Elem = undefined;
            assert(try q.getUncancelable(io, &buf, 1) == 1);
            return buf[0];
        }

        /// Returns buffer length in `Elem` units.
        pub fn capacity(q: *const @This()) usize {
            return @divExact(q.type_erased.buffer.len, @sizeOf(Elem));
        }
    };
}

/// Calls `function` with `args`, such that the return value of the function is
/// not guaranteed to be available until `await` is called.
///
/// `function` *may* be called immediately, before `async` returns. This has
/// weaker guarantees than `concurrent`, making more portable and reusable.
///
/// When this function returns, it is guaranteed that `function` has already
/// been called and completed, or it has successfully been assigned a unit of
/// concurrency.
///
/// See also:
/// * `Group`
pub fn async(
    io: Io,
    function: anytype,
    args: std.meta.ArgsTuple(@TypeOf(function)),
) Future(@typeInfo(@TypeOf(function)).@"fn".return_type.?) {
    const Result = @typeInfo(@TypeOf(function)).@"fn".return_type.?;
    const Args = @TypeOf(args);
    const TypeErased = struct {
        fn start(context: *const anyopaque, result: *anyopaque) void {
            const args_casted: *const Args = @ptrCast(@alignCast(context));
            const result_casted: *Result = @ptrCast(@alignCast(result));
            result_casted.* = @call(.auto, function, args_casted.*);
        }
    };
    var future: Future(Result) = undefined;
    future.any_future = io.vtable.async(
        io.userdata,
        @ptrCast(&future.result),
        .of(Result),
        @ptrCast(&args),
        .of(Args),
        TypeErased.start,
    );
    return future;
}

pub const ConcurrentError = error{
    /// May occur due to a temporary condition such as resource exhaustion, or
    /// to the Io implementation not supporting concurrency.
    ConcurrencyUnavailable,
};

/// Calls `function` with `args`, such that the return value of the function is
/// not guaranteed to be available until `await` is called, allowing the caller
/// to progress while waiting for any `Io` operations.
///
/// This has stronger guarantee than `async`, placing restrictions on what kind
/// of `Io` implementations are supported. By calling `async` instead, one
/// allows, for example, stackful single-threaded blocking I/O.
pub fn concurrent(
    io: Io,
    function: anytype,
    args: std.meta.ArgsTuple(@TypeOf(function)),
) ConcurrentError!Future(@typeInfo(@TypeOf(function)).@"fn".return_type.?) {
    const Result = @typeInfo(@TypeOf(function)).@"fn".return_type.?;
    const Args = @TypeOf(args);
    const TypeErased = struct {
        fn start(context: *const anyopaque, result: *anyopaque) void {
            const args_casted: *const Args = @ptrCast(@alignCast(context));
            const result_casted: *Result = @ptrCast(@alignCast(result));
            result_casted.* = @call(.auto, function, args_casted.*);
        }
    };
    var future: Future(Result) = undefined;
    future.any_future = try io.vtable.concurrent(
        io.userdata,
        @sizeOf(Result),
        .of(Result),
        @ptrCast(&args),
        .of(Args),
        TypeErased.start,
    );
    return future;
}

/// Waits until a specified amount of time has passed on `clock`.
///
/// See also:
/// * `Clock.Duration.sleep`
/// * `Clock.Timestamp.wait`
/// * `Timeout.sleep`
pub fn sleep(io: Io, duration: Duration, clock: Clock) Cancelable!void {
    return io.vtable.sleep(io.userdata, .{ .duration = .{
        .raw = duration,
        .clock = clock,
    } });
}

pub const LockedStderr = struct {
    file_writer: *File.Writer,
    terminal_mode: Terminal.Mode,

    pub fn terminal(ls: LockedStderr) Terminal {
        return .{
            .writer = &ls.file_writer.interface,
            .mode = ls.terminal_mode,
        };
    }

    pub fn clear(ls: LockedStderr, buffer: []u8) Cancelable!void {
        const fw = ls.file_writer;
        std.Progress.clearWrittenWithEscapeCodes(fw) catch |err| switch (err) {
            error.WriteFailed => switch (fw.err.?) {
                error.Canceled => |e| return e,
                else => {},
            },
        };
        fw.interface.flush() catch |err| switch (err) {
            error.WriteFailed => switch (fw.err.?) {
                error.Canceled => |e| return e,
                else => {},
            },
        };
        fw.interface.buffer = buffer;
    }
};

/// For doing application-level writes to the standard error stream.
/// Coordinates also with debug-level writes that are ignorant of Io interface
/// and implementations.
///
/// See also:
/// * `tryLockStderr`
pub fn lockStderr(io: Io, buffer: []u8, terminal_mode: ?Terminal.Mode) Cancelable!LockedStderr {
    const ls = try io.vtable.lockStderr(io.userdata, terminal_mode);
    try ls.clear(buffer);
    return ls;
}

/// Same as `lockStderr` but non-blocking.
pub fn tryLockStderr(io: Io, buffer: []u8, terminal_mode: ?Terminal.Mode) Cancelable!?LockedStderr {
    const ls = (try io.vtable.tryLockStderr(io.userdata, terminal_mode)) orelse return null;
    try ls.clear(buffer);
    return ls;
}

pub fn unlockStderr(io: Io) void {
    return io.vtable.unlockStderr(io.userdata);
}

/// Obtains entropy from a cryptographically secure pseudo-random number
/// generator.
///
/// The implementation *may* store RNG state in process memory and use it to
/// fill `buffer`.
///
/// The randomness is seeded by `randomSecure`, or a less secure mechanism upon
/// failure.
///
/// Threadsafe.
///
/// See also `randomSecure`.
pub fn random(io: Io, buffer: []u8) void {
    return io.vtable.random(io.userdata, buffer);
}

pub const RandomSecureError = error{EntropyUnavailable} || Cancelable;

/// Obtains cryptographically secure entropy from outside the process.
///
/// Always makes a syscall, or otherwise avoids dependency on process memory,
/// in order to obtain fresh randomness. Does not rely on stored RNG state.
///
/// Does not have any fallback mechanisms; returns `error.EntropyUnavailable`
/// if any problems occur.
///
/// Threadsafe.
///
/// See also `random`.
pub fn randomSecure(io: Io, buffer: []u8) RandomSecureError!void {
    return io.vtable.randomSecure(io.userdata, buffer);
}

test {
    _ = net;
    _ = File;
    _ = Dir;
    _ = Reader;
    _ = Writer;
    _ = Evented;
    _ = Threaded;
    _ = RwLock;
    _ = Semaphore;
    _ = @import("Io/test.zig");
}

/// An implementation of `Io` which simulates a system supporting no `Io` operations.
///
/// This system has the following properties:
/// * Concurrency is unavailable.
/// * The stdio handles are pipes whose remote ends are already closed.
/// * The filesystem is entirely empty, including that the cwd is no longer present.
/// * The filesystem is full, so attempting to create entries always returns `error.NoSpaceLeft`.
/// * No entropy source is supported, so `randomSecure` always returns `error.EntropyUnavailable`, and `random` always returns (fills the buffer) with 0.
/// * No clocks are supported, so `now` and `sleep` always return `error.UnsupportedClock`.
/// * No network is connected, so network operations always return `error.NetworkDown`.
pub const failing: std.Io = .{
    .userdata = null,
    .vtable = &.{
        .crashHandler = noCrashHandler,

        .async = noAsync,
        .concurrent = failingConcurrent,
        .await = unreachableAwait,
        .cancel = unreachableCancel,

        .groupAsync = noGroupAsync,
        .groupConcurrent = failingGroupConcurrent,
        .groupAwait = unreachableGroupAwait,
        .groupCancel = unreachableGroupCancel,

        .recancel = unreachableRecancel,
        .swapCancelProtection = unreachableSwapCancelProtection,
        .checkCancel = unreachableCheckCancel,

        .futexWait = noFutexWait,
        .futexWaitUncancelable = noFutexWaitUncancelable,
        .futexWake = noFutexWake,

        .operate = failingOperate,
        .batchAwaitAsync = unreachableBatchAwaitAsync,
        .batchAwaitConcurrent = unreachableBatchAwaitConcurrent,
        .batchCancel = unreachableBatchCancel,

        .dirCreateDir = failingDirCreateDir,
        .dirCreateDirPath = failingDirCreateDirPath,
        .dirCreateDirPathOpen = failingDirCreateDirPathOpen,
        .dirOpenDir = failingDirOpenDir,
        .dirStat = failingDirStat,
        .dirStatFile = failingDirStatFile,
        .dirAccess = failingDirAccess,
        .dirCreateFile = failingDirCreateFile,
        .dirCreateFileAtomic = failingDirCreateFileAtomic,
        .dirOpenFile = failingDirOpenFile,
        .dirClose = unreachableDirClose,
        .dirRead = noDirRead,
        .dirRealPath = failingDirRealPath,
        .dirRealPathFile = failingDirRealPathFile,
        .dirDeleteFile = failingDirDeleteFile,
        .dirDeleteDir = failingDirDeleteDir,
        .dirRename = failingDirRename,
        .dirRenamePreserve = failingDirRenamePreserve,
        .dirSymLink = failingDirSymLink,
        .dirReadLink = failingDirReadLink,
        .dirSetOwner = failingDirSetOwner,
        .dirSetFileOwner = failingDirSetFileOwner,
        .dirSetPermissions = failingDirSetPermissions,
        .dirSetFilePermissions = failingDirSetFilePermissions,
        .dirSetTimestamps = noDirSetTimestamps,
        .dirHardLink = failingDirHardLink,

        .fileStat = failingFileStat,
        .fileLength = failingFileLength,
        .fileClose = unreachableFileClose,
        .fileWritePositional = failingFileWritePositional,
        .fileWriteFileStreaming = noFileWriteFileStreaming,
        .fileWriteFilePositional = noFileWriteFilePositional,
        .fileReadPositional = failingFileReadPositional,
        .fileSeekBy = failingFileSeekBy,
        .fileSeekTo = failingFileSeekTo,
        .fileSync = failingFileSync,
        .fileIsTty = unreachableFileIsTty,
        .fileEnableAnsiEscapeCodes = unreachableFileEnableAnsiEscapeCodes,
        .fileSupportsAnsiEscapeCodes = unreachableFileSupportsAnsiEscapeCodes,
        .fileSetLength = failingFileSetLength,
        .fileSetOwner = failingFileSetOwner,
        .fileSetPermissions = failingFileSetPermissions,
        .fileSetTimestamps = noFileSetTimestamps,
        .fileLock = failingFileLock,
        .fileTryLock = failingFileTryLock,
        .fileUnlock = unreachableFileUnlock,
        .fileDowngradeLock = failingFileDowngradeLock,
        .fileRealPath = failingFileRealPath,
        .fileHardLink = failingFileHardLink,

        .fileMemoryMapCreate = failingFileMemoryMapCreate,
        .fileMemoryMapDestroy = unreachableFileMemoryMapDestroy,
        .fileMemoryMapSetLength = unreachableFileMemoryMapSetLength,
        .fileMemoryMapRead = unreachableFileMemoryMapRead,
        .fileMemoryMapWrite = unreachableFileMemoryMapWrite,

        .processExecutableOpen = failingProcessExecutableOpen,
        .processExecutablePath = failingProcessExecutablePath,
        .lockStderr = unreachableLockStderr,
        .tryLockStderr = noTryLockStderr,
        .unlockStderr = unreachableUnlockStderr,
        .processCurrentPath = failingProcessCurrentPath,
        .processSetCurrentDir = failingProcessSetCurrentDir,
        .processSetCurrentPath = failingProcessSetCurrentPath,
        .processReplace = failingProcessReplace,
        .processSpawn = failingProcessSpawn,
        .childWait = unreachableChildWait,
        .childKill = unreachableChildKill,

        .progressParentFile = failingProgressParentFile,
        .inheritParentDir = failingInheritParentDir,
        .inheritParentFile = failingInheritParentFile,

        .random = noRandom,
        .randomSecure = failingRandomSecure,

        .now = noNow,
        .clockResolution = failingClockResolution,
        .sleep = noSleep,

        .netListenIp = failingNetListenIp,
        .netAccept = failingNetAccept,
        .netBindIp = failingNetBindIp,
        .netConnectIp = failingNetConnectIp,
        .netListenUnix = failingNetListenUnix,
        .netConnectUnix = failingNetConnectUnix,
        .netSocketCreatePair = failingNetSocketCreatePair,
        .netWriteFile = failingNetWriteFile,
        .netClose = unreachableNetClose,
        .netShutdown = failingNetShutdown,
        .netInterfaceNameResolve = failingNetInterfaceNameResolve,
        .netInterfaceName = unreachableNetInterfaceName,
        .netLookup = failingNetLookup,
    },
};

pub fn noCrashHandler(userdata: ?*anyopaque) void {
    _ = userdata;
}

pub fn noAsync(userdata: ?*anyopaque, result: []u8, result_alignment: std.mem.Alignment, context: []const u8, context_alignment: std.mem.Alignment, start: *const fn (context: *const anyopaque, result: *anyopaque) void) ?*AnyFuture {
    _ = userdata;
    _ = result_alignment;
    _ = context_alignment;
    start(context.ptr, result.ptr);
    return null;
}

pub fn failingConcurrent(
    userdata: ?*anyopaque,
    result_len: usize,
    result_alignment: std.mem.Alignment,
    context: []const u8,
    context_alignment: std.mem.Alignment,
    start: *const fn (context: *const anyopaque, result: *anyopaque) void,
) ConcurrentError!*AnyFuture {
    _ = userdata;
    _ = result_len;
    _ = result_alignment;
    _ = context;
    _ = context_alignment;
    _ = start;
    return error.ConcurrencyUnavailable;
}

pub fn unreachableAwait(
    userdata: ?*anyopaque,
    any_future: *AnyFuture,
    result: []u8,
    result_alignment: std.mem.Alignment,
) void {
    _ = userdata;
    _ = any_future;
    _ = result;
    _ = result_alignment;
    unreachable;
}

pub fn unreachableCancel(
    userdata: ?*anyopaque,
    any_future: *AnyFuture,
    result: []u8,
    result_alignment: std.mem.Alignment,
) void {
    _ = userdata;
    _ = any_future;
    _ = result;
    _ = result_alignment;
    unreachable;
}

pub fn noGroupAsync(
    userdata: ?*anyopaque,
    group: *Group,
    context: []const u8,
    context_alignment: std.mem.Alignment,
    start: *const fn (context: *const anyopaque) void,
) void {
    _ = userdata;
    _ = group;
    _ = context_alignment;
    start(context.ptr);
}

pub fn failingGroupConcurrent(
    userdata: ?*anyopaque,
    group: *Group,
    context: []const u8,
    context_alignment: std.mem.Alignment,
    start: *const fn (context: *const anyopaque) void,
) ConcurrentError!void {
    _ = userdata;
    _ = group;
    _ = context;
    _ = context_alignment;
    _ = start;
    return error.ConcurrencyUnavailable;
}

pub fn unreachableGroupAwait(userdata: ?*anyopaque, group: *Group, token: *anyopaque) Cancelable!void {
    _ = userdata;
    _ = group;
    _ = token;
    unreachable;
}

pub fn unreachableGroupCancel(userdata: ?*anyopaque, group: *Group, token: *anyopaque) void {
    _ = userdata;
    _ = group;
    _ = token;
    unreachable;
}

pub fn unreachableRecancel(userdata: ?*anyopaque) void {
    _ = userdata;
    unreachable;
}

pub fn unreachableSwapCancelProtection(userdata: ?*anyopaque, new: CancelProtection) CancelProtection {
    _ = userdata;
    _ = new;
    unreachable;
}

pub fn unreachableCheckCancel(userdata: ?*anyopaque) Cancelable!void {
    _ = userdata;
    unreachable;
}

pub fn noFutexWait(userdata: ?*anyopaque, ptr: *const u32, expected: u32, timeout: Timeout) Cancelable!void {
    _ = userdata;
    std.debug.assert(ptr.* == expected or timeout != .none);
}

pub fn noFutexWaitUncancelable(userdata: ?*anyopaque, ptr: *const u32, expected: u32) void {
    _ = userdata;
    std.debug.assert(ptr.* == expected);
}

pub fn noFutexWake(userdata: ?*anyopaque, ptr: *const u32, max_waiters: u32) void {
    _ = userdata;
    _ = ptr;
    _ = max_waiters;
    // no-op
}

pub fn failingOperate(userdata: ?*anyopaque, operation: Operation) Cancelable!Operation.Result {
    _ = userdata;
    return switch (operation) {
        .file_read_streaming => .{ .file_read_streaming = error.InputOutput },
        .file_write_streaming => .{ .file_write_streaming = error.InputOutput },
        .device_io_control => unreachable,
        .net_receive => .{ .net_receive = .{ error.NetworkDown, 0 } },
        .net_send => .{ .net_send = .{ error.NetworkDown, 0 } },
        .net_read => .{ .net_read = error.NetworkDown },
        .net_write => .{ .net_write = error.NetworkDown },
    };
}

pub fn unreachableBatchAwaitAsync(userdata: ?*anyopaque, b: *Batch) Cancelable!void {
    _ = userdata;
    _ = b;
    unreachable;
}

pub fn unreachableBatchAwaitConcurrent(userdata: ?*anyopaque, b: *Batch, timeout: Timeout) Batch.AwaitConcurrentError!void {
    _ = userdata;
    _ = b;
    _ = timeout;
    unreachable;
}

pub fn unreachableBatchCancel(userdata: ?*anyopaque, b: *Batch) void {
    _ = userdata;
    _ = b;
    unreachable;
}

pub fn failingDirCreateDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!void {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = permissions;
    return error.NoSpaceLeft;
}

pub fn failingDirCreateDirPath(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirPathError!Dir.CreatePathStatus {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = permissions;
    return error.NoSpaceLeft;
}

pub fn failingDirCreateDirPathOpen(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions, options: Dir.OpenOptions) Dir.CreateDirPathOpenError!Dir {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = permissions;
    _ = options;
    return error.NoSpaceLeft;
}

pub fn failingDirOpenDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.OpenOptions) Dir.OpenError!Dir {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = options;
    return error.FileNotFound;
}

pub fn failingDirStat(userdata: ?*anyopaque, dir: Dir) Dir.StatError!Dir.Stat {
    _ = userdata;
    _ = dir;
    return error.Streaming;
}

pub fn failingDirStatFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.StatFileOptions) Dir.StatFileError!File.Stat {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = options;
    return error.FileNotFound;
}

pub fn failingDirAccess(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.AccessOptions) Dir.AccessError!void {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = options;
    return error.FileNotFound;
}

pub fn failingDirCreateFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.CreateFileOptions) File.OpenError!File {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = options;
    return error.NoSpaceLeft;
}

pub fn failingDirCreateFileAtomic(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.CreateFileAtomicOptions) Dir.CreateFileAtomicError!File.Atomic {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = options;
    return error.NoSpaceLeft;
}

pub fn failingDirOpenFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.OpenFileOptions) File.OpenError!File {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = flags;
    return error.FileNotFound;
}

pub fn unreachableDirClose(userdata: ?*anyopaque, dirs: []const Dir) void {
    _ = userdata;
    _ = dirs;
    unreachable;
}

pub fn noDirRead(userdata: ?*anyopaque, dir_reader: *Dir.Reader, buffer: []Dir.Entry) Dir.Reader.Error!usize {
    _ = userdata;
    _ = buffer;
    dir_reader.state = .finished;
    return 0;
}

pub fn failingDirRealPath(userdata: ?*anyopaque, dir: Dir, out_buffer: []u8) Dir.RealPathError!usize {
    _ = userdata;
    _ = dir;
    _ = out_buffer;
    return error.FileNotFound;
}

pub fn failingDirRealPathFile(userdata: ?*anyopaque, dir: Dir, path_name: []const u8, out_buffer: []u8) Dir.RealPathFileError!usize {
    _ = userdata;
    _ = dir;
    _ = path_name;
    _ = out_buffer;
    return error.FileNotFound;
}

pub fn failingDirDeleteFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteFileError!void {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    return error.FileNotFound;
}

pub fn failingDirDeleteDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8) Dir.DeleteDirError!void {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    return error.FileNotFound;
}

pub fn failingDirRename(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenameError!void {
    _ = userdata;
    _ = old_dir;
    _ = old_sub_path;
    _ = new_dir;
    _ = new_sub_path;
    return error.FileNotFound;
}

pub fn failingDirRenamePreserve(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8) Dir.RenamePreserveError!void {
    _ = userdata;
    _ = old_dir;
    _ = old_sub_path;
    _ = new_dir;
    _ = new_sub_path;
    return error.FileNotFound;
}

pub fn failingDirSymLink(userdata: ?*anyopaque, dir: Dir, target_path: []const u8, sym_link_path: []const u8, flags: Dir.SymLinkFlags) Dir.SymLinkError!void {
    _ = userdata;
    _ = dir;
    _ = target_path;
    _ = sym_link_path;
    _ = flags;
    return error.FileNotFound;
}

pub fn failingDirReadLink(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, buffer: []u8) Dir.ReadLinkError!usize {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = buffer;
    return error.FileNotFound;
}

pub fn failingDirSetOwner(userdata: ?*anyopaque, dir: Dir, owner: ?File.Uid, group: ?File.Gid) Dir.SetOwnerError!void {
    _ = userdata;
    _ = dir;
    _ = owner;
    _ = group;
    return error.FileNotFound;
}

pub fn failingDirSetFileOwner(userdata: ?*anyopaque, dir: std.Io.Dir, sub_path: []const u8, owner: ?File.Uid, group: ?File.Gid, options: Dir.SetFileOwnerOptions) Dir.SetFileOwnerError!void {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = owner;
    _ = group;
    _ = options;
    return error.FileNotFound;
}

pub fn failingDirSetPermissions(userdata: ?*anyopaque, dir: Dir, permissions: Dir.Permissions) Dir.SetPermissionsError!void {
    _ = userdata;
    _ = dir;
    _ = permissions;
    return error.FileNotFound;
}

pub fn failingDirSetFilePermissions(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: File.Permissions, options: Dir.SetFilePermissionsOptions) Dir.SetFilePermissionsError!void {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = permissions;
    _ = options;
    return error.FileNotFound;
}

pub fn noDirSetTimestamps(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.SetTimestampsOptions) Dir.SetTimestampsError!void {
    _ = userdata;
    _ = dir;
    _ = sub_path;
    _ = options;
    // no-op
}

pub fn failingDirHardLink(userdata: ?*anyopaque, old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8, options: Dir.HardLinkOptions) Dir.HardLinkError!void {
    _ = userdata;
    _ = old_dir;
    _ = old_sub_path;
    _ = new_dir;
    _ = new_sub_path;
    _ = options;
    return error.FileNotFound;
}

pub fn failingFileStat(userdata: ?*anyopaque, file: File) File.StatError!File.Stat {
    _ = userdata;
    _ = file;
    return error.Streaming;
}

pub fn failingFileLength(userdata: ?*anyopaque, file: File) File.LengthError!u64 {
    _ = userdata;
    _ = file;
    return error.Streaming;
}

pub fn unreachableFileClose(userdata: ?*anyopaque, files: []const File) void {
    _ = userdata;
    _ = files;
    unreachable;
}

pub fn failingFileWritePositional(userdata: ?*anyopaque, file: File, header: []const u8, data: []const []const u8, splat: usize, offset: u64) File.WritePositionalError!usize {
    _ = userdata;
    _ = file;
    _ = offset;
    if (header.len != 0) return error.BrokenPipe;
    for (data[0 .. data.len - 1]) |item| {
        if (item.len > 0) return error.BrokenPipe;
    }
    if (data[data.len - 1].len != 0 and splat != 0) return error.BrokenPipe;
    return 0;
}

pub fn noFileWriteFileStreaming(userdata: ?*anyopaque, file: File, header: []const u8, file_reader: *Io.File.Reader, limit: Io.Limit) File.Writer.WriteFileError!usize {
    _ = userdata;
    _ = file;
    _ = header;
    _ = file_reader;
    _ = limit;
    return error.Unimplemented;
}

pub fn noFileWriteFilePositional(userdata: ?*anyopaque, file: File, header: []const u8, file_reader: *Io.File.Reader, limit: Io.Limit, offset: u64) File.WriteFilePositionalError!usize {
    _ = userdata;
    _ = file;
    _ = header;
    _ = file_reader;
    _ = limit;
    _ = offset;
    return error.Unimplemented;
}

pub fn failingFileReadPositional(userdata: ?*anyopaque, file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usize {
    _ = userdata;
    _ = file;
    _ = offset;
    for (data) |item| {
        if (item.len > 0) return error.InputOutput;
    }
    return 0;
}

pub fn failingFileSeekBy(userdata: ?*anyopaque, file: File, relative_offset: i64) File.SeekError!void {
    _ = userdata;
    _ = file;
    _ = relative_offset;
    return error.Unseekable;
}

pub fn failingFileSeekTo(userdata: ?*anyopaque, file: File, absolute_offset: u64) File.SeekError!void {
    _ = userdata;
    _ = file;
    _ = absolute_offset;
    return error.Unseekable;
}

pub fn failingFileSync(userdata: ?*anyopaque, file: File) File.SyncError!void {
    _ = userdata;
    _ = file;
    return error.NoSpaceLeft;
}

pub fn unreachableFileIsTty(userdata: ?*anyopaque, file: File) Cancelable!bool {
    _ = userdata;
    _ = file;
    unreachable;
}

pub fn unreachableFileEnableAnsiEscapeCodes(userdata: ?*anyopaque, file: File) File.EnableAnsiEscapeCodesError!void {
    _ = userdata;
    _ = file;
    unreachable;
}

pub fn unreachableFileSupportsAnsiEscapeCodes(userdata: ?*anyopaque, file: File) Cancelable!bool {
    _ = userdata;
    _ = file;
    unreachable;
}

pub fn failingFileSetLength(userdata: ?*anyopaque, file: File, length: u64) File.SetLengthError!void {
    _ = userdata;
    _ = file;
    _ = length;
    return error.NonResizable;
}

pub fn failingFileSetOwner(userdata: ?*anyopaque, file: File, owner: ?File.Uid, group: ?File.Gid) File.SetOwnerError!void {
    _ = userdata;
    _ = file;
    _ = owner;
    _ = group;
    return error.FileNotFound;
}

pub fn failingFileSetPermissions(userdata: ?*anyopaque, file: File, permissions: File.Permissions) File.SetPermissionsError!void {
    _ = userdata;
    _ = file;
    _ = permissions;
    return error.FileNotFound;
}

pub fn noFileSetTimestamps(userdata: ?*anyopaque, file: File, options: File.SetTimestampsOptions) File.SetTimestampsError!void {
    _ = userdata;
    _ = file;
    _ = options;
    // no-op
}

pub fn failingFileLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!void {
    _ = userdata;
    _ = file;
    _ = lock;
    return error.FileLocksUnsupported;
}

pub fn failingFileTryLock(userdata: ?*anyopaque, file: File, lock: File.Lock) File.LockError!bool {
    _ = userdata;
    _ = file;
    _ = lock;
    return error.FileLocksUnsupported;
}

pub fn unreachableFileUnlock(userdata: ?*anyopaque, file: File) void {
    _ = userdata;
    _ = file;
    unreachable;
}

pub fn failingFileDowngradeLock(userdata: ?*anyopaque, file: File) File.DowngradeLockError!void {
    _ = userdata;
    _ = file;
    // no-op
}

pub fn failingFileRealPath(userdata: ?*anyopaque, file: File, out_buffer: []u8) File.RealPathError!usize {
    _ = userdata;
    _ = file;
    _ = out_buffer;
    return error.FileNotFound;
}

pub fn failingFileHardLink(userdata: ?*anyopaque, file: File, new_dir: Dir, new_sub_path: []const u8, options: File.HardLinkOptions) File.HardLinkError!void {
    _ = userdata;
    _ = file;
    _ = new_dir;
    _ = new_sub_path;
    _ = options;
    return error.FileNotFound;
}

pub fn failingFileMemoryMapCreate(userdata: ?*anyopaque, file: File, options: File.MemoryMap.CreateOptions) File.MemoryMap.CreateError!File.MemoryMap {
    _ = userdata;
    _ = file;
    _ = options;
    return error.AccessDenied;
}

pub fn unreachableFileMemoryMapDestroy(userdata: ?*anyopaque, mm: *File.MemoryMap) void {
    _ = userdata;
    _ = mm;
    unreachable;
}

pub fn unreachableFileMemoryMapSetLength(userdata: ?*anyopaque, mm: *File.MemoryMap, new_len: usize) File.MemoryMap.SetLengthError!void {
    _ = userdata;
    _ = mm;
    _ = new_len;
    unreachable;
}

pub fn unreachableFileMemoryMapRead(userdata: ?*anyopaque, mm: *File.MemoryMap) File.ReadPositionalError!void {
    _ = userdata;
    _ = mm;
    unreachable;
}

pub fn unreachableFileMemoryMapWrite(userdata: ?*anyopaque, mm: *File.MemoryMap) File.WritePositionalError!void {
    _ = userdata;
    _ = mm;
    unreachable;
}

pub fn failingProcessExecutableOpen(userdata: ?*anyopaque, flags: Dir.OpenFileOptions) std.process.OpenExecutableError!File {
    _ = userdata;
    _ = flags;
    return error.FileNotFound;
}

pub fn failingProcessExecutablePath(userdata: ?*anyopaque, buffer: []u8) std.process.ExecutablePathError!usize {
    _ = userdata;
    _ = buffer;
    return error.FileNotFound;
}

pub fn unreachableLockStderr(userdata: ?*anyopaque, terminal_mode: ?Terminal.Mode) Cancelable!LockedStderr {
    _ = userdata;
    _ = terminal_mode;
    unreachable;
}

pub fn noTryLockStderr(userdata: ?*anyopaque, terminal_mode: ?Terminal.Mode) Cancelable!?LockedStderr {
    _ = userdata;
    _ = terminal_mode;
    return null;
}

pub fn unreachableUnlockStderr(userdata: ?*anyopaque) void {
    _ = userdata;
    unreachable;
}

pub fn failingProcessCurrentPath(userdata: ?*anyopaque, buffer: []u8) std.process.CurrentPathError!usize {
    _ = userdata;
    _ = buffer;
    return error.CurrentDirUnlinked;
}

pub fn failingProcessSetCurrentDir(userdata: ?*anyopaque, dir: Dir) std.process.SetCurrentDirError!void {
    _ = userdata;
    _ = dir;
    return error.FileNotFound;
}

pub fn failingProcessSetCurrentPath(userdata: ?*anyopaque, path: []const u8) std.process.SetCurrentPathError!void {
    _ = userdata;
    _ = path;
    return error.FileNotFound;
}

pub fn failingProcessReplace(userdata: ?*anyopaque, options: std.process.ReplaceOptions) std.process.ReplaceError {
    _ = userdata;
    _ = options;
    return error.OperationUnsupported;
}

pub fn failingProcessSpawn(userdata: ?*anyopaque, options: std.process.SpawnOptions) std.process.SpawnError!std.process.Child {
    _ = userdata;
    _ = options;
    return error.OperationUnsupported;
}

pub fn unreachableChildWait(userdata: ?*anyopaque, child: *std.process.Child) std.process.Child.WaitError!std.process.Child.Term {
    _ = userdata;
    _ = child;
    unreachable;
}

pub fn unreachableChildKill(userdata: ?*anyopaque, child: *std.process.Child) void {
    _ = userdata;
    _ = child;
    unreachable;
}

pub fn failingProgressParentFile(userdata: ?*anyopaque) std.Progress.ParentFileError!File {
    _ = userdata;
    return error.UnsupportedOperation;
}

pub fn failingInheritParentDir(userdata: ?*anyopaque, handle: Dir.Handle) InheritParentHandleError!Dir {
    _ = userdata;
    _ = handle;
    return error.UnsupportedOperation;
}

pub fn failingInheritParentFile(userdata: ?*anyopaque, handle: File.Handle, flags: File.Flags) InheritParentHandleError!File {
    _ = userdata;
    _ = handle;
    _ = flags;
    return error.UnsupportedOperation;
}

pub fn noRandom(userdata: ?*anyopaque, buffer: []u8) void {
    _ = userdata;
    @memset(buffer, 0);
}

pub fn failingRandomSecure(userdata: ?*anyopaque, buffer: []u8) RandomSecureError!void {
    _ = userdata;
    _ = buffer;
    return error.EntropyUnavailable;
}

pub fn noNow(userdata: ?*anyopaque, clock: Clock) Timestamp {
    _ = userdata;
    _ = clock;
    return .zero;
}

pub fn failingClockResolution(userdata: ?*anyopaque, clock: Clock) Clock.ResolutionError!Duration {
    _ = userdata;
    _ = clock;
    return error.ClockUnavailable;
}

pub fn noSleep(userdata: ?*anyopaque, clock: Timeout) Cancelable!void {
    _ = userdata;
    _ = clock;
}

pub fn failingNetListenIp(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ListenOptions) net.IpAddress.ListenError!net.Socket {
    _ = userdata;
    _ = address;
    _ = options;
    return error.NetworkDown;
}

pub fn failingNetAccept(userdata: ?*anyopaque, listen_fd: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socket {
    _ = userdata;
    _ = listen_fd;
    _ = options;
    return error.NetworkDown;
}

pub fn failingNetBindIp(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.BindOptions) net.IpAddress.BindError!net.Socket {
    _ = userdata;
    _ = address;
    _ = options;
    return error.NetworkDown;
}

pub fn failingNetConnectIp(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ConnectOptions) net.IpAddress.ConnectError!net.Socket {
    _ = userdata;
    _ = address;
    _ = options;
    return error.NetworkDown;
}

pub fn failingNetListenUnix(userdata: ?*anyopaque, address: *const net.UnixAddress, options: net.UnixAddress.ListenOptions) net.UnixAddress.ListenError!net.Socket.Handle {
    _ = userdata;
    _ = address;
    _ = options;
    return error.NetworkDown;
}

pub fn failingNetConnectUnix(userdata: ?*anyopaque, address: *const net.UnixAddress) net.UnixAddress.ConnectError!net.Socket.Handle {
    _ = userdata;
    _ = address;
    return error.NetworkDown;
}

pub fn failingNetSocketCreatePair(userdata: ?*anyopaque, options: net.Socket.CreatePairOptions) net.Socket.CreatePairError![2]net.Socket {
    _ = userdata;
    _ = options;
    return error.OperationUnsupported;
}

pub fn failingNetWriteFile(userdata: ?*anyopaque, handle: net.Socket.Handle, header: []const u8, file_reader: *Io.File.Reader, limit: Io.Limit) net.Stream.Writer.WriteFileError!usize {
    _ = userdata;
    _ = handle;
    _ = header;
    _ = file_reader;
    _ = limit;
    return error.NetworkDown;
}

pub fn unreachableNetClose(userdata: ?*anyopaque, sockets: []const net.Socket) void {
    _ = userdata;
    _ = sockets;
    unreachable;
}

pub fn failingNetShutdown(userdata: ?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!void {
    _ = userdata;
    _ = handle;
    _ = how;
    return error.NetworkDown;
}

pub fn failingNetInterfaceNameResolve(userdata: ?*anyopaque, name: *const net.Interface.Name) net.Interface.Name.ResolveError!net.Interface {
    _ = userdata;
    _ = name;
    return error.InterfaceNotFound;
}

pub fn unreachableNetInterfaceName(userdata: ?*anyopaque, interface: net.Interface) net.Interface.NameError!net.Interface.Name {
    _ = userdata;
    _ = interface;
    unreachable;
}

pub fn failingNetLookup(userdata: ?*anyopaque, host_name: net.HostName, resolved: *Queue(net.HostName.LookupResult), options: net.HostName.LookupOptions) net.HostName.LookupError!void {
    _ = userdata;
    _ = host_name;
    _ = resolved;
    _ = options;
    return error.NetworkDown;
}

test failing {
    const f: Io = .failing;
    // file stuff
    try std.testing.expectError(error.NoSpaceLeft, Dir.createDir(.cwd(), f, "test", .default_dir));
    try std.testing.expectError(error.NoSpaceLeft, Dir.createFile(.cwd(), f, "test", .{}));
    try std.testing.expectError(error.FileNotFound, Dir.openDir(.cwd(), f, "test", .{}));
    try std.testing.expectError(error.FileNotFound, Dir.openFile(.cwd(), f, "test", .{}));
    try File.writeStreamingAll(.stdout(), f, &.{});
    try std.testing.expectError(error.AccessDenied, File.MemoryMap.create(f, .stdout(), .{ .len = 0 }));
    // async stuff
    const closure = struct {
        var foo: usize = 0;
        fn doOp() void {
            foo = 4;
        }
    };
    var future = f.async(closure.doOp, .{});
    _ = future.await(f);
    try std.testing.expect(closure.foo == 4);
    // random stuff
    var buffer: [1]u8 = undefined;
    f.random(&buffer);
    try std.testing.expect(buffer[0] == 0);
}