std::io
Input and output: the standard streams, readers and writers, files
opened at a position, and the one error type they all return.
io.print, io.write and io.inspect write to standard output,
io.eprint and io.ewrite to standard error, and io.read_line reads
standard input. Reader and Writer are streams: the standard ones
(io.stdin, io.stdout, io.stderr), files that std::fs opens, and
readers and writers the program makes over data or functions. A File
is a file read and written at a position. io.capture and io.replay
run a function against given input and return what it printed, which is
how a test checks a program’s output.
Import with import std::io.
Exports
Section titled “Exports”Standard streams
Section titled “Standard streams”io.print(x) and io.write(x) write x’s Display text to standard
output, print with a newline after it; io.inspect(x) writes its
Debug text and a newline. io.eprint(x) and io.ewrite(x) are print
and write for standard error. Each call is one write: two tasks
printing at once never interleave inside a line.
io.read_line() returns Ok(None) at the end of the input, so a loop
ends on Ok(Some(line)) = io.read_line() else { break }, and an
io.read_line()? does not treat the end as a failure.
The three standard streams are also values: once constants
io.stdin: Reader, io.stdout: Writer and io.stderr: Writer, of the
host types io.Reader and io.Writer, written with no parentheses
(Writer.print(io.stderr, "warning")).
- A stream value names the stream outside the program and never
changes. Using it moves the stream on, and where a use goes is decided
when it is made, so a value read before an
io.capturebegan writes into the capture inside it. Reader.read_line(r)on standard input returns whatio.read_line()returns and reads from the same buffer. A write toio.stdoutlands in order withio.print’s. Insideio.capturethe handles reach the capture asio.printandio.read_linedo.- A read of standard input that is waiting for input is a safe point. A
task cancelled while it waits (
Task.cancel, the teardown of itsconcurrentblock, a supervisor drain) unwinds there at once, as one waiting on a channel does, and what arrives afterwards is returned to the next read, a partial line included.
Readers and writers
Section titled “Readers and writers”Reader.lines and Reader.chunks read their reader as they run and
hand an item on before they read the next, so each runs once; fs.lines
and fs.chunks open the file on each run and are replayable. A failure
is an item, and the last. io.lines() is Reader.lines(io.stdin).
A reader over a function or a sequence (Reader.from_fn,
Reader.from_chunks, Reader.from_text_chunks) skips an empty chunk.
Reader.from_fn’s function runs on the task of each read that needs a
chunk, inside the io.capture that read is in, and a trap in it is a
trap of the read. A sequence’s pipeline runs on the task of the first
read, which starts it, and keeps that read’s io.capture.
A writer over a file is buffered: Writer.flush sends what it holds on,
and Writer.close flushes and closes, returning the error of a write the
buffer held or of the close, since a failed close of a written file can
lose data.
- An operation on a closed stream, a second close included, is
Closed. Closing a standard stream does nothing. Reader.close_quietlyandWriter.close_quietlyclose and drop the result, the form for adefer.Writer.discardgives a writer up instead, so aReplaceAtomicallyfile write that fails leaves the old file; defer it andWriter.closeon the success path.- A stream the program no longer holds is closed when its memory is
reclaimed, and what a writer the program never closed has buffered is
flushed when the program ends (a
Writer.from_fnwriter’s is dropped, since nothing may run itswritethen). - Each call on a stream is atomic, so two tasks sharing one never interleave inside a call.
enum Error
Section titled “enum Error”enum Error NotFound { path: String } AlreadyExists { path: String } PermissionDenied { path: String } NotADirectory { path: String } IsADirectory { path: String } DirectoryNotEmpty { path: String } InvalidPath { path: String, reason: String } InvalidText { path: String, offset: Int } NoSpace { path: String } ReadOnly { path: String } TooManyOpen Closed BrokenPipe TimedOut Unsupported { operation: String, target: String } Other { operation: String, path: String, code: String } end
What went wrong in an input or output operation: one error type for
files and the standard streams. A variant a program branches on names
the path it is about, as the program passed it. Other is a failure no
variant names: it keeps the operation ("open", "read"), the path and
the operating system’s error code ("EIO"), never the operating
system’s own wording. Display writes a sentence for every variant,
such as notes.txt: not found or read a.txt: input/output error (EIO).
A failure is the same variant on every operating system. A missing
directory above the path is NotFound, and a file where a directory
should be is NotADirectory, on Windows too. On Windows a symlink loop
and a read_link of a file carry the Unix codes ("ELOOP",
"EINVAL").
case fs.read_text("notes.txt") Ok(text) -> io.print(text) Err(io.Error.NotFound{path: _}) -> io.print("no notes yet") Err(e) -> io.eprint("cannot read the notes: ${e}") end
Variants
-
NotFoundNothing is at
path. A write into a missing directory names the directory. -
AlreadyExistsSomething is already at
path. -
PermissionDeniedThe operating system refused access to
path. -
NotADirectoryA directory was needed and
pathis something else. -
IsADirectoryA file was needed and
pathis a directory. -
DirectoryNotEmptyThe directory at
pathstill holds entries. -
InvalidPathpathcannot name a file: it is empty or holds a NUL byte. -
InvalidTextWhat was read is not UTF-8 text.
offsetis the byte offset of the first sequence that is not, from the start of the file, or of the line for a line read.pathis<stdin>for standard input. -
NoSpaceThe device holding
pathis full. -
ReadOnlypathis on a read-only file system. -
TooManyOpenThe process has too many files open.
-
ClosedThe stream was already closed.
-
BrokenPipeThe reader at the other end of a pipe has gone, as with
| head. -
TimedOutThe operation passed its deadline.
-
UnsupportedThe target the program runs on cannot do
operation, as starting a process in a js/wasm module (capability classes). -
OtherAny other failure: the operation, the path and the operating system’s error code.
assert "${Error.NotFound{path: "notes.txt"}}" == "notes.txt: not found"
failed = Error.Other{operation: "read", path: "a.txt", code: "EIO"}
assert "${failed}" == "read a.txt: input/output error (EIO)"
refused = Error.Unsupported{operation: "process.run", target: "js/wasm"}
assert "${refused}" == "process.run is not supported on js/wasm"
assert "${Error.TooManyOpen}" == "too many open files"
Error.to_string
Section titled “Error.to_string”impl Display for Error
fn to_string(e: Error) -> String
impl Display.to_string
Error.inspect
Section titled “Error.inspect”impl Debug for Error
fn inspect(value: Error) -> String
impl Debug.inspect
Error.equal
Section titled “Error.equal”impl Equatable for Error
fn equal(a: Error, b: Error) -> Bool
impl Equatable.equal
io.print
Section titled “io.print”fn print<T>(value: T) -> Unit where T: Display
Prints value to standard output, followed by a newline. It takes any
value whose type implements Display and writes its
Display.to_string text: a String as it is, with no quotes, and a
number or a list without converting it first. A type of your own
prints once it has an impl Display or a derive Display.
io.inspect prints the Debug form, which every value has.
io.print("hello") // prints: hello io.print(42) // prints: 42
run = capture("", fn ->
print("hello")
print(42)
print([1, 2])
end)
assert run.output == "hello\n42\n[1, 2]\n"
io.write
Section titled “io.write”fn write<T>(value: T) -> Unit where T: Display
Prints value to standard output with no newline after it. It writes
the same text as io.print, the value’s Display.to_string. Use it for
a prompt that the user answers on the same line, or to build one line
of output from several writes.
io.write("> ") // prints: > (and no newline) io.read_line() // the user types on the same line
run = capture("", fn ->
write("a")
write(1)
print("!")
end)
assert run.output == "a1!\n"
io.inspect
Section titled “io.inspect”fn inspect<T>(value: T) -> Unit
Prints value to standard output as code would write it, followed by
a newline: its Debug.inspect text, in which a String has its quotes
and a struct its name and fields. Every value can be inspected, with no
derive or impl: a type that writes no impl Debug gets one made
from its structure, and a value of an opaque type prints as
<opaque T>. Write an impl Debug only to change the text. dbg
prints a value and returns it, so it fits inside an expression or a
pipeline.
io.inspect([1, 2, 3]) // prints: [1, 2, 3] io.inspect("hello") // prints: "hello"
run = capture("", fn ->
inspect("hello")
inspect(Some(1))
end)
assert run.output == "\"hello\"\nSome(1)\n"
io.eprint
Section titled “io.eprint”fn eprint<T>(value: T) -> Unit where T: Display
Prints a value’s user-facing representation to stderr, followed by a
newline: io.print for the error stream. Use it for warnings, progress
and failures, which stay out of the output another program reads from
stdout.
io.eprint("warning: no config file, using defaults")
run = capture("", fn ->
eprint("warning: low disk")
print("done")
end)
assert run.output == "done\n"
assert run.errors == "warning: low disk\n"
io.ewrite
Section titled “io.ewrite”fn ewrite<T>(value: T) -> Unit where T: Display
Writes a value’s user-facing representation to stderr with no trailing
newline: io.write for the error stream.
io.ewrite("working...")
run = capture("", fn ->
ewrite("a")
ewrite(1)
end)
assert run.errors == "a1"
io.read_line
Section titled “io.read_line”fn read_line() -> Result<Maybe<String>, Error>
Reads the next line of standard input, without its \n and a \r
before it. Returns Ok(None) at the end of the input, and Err when the
read fails. A line that is not UTF-8 is
Err(io.Error.InvalidText{path: "<stdin>", offset:}), offset being
the byte offset of its first bad sequence within the line; the lines
after it read as usual. A last line with
no newline is still a line. Inside io.capture it reads the capture’s
input instead. A task cancelled while the read waits for input stops
there at once, and the input that arrives later is the next read’s.
case io.read_line() Ok(Some(name)) -> io.print("hello, ${name}") _ -> io.print("hello, stranger") end
lines = capture("one\ntwo\r\n", fn -> [read_line(), read_line(), read_line()])
assert lines.value == [Result.Ok(Some("one")), Result.Ok(Some("two")), Result.Ok(None)]
io.lines
Section titled “io.lines”fn lines() -> Iter<Result<String, Error>>
Each line of standard input, as io.read_line reads them:
Reader.lines(io.stdin), from the same buffer. It reads as it runs, so
a loop over it handles each line before the next is read, and it runs
once: a second run carries on from where the input is. Inside
io.capture it reads the capture’s input.
io.lines() |> Iter.each(fn line -> case line Ok(text) -> io.print(String.uppercase(text)) Err(e) -> io.eprint(e) end end)
run = capture("one\ntwo\n", fn ->
first = read_line()
(first, Result.collect(lines()))
end)
assert run.value == (Result.Ok(Some("one")), Result.Ok(["two"]))
type Reader
Section titled “type Reader”type Reader
A stream bytes are read from. Standard input is one (io.stdin). A
Reader is a value that names something outside the program: the value
never changes, and reading it moves the stream it names on.
Reader.read_line
Section titled “Reader.read_line”fn read_line(r: Reader) -> Result<Maybe<String>, Error>
type function on Reader
The next line without its \n (and a \r before it), or Ok(None)
at the end of the stream. A last line with no newline is still a
line. A line that is not UTF-8 is InvalidText, with the offset of
the first bad byte in the line.
case Reader.read_line(io.stdin) Ok(Some(line)) -> io.print("got ${line}") Ok(None) -> io.print("no input") Err(e) -> io.eprint(e) end
import std::io
run = capture("a\nb", fn ->
[Reader.read_line(io.stdin), io.read_line(), Reader.read_line(io.stdin)]
end)
assert run.value == [Result.Ok(Some("a")), Result.Ok(Some("b")), Result.Ok(None)]
r = Reader.from_text("one\r\ntwo")
assert [Reader.read_line(r), Reader.read_line(r), Reader.read_line(r)] == [
Result.Ok(Some("one")),
Result.Ok(Some("two")),
Result.Ok(None),
]
Reader.read
Section titled “Reader.read”fn read(r: Reader, max: PositiveInt = 65536) -> Result<Maybe<Bytes>, Error>
type function on Reader
Up to max bytes, at least one, or Ok(None) at the end of the
stream. A read returns what is ready, so it may return fewer than
max bytes before the end. max is a PositiveInt.
case Reader.read(r, max: 4096) Ok(Some(chunk)) -> Bytes.length(chunk) Ok(None) -> 0 Err(_) -> -1 end
r = Reader.from_text("abcdef")
assert Reader.read(r, max: 4) == Result.Ok(Some(String.to_bytes("abcd")))
assert Reader.read(r) == Result.Ok(Some(String.to_bytes("ef")))
assert Reader.read(r) == Result.Ok(None)
Reader.read_all
Section titled “Reader.read_all”fn read_all(r: Reader) -> Result<Bytes, Error>
type function on Reader
Everything left in the stream; after it the reader is at its end.
data = Reader.read_all(r)?
r = Reader.from_text("a\nbc")
_ = Reader.read_line(r)
assert Reader.read_all(r) == Result.Ok(String.to_bytes("bc"))
assert Reader.read_all(r) == Result.Ok(String.to_bytes(""))
Reader.read_all_text
Section titled “Reader.read_all_text”fn read_all_text(r: Reader) -> Result<String, Error>
type function on Reader
Everything left in the stream as text. Bytes that are not UTF-8 are
InvalidText, with the offset of the first bad one from where the
read began.
text = Reader.read_all_text(io.stdin)?
import std::io
run = capture("one\ntwo\n", fn -> Reader.read_all_text(io.stdin))
assert run.value == Result.Ok("one\ntwo\n")
bad = Reader.from_bytes(Bytes.concat(String.to_bytes("hi"), Bytes.from_list([255])))
assert Reader.read_all_text(bad) == Result.Err(Error.InvalidText{path: "<bytes>", offset: 2})
Reader.lines
Section titled “Reader.lines”fn lines(r: Reader) -> Iter<Result<String, Error>>
type function on Reader
Each line left in the stream, without its \n and a \r before it,
as Reader.read_line reads them. The iterator reads r as it runs,
so it runs once: a second run carries on from where the stream is,
which after a run to the end yields nothing. A failure (a line that
is not UTF-8, a read that fails) is an item, and the last one. A
consumer that stops early leaves the rest of the stream unread, and
the reader open. These are the iterators that are not replayable
(Iteration). fs.lines(path) opens the file on
each run, so it can run again.
count = Reader.lines(r) |> Iter.count()
r = Reader.from_text("pear\r\napple")
each = Reader.lines(r)
assert Result.collect(each) == Ok(["pear", "apple"])
assert Iter.to_list(each) == []
bad = Reader.from_bytes(Bytes.concat(String.to_bytes("ok\n"), Bytes.from_list([255, 10, 65])))
assert Iter.to_list(Reader.lines(bad)) == [
Ok("ok"),
Err(Error.InvalidText{path: "<bytes>", offset: 0}),
]
Reader.chunks
Section titled “Reader.chunks”fn chunks(r: Reader, size: PositiveInt = 65536) -> Iter<Result<Bytes, Error>>
type function on Reader
The rest of the stream in pieces of at most size bytes, as
Reader.read reads them. Like Reader.lines, it reads r as it
runs, so it runs once, and a failure is the last item.
sizes = Reader.chunks(r, size: 4096) |> Iter.map(fn chunk -> Result.map(chunk, Bytes.length)) |> Result.collect()
r = Reader.from_text("abcde")
assert Result.collect(Reader.chunks(r, size: 2)) == Ok([
String.to_bytes("ab"),
String.to_bytes("cd"),
String.to_bytes("e"),
])
Reader.copy_to
Section titled “Reader.copy_to”fn copy_to(r: Reader, w: Writer) -> Result<Int, Error>
type function on Reader
Copies everything left in r into w and returns how many bytes it
copied. It reads and writes a chunk at a time, so a large file never
has to fit in memory.
copied = Reader.copy_to(io.stdin, io.stdout)?
import std::io
run = capture("", fn -> Reader.copy_to(Reader.from_text("hello\n"), io.stdout))
assert run.value == Result.Ok(6)
assert run.output == "hello\n"
Reader.close
Section titled “Reader.close”fn close(r: Reader) -> Result<Unit, Error>
type function on Reader
Closes the stream. A second close is Closed, and so is any read
after the first. Closing standard input does nothing.
Reader.close(r)?
r = Reader.from_text("x")
assert Reader.close(r) == Result.Ok(Unit)
assert Reader.read_line(r) == Result.Err(Error.Closed)
assert Reader.close(r) == Result.Err(Error.Closed)
Reader.close_quietly
Section titled “Reader.close_quietly”fn close_quietly(r: Reader) -> Unit
type function on Reader
Closes the stream and ignores the outcome: the form for a defer,
which cannot report a failure. A reader has nothing to lose on a
failed close.
r = fs.open("notes.txt")? defer Reader.close_quietly(r)
r = Reader.from_text("x")
Reader.close_quietly(r)
Reader.close_quietly(r)
assert Reader.read_line(r) == Result.Err(Error.Closed)
Reader.from_bytes
Section titled “Reader.from_bytes”fn from_bytes(data: Bytes) -> Reader
type function on Reader
A reader over bytes the program holds, for tests and for code
written against Reader.
r = Reader.from_bytes(String.to_bytes("a\nb\n"))
r = Reader.from_bytes(String.to_bytes("a\nb\n"))
assert Reader.read_line(r) == Result.Ok(Some("a"))
Reader.from_text
Section titled “Reader.from_text”fn from_text(text: String) -> Reader
type function on Reader
A reader over text the program holds.
r = Reader.from_text("pear\napple\n")
r = Reader.from_text("pear\napple\n")
assert Reader.read_all_text(r) == Result.Ok("pear\napple\n")
Reader.from_fn
Section titled “Reader.from_fn”fn from_fn(next: () -> Result<Maybe<Bytes>, Error>) -> Reader
type function on Reader
A reader that calls next each time it needs more bytes: Ok(Some(chunk))
is the next chunk, Ok(None) the end of the stream, and Err(e) a
failure the read that asked returns with. An empty chunk is skipped.
next runs when a read needs it, on the task that reads and inside
the io.capture that read is in, so a reader adapts any source a
function can pull from. A trap in next is a trap of the read.
next must not read the reader it feeds.
yes = Reader.from_fn(fn -> Ok(Some(String.to_bytes("y\n"))))
inner = Reader.from_text("a\nb\n")
one_byte_at_a_time = Reader.from_fn(fn -> Reader.read(inner, max: 1))
assert Reader.read_line(one_byte_at_a_time) == Result.Ok(Some("a"))
assert Reader.read_all_text(one_byte_at_a_time) == Result.Ok("b\n")
failing = Reader.from_fn(fn -> Result.Err(Error.TimedOut))
assert Reader.read_line(failing) == Result.Err(Error.TimedOut)
Reader.from_chunks
Section titled “Reader.from_chunks”fn from_chunks(chunks: Iter<Bytes>) -> Reader
type function on Reader
A reader over a sequence of chunks, pulled one at a time as reads need them, so the sequence may be long or never end. The sequence runs on the task of the first read. Closing the reader stops it.
r = Reader.from_chunks([String.to_bytes("ab"), String.to_bytes("c\n")])
r = Reader.from_chunks([String.to_bytes("one\ntw"), String.to_bytes("o\n")])
assert Reader.read_line(r) == Result.Ok(Some("one"))
assert Reader.read_line(r) == Result.Ok(Some("two"))
assert Reader.read_line(r) == Result.Ok(None)
endless = Reader.from_chunks(Iter.repeat(String.to_bytes("y\n")))
assert Reader.read_line(endless) == Result.Ok(Some("y"))
assert Reader.close(endless) == Result.Ok(Unit)
Reader.from_text_chunks
Section titled “Reader.from_text_chunks”fn from_text_chunks(chunks: Iter<String>) -> Reader
type function on Reader
A reader over a sequence of text chunks, as from_chunks is over
bytes.
r = Reader.from_text_chunks(["pear\n", "apple\n"])
r = Reader.from_text_chunks(
Iter.from(1)
|> Iter.map(fn n -> "${n}\n")
)
assert [Reader.read_line(r), Reader.read_line(r)] == [Result.Ok(Some("1")), Result.Ok(Some("2"))]
Reader.release
Section titled “Reader.release”impl Release for Reader
fn release(r: Reader) -> Unit
impl Release.release
Reader.inspect
Section titled “Reader.inspect”impl Debug for Reader
fn inspect(value: Reader) -> String
impl Debug.inspect
type Writer
Section titled “type Writer”type Writer
A stream bytes are written to. Standard output and standard error are
two (io.stdout, io.stderr).
Writer.write
Section titled “Writer.write”fn write(w: Writer, data: Bytes) -> Result<Unit, Error>
type function on Writer
Writes data to the stream as it is. A writer over a file buffers
what it is given; flush and close send it on.
Writer.write(io.stdout, String.to_bytes("hi\n"))
import std::io
run = capture("", fn -> Writer.write(io.stderr, String.to_bytes("oops")))
assert run.value == Result.Ok(Unit)
assert run.errors == "oops"
Writer.write_text
Section titled “Writer.write_text”fn write_text(w: Writer, text: String) -> Result<Unit, Error>
type function on Writer
Writes text to the stream as it is, with no newline added.
Writer.write_text(w, "# generated\n")
import std::io
run = capture("", fn -> Writer.write_text(io.stdout, "a"))
assert run.output == "a"
Writer.print
Section titled “Writer.print”fn print(w: Writer, value: Display) -> Result<Unit, Error>
type function on Writer
Writes a value’s user-facing representation and a newline to the
stream, as io.print does to stdout.
Writer.print(io.stderr, "warning: low disk")
import std::io
run = capture("", fn ->
io.print("one")
_ = Writer.print(io.stdout, 2)
_ = Writer.print(io.stderr, "three")
end)
assert run.output == "one\n2\n"
assert run.errors == "three\n"
Writer.flush
Section titled “Writer.flush”fn flush(w: Writer) -> Result<Unit, Error>
type function on Writer
Sends what the writer has buffered on to the file it writes. The standard streams are not buffered, so flushing one does nothing.
Writer.flush(w)?
import std::io
assert Writer.flush(io.stdout) == Result.Ok(Unit)
Writer.close
Section titled “Writer.close”fn close(w: Writer) -> Result<Unit, Error>
type function on Writer
Flushes the stream and closes it, and returns whether everything
written reached the file: a failed close of a written file means
data may be lost. A second close is Closed, and so is any write
after the first. Closing a standard stream does nothing.
Writer.close(w)?
import std::io
assert Writer.close(io.stdout) == Result.Ok(Unit)
Writer.close_quietly
Section titled “Writer.close_quietly”fn close_quietly(w: Writer) -> Unit
type function on Writer
Closes the stream and ignores the outcome. A close commits what was
written, so this is for a writer whose partial output is fine to
keep: a log, a stream, a file not written with ReplaceAtomically.
A file write that should leave the old file when it fails defers
Writer.discard instead.
w = fs.create("trace.log", mode: .Append)? defer Writer.close_quietly(w)
import std::io
run = capture("", fn -> Writer.close_quietly(io.stdout))
assert run.value == Unit
Writer.discard
Section titled “Writer.discard”fn discard(w: Writer) -> Unit
type function on Writer
Gives up a writer still open. A ReplaceAtomically writer from
fs.create drops its temporary file and leaves the old file as it
was; any other writer is closed, and a Writer.from_fn writer drops
what it holds. A closed writer is left alone, so discard after a
close does nothing.
A writer must be closed with Writer.close(w)? on the success path:
the close commits the write and reports a failed close. Defer the
discard on the line after the writer is made, and it throws the
output away when the function leaves any other way, by an Err or a
trap.
fn save(path: String, rows: List<String>) -> Result<Unit, io.Error> w = fs.create(path, mode: .ReplaceAtomically)? defer Writer.discard(w) Writer.write_lines(w, rows)? Writer.close(w)? Ok(Unit) end
(_, data) = Writer.collect(fn w ->
_ = Writer.write_text(w, "kept")
_ = Writer.close(w)
Writer.discard(w)
end)
assert Bytes.to_string(data) == Result.Ok("kept")
(late, _) = Writer.collect(fn w ->
Writer.discard(w)
Writer.write_text(w, "x")
end)
assert late == Result.Err(Error.Closed)
Writer.write_all
Section titled “Writer.write_all”fn write_all(w: Writer, chunks: Iter<Bytes>) -> Result<Unit, Error>
type function on Writer
Writes each chunk in order and stops at the first failure, which it returns. A chunk is pulled when the one before it is written, so the sequence may be long.
Writer.write_all(w, [header, body])?
(written, data) = Writer.collect(fn w ->
Writer.write_all(w, [String.to_bytes("ab"), String.to_bytes("c")])
end)
assert written == Result.Ok(Unit)
assert data == String.to_bytes("abc")
Writer.write_lines
Section titled “Writer.write_lines”fn write_lines<T>(w: Writer, lines: Iter<T>) -> Result<Unit, Error> where T: Display
type function on Writer
Writes each item’s user-facing representation followed by \n, as
Writer.print writes one, and stops at the first failure, which it
returns.
Writer.write_lines(io.stdout, ["pear", "apple"])?
(_, data) = Writer.collect(fn w ->
Writer.write_lines(
w,
Iter.from(1)
|> Iter.take(3),
)
end)
assert data == String.to_bytes("1\n2\n3\n")
full = Writer.from_fn(unbuffered: True, fn _ -> Result.Err(Error.BrokenPipe))
assert Writer.write_lines(full, ["a", "b"]) == Result.Err(Error.BrokenPipe)
Writer.from_fn
Section titled “Writer.from_fn”fn from_fn(close: () -> Result<Unit, Error> = fn -> Ok(Unit), unbuffered: Bool = False, write: (Bytes) -> Result<Unit, Error>) -> Writer
type function on Writer
A writer that hands what is written to write, for code written
against Writer that should send its bytes somewhere a function can
reach: a channel, a list, another writer. The writer is buffered, so
write receives what accumulated when the buffer fills and on
flush and close, and the boundaries of the program’s writes are
not kept; with unbuffered: True each write reaches write as it is
made. close, named, runs when the writer is closed, after the last
bytes. An Err from either is the error the write, flush or close
returns, and a buffered writer returns a failed send’s error to every
later write, as a writer over a file does. Both run on the task that
writes, flushes or closes, inside its io.capture. write may write
to another writer, but not to the one it is fed by.
Close the writer when done: once the program no longer holds it, or
when the program ends, what it still buffers is dropped, since
nothing may run write then.
w = Writer.from_fn(fn chunk -> Channel.send(sender, chunk))
(_, data) = Writer.collect(fn sink ->
upper = Writer.from_fn(fn chunk ->
text = Bytes.to_string(chunk) |> Result.with_default("")
Writer.write_text(sink, String.uppercase(text))
end)
_ = Writer.write_text(upper, "hello, ")
_ = Writer.write_text(upper, "world")
Writer.close(upper)
end)
assert data == String.to_bytes("HELLO, WORLD")
failing = Writer.from_fn(unbuffered: True, fn _ -> Result.Err(Error.NoSpace{path: "disk"}))
assert Writer.write_text(failing, "x") == Result.Err(Error.NoSpace{path: "disk"})
Writer.collect
Section titled “Writer.collect”fn collect<T>(body: (Writer) -> T) -> (T, Bytes)
type function on Writer
Calls body with a writer into memory and returns what body
returned and every byte it wrote. The writer is closed when body
returns, so a write through it after that is Closed. It is the
writer a test hands code written against Writer;
Bytes.to_string reads the bytes as text.
(_, data) = Writer.collect(fn w -> Writer.print(w, "hi"))
(value, data) = Writer.collect(fn w ->
_ = Writer.print(w, "one")
_ = Writer.write(w, String.to_bytes("two"))
42
end)
assert value == 42
assert Bytes.to_string(data) == Result.Ok("one\ntwo")
(kept, _) = Writer.collect(fn w -> w)
assert Writer.write_text(kept, "late") == Result.Err(Error.Closed)
Writer.release
Section titled “Writer.release”impl Release for Writer
fn release(w: Writer) -> Unit
impl Release.release
Writer.commit
Section titled “Writer.commit”impl Commit for Writer
fn commit(w: Writer) -> Result<Unit, Error>
impl Commit.commit
Writer.inspect
Section titled “Writer.inspect”impl Debug for Writer
fn inspect(value: Writer) -> String
impl Debug.inspect
io.stdin
Section titled “io.stdin”once stdin: Reader
The program’s standard input. Reader.read_line(io.stdin) reads what
io.read_line() reads, from the same buffer. The value names the
stream, not a place: inside io.capture it reads the capture’s input,
even when it was read before the capture began.
io.stdout
Section titled “io.stdout”once stdout: Writer
The program’s standard output. Writer.print(io.stdout, x) writes where
io.print(x) writes, in order with it, and inside io.capture into the
capture’s output.
import std::io
w = io.stdout
run = capture("", fn -> Writer.print(w, "inside"))
assert run.output == "inside\n"
io.stderr
Section titled “io.stderr”once stderr: Writer
The program’s standard error, where io.eprint writes.
type File
Section titled “type File”type File
One file open for reads and writes at a position, from fs.open_file.
A Reader and a Writer are streams: read or written front to back,
through a buffer. A File is not. Each call is one operation on the
file, with no buffer between the program and the file, so a write is in
the file when the call returns and the next read sees it. File.read
and File.write start at the file’s position and move it on;
File.read_at and File.write_at name their own position and leave
the file’s where it was. For reading or writing a whole file in order,
fs.open and fs.create are the simpler handles.
File.read
Section titled “File.read”fn read(f: File, max: PositiveInt = 65536) -> Result<Maybe<Bytes>, Error>
type function on File
Up to max bytes at the position, which moves past them, or
Ok(None) at or past the end. max is a PositiveInt.
header = File.read(f, max: 16)?
File.read_at
Section titled “File.read_at”fn read_at(f: File, position: NonNegativeInt, max: PositiveInt) -> Result<Maybe<Bytes>, Error>
type function on File
Up to max bytes at position, or Ok(None) at or past the end.
The file’s position stays where it was.
record = File.read_at(f, 512 * n, max: 512)?
File.write
Section titled “File.write”fn write(f: File, data: Bytes) -> Result<Unit, Error>
type function on File
Writes data at the position, which moves past it. A file opened
with Access.Read is PermissionDenied.
File.write(f, String.to_bytes("hello"))?
File.write_at
Section titled “File.write_at”fn write_at(f: File, position: NonNegativeInt, data: Bytes) -> Result<Unit, Error>
type function on File
Writes data at position. A position past the end fills the gap
with zero bytes. The file’s position stays where it was.
File.write_at(f, 0, header)?
File.seek
Section titled “File.seek”fn seek(f: File, position: NonNegativeInt) -> Result<Unit, Error>
type function on File
Moves the position to position, counted in bytes from the start. A
position past the end is allowed, and a write there fills the gap
with zero bytes. A position counted back from the end or from here
is an Int, which NonNegativeInt.try_from checks: None when it is
before the start.
File.seek(f, 0)? case NonNegativeInt.try_from(File.size(f)? - 16) Some(at) -> File.seek(f, at)? None -> File.seek(f, 0)? end
File.position
Section titled “File.position”fn position(f: File) -> Result<NonNegativeInt, Error>
type function on File
The position File.read and File.write start at.
File.size
Section titled “File.size”fn size(f: File) -> Result<NonNegativeInt, Error>
type function on File
The file’s size in bytes now.
File.truncate
Section titled “File.truncate”fn truncate(f: File, size: NonNegativeInt) -> Result<Unit, Error>
type function on File
Makes the file size bytes long: what is past it is dropped, and a
longer size adds zero bytes. The position stays where it was.
File.truncate(f, 0)?
File.close
Section titled “File.close”fn close(f: File) -> Result<Unit, Error>
type function on File
Closes the file. A second close is Closed, as is every call on a
closed file. A write reaches the file as it is made, so nothing is
lost by a deferred File.close_quietly; end the success path with
File.close(f)? when a failed close should be reported.
File.close_quietly
Section titled “File.close_quietly”fn close_quietly(f: File) -> Unit
type function on File
Closes the file and ignores the outcome: the form for a defer.
File.release
Section titled “File.release”impl Release for File
fn release(f: File) -> Unit
impl Release.release
File.inspect
Section titled “File.inspect”impl Debug for File
fn inspect(value: File) -> String
impl Debug.inspect
struct Captured
Section titled “struct Captured”struct Captured<T> value: T output: String errors: String transcript: String end
What io.capture returns: the value run returned, everything it
printed to stdout and to stderr, and its stdout and input together as a
transcript.
Captured.inspect
Section titled “Captured.inspect”impl Debug for Captured<T>
fn inspect<T>(value: Captured<T>) -> String where T: Debug
impl Debug.inspect
io.capture
Section titled “io.capture”fn capture<T>(input: String, run: () -> T) -> Captured<T>
Calls run with input as its standard input and returns what it
returned together with everything it printed.
While run runs, io.read_line reads input one line at a time with
the line ending stripped, as it reads stdin (\n or \r\n; a last line
with no newline is still a line), and returns Ok(None) once it is used
up. io.print, io.write and io.inspect append exactly what they
would have written to stdout to output, and io.eprint and
io.ewrite what they would have written to stderr to errors. The
standard stream handles reach the capture the same way: writes through
io.stdout and io.stderr go to the same places, and
Reader.read_line(io.stdin) reads input. dbg, files and the
runtime’s own diagnostics are not redirected (std::fs::testing.run gives a
call its own files). In a test case outside any io.capture, stderr is
part of the case’s output, which the report shows under the case.
The redirection lasts for the call and follows its tasks: a task
spawned inside run reads and writes the same capture, and two tasks
each running their own io.capture at the same time never see each
other’s input or output. An inner io.capture takes over for its own
call, so its output and reads land only in its own Captured, and an
inner capture’s reads are in its own transcript only. Once io.capture
returns, its capture is closed: a task that outlives the call (a
supervised one) reads and writes whatever was in force where
io.capture was called. If run traps, the trap propagates as it would
without the capture and the output captured so far is dropped.
io.capture works outside tests too, in nomi run and in nomi build
executables.
Passing a program’s main is how a test checks what the program prints
for a given input: io.capture("the fox the dog\n", main). For a
program that asks and answers in turn, io.replay reads better. A
program that reads nothing is checked through output, which holds the
output as it was written.
run = capture("", fn ->
print("hi")
write(1)
42
end)
assert run.value == 42
assert run.output == "hi\n1"
echo = capture("one\ntwo", fn -> [read_line(), read_line(), read_line()])
assert echo.value == [Result.Ok(Some("one")), Result.Ok(Some("two")), Result.Ok(None)]
assert echo.output == ""
asked = capture("Ada", fn ->
write("name: ")
case read_line()
Ok(Some(name)) -> print("hello, ${name}")
_ -> print("hello, stranger")
end
end)
assert asked.output == "name: hello, Ada\n"
assert asked.transcript == "name: \n > Ada\nhello, Ada\n"
struct Replayed
Section titled “struct Replayed”struct Replayed output: String transcript: String expected: String unread: Int end
What io.replay returns. assert holds on it when the transcript
matches the script, and its failure shows a line diff of the two. It
does not hold what run returned; use io.capture to check that.
Replayed.failure
Section titled “Replayed.failure”impl Assertable for Replayed
fn failure(replayed: Replayed) -> Maybe<AssertionDetails>
impl Assertable.failure
Replayed.inspect
Section titled “Replayed.inspect”impl Debug for Replayed
fn inspect(value: Replayed) -> String
impl Debug.inspect
io.replay
Section titled “io.replay”fn replay<T>(script: String, run: () -> T) -> Replayed
Runs run against a script of an interactive session and returns a
Replayed that assert checks: assert io.replay(script, main).
The script is the session, output and input in order. Its base column
is the start of each line of its value; for a """ script, which
removes its baseline, that is the closing delimiter’s column when no
line sits left of it, so write output there and indent the input lines
under it. Every line of the script follows one rule:
- A line indented past the base column, by spaces or tabs, whose text
then starts with
>is input. What follows>is what the nextio.read_linereturns, leading spaces included.>alone after the indentation (a>whose trailing space was dropped) is an empty line. - Every other line is output the program must print, exactly as
written, indentation included: indentation past the closing
delimiter’s column is part of the output, even on every line. A blank
line is a blank output line.
>at the base column,>>, and>with no space after it are output. - An indented output line whose text starts with
>would read as input, so it is written with a backslash before the>: the script line\> quotedis the output> quoted. The backslash is removed only there, after the indentation and before what would otherwise be input; one already there takes one more (\\> xis the output\> x). A backslash anywhere else is the character itself. A"""literal does not process escapes, so the script writes\>as it is.
Every script is accepted. A prompt written before a read
(io.write("age: ")) is output on a line of its own, with the input on
the next line.
run runs as under io.capture, and its transcript must equal the
script. Trailing spaces, tabs and carriage returns on each line, and a
final newline, do not count, so a """ script, which drops its last
newline, matches output that ends in one, and a prompt’s trailing space
need not be written. Once the script’s input is used up, io.read_line
returns Ok(None), and that read adds nothing to the transcript; the
prompt it answered stays on one line with what is printed next. An input
line the program never read fails the replay, and the reason says how
many were left. A read writes its line into the transcript at the
indentation the script’s input line has, so a transcript that matches
is the script line for line; Replayed’s transcript and expected
hold the two in that form, and output holds what run printed byte
for byte.
A failed replay shows the same line diff a failed == over multi-line
Strings shows, with the script as expected (-) and the transcript as
actual (+), under the header io.replay: the transcript (-) and what main printed (+) differ. Each script line written in a """ literal
carries its line in the file, and the text column holds each line as
the script writes it. The assertion above the diff writes that literal
collapsed, as ==’s does:
line 12: the transcript differs from the script
assert io.replay(""" lines 14-18 """, main)
io.replay: the transcript (-) and what main printed (+) differ
14 │ What is your name?
15 │ > Ada
16 - │ Hello, Ada. Your age?
+ │ Hello, Ada. Your age:
17 │ > 36
18 │ Ada is 36
A script holds stdout only. What run writes to stderr is captured and
dropped: it neither appears in the transcript nor fails the replay, so a
program’s warnings need not be written into every script. Check them
with io.capture’s errors.
greet = fn ->
write("name: ")
case read_line()
Ok(Some(name)) -> print("hello, ${name}")
_ -> print("hello, stranger")
end
end
assert replay(
"""
name:
> Ada
hello, Ada
""",
greet,
)
assert replay(
"""
name: hello, stranger
""",
greet,
)
table = fn ->
print("-10.0 C | 14.0 F")
print(" -5.0 C | 23.0 F")
end
assert replay(
"""
-10.0 C | 14.0 F
-5.0 C | 23.0 F
""",
table,
)
refute replay(
"""
name:
> Ada
> Grace
hello, Ada
""",
greet,
)
repl = fn ->
write("> ")
case read_line()
Ok(Some(word)) -> print("you said ${word}")
_ -> print("bye")
end
end
assert replay(
"""
>
> hey
you said hey
""",
repl,
)
warned = fn ->
eprint("warning: no config")
print("ready")
end
assert replay(
"""
ready
""",
warned,
)
ages = fn ->
print("What is your name?")
name = read_line() |> Result.with_default(None) |> Maybe.with_default("")
write("Hello, ${name}. Your age: ")
age = read_line() |> Result.with_default(None) |> Maybe.with_default("")
print("${name} is ${age}")
end
assert replay(
"""
What is your name?
> Ada
Hello, Ada. Your age:
> 36
Ada is 36
""",
ages,
)
quoted = fn -> print(" > not input")
assert replay(
"""
\> not input
""",
quoted,
)