Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-10 09:08:39 -06:00
commit 956a3b24a1
1625 files changed
+43424

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
# Tests of the containers: what they check of what they are asked for, what they
# close of their elements, and what they do where an allocator gives no memory,
# with the helpers of std they lean on.
import std::io;
import system;
import std::testing;
# A byte writer lays words out least significant byte first, and writes over
# what it wrote, as a length known only after what it counts.
@test def byte_writers_lay_out_words_and_lengths(t: &mut tester): void {
var w := byte_writer::new();
w.byte(0xAA);
val at := w.begin_length();
w.u16(0x0201);
w.u64(0x0807060504030201);
w.put_terminated("hi");
w.end_length(at);
t.expects(w.get_u32(at) == 13 && w.get_byte(5) == 0x01 && w.get_byte(6) == 0x02 && w.length == 18);
t.expects(w.align_to(8) == 24 && w.get_byte(23) == 0 && w.get_u64(7) == 0x0807060504030201);
w.set_u16(1, 0xBEEF);
w.set_byte(0, 1);
t.expects(w.view()[1] == 0xEF && w.view()[2] == 0xBE && w.get_byte(0) == 1);
w.zeros(3);
t.expects(w.length == 27 && pair_high(pair_key(5, 6)) == 5 && pair_low(pair_key(5, 6)) == 6);
w.rewind(5);
w.byte(9);
t.expects(w.length == 6 && w.get_byte(5) == 9 && w.get_u32(1) == 0xBEEF);
}
+247
View File
@@ -0,0 +1,247 @@
# Tests of finding what a glob matches in a tree of files: wildcards, `**`,
# braces, hidden names, links, roots, directories, repeats, and directories
# that can't be read. Every path is listed relative to the tree, with `/`
# between names.
import std::io;
import std::process;
import system;
import std::io::glob;
import std::testing;
# A tree of files of a test's own, removed with all it holds where the test
# returns:
#
# a.sakura b.txt .hidden.sakura 名前.sakura Upper.SAKURA src-old.txt
# docs/
# src/main.sakura src/notes.txt src/util/text.sakura src/util/deep/x.sakura
# src/.git/config.sakura
# test/t.sakura
#
# and on Linux, `link`, a link to `src`, and `loop`, a link to itself.
struct tree : fixture<tree>, owning {
var at: path;
}
def tree::setup(t: &mut tester): tree {
var made := tree { at = made_directory() };
for dir in ["docs", "src", "src/util", "src/util/deep", "src/.git", "test"] {
val at := made.at.join(dir);
_ = io::create_directory(&at);
}
for file in [
"a.sakura", "b.txt", ".hidden.sakura", "名前.sakura", "Upper.SAKURA", "src-old.txt", "src/main.sakura", "src/notes.txt",
"src/util/text.sakura", "src/util/deep/x.sakura", "src/.git/config.sakura", "test/t.sakura"
] {
val at := made.at.join(file);
_ = io::write_file(&at, "");
}
when os == linux {
var link := process::command::new("ln");
link.directory(&made.at);
link.arguments(["-s", "src", "link"]);
_ = link.run();
var loop := process::command::new("ln");
loop.directory(&made.at);
loop.arguments(["-s", "loop", "loop"]);
_ = loop.run();
}
return made;
}
def tree::close(&mut this): void {
when os == windows {
var removing := process::command::new("cmd");
removing.arguments(["/d", "/c", "rmdir", "/s", "/q", this.at.view()]);
_ = removing.run();
return;
}
var remove := process::command::new("rm");
remove.arguments(["-rf", this.at.view()]);
_ = remove.run();
}
# Makes a directory no other run has, by making it only where nothing is.
def made_directory(): path {
# Windows keeps its temporary files where `TEMP` says.
when os == windows {
for n in 0..10000 {
val named := path::parse($"{temporary()}\\sakura-glob-{n}") else (_) { break; };
var at := io::absolute(&named) else (_) { break; };
if io::create_directory(&at) is error(_) {
continue;
}
return move(at);
}
}
for n in 0..10000 {
var at := path::parse($"/tmp/sakura-glob-{n}") else (_) { break; };
if io::create_directory(&at) is error(_) {
continue;
}
return move(at);
}
system::abort();
return path::new();
}
# A path's text with `/` between its names, as Windows writes `\`.
def forward(text: strview): string {
var made := string::from(text, nothing {});
for k in 0..made.length {
if made[k] == '\\' {
made[k] = '/';
}
}
return made;
}
# What a glob finds in a tree, read with the options, which by default tell
# cases apart on every system: each path relative to the tree, with a space
# between them, or why it stopped.
def found(planted: &tree, text: strview, settings: glob::options = glob::options { folds_case = false }): string {
val made := glob::pattern::parse(text, settings) else (e) { return e.describe(); };
var listed := string::new(nothing {});
var got := made.find(&planted.at);
match got {
value(&paths) => {
for &each in paths {
if listed.length != 0 {
listed.push(' ');
}
if each.relative_to(&planted.at) is some(&relative) {
listed.append(forward(relative.view()).view());
} else {
listed.append(forward(each.view()).view());
}
}
}
error(&why) => listed.append(why.describe().view());
}
return listed;
}
@test def wildcards_find_the_names_of_a_directory(t: &mut tester, planted: tree): void {
t.expects(found(&planted, "*.sakura") == "a.sakura 名前.sakura");
t.expects(found(&planted, "*.sakura", glob::options { folds_case = true }) == "Upper.SAKURA a.sakura 名前.sakura");
t.expects(found(&planted, "?.*") == "a.sakura b.txt");
t.expects(found(&planted, "[ab].*") == "a.sakura b.txt");
t.expects(found(&planted, ".*") == ".hidden.sakura");
}
@test def two_stars_find_every_directory_below(t: &mut tester, planted: tree): void {
t.expects(found(&planted, "**/*.sakura") == "a.sakura src/main.sakura src/util/deep/x.sakura src/util/text.sakura test/t.sakura 名前.sakura");
t.expects(found(&planted, "src/**") == "src src/main.sakura src/notes.txt src/util src/util/deep src/util/deep/x.sakura src/util/text.sakura");
# In order by their bytes, as a shell orders them.
t.expects(found(&planted, "**/*.txt") == "b.txt src-old.txt src/notes.txt");
t.expects(found(&planted, "**/deep") == "src/util/deep");
t.expects(found(&planted, "**/util/**/*.sakura") == "src/util/deep/x.sakura src/util/text.sakura");
val hidden := glob::options { hidden = true, folds_case = false };
t.expects(found(&planted, "**/*.sakura", hidden) == ".hidden.sakura a.sakura src/.git/config.sakura src/main.sakura src/util/deep/x.sakura src/util/text.sakura test/t.sakura 名前.sakura");
}
@test def braces_find_each_once(t: &mut tester, planted: tree): void {
t.expects(found(&planted, "{src,test}/*.sakura") == "src/main.sakura test/t.sakura");
t.expects(found(&planted, "{src/**/x.sakura,**/deep/*.sakura}") == "src/util/deep/x.sakura");
t.expects(found(&planted, "{a,b}.*") == "a.sakura b.txt");
}
@test def names_as_written_are_joined_on(t: &mut tester, planted: tree): void {
t.expects(found(&planted, "a.sakura") == "a.sakura");
t.expects(found(&planted, "src/util/text.sakura") == "src/util/text.sakura");
t.expects(found(&planted, "nothing.sakura") == "" && found(&planted, "missing/*.sakura") == "");
t.expects(found(&planted, "a.sakura/*") == "" && found(&planted, "b.txt/**") == "b.txt");
t.expects(found(&planted, ".") == "." && found(&planted, "src/../test/*") == "src/../test/t.sakura");
}
@test def a_slash_last_finds_directories(t: &mut tester, planted: tree): void {
when os == linux {
t.expects(found(&planted, "*/") == "docs link src test");
t.expects(found(&planted, "**/") == "docs link src src/util src/util/deep test");
} else {
t.expects(found(&planted, "*/") == "docs src test");
t.expects(found(&planted, "**/") == "docs src src/util src/util/deep test");
}
t.expects(found(&planted, "src/*/") == "src/util" && found(&planted, "a.sakura/") == "");
}
@test def links_are_followed_where_named_but_not_by_two_stars(t: &mut tester, planted: tree): void {
when os != linux {
return;
}
t.expects(found(&planted, "*/main.sakura") == "link/main.sakura src/main.sakura");
t.expects(found(&planted, "link/**/*.sakura") == "link/main.sakura link/util/deep/x.sakura link/util/text.sakura");
t.expects(found(&planted, "l*") == "link loop");
t.expects(found(&planted, "**/main.sakura") == "src/main.sakura");
# A link leading around in a circle is passed over.
t.expects(found(&planted, "loop/*") == "" && found(&planted, "*/x") == "");
}
@test def a_glob_from_a_root_finds_from_there(t: &mut tester, planted: tree): void {
var rooted := glob::escape(planted.at.view());
rooted.append("/src/*.sakura");
t.expects(found(&planted, rooted.view()) == "src/main.sakura");
val made := glob::pattern::parse(rooted.view()) else (_) { t.expects(false); return; };
val elsewhere := path::parse("elsewhere") else (_) { t.expects(false); return; };
var got := made.find(&elsewhere);
if got is value(&paths) {
t.expects(paths.length == 1 && paths[0].is_absolute);
} else {
t.expects(false);
}
}
@test def a_directory_that_cannot_be_read_stops_the_search(t: &mut tester, planted: tree): void {
when os != linux {
return;
}
val locked := planted.at.join("locked");
_ = io::create_directory(&locked);
val inside := locked.join("inside.sakura");
_ = io::write_file(&inside, "");
_ = io::set_permissions(&locked, 0);
# Where it can be read anyway, as by the superuser, there's nothing to test.
if io::directory::open(&locked) is error(_) {
t.expects(found(&planted, "locked/*") == $"`{locked.view()}` could not be read: permission_denied");
t.expects(found(&planted, "**/*.sakura").starts_with("`"));
t.expects(found(&planted, "*.txt") == "b.txt src-old.txt");
}
_ = io::set_permissions(&locked, 0o755);
}
# Every path of the tree, but through links, relative to it, as `**` finds them
# with hidden names.
def everything(planted: &tree): vector<string> {
var all := vector::<string>::new();
val made := glob::pattern::parse("**", glob::options { hidden = true, folds_case = false }) else (_) { return all; };
var got := made.find(&planted.at);
if got is value(&paths) {
for &each in paths {
if each.relative_to(&planted.at) is some(&relative) {
all.append(forward(relative.view()));
}
}
}
return all;
}
@test def what_is_found_is_what_matches(t: &mut tester, planted: tree): void {
val all := everything(&planted);
t.expects(all.length > 15);
for text in ["**/*.sakura", "src/**", "**/util/*", "*.txt", "{src,test}/**/*.sakura", "**/[a-m]*", "?.sakura", "**/.*/*"] {
val made := glob::pattern::parse(text, glob::options { folds_case = false }) else (_) { t.expects(false); continue; };
var matched := string::new(nothing {});
for &each in all {
continue if !made.matches(each.view());
if matched.length != 0 {
matched.push(' ');
}
matched.append(each.view());
}
t.expects(found(&planted, text).view() == matched.view(), text);
}
}
+166
View File
@@ -0,0 +1,166 @@
# Tests of reading globs and matching text against them: each wildcard, sets,
# `**`, braces, escapes, hidden names, case, roots, directories, the mistakes a
# glob can hold, and `escape`.
import std::io::glob;
import std::testing;
# Whether a glob matches text, read with the options, which by default tell
# cases apart on every system.
def fits(text: strview, path: strview, settings: glob::options = glob::options { folds_case = false }): bool {
val made := glob::pattern::parse(text, settings) else (_) { return false; };
return made.matches(path);
}
# Whether reading a glob fails with a kind of mistake, at a byte.
def fails_with(text: strview, kind: glob::error_kind, offset: u64): bool {
match glob::pattern::parse(text) {
value(&_) => return false;
error(e) => return e.kind == kind && e.offset == offset;
}
return false;
}
@test def a_star_matches_any_run_within_a_name(t: &mut tester): void {
t.expects(fits("*.c", "a.c") && fits("*.c", "abc.c") && fits("*", "x"));
t.expects(!fits("*.c", "a.h") && !fits("*.c", "dir/a.c"));
t.expects(fits("a*", "a") && fits("*a*b*c", "xaybzc") && fits("*a*b*c", "abc"));
t.expects(!fits("*a*b*c", "acb") && !fits("a*b", "a/b"));
# Stars take back what they took, but only the last seen needs to.
t.expects(!fits("a*a*a*a*b", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
t.expects(fits("*?", "a") && !fits("*?", ""));
# More than two stars, or two within a name, are one.
t.expects(fits("a***b", "axyzb") && fits("a**b", "axyzb") && !fits("a**b", "ax/yb"));
}
@test def a_question_mark_matches_one_character(t: &mut tester): void {
t.expects(fits("?.c", "a.c") && !fits("?.c", "ab.c") && !fits("?.c", ".c"));
# A character is a code point, of however many bytes.
t.expects(fits("?", "é") && fits("?", "日") && fits("?", "😀") && !fits("??", "é"));
t.expects(fits("a?c", "a日c") && fits("*?本", "日本"));
# A star takes whole characters, never half of one.
t.expects(!fits("*\xA9", "é") && !fits("*\xA9", "\xC3\xC3\xA9") && fits("*\xA9", "a\xA9"));
# A byte that starts none is one of its own.
t.expects(fits("?", "\xFF") && fits("a?b", "a\xFFb") && !fits("?", "\xFF\xFF"));
}
@test def a_set_matches_one_character_of_its_own(t: &mut tester): void {
t.expects(fits("[abc].c", "b.c") && !fits("[abc].c", "d.c"));
t.expects(fits("[a-c]x", "bx") && !fits("[a-c]x", "dx"));
t.expects(fits("[!a-c]x", "dx") && !fits("[!a-c]x", "ax") && fits("[^a]x", "bx"));
# A `]` first is one, as is a `-` first or last.
t.expects(fits("[]]x", "]x") && fits("[!]]x", "ax") && !fits("[!]]x", "]x"));
t.expects(fits("[a-]x", "-x") && fits("[-a]x", "-x") && !fits("[a-]x", "bx"));
# Escapes and characters of more than a byte.
t.expects(fits("[\\]]", "]") && fits("[\\!a]", "!"));
t.expects(fits("[é-ë]", "ê") && !fits("[é-ë]", "e") && fits("[日本]", "本"));
# A set never matches the `.` starting a hidden name.
t.expects(!fits("[.]x", ".x") && fits("[.]x", ".x", glob::options { hidden = true, folds_case = false }));
}
@test def two_stars_match_any_number_of_names(t: &mut tester): void {
t.expects(fits("src/**/*.sakura", "src/a.sakura") && fits("src/**/*.sakura", "src/a/b/c.sakura"));
t.expects(!fits("src/**/*.sakura", "lib/a.sakura") && !fits("src/**/*.sakura", "src/.git/a.sakura"));
t.expects(fits("**", "a") && fits("**", "a/b/c") && fits("**/x", "x") && fits("**/x", "a/b/x"));
t.expects(fits("a/**", "a") && fits("a/**", "a/b/c") && !fits("a/**", "b"));
t.expects(fits("a/**/b/**/c", "a/b/c") && fits("a/**/b/**/c", "a/x/b/y/b/z/c") && !fits("a/**/b/**/c", "a/c"));
t.expects(fits("**/**/x", "x") && fits("**/**/x", "a/b/x"));
# `.` alone, or a root alone, is matched only by a glob naming it.
t.expects(!fits("**", ".") && !fits("**", "") && fits(".", ".") && fits("/", "/") && !fits("/**", "/"));
}
@test def braces_make_globs_of_their_own(t: &mut tester): void {
t.expects(fits("{src,test}/*.sakura", "src/a.sakura") && fits("{src,test}/*.sakura", "test/a.sakura"));
t.expects(!fits("{src,test}/*.sakura", "lib/a.sakura"));
t.expects(fits("a{b,{c,d}}e", "abe") && fits("a{b,{c,d}}e", "ace") && fits("a{b,{c,d}}e", "ade"));
t.expects(fits("{a,b}{c,d}", "bd") && fits("{,x}y", "y") && fits("{,x}y", "xy"));
t.expects(fits("{a/b,c}/d", "a/b/d") && fits("{a/b,c}/d", "c/d") && !fits("{a/b,c}/d", "a/d"));
t.expects(fits("x{a}", "xa") && fits("{[,]}", ",") && fits("{a\\,b,c}", "a,b"));
}
@test def escapes_match_what_they_escape(t: &mut tester): void {
t.expects(fits("\\*", "*") && !fits("\\*", "a") && fits("a\\?b", "a?b") && !fits("a\\?b", "axb"));
t.expects(fits("\\{a,b\\}", "{a,b}") && fits("\\[a]", "[a]") && fits("a\\\\b", "a\\b"));
# An escaped `/` still separates names.
t.expects(fits("a\\/b", "a/b"));
}
@test def hidden_names_are_matched_only_by_a_dot(t: &mut tester): void {
val hidden := glob::options { hidden = true, folds_case = false };
t.expects(fits(".*", ".git") && !fits("*", ".git") && fits(".git/*", ".git/config"));
t.expects(!fits("**/x", ".a/x") && fits("**/x", ".a/x", hidden) && fits("*", ".git", hidden));
# Neither `.` nor `..` is ever a wildcard's.
t.expects(!fits("*", "..", hidden) && !fits("?", ".", hidden) && !fits("**/x", "../x", hidden));
t.expects(fits("..", "..") && fits("../*.c", "../a.c"));
}
@test def letters_match_in_either_case_where_asked(t: &mut tester): void {
val folded := glob::options { folds_case = true };
t.expects(!fits("*.TXT", "a.txt") && fits("*.TXT", "a.txt", folded));
t.expects(fits("[A-C]", "b", folded) && fits("[!a-c]", "D", folded) && !fits("[!a-c]", "B", folded));
t.expects(fits("SRC/*", "src/a", folded) && !fits("SRC/*", "src/a"));
t.expects(fits("É", "É", folded) && !fits("é", "É", folded));
}
@test def roots_and_directories_are_matched_too(t: &mut tester): void {
t.expects(fits("/usr/*", "/usr/lib") && !fits("/usr/*", "usr/lib") && !fits("*", "/usr"));
t.expects(fits("*/", "src/") && !fits("*/", "src") && fits("src", "src/"));
t.expects(fits("a//b", "a/b") && fits("./a/*", "a/x") && fits("a/*", "a/./x") && fits("a/b", "a//b"));
val made := glob::pattern::parse("*/") else (_) { return; };
t.expects(made.directories && made.text == "*/");
}
@test def a_glob_without_wildcards_is_literal(t: &mut tester): void {
for text in ["src/main.sakura", "a\\*b", "/usr/lib", "."] {
val made := glob::pattern::parse(text) else (_) { t.expects(false); continue; };
t.expects(made.is_literal);
}
for text in ["src/*.c", "{a,b}", "a?", "[ab]", "**"] {
val made := glob::pattern::parse(text) else (_) { t.expects(false); continue; };
t.expects(!made.is_literal);
}
}
@test def mistakes_are_found_where_they_are(t: &mut tester): void {
t.expects(fails_with("", glob::error_kind::empty, 0));
t.expects(fails_with("a\\", glob::error_kind::trailing_escape, 1));
t.expects(fails_with("x[ab", glob::error_kind::unclosed_set, 1));
t.expects(fails_with("[]", glob::error_kind::unclosed_set, 0));
t.expects(fails_with("{a,{b}", glob::error_kind::unclosed_brace, 0));
t.expects(fails_with("a}", glob::error_kind::unopened_brace, 1));
t.expects(fails_with("{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}", glob::error_kind::too_many_choices, 0));
t.expects(!fails_with("{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}", glob::error_kind::too_many_choices, 0));
# A brace or escape within a set is the set's.
t.expects(fits("[{]", "{") && fits("[}]", "}"));
match glob::pattern::parse("a}") {
value(&_) => t.expects(false);
error(e) => t.expects(e.describe() == "A `}` has no `{` opening it. (at byte 1)");
}
}
@test def escaped_text_matches_only_itself(t: &mut tester): void {
val escaped := glob::escape("notes[1].txt");
t.expects(escaped == "notes\\[1\\].txt");
for text in ["notes[1].txt", "a*b?c", "{x,y}", "back\\slash", "]!^-"] {
val made := glob::pattern::parse(glob::escape(text)) else (_) { t.expects(false); continue; };
t.expects(made.is_literal);
when os == windows {
continue;
}
t.expects(made.matches(text));
}
}
+299
View File
@@ -0,0 +1,299 @@
# Tests of streams: what reads and writes bytes, the buffered readers and writers over
# any of them, and what owns or borrows what it reads or writes.
import std::io;
import system;
import std::testing;
# A file of a test's own, removed where the test returns.
struct scratch : fixture<scratch>, owning {
var at: path;
}
# Makes a file no other run has, by creating it only where nothing is.
def scratch::setup(t: &mut tester): scratch {
# Windows keeps its temporary files where `TEMP` says.
when os == windows {
for n in 0..10000 {
val named := path::parse($"{temporary()}\\sakura-streams-{n}.txt") else (_) { break; };
var at := io::absolute(&named) else (_) { break; };
val flags := open_flags::write | open_flags::create | open_flags::exclusive;
val made := io::file::open(&at, flags) else (_) { continue; };
return scratch { at = move(at) };
}
}
for n in 0..10000 {
var at := path::parse($"/tmp/sakura-streams-{n}.txt") else (_) { break; };
val flags := open_flags::write | open_flags::create | open_flags::exclusive;
val made := io::file::open(&at, flags) else (_) { continue; };
return scratch { at = move(at) };
}
system::abort();
return scratch {};
}
def scratch::close(&mut this): void {
_ = io::remove(&this.at);
}
# How many counted streams have been closed.
var counted_closed: u64 = 0;
# How many bytes had been written to the last counted stream closed, as what closes
# a value leaves it zeroed.
var counted_closed_with: u64 = 0;
# A stream that counts what is written to it and gives what it holds to read, and
# that closes, as a file does.
struct counted : readable, writable, owning {
var open: bool;
var written: u64;
var left: strview;
}
def counted::read(&mut this, into: slice<u8>): result<u64, io_error> {
if !this.open {
return io_error::invalid;
}
return this.left.read(into);
}
def counted::write(&mut this, data: span<u8>): result<void, io_error> {
if !this.open {
return io_error::invalid;
}
this.written += data.length;
return;
}
def counted::close(&mut this): void {
if this.open {
counted_closed++;
counted_closed_with = this.written;
this.open = false;
}
}
# Which of the stream traits a type has, as bits: readable, writable, flushable, and
# seekable, from the lowest.
def streams_of<T>(): u8 {
var bits: u8 = 0;
if const T is readable {
bits = bits | 1;
}
if const T is writable {
bits = bits | 2;
}
if const T is flushable {
bits = bits | 4;
}
if const T is seekable {
bits = bits | 8;
}
return bits;
}
# Reads lines, and writes each with its length, through whatever is given.
def answer<S>(input: &mut io::reader<S>, out: &mut writable): void where S: readable {
for line in input.lines() {
_ = out.write($"{line.length}:{line};");
}
}
@test def streams_are_what_they_read_and_write(t: &mut tester): void {
t.expects(streams_of::<io::file>() == 11 && streams_of::<io::console>() == 3);
t.expects(streams_of::<io::reader<io::file>>() == 1 && streams_of::<io::writer<io::file>>() == 6);
t.expects(streams_of::<string>() == 2 && streams_of::<strview>() == 1);
# A reference that writes has the traits of what it refers to, and one that only
# reads has none, since reading and writing move a stream along. A pointer has none.
t.expects(streams_of::<&mut io::file>() == 11 && streams_of::<&mut io::writer<string>>() == 6);
t.expects(streams_of::<&io::file>() == 0 && streams_of::<&strview>() == 0);
t.expects(streams_of::<*mut io::file>() == 0);
}
@test def streams_copy_into_one_another(t: &mut tester, s: scratch): void {
var opened := io::file::open(&s.at, open_flags::read | open_flags::write) else (_) {
t.expects(false);
return;
};
var text: strview = "copied through a file\n";
val wrote := io::copy_all(&mut text, &mut opened) else (_) { t.expects(false); return; };
t.expects(wrote == 22 && text.length == 0);
_ = opened.seek(0);
var said := string::new(nothing {});
val read := io::copy_all(&mut opened, &mut said) else (_) { t.expects(false); return; };
t.expects(read == 22 && said.view() == "copied through a file\n");
# Arguments are referred to as the parameters ask, and a stream behind a pointer is
# given through `through`.
var again: strview = "again";
val p := (&mut said) as *mut string;
_ = io::copy_all(again, through(p));
t.expects(said.view() == "copied through a file\nagain" && again.length == 0);
var rest: strview = "all of the rest";
val all := io::read_all(&mut rest) else (_) { t.expects(false); return; };
t.expects(all.view() == "all of the rest");
}
@test def readers_read_lines_of_any_stream(t: &mut tester): void {
var input := io::reader_of("first\r\nsecond\n\nlast");
var seen := string::new(nothing {});
var count := 0u;
for line in input.lines() {
seen.append(line.view());
seen.append("|");
count++;
}
t.expects(seen.view() == "first|second||last|" && count == 4 && input.error is none);
var bytes := io::reader_of("0123456789");
val four := bytes.read_exactly(4) else (_) { t.expects(false); return; };
val rest := bytes.read_all() else (_) { t.expects(false); return; };
t.expects(four.view() == "0123" && rest.view() == "456789");
t.expects(bytes.read_exactly(1).error == io_error::unexpected_end);
# Borrowed, the view read is the caller's, which the reader moves along.
var text: strview = "a\nb\n";
{
var borrowed := io::reader_of(&mut text);
_ = borrowed.read_line();
}
t.expects(text.length == 0);
# The same function reads text in a test that reads the console in a program.
var asked := io::reader_of("2 + 2\n3 * 4\n");
var said := string::new(nothing {});
answer(&mut asked, &mut said);
t.expects(said.view() == "5:2 + 2;5:3 * 4;");
}
@test def writers_write_to_any_stream(t: &mut tester): void {
var said := string::new(nothing {});
{
var out := io::writer_of(&mut said);
_ = out.write("held ");
_ = out.write_line("then written");
t.expects(said.length == 0);
_ = out.flush();
t.expects(said.view() == "held then written\n");
_ = out.write("at close");
}
t.expects(said.view() == "held then written\nat close");
val as_trait: &mut writable = &mut said;
{
var out := io::writer_of(as_trait);
_ = out.write("!");
}
t.expects(said.view().ends_with("!"));
# What is too large to hold goes straight through, after what was held.
var big := string::new(nothing {});
var filler := string::new(nothing {});
for _ in 0..20000 {
filler.push('x');
}
{
var out := io::writer_of(&mut big);
_ = out.write("a");
_ = out.write(filler.view());
t.expects(big.length == 20001 && big[0] == 'a');
}
}
@test def writers_flush_what_they_write_to(t: &mut tester): void {
var said := string::new(nothing {});
var inner := io::writer_of(&mut said);
{
var outer := io::writer_of(&mut inner);
_ = outer.write("stacked");
t.expects(said.length == 0);
_ = outer.flush();
t.expects(said.view() == "stacked");
}
}
@test def readers_and_writers_close_what_they_own(t: &mut tester): void {
counted_closed = 0;
{
var out := io::writer_of(counted { open = true });
_ = out.write("abc");
}
t.expects(counted_closed == 1);
# Closed by hand, a writer writes what it holds, then closes what it owns at
# once, and its scope ending closes nothing twice.
{
var out := io::writer_of(counted { open = true });
_ = out.write("abcd");
out.close();
t.expects(counted_closed == 2 && counted_closed_with == 4);
}
t.expects(counted_closed == 2);
# Borrowing, they close nothing, by hand or not.
var kept := counted { open = true, left = "kept\n" };
{
var out := io::writer_of(&mut kept);
_ = out.write("ef");
out.close();
var input := io::reader_of(&mut kept);
val line := input.read_line() else { t.expects(false); return; };
t.expects(line.view() == "kept");
}
t.expects(counted_closed == 2 && kept.open && kept.written == 2);
# Moved from, one writes nothing and closes nothing, and the one moved to closes.
{
var a := io::writer_of(counted { open = true });
var b := move(a);
t.expects(a.write("x").error == io_error::invalid);
_ = b.write("y");
}
t.expects(counted_closed == 3);
{
var input := io::reader_of(counted { open = true, left = "read" });
val all := input.read_all() else (_) { t.expects(false); return; };
t.expects(all.view() == "read");
}
t.expects(counted_closed == 4);
# Closing the standard output closes nothing of the console, which `output()`
# lends again.
io::output().close();
var info: file_info;
val handle: system::fd = system::fd::stdout;
t.expects(handle.stat(&mut info) == 0 && io::output().write("") is value);
}
@test def readers_and_writers_take_files_over(t: &mut tester, s: scratch): void {
{
var made := io::file::create(&s.at) else (_) { t.expects(false); return; };
var out := io::writer_of(move(made));
t.expects(!made.is_open);
for i in 0..3000 {
_ = out.write($"{i % 10}");
}
_ = out.write_line("!");
t.expects(io::info(&s.at).value.size == 0);
}
t.expects(io::info(&s.at).value.size == 3002);
var opened := io::file::open(&s.at) else (_) { t.expects(false); return; };
{
var input := io::reader_of(&mut opened);
val all := input.read_all() else (_) { t.expects(false); return; };
t.expects(all.length == 3002 && all.view().ends_with("789!\n"));
}
t.expects(opened.is_open);
_ = opened.seek(0);
var input := io::reader_of(move(opened));
val first := input.read_exactly(3) else (_) { t.expects(false); return; };
t.expects(first.view() == "012" && !opened.is_open);
}