← std

std/io.kur

//! Input and output through the standard streams and files.
//!
//! Process I/O over the POSIX `read`/`write`/`open`/`close`/`fstat` calls:
//! printing to standard output (`print`) and standard error (`eprint`),
//! any `Printable` value: `print("done\n")`, `print(f"{n} files\n")`;
//! the owning descriptor type `File!`; `Output!`, the one buffered writer,
//! of standard output, standard error or a file (`File!::output`);
//! `Input!`, the one buffered reader, of standard input (`stdin`) or a file
//! (`File!::input`);
//! and `Error`, the error of every operating-system call of the library.
//! Paths are any byte view (`c_string`); `std::fs` works with them whole.

use package as std;

use alloc::buffer::Buffer!;
use core::mem::alloca;
use core::ptr::offset;
use core::slice::ReadBytes;
use core::str::Str;
use core::fmt::{Format, Printable, Writer};
use core::option::{Option, Result};
// The system calls: a read or write a signal interrupts is made again,
// descriptors are opened close-on-exec, and a failure is an errno.
use libc::io::{kur_libc_fs_read, kur_libc_fs_write, kur_libc_fs_open_read, kur_libc_fs_create, kur_libc_fs_close,
    kur_libc_fs_regular_size, kur_libc_fs_size_hint, kur_libc_stdin_claim, kur_libc_stdin_release, kur_libc_error_kind,
    kur_libc_error_message};

/// A path, name or argument for C: the bytes of a view, read through the
/// capability that permits it, followed by a NUL, in a buffer the caller
/// frees once the call is made. The C functions (`libc`) that take one also
/// take its length, and fail with EINVAL when the bytes hold a NUL of their
/// own, which C would read as the end.
forall C, S where ReadBytes[C, S], Copy[S].
fn c_string(&cx: C, bytes: S) -> Buffer! {
    Buffer!::new().write(&cx, bytes).write_byte(0u8)
}

/// An I/O error: the `errno` of the system call that failed, or EIO (5)
/// for a failure the system did not report itself (a `write` that made no
/// progress). Every fallible function here reports one. It describes itself
/// (`message`), says what kind of failure it is (`kind`), and formats as
/// its description and its number, `No such file or directory (error 2)`,
/// so `f"cannot read {path}: {e}\n"` reports it.
exposed struct Error {
    errno: i32,
}

/// What kind of failure an `Error` is, for code that handles some kinds:
/// the errnos a portable program tells apart, whatever their numbers on
/// the host. `Other` is every other errno; `errno` still tells them apart.
exposed enum ErrorKind {
    // ENOENT: no such file or directory.
    NotFound,
    // EACCES or EPERM.
    PermissionDenied,
    // EEXIST.
    AlreadyExists,
    // EISDIR: a directory where a file was wanted.
    IsADirectory,
    // ENOTDIR: a file where a directory was wanted, in a path.
    NotADirectory,
    // ENOTEMPTY: removing a directory that holds something.
    DirectoryNotEmpty,
    // EINVAL: an argument the call does not take, such as a path holding a NUL.
    InvalidInput,
    // EPIPE: writing to a pipe nothing reads any more.
    BrokenPipe,
    // EINTR: a signal interrupted the call.
    Interrupted,
    // EAGAIN or EWOULDBLOCK: the call would have had to wait.
    WouldBlock,
    // ETIMEDOUT.
    TimedOut,
    // EBUSY: in use, such as standard input held by an `Input!`.
    Busy,
    // ENOSPC: no space left on the device.
    StorageFull,
    // ENOMEM.
    OutOfMemory,
    // ENOSYS or ENOTSUP: the host does not do it.
    Unsupported,
    // Any other errno.
    Other,
}

impl Error {
    /// The error a negative return of a C function (`libc`) stands for.
    fn of_return(n: isize) -> Error {
        Error.{ errno: 0i32 - (n as i32) }
    }

    /// EIO, for a failure the system did not report itself.
    fn io() -> Error {
        Error.{ errno: 5i32 }
    }

    /// The kind of failure, from the errno: the C runtime sorts the host's
    /// numbers into the kinds.
    fn kind(self) -> ErrorKind {
        let k = unsafe kur_libc_error_kind(self.errno);
        if k == 1i32 {
            ErrorKind::NotFound
        } else if k == 2i32 {
            ErrorKind::PermissionDenied
        } else if k == 3i32 {
            ErrorKind::AlreadyExists
        } else if k == 4i32 {
            ErrorKind::IsADirectory
        } else if k == 5i32 {
            ErrorKind::NotADirectory
        } else if k == 6i32 {
            ErrorKind::DirectoryNotEmpty
        } else if k == 7i32 {
            ErrorKind::InvalidInput
        } else if k == 8i32 {
            ErrorKind::BrokenPipe
        } else if k == 9i32 {
            ErrorKind::Interrupted
        } else if k == 10i32 {
            ErrorKind::WouldBlock
        } else if k == 11i32 {
            ErrorKind::TimedOut
        } else if k == 12i32 {
            ErrorKind::Busy
        } else if k == 13i32 {
            ErrorKind::StorageFull
        } else if k == 14i32 {
            ErrorKind::OutOfMemory
        } else if k == 15i32 {
            ErrorKind::Unsupported
        } else {
            ErrorKind::Other
        }
    }

    /// The C library's description of the errno, as `strerror` gives it
    /// (`No such file or directory`), read thread-safely (`strerror_r`).
    fn message(self) -> Buffer! {
        var text = Buffer!::with_capacity(128usize);
        let room = &text.remaining_capacity();
        let dest = unsafe &text.tail_ptr();
        // `dest[0..room)` is the room `text` has; the call writes at most
        // `room` bytes there and says how many.
        let n = unsafe kur_libc_error_message(self.errno, dest, room);
        unsafe text.commit(n)
    }
}

/// An error formats as its description and its errno:
/// `No such file or directory (error 2)`.
forall W where Writer[W].
instance Format[Error, W] {
    fn format(value: Error, out: W) -> (Error, W) {
        (value, Printable[Error, W]::print(value, out))
    }
}

/// An error prints as it formats: `No such file or directory (error 2)`.
forall W where Writer[W].
instance Printable[Error, W] {
    fn print(value: Error, out: W) -> W {
        out.put(value.message()).put(" (error ").put(value.errno).put(")")
    }
}

// -------------------------------------------------------------- output --
// Output goes through an `Output!`: over standard output (`stdout`, and
// `print`), standard error (`stderr`, and `eprint`), or a file it owns
// (`File!::output`). No safe function takes a descriptor number: a number
// could name a descriptor a `File!` owns, or one closed and reused, and
// writing to it would go around the `File!` that owns it.
//
// `write_all` retries partial writes (`write(2)` may write fewer bytes
// than requested, even to a regular file) until every byte is written. It
// fails with the call's errno on a negative return, and with EIO on zero
// progress (`write` returning 0, which POSIX permits and which would
// otherwise loop forever). `Output!::finish` returns the first failure; a
// caller that prints to its own stdout or stderr and has no recovery
// discards it, while a program whose output is its product checks it.
// Writing to a closed pipe is such a failure (EPIPE), not the end of the
// process: the C `main` the compiler writes for an executable ignores
// SIGPIPE.

/// Writes `ptr[0..len)` to `fd`, retrying partial writes. Caller:
/// `ptr[0..len)` is readable, and `fd` is a descriptor the caller may write:
/// standard output or error, or one a `File!` it holds owns.
unsafe fn write_all(fd: i32, ptr: *u8, len: usize) -> Result[(), Error] {
    var done = 0usize;
    while done < len {
        let n = unsafe kur_libc_fs_write(fd, unsafe offset(ptr, done), len - done);
        if n < 0isize {
            return Result::Err.(Error::of_return(n));
        }
        if n == 0isize {
            return Result::Err.(Error::io());
        }
        done = done + (n as usize);
    }
    Result::Ok.(())
}

// `print` writes to standard output (descriptor 1), `eprint` to standard
// error (descriptor 2): the process's own streams, which any of its code
// may write. Each writes through an `Output!` of its own, finished before
// it returns, so what it prints is written by the time it returns.

/// Prints `x` to standard output (`Printable`): `print("done\n")`,
/// `print(f"{n} files\n")`. Returns an I/O error on failure.
forall T where Printable[T, Output!].
fn print(x: T) -> Result[(), Error] {
    stdout().put(x).finish()
}

/// Prints `x` to standard error, as `print` does to standard output.
forall T where Printable[T, Output!].
fn eprint(x: T) -> Result[(), Error] {
    stderr().put(x).finish()
}

// --------------------------------------------------------------- input --

/// Reads at most `max` bytes from `fd`, with one `read(2)`, appending them
/// to `buf`: how many, which is 0 at the end of the input (and for a `max`
/// of 0, which reads nothing). Fewer than `max` is no sign of the end: a
/// pipe gives what it has. The error of a failed read, with `buf` as it
/// was. Caller: `fd` is a descriptor the caller may read: stdin, or one a
/// `File!` it holds owns.
unsafe fn read_into(fd: i32, &buf: Buffer!, max: usize) -> Result[usize, Error] {
    if max == 0usize {
        return Result::Ok.(0usize);
    }
    buf = buf.reserve(max);
    let dest = unsafe &buf.tail_ptr();
    let n = unsafe kur_libc_fs_read(fd, dest, max);
    if n < 0isize {
        return Result::Err.(Error::of_return(n));
    }
    // A successful read returning `n` wrote exactly `dest[0..n)`, with
    // `n <= max`, inside the room `reserve` made. `n < 0` has been ruled
    // out, so the cast cannot turn an error into a length.
    buf = unsafe buf.commit(n as usize);
    Result::Ok.(n as usize)
}

/// Reads `fd` to EOF, appending to `b` and returning it. Each read fills
/// the room `b` has, and a full `b` grows first, by at least 4096 bytes and
/// at least doubling, so a `b` made with room for all the input and one
/// byte more reads it without growing. A read error frees what was read and
/// is returned: it never looks like the end of the input. Caller: `fd` is a
/// descriptor the caller may read, as for `read_into`.
unsafe fn read_to_end_from(fd: i32, b: Buffer!) -> Result[Buffer!, Error] {
    var b = b;
    while true {
        let room = &b.remaining_capacity();
        match unsafe read_into(fd, &b, if room == 0usize { 4096usize } else { room }) {
            Ok(n) => if n == 0usize {
                return Result::Ok.(b);
            },
            Err(e) => {
                b.destroy();
                return Result::Err.(e);
            },
        }
    }
    Result::Ok.(b)
}

// Input comes through an `Input!`: over standard input (`stdin`) or a file
// it owns (`File!::input`). It reads ahead into a buffer of 64 KiB when it
// looks for the end of a line, and hands those bytes out before it reads
// more. Bytes an `Input!` has read ahead are its own: another reader of
// standard input would skip them. So one `Input!` at a time holds standard
// input, by a flag io.c keeps (`kur_libc_stdin_claim`): `stdin` fails with
// EBUSY while one holds it. `read_to_end` gives it back with the rest of
// the input, and `finish` with the bytes read ahead and not yet returned.
// Code that reads standard input without an `Input!` (a C library, a child
// process `std::process` starts) does not see the bytes one has read ahead.

/// What an `Input!` reads: standard input, which it holds until its end
/// (`read_to_end` or `finish`), or a file it owns and closes then.
enum Source! {
    Stdin,
    File(File!),
}

impl Source! {
    /// The descriptor read: 0 for standard input, or the file's.
    fn descriptor(&self) -> i32 {
        let (source, fd) = match self {
            Stdin => (Source!::Stdin, 0i32),
            File(f) => {
                var f = f;
                let fd = &f.descriptor();
                (Source!::File.(f), fd)
            },
        };
        self = source;
        fd
    }

    /// The room to read the rest of the source into without growing the
    /// buffer, beyond what was read ahead: for a file, its size and 4096
    /// bytes for the read that finds the end (only those bytes for a pipe,
    /// device or socket, whose size says nothing); nothing for standard
    /// input, read as it comes. A directory is EISDIR.
    fn room(&self) -> Result[usize, Error] {
        let (source, room) = match self {
            Stdin => (Source!::Stdin, Result::Ok.(0usize)),
            File(f) => {
                var f = f;
                let fd = &f.descriptor();
                // `fd` is the descriptor `f` owns.
                let hint = unsafe kur_libc_fs_size_hint(fd);
                let room = if hint < 0isize { Result::Err.(Error::of_return(hint)) } else { Result::Ok.((hint as usize) + 4096usize) };
                (Source!::File.(f), room)
            },
        };
        self = source;
        room
    }

    /// Gives standard input back, or closes the file and reports a failed
    /// `close(2)`.
    fn finish(self) -> Result[(), Error] {
        match self {
            Stdin => {
                unsafe kur_libc_stdin_release();
                Result::Ok.(())
            },
            File(f) => f.close(),
        }
    }
}

/// A buffered reader of standard input or a file: lines (`read_line`),
/// chunks (`read`, `read_exact`) and the rest (`read_to_end`). Standard
/// input's is the one reader of it while it lives (see `stdin`). Its end,
/// `read_to_end` or `finish`, gives standard input back or closes the file.
struct Input! {
    source: Source!,
    // What was read ahead and not returned yet, `ahead[start..)`; none
    // until `read_line` first reads ahead.
    ahead: Option[Buffer!],
    start: usize,
}

/// Standard input, held by the `Input!` returned until its `read_to_end`
/// or `finish`, or EBUSY while another `Input!` holds it.
fn stdin() -> Result[Input!, Error] {
    let claimed = unsafe kur_libc_stdin_claim();
    if claimed != 0i32 {
        Result::Err.(Error.{ errno: claimed })
    } else {
        Result::Ok.(Input!.{ source: Source!::Stdin, ahead: Option::None, start: 0usize })
    }
}

impl Input! {
    /// The next line, without its newline: `None` at the end of input,
    /// when no byte is left to read; an empty line is `Some` of an empty
    /// buffer, and a last line with no newline is still a line. A read
    /// error is returned, and the bytes of the line read before it are lost
    /// with it. It reads ahead, 64 KiB at a time.
    fn read_line(&self) -> Result[Option[Buffer!], Error] {
        var { source, ahead, start } = self;
        let fd = &source.descriptor();
        var buf = match ahead {
            Some(buf) => buf,
            None => Buffer!::with_capacity(65536usize),
        };
        var line = Buffer!::new();
        while true {
            let n = &buf.len();
            let p = unsafe &buf.as_ptr();
            // `p[0..n)` are the bytes `buf` holds, unchanged until `buf`
            // is pushed to or freed.
            var end = start;
            while end < n && unsafe *(unsafe offset(p, end)) != b'\n' {
                end = end + 1usize;
            }
            line = unsafe Writer[Buffer!]::write_raw(line, unsafe offset(p, start), end - start);
            if end < n {
                self = Input!.{ source, ahead: Option::Some.(buf), start: end + 1usize };
                return Result::Ok.(Option::Some.(line));
            }
            // Every byte read ahead is in `line`: read more into the room.
            start = 0usize;
            buf = buf.clear();
            let room = &buf.remaining_capacity();
            // `fd` is standard input, which this `Input!` holds, or the
            // descriptor of the file it owns.
            match unsafe read_into(fd, &buf, room) {
                Err(e) => {
                    self = Input!.{ source, ahead: Option::Some.(buf), start };
                    line.destroy();
                    return Result::Err.(e);
                },
                Ok(got) => if got == 0usize {
                    self = Input!.{ source, ahead: Option::Some.(buf), start };
                    if &line.len() > 0usize {
                        return Result::Ok.(Option::Some.(line));
                    }
                    line.destroy();
                    return Result::Ok.(Option::None);
                },
            }
        }
        self = Input!.{ source, ahead: Option::Some.(buf), start };
        Result::Ok.(Option::Some.(line))
    }

    /// The rest of the input, read to its end, the bytes read ahead first,
    /// and the reading ended: standard input is given back, for the next
    /// `stdin`, and a file is closed. A file's is read into a buffer sized
    /// up front by the file's size, so a regular file is read without
    /// growing it; reading goes on to EOF whatever the size said, so a file
    /// that grows or shrinks meanwhile is read as it is, and a pipe, device
    /// or socket is read until it ends. A directory is EISDIR. A failure to
    /// read, or else to close the file, is the error: a read error takes
    /// precedence, and a failed close frees what was read.
    fn read_to_end(self) -> Result[Buffer!, Error] {
        var { source, ahead, start } = self;
        let fd = &source.descriptor();
        let all = match &source.room() {
            Err(e) => {
                match ahead {
                    Some(buf) => buf.destroy(),
                    None => (),
                }
                Result::Err.(e)
            },
            Ok(room) => {
                let rest = match ahead {
                    Some(buf) => rest_of(buf, start, room),
                    None => Buffer!::with_capacity(room),
                };
                // `fd` is standard input, which this `Input!` holds, or the
                // descriptor of the file it owns.
                unsafe read_to_end_from(fd, rest)
            },
        };
        match source.finish() {
            Ok(nothing) => all,
            Err(e) => match all {
                Ok(read) => {
                    read.destroy();
                    Result::Err.(e)
                },
                Err(failed) => Result::Err.(failed),
            },
        }
    }

    /// Reads at most `max` bytes, appending them to `buf`: how many, which
    /// is 0 at the end of the input (and for a `max` of 0). Bytes read ahead
    /// come first, and while there are any, no more are read; else it is
    /// one `read(2)`. Fewer than `max` is no sign of the end (a pipe gives
    /// what it has); read until it returns 0. A failed read is the error,
    /// with `buf` as it was.
    fn read(&self, &buf: Buffer!, max: usize) -> Result[usize, Error] {
        var { source, ahead, start } = self;
        match ahead {
            Some(held) => {
                var held = held;
                let n = &held.len();
                if start < n {
                    let count = if n - start < max { n - start } else { max };
                    let p = unsafe &held.as_ptr();
                    // `p[start..n)` are bytes `held` holds, and `count <= n - start`.
                    buf = unsafe Writer[Buffer!]::write_raw(buf, unsafe offset(p, start), count);
                    self = Input!.{ source, ahead: Option::Some.(held), start: start + count };
                    return Result::Ok.(count);
                }
                ahead = Option::Some.(held);
            },
            None => {
                ahead = Option::None;
            },
        }
        let fd = &source.descriptor();
        // `fd` is standard input, which this `Input!` holds, or the
        // descriptor of the file it owns.
        let got = unsafe read_into(fd, &buf, max);
        self = Input!.{ source, ahead, start };
        got
    }

    /// Reads `size` bytes, appending them to `buf`, again after each short
    /// read: how many, which is fewer only at the end of the input. Bytes
    /// read ahead come first. A failed read is the error, even when some
    /// bytes were appended before it; they stay in `buf`.
    fn read_exact(&self, &buf: Buffer!, size: usize) -> Result[usize, Error] {
        var done = 0usize;
        while done < size {
            match &self.read(&buf, size - done) {
                Ok(n) => if n == 0usize {
                    return Result::Ok.(done);
                } else {
                    done = done + n;
                },
                Err(e) => return Result::Err.(e),
            }
        }
        Result::Ok.(done)
    }

    /// Ends the reading: the bytes read ahead and not returned yet, which
    /// no later reader sees. Standard input is given back, for the next
    /// `stdin`; a file is closed, and a failed `close(2)` is the error, with
    /// those bytes freed.
    fn finish(self) -> Result[Buffer!, Error] {
        let { source, ahead, start } = self;
        let rest = match ahead {
            Some(buf) => rest_of(buf, start, 0usize),
            None => Buffer!::with_capacity(0usize),
        };
        match source.finish() {
            Ok(nothing) => Result::Ok.(rest),
            Err(e) => {
                rest.destroy();
                Result::Err.(e)
            },
        }
    }
}

/// `buf[start..)` in a buffer of its own, with room for `room` bytes more;
/// `buf` is freed.
fn rest_of(buf: Buffer!, start: usize, room: usize) -> Buffer! {
    var buf = buf;
    let n = &buf.len();
    let p = unsafe &buf.as_ptr();
    // `p[start..n)` are bytes `buf` holds, and `buf` is freed after the copy.
    let rest = unsafe Writer[Buffer!]::write_raw(Buffer!::with_capacity(n - start + room), unsafe offset(p, start), n - start);
    buf.destroy();
    rest
}

// ----------------------------------------------------------- File! --
// An owner of exactly one open descriptor, with one terminal operation,
// `close`, which `Input!::finish` and `Output!::finish` reach for a file
// they own. `File!` is restricted so that a safe constructor never accepts
// an arbitrary integer and later reads, writes or closes it: without that,
// safe code could build `File! { fd: 3 }` over a descriptor it never opened
// and close whatever the process holds at that number. A `File!` comes
// only from `open_read` and `create`, which open a fresh descriptor, or
// from `unsafe adopt`. No safe function here takes a bare descriptor to
// read or close.
//
// Standard input, output and error stay bare `i32`s (0/1/2), never
// `File!`: they are borrowed process handles this program did not open
// and must not close. Only this module names them, in `stdin`, `stdout`
// and `stderr`, which make an `Input!` or an `Output!` over one. A `File!`
// never gets one of their numbers: the C `main` the compiler writes for an
// executable opens /dev/null on each of the three the process started
// without, before the program runs.
/// Owns one open file descriptor. Read it through `input`, write it
/// through `output`, or call `close` to consume it.
struct File! {
    fd: i32,
}

impl File! {
    /// Opens the file at `path`, any byte view read through `cx`,
    /// read-only. Safe: the descriptor it wraps is always one this call
    /// opened. Fails with the errno of `open(2)`, or EINVAL for a path
    /// holding a NUL.
    forall C, S where ReadBytes[C, S], Copy[S].
    fn open_read(&cx: C, path: S) -> Result[File!, Error] {
        var text = c_string(&cx, path);
        let p = unsafe &text.as_ptr();
        // `p` holds the path's `len` bytes and a NUL.
        let fd = unsafe kur_libc_fs_open_read(p, &text.len() - 1usize);
        text.destroy();
        if fd < 0i32 {
            Result::Err.(Error.{ errno: 0i32 - fd })
        } else {
            Result::Ok.(File!.{ fd })
        }
    }

    /// Creates the file at `path`, or empties it, and opens it for writing;
    /// a new file gets mode 0644 less the umask. Fails as `open_read` does.
    forall C, S where ReadBytes[C, S], Copy[S].
    fn create(&cx: C, path: S) -> Result[File!, Error] {
        var text = c_string(&cx, path);
        let p = unsafe &text.as_ptr();
        let fd = unsafe kur_libc_fs_create(p, &text.len() - 1usize);
        text.destroy();
        if fd < 0i32 {
            Result::Err.(Error.{ errno: 0i32 - fd })
        } else {
            Result::Ok.(File!.{ fd })
        }
    }

    /// Wraps an already-open descriptor obtained elsewhere as an owning
    /// `File!`. Caller: `fd` is live and open with no other owner, and this
    /// `File!`'s `close` is the program's only remaining use of it -- the
    /// `HeapAllocator::adopt_raw` obligation, for descriptors.
    unsafe fn adopt(fd: i32) -> File! {
        File!.{ fd }
    }

    /// Closes the descriptor.
    ///
    /// The terminal operation: the checker requires every `File!` to reach
    /// `close`. The `File!` is consumed even when `close(2)` fails, which is
    /// reported with its errno.
    fn close(self) -> Result[(), Error] {
        let { fd } = self;
        let status = unsafe kur_libc_fs_close(fd);
        if status != 0i32 {
            Result::Err.(Error.{ errno: status })
        } else {
            Result::Ok.(())
        }
    }

    /// The byte size of a regular file, from `fstat(2)`. Anything else is an
    /// error: EISDIR for a directory, EINVAL for a pipe, device or socket,
    /// whose size says nothing about what a read will return. A `u64`, as
    /// `std::fs::Metadata`'s `size` is: a file's size is the file system's
    /// number, which a 32-bit address space need not hold.
    fn file_size(&self) -> Result[u64, Error] {
        let { fd } = self;
        let size = unsafe alloca[u64]();
        unsafe *size = 0u64;
        // `size` is a live `u64`.
        let code = unsafe kur_libc_fs_regular_size(fd, size);
        self = File!.{ fd };
        if code != 0i32 {
            Result::Err.(Error.{ errno: code })
        } else {
            Result::Ok.(unsafe *size)
        }
    }

    /// The descriptor's number, for a C interface or another process (a
    /// `std::process::Stdio!::File` hands a child a copy). No safe function
    /// takes a number to read, write or close, so it grants nothing.
    fn descriptor(&self) -> i32 {
        let { fd } = self;
        self = File!.{ fd };
        fd
    }

    /// A reader of the file from its offset, which owns it and closes it on
    /// `read_to_end` or `finish`.
    fn input(self) -> Input! {
        Input!.{ source: Source!::File.(self), ahead: Option::None, start: 0usize }
    }

    /// A buffered writer to the file at its offset, which owns it and
    /// closes it on `finish`.
    fn output(self) -> Output! {
        Output!.{ sink: Sink!::File.(self), buf: Buffer!::new(), error: 0i32 }
    }
}

// ---------------------------------------------------------------------
// Buffered output: a writer for f-strings and the `core::fmt` protocol.
//
//     let done = f"{name}: {count}\n".write(stdout()).finish();
//
// Output collects bytes and writes them once 4 KiB have gathered, on
// `flush`, or on `finish`; one raw write of 4 KiB or more goes out at once,
// after them. Its error is sticky: once a write fails, the
// rest is dropped, and `finish` reports the first failure (`error` holds
// its errno, 0 until then).

/// Where an `Output!` writes: standard output or error, which it does not
/// own and never closes, or a file it owns and closes on `finish`.
enum Sink! {
    // standard output (1) or standard error (2)
    Stream(i32),
    File(File!),
}

impl Sink! {
    /// The descriptor written to.
    fn descriptor(&self) -> i32 {
        let (sink, fd) = match self {
            Stream(fd) => (Sink!::Stream.(fd), fd),
            File(f) => {
                var f = f;
                let fd = &f.descriptor();
                (Sink!::File.(f), fd)
            },
        };
        self = sink;
        fd
    }

    /// Closes the file, reporting a failed `close(2)`; a stream stays open.
    fn close(self) -> Result[(), Error] {
        match self {
            Stream(fd) => Result::Ok.(()),
            File(f) => f.close(),
        }
    }
}

/// Buffered writer to standard output, standard error or a file. Call
/// `finish` to flush it and close the file.
struct Output! {
    sink: Sink!,
    buf: Buffer!,
    error: i32,
}

/// A buffered writer for standard output.
fn stdout() -> Output! {
    Output!.{ sink: Sink!::Stream.(1i32), buf: Buffer!::new(), error: 0i32 }
}

/// A buffered writer for standard error.
fn stderr() -> Output! {
    Output!.{ sink: Sink!::Stream.(2i32), buf: Buffer!::new(), error: 0i32 }
}

impl Output! {
    /// Writes what has gathered so far.
    fn flush(self) -> Output! {
        var { sink, buf, error } = self;
        let n = &buf.len();
        if n == 0usize || error != 0i32 {
            return Output!.{ sink, buf: buf.clear(), error };
        }
        let fd = &sink.descriptor();
        let p = unsafe &buf.as_ptr();
        // `p` addresses the `n` bytes `buf` holds, and `buf` outlives the
        // write; `fd` is standard output or error, or the descriptor of the
        // file this `Output!` owns.
        let written = unsafe write_all(fd, p, n);
        let error = match written {
            Ok(nothing) => 0i32,
            Err(e) => e.errno,
        };
        Output!.{ sink, buf: buf.clear(), error }
    }

    /// Writes what is left, closes the file of one over a file, and reports
    /// the first failure, if any: a failed write before a failed close.
    fn finish(self) -> Result[(), Error] {
        let { sink, buf, error } = self.flush();
        buf.destroy();
        let closed = sink.close();
        if error == 0i32 {
            closed
        } else {
            Result::Err.(Error.{ errno: error })
        }
    }

    /// Writes what has gathered once it reaches 4 KiB.
    fn gathered(self) -> Output! {
        var { sink, buf, error } = self;
        let n = &buf.len();
        let out = Output!.{ sink, buf, error };
        if n >= 4096usize { out.flush() } else { out }
    }
}

/// Output as a writer: bytes gather and are written 4 KiB at a time.
instance Writer[Output!] {
    fn write_byte(self: Output!, byte: u8) -> Output! {
        let { sink, buf, error } = self;
        Output!.{ sink, buf: buf.write_byte(byte), error }.gathered()
    }
    fn write_static(self: Output!, bytes: Str['static]) -> Output! {
        let { sink, buf, error } = self;
        Output!.{ sink, buf: buf.write_static(bytes), error }.gathered()
    }
    /// Caller: `ptr[0..len)` is readable for the whole call
    /// (`Writer::write_raw`).
    unsafe fn write_raw(self: Output!, ptr: *u8, len: usize) -> Output! {
        if len < 4096usize {
            let { sink, buf, error } = self;
            return Output!.{ sink, buf: unsafe Writer[Buffer!]::write_raw(buf, ptr, len), error }.gathered();
        }
        // 4 KiB or more is written where it lies, after what has gathered,
        // rather than copied: `print` of a whole buffer.
        var { sink, buf, error } = self.flush();
        if error != 0i32 {
            return Output!.{ sink, buf, error };
        }
        let fd = &sink.descriptor();
        // `fd` is standard output or error, or the file's, as for `flush`.
        let error = match unsafe write_all(fd, ptr, len) {
            Ok(nothing) => 0i32,
            Err(e) => e.errno,
        };
        Output!.{ sink, buf, error }
    }
}