Docs · Standard library

@io

@io holds the Writer and Reader interfaces, the standard streams stdin, stdout, and stderr, buffered reading and writing, and the program's arguments. On WebAssembly the streams and arguments go through WASI; on x86-64-linux and arm64-linux they go through libc. Guide 10, Collections and strings introduces buffered output.

Vyi
import { Writer, Reader, stdin, stdout, stderr } from "@io"
import { BufferedWriter, BufferedReader } from "@io"
import { ReadError, WriteError, args, ArgList } from "@io"

Exports

NameKindSummary
Writerinterfaceanything bytes can be written to
Readerinterfaceanything bytes can be read from
stdout, stderrconthe standard output and error streams
stdinconthe standard input stream
WriteError, ReadErrorerror declarationswhy a stream write or read failed
BufferedWriterstructcollects small writes in memory you provide
BufferedReaderstructreads ahead into memory you provide; reads lines
argsfunctionthe program's arguments
ArgListstructwhat args() returns

Every operation that can fail returns error!T, the open error type (error model), so a try passes the failure on from any function that returns !T.

Writer and Reader

Vyi
interface Writer {
    fn (w: ~Writer) write(buf: [*con]u8) error!i32,
}

interface Reader {
    fn (r: ~Reader) read(buf: [*mut]u8) error!i32,
}
MethodContract
write(buf)writes all of buf and returns buf.len, or fails
read(buf)waits until at least one byte is available, reads at most buf.len bytes into buf, and returns how many; Ok(0) only at the end of the input

A short read (fewer than buf.len bytes) is normal; read again for more. The end of the input is Ok(0), never an error.

The receiver ~Writer accepts a method that takes the value or a pointer of either kind (guide 12). The standard streams, BufferedWriter, BufferedReader, and @mem's Buffer satisfy them:

TypeWriterReader
stdout, stderryesno
stdinnoyes
BufferedWriteryesno
BufferedReadernoyes
Buffer (@mem)yesyes
Vyi
import { Writer, stdout } from "@io"
import { Buffer, ArenaAllocator, systemAllocator } from "@mem"
import { print } from "@fmt"

fn greet(out: Writer) error!i32 {
    return out.write("hello\n")
}

fn main() !u8 {
    mut arena = ArenaAllocator.new(systemAllocator)
    defer arena.deinit()

    try greet(&stdout)          // prints hello
    mut saved = Buffer.fromAlloc(&arena)
    try greet(&saved)
    print(saved.asBytes())      // prints hello
    return Ok(0)
}

The standard streams

NameDescriptorSatisfiesMethods
stdin0Readerread
stdout1Writerwrite, writeInt, writeUint
stderr2Writerwrite, writeInt, writeUint

The streams are con values of types @io does not export, so these three are the only streams. Pass one where a Writer or Reader is expected as &stdout.

MethodSignatureResult
writefn (w: WriteStream) write(buf: [*con]u8) error!i32writes all of buf, repeating short writes, and returns buf.len
writeIntfn (w: WriteStream) writeInt(n: i64) error!i32writes n in base 10 and returns the bytes written; allocates nothing
writeUintfn (w: WriteStream) writeUint(n: u64) error!i32writes n in base 10 and returns the bytes written; allocates nothing
readfn (r: ReadStream) read(buf: [*mut]u8) error!i32the Reader contract above

Nothing is buffered: each call is one or more system calls. println from @fmt writes to stdout too, and the two can be mixed.

Vyi
import { stdout, stderr } from "@io"

fn main() !u8 {
    try stdout.write("total: ")
    try stdout.writeInt(-42)
    try stdout.write("\n")      // prints total: -42
    try stderr.write("done\n")
    return Ok(0)
}

Errors

Vyi
error WriteError {
    Interrupted "write interrupted";
    BadDescriptor "bad write descriptor";
    NoSpace "no space on write stream";
    Broken "broken write stream";
}

error ReadError {
    Interrupted "read interrupted";
    BadDescriptor "bad read descriptor";
    Broken "broken read stream";
}

Which member a failed stream call gives depends on the target:

FailureWebAssemblyx86-64-linux, arm64-linux
interrupted by a signalInterruptedBroken
invalid descriptorBadDescriptorBroken
device full (write)NoSpaceBroken
a write that makes no progressBrokenBroken
anything elseBrokenBroken

A failure that reaches the end of main prints its message, as in error: broken write stream, and the program exits with status 1. To handle one, match on the error value by member path; a match over error needs a default arm:

Vyi
import { stdout, stderr, WriteError } from "@io"

fn describe(e: error) [*con]u8 {
    return match e {
        WriteError.NoSpace: "disk full\n",
        WriteError.Broken:  "output closed\n",
        default:            "write failed\n",
    }
}

fn main() !u8 {
    if Err(e) = stdout.write("saved\n") {   // prints saved
        try stderr.write(describe(e))
        return Ok(1)
    }
    return Ok(0)
}

BufferedWriter

MemberSignatureResult
newfn (BufferedWriter) new(inner: Writer, storage: [*mut]u8) BufferedWritera writer that collects bytes in storage and sends them to inner
writefn (b: *mut BufferedWriter) write(buf: [*con]u8) error!i32adds buf to storage, flushing first when it does not fit; returns buf.len
flushfn (b: *mut BufferedWriter) flush() error!()sends the collected bytes to inner and empties storage
fieldspub inner: Writer, pub storage: [*mut]u8, pub used: i32used is the number of bytes waiting
  • Nothing flushes for you. Bytes still in storage when the program ends are lost. Call flush when you are done.
  • When buf does not fit in the space left, write flushes the waiting bytes first. A buf at least as long as storage is flushed past and sent to inner directly, so bytes always arrive in order.
  • storage is yours: memory from an allocator or a fixed array. The writer allocates nothing.
  • A failure from inner is returned from write or flush unchanged.
Vyi
import { BufferedWriter, stdout } from "@io"

fn main() !u8 {
    mut space = [64]u8[]
    mut out = BufferedWriter.new(&stdout, [*mut]u8(&space))
    try out.write("one ")
    try out.write("two ")
    try out.write("three\n")
    try out.flush()            // prints one two three
    return Ok(0)
}

BufferedReader

MemberSignatureResult
newfn (BufferedReader) new(inner: Reader, storage: [*mut]u8) BufferedReadera reader that reads ahead from inner into storage
readLinefn (b: *mut BufferedReader) readLine() error!?[*con]u8Some(line) without its \n, or None at the end of the input
readAllfn (b: *mut BufferedReader) readAll(a: Allocator) error![*con]u8the rest of the input, in memory from a
readfn (b: *mut BufferedReader) read(buf: [*mut]u8) error!i32the Reader contract; buffered bytes first, then inner directly
fieldspub inner: Reader, pub storage: [*mut]u8, pub start: i32, pub end: i32storage[start..end] holds the bytes read ahead and not yet used

readLine() returns error!?[*con]u8: the error union is the read failing, and the optional inside is the end of the input. Unwrap both, as in con line = try input.readLine() and then if Some(text) = line.

  • The line is a view into storage. It is valid until the next call on the same reader. Copy it to keep it.
  • storage must be longer than the longest line. A line that fills storage without a \n panics with bufferedreader: line longer than storage.
  • A last line with no \n is returned as a line of its own.
  • readAll grows a @mem Buffer through a, so it can fail with OutOfMemory; the bytes it returns belong to a.
Vyi
import { BufferedReader, stdin } from "@io"
import { println } from "@fmt"

fn main() !u8 {
    mut space = [256]u8[]
    mut input = BufferedReader.new(&stdin, [*mut]u8(&space))
    mut count = 0
    for {
        con line = try input.readLine()
        if Some(text) = line {
            count += 1
            println(text)
        } else {
            break
        }
    }
    println(count)
    return Ok(0)
}

Fed first, second, and last on three lines, this prints the three lines and then 3.

Program arguments

MemberSignatureResult
argsfn args() ArgListthe program's arguments
lengthfn (a: ArgList) length() i32the number of entries
atfn (a: ArgList) at(i: i32) [*con]u8entry i, for 0 <= i < length(), without its terminating zero byte
fieldspub buf: [*con]u8, pub count: i32the entries one after another, each ended by a zero byte; count is length()

args() allocates nothing, and the views at returns stay valid for the whole program. at(i) walks buf from the start, so it takes time proportional to the bytes before entry i.

The list holds the arguments that follow the program, in order. The program's name is not in it, on any target.

On WebAssembly, the entries, their zero bytes, and 4 bytes per entry must fit in 16 KiB, or args() panics with out of memory. The native targets have no limit.

Vyi
import { args } from "@io"
import { println } from "@fmt"

fn main() !u8 {
    con list = args()
    for i in 0..list.length() {
        println(list.at(i))
    }
    return Ok(0)
}

vyi run main.vyi -- red green prints red and green on two lines.

See also: @mem for Buffer and allocators, the error model, and guide 10, Collections and strings.