Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

read

Returns the number of bytes that were read, which can be less than buf.len. If 0 bytes were read, that means EOF. If fd is opened in non blocking mode, the function will return error.WouldBlock when EAGAIN is received.

Linux has a limit on how many bytes may be transferred in one read call, which is 0x7ffff000 on both 64-bit and 32-bit systems. This is due to using a signed C int as the return value, as well as stuffing the errno codes into the last 4096 values. This is noted on the read man page. The limit on Darwin is 0x7fffffff, trying to read more than that returns EINVAL. The corresponding POSIX limit is maxInt(isize).

posix.read
pub fn read(fd: fd_t, buf: []u8) ReadError!usize

File

lib/std/posix.zig:400

Code

pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
    if (buf.len == 0) return 0;
    if (native_os == .windows) @compileError("unsupported OS");
    if (native_os == .wasi) @compileError("unsupported OS");

    // Prevents EINVAL.
    const max_count = switch (native_os) {
        .linux => 0x7ffff000,
        .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => maxInt(i32),
        else => maxInt(isize),
    };
    while (true) {
        const rc = system.read(fd, buf.ptr, @min(buf.len, max_count));
        switch (errno(rc)) {
            .SUCCESS => return @intCast(rc),
            .INTR => continue,
            .INVAL => unreachable,
            .FAULT => unreachable,
            .AGAIN => return error.WouldBlock,
            .CANCELED => return error.Canceled,
            .BADF => return error.Unexpected, // use after free
            .IO => return error.InputOutput,
            .ISDIR => return error.IsDir,
            .NOBUFS => return error.SystemResources,
            .NOMEM => return error.SystemResources,
            .NOTCONN => return error.SocketUnconnected,
            .CONNRESET => return error.ConnectionResetByPeer,
            .TIMEDOUT => return error.Unexpected,
            else => |err| return unexpectedErrno(err),
        }
    }
}