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.
import { Writer, Reader, stdin, stdout, stderr } from "@io"
import { BufferedWriter, BufferedReader } from "@io"
import { ReadError, WriteError, args, ArgList } from "@io"Exports
| Name | Kind | Summary |
|---|---|---|
Writer | interface | anything bytes can be written to |
Reader | interface | anything bytes can be read from |
stdout, stderr | con | the standard output and error streams |
stdin | con | the standard input stream |
WriteError, ReadError | error declarations | why a stream write or read failed |
BufferedWriter | struct | collects small writes in memory you provide |
BufferedReader | struct | reads ahead into memory you provide; reads lines |
args | function | the program's arguments |
ArgList | struct | what 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
interface Writer {
fn (w: ~Writer) write(buf: [*con]u8) error!i32,
}
interface Reader {
fn (r: ~Reader) read(buf: [*mut]u8) error!i32,
}| Method | Contract |
|---|---|
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:
| Type | Writer | Reader |
|---|---|---|
stdout, stderr | yes | no |
stdin | no | yes |
BufferedWriter | yes | no |
BufferedReader | no | yes |
Buffer (@mem) | yes | yes |
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
| Name | Descriptor | Satisfies | Methods |
|---|---|---|---|
stdin | 0 | Reader | read |
stdout | 1 | Writer | write, writeInt, writeUint |
stderr | 2 | Writer | write, 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.
| Method | Signature | Result |
|---|---|---|
write | fn (w: WriteStream) write(buf: [*con]u8) error!i32 | writes all of buf, repeating short writes, and returns buf.len |
writeInt | fn (w: WriteStream) writeInt(n: i64) error!i32 | writes n in base 10 and returns the bytes written; allocates nothing |
writeUint | fn (w: WriteStream) writeUint(n: u64) error!i32 | writes n in base 10 and returns the bytes written; allocates nothing |
read | fn (r: ReadStream) read(buf: [*mut]u8) error!i32 | the 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.
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
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:
| Failure | WebAssembly | x86-64-linux, arm64-linux |
|---|---|---|
| interrupted by a signal | Interrupted | Broken |
| invalid descriptor | BadDescriptor | Broken |
| device full (write) | NoSpace | Broken |
| a write that makes no progress | Broken | Broken |
| anything else | Broken | Broken |
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:
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
| Member | Signature | Result |
|---|---|---|
new | fn (BufferedWriter) new(inner: Writer, storage: [*mut]u8) BufferedWriter | a writer that collects bytes in storage and sends them to inner |
write | fn (b: *mut BufferedWriter) write(buf: [*con]u8) error!i32 | adds buf to storage, flushing first when it does not fit; returns buf.len |
flush | fn (b: *mut BufferedWriter) flush() error!() | sends the collected bytes to inner and empties storage |
| fields | pub inner: Writer, pub storage: [*mut]u8, pub used: i32 | used is the number of bytes waiting |
- Nothing flushes for you. Bytes still in
storagewhen the program ends are lost. Callflushwhen you are done. - When
bufdoes not fit in the space left,writeflushes the waiting bytes first. Abufat least as long asstorageis flushed past and sent toinnerdirectly, so bytes always arrive in order. storageis yours: memory from an allocator or a fixed array. The writer allocates nothing.- A failure from
inneris returned fromwriteorflushunchanged.
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
| Member | Signature | Result |
|---|---|---|
new | fn (BufferedReader) new(inner: Reader, storage: [*mut]u8) BufferedReader | a reader that reads ahead from inner into storage |
readLine | fn (b: *mut BufferedReader) readLine() error!?[*con]u8 | Some(line) without its \n, or None at the end of the input |
readAll | fn (b: *mut BufferedReader) readAll(a: Allocator) error![*con]u8 | the rest of the input, in memory from a |
read | fn (b: *mut BufferedReader) read(buf: [*mut]u8) error!i32 | the Reader contract; buffered bytes first, then inner directly |
| fields | pub inner: Reader, pub storage: [*mut]u8, pub start: i32, pub end: i32 | storage[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. storagemust be longer than the longest line. A line that fillsstoragewithout a\npanics withbufferedreader: line longer than storage.- A last line with no
\nis returned as a line of its own. readAllgrows a@memBufferthrougha, so it can fail withOutOfMemory; the bytes it returns belong toa.
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
| Member | Signature | Result |
|---|---|---|
args | fn args() ArgList | the program's arguments |
length | fn (a: ArgList) length() i32 | the number of entries |
at | fn (a: ArgList) at(i: i32) [*con]u8 | entry i, for 0 <= i < length(), without its terminating zero byte |
| fields | pub buf: [*con]u8, pub count: i32 | the 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.
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.