Initial Commit
This commit is contained in:
1625 files changed
+43424
No files matched your search
@@ -0,0 +1,221 @@
|
||||
# Tests of the allocators: an arena hands out blocks one after another, grows the
|
||||
# last where it is, and frees them all at once, by reset, rewind, or close; the
|
||||
# containers keep their memory in one; and nodes linked by reference live in one.
|
||||
# A pool hands out blocks of one size, those given back first, makes and unmakes
|
||||
# values in them, and holds a list's nodes.
|
||||
import std::allocators;
|
||||
import std::containers;
|
||||
import std::testing;
|
||||
|
||||
|
||||
@test def arenas_hand_out_blocks_one_after_another(t: &mut tester): void {
|
||||
var a := arena::new(1024);
|
||||
val first := a.acquire(10, 1);
|
||||
val second := a.acquire(10, 1);
|
||||
val third := a.acquire(8, 8);
|
||||
t.expects(second == first + 10 && third == first + 24 && (third as u64) % 8 == 0);
|
||||
|
||||
# A block too large for what is left of a chunk starts another, and one larger
|
||||
# than a chunk has a chunk of its own.
|
||||
val big := a.acquire(5000, 16);
|
||||
t.expects(big != null && (big as u64) % 16 == 0);
|
||||
for i in 0..5000u { big[i] = (i % 251) as u8; }
|
||||
val after := a.acquire(16, 16);
|
||||
t.expects(after != null && big[4999] == (4999 % 251) as u8);
|
||||
}
|
||||
|
||||
@test def arenas_grow_and_give_back_the_last_block_where_it_is(t: &mut tester): void {
|
||||
var a := arena::new(1024);
|
||||
val block := a.acquire(16, 8);
|
||||
block[0] = 7;
|
||||
val grown := a.resize(block, 16, 64, 8);
|
||||
t.expects(grown == block && grown[0] == 7);
|
||||
|
||||
# A block that is not the last is copied.
|
||||
val other := a.acquire(16, 8);
|
||||
val moved := a.resize(grown, 64, 128, 8);
|
||||
t.expects(moved != grown && moved[0] == 7);
|
||||
|
||||
# The last block given back is where the next begins.
|
||||
a.dispose(moved, 128);
|
||||
t.expects(a.acquire(32, 8) == moved);
|
||||
a.dispose(other, 16);
|
||||
t.expects(a.acquire(8, 8) != other);
|
||||
}
|
||||
|
||||
@test def arenas_free_what_they_handed_out_by_reset_and_rewind(t: &mut tester): void {
|
||||
var a := arena::new(512);
|
||||
val first := a.acquire(100, 16);
|
||||
for _ in 0..20u { a.acquire(100, 16); }
|
||||
a.reset();
|
||||
t.expects(a.acquire(100, 16) == first);
|
||||
|
||||
val point := a.mark();
|
||||
val kept := a.acquire(64, 16);
|
||||
for _ in 0..20u { a.acquire(200, 16); }
|
||||
a.rewind(point);
|
||||
t.expects(a.acquire(64, 16) == kept);
|
||||
|
||||
}
|
||||
|
||||
@test def arenas_over_a_buffer_hand_it_out_first(t: &mut tester): void {
|
||||
var bytes: u8[1024];
|
||||
var a := arena::over(bytes[:]);
|
||||
val low := (&bytes) as *u8 as u64;
|
||||
val made := a.acquire(100, 8) as u64;
|
||||
t.expects(made >= low && made + 100 <= low + 1024);
|
||||
|
||||
# Once it is full, blocks come from the heap.
|
||||
val more := a.acquire(2000, 8) as u64;
|
||||
t.expects(more + 2000 <= low || more >= low + 1024);
|
||||
}
|
||||
|
||||
@test def containers_keep_their_memory_in_an_arena(t: &mut tester): void {
|
||||
var a := arena::new();
|
||||
val alloc: maybe<&mut allocator> = &mut a;
|
||||
|
||||
var numbers := vector::<u64>::new(alloc);
|
||||
for i in 0..1000u { numbers.append(i * 3); }
|
||||
var total: u64 = 0;
|
||||
for &n in numbers { total += n; }
|
||||
t.expects(numbers.length == 1000 && total == 1498500);
|
||||
|
||||
var names := dict::<u64, u64>::new(alloc);
|
||||
for i in 0..500u { names.set(i, i + 1); }
|
||||
t.expects(names.length == 500 && names[499] == 500);
|
||||
|
||||
var text := string::new(alloc);
|
||||
for _ in 0..100u { text.append("ab"); }
|
||||
t.expects(text.length == 200 && text[199] == 'b' as u8);
|
||||
|
||||
var nested := vector::<vector<u32>>::new(alloc);
|
||||
for i in 0..50u {
|
||||
var inner := vector::<u32>::new(alloc);
|
||||
inner.append(i as u32);
|
||||
nested.append(move(inner));
|
||||
}
|
||||
t.expects(nested.length == 50 && nested[49][0] == 49);
|
||||
}
|
||||
|
||||
struct arena_node {
|
||||
var value: u64;
|
||||
var next: maybe<&arena_node>;
|
||||
}
|
||||
|
||||
@test def an_arena_holds_nodes_linked_by_reference(t: &mut tester): void {
|
||||
var a := arena::new();
|
||||
val alloc: maybe<&mut allocator> = &mut a;
|
||||
|
||||
# Nodes made in an arena live until it rewinds past them, so they link to one
|
||||
# another by reference, and are given back together.
|
||||
val point := a.mark();
|
||||
var front: maybe<&arena_node> = nothing {};
|
||||
for i in 0..500u {
|
||||
val made := acquire::<arena_node>(alloc, 1);
|
||||
made[0] = arena_node { value = i, next = front };
|
||||
front = through(made);
|
||||
}
|
||||
var sum: u64 = 0;
|
||||
var count: u64 = 0;
|
||||
while front is some(&each) {
|
||||
sum += each.value;
|
||||
count++;
|
||||
front = each.next;
|
||||
}
|
||||
t.expects(count == 500 && sum == 124750);
|
||||
a.rewind(point);
|
||||
}
|
||||
|
||||
@test def pools_hand_out_the_blocks_given_back_first(t: &mut tester): void {
|
||||
var p := pool::new(24, 8);
|
||||
t.expects(p.block_size() == 24);
|
||||
val a := p.acquire(24, 8);
|
||||
val b := p.acquire(16, 8);
|
||||
val c := p.acquire(24, 8);
|
||||
t.expects(a != null && b == a + 24 && c == b + 24 && p.count() == 3);
|
||||
|
||||
# A block given back is the next handed out, the last given back first.
|
||||
p.dispose(b, 16);
|
||||
p.dispose(a, 24);
|
||||
t.expects(p.count() == 1 && p.acquire(24, 8) == a && p.acquire(24, 8) == b);
|
||||
|
||||
# Of a size or alignment larger than its blocks, it hands out nothing.
|
||||
t.expects(p.acquire(25, 8) == null && p.acquire(8, 16) == null && p.count() == 3);
|
||||
val aligned := pool::new(20, 16);
|
||||
t.expects(aligned.block_size() == 32);
|
||||
}
|
||||
|
||||
@test def pools_hand_out_their_chunks_again_once_reset(t: &mut tester): void {
|
||||
# More blocks than a chunk holds take more chunks, each carved in turn, and a
|
||||
# pool reset carves them again from the first.
|
||||
var p := pool::new(64, 8);
|
||||
val first := p.acquire(64, 8);
|
||||
for _ in 0..3000u {
|
||||
_ = p.acquire(64, 8);
|
||||
}
|
||||
t.expects(p.count() == 3001);
|
||||
p.reset();
|
||||
t.expects(p.count() == 0 && p.acquire(64, 8) == first);
|
||||
for _ in 0..3000u {
|
||||
_ = p.acquire(64, 8);
|
||||
}
|
||||
t.expects(p.count() == 3001);
|
||||
}
|
||||
|
||||
# The values of the pooled values closed, from any test.
|
||||
var pooled_closed: u64;
|
||||
|
||||
struct pooled : owning {
|
||||
var value: u64;
|
||||
}
|
||||
|
||||
def pooled::close(&mut this): void {
|
||||
pooled_closed += this.value;
|
||||
}
|
||||
|
||||
@test def pools_make_values_and_close_them_as_they_are_unmade(t: &mut tester): void {
|
||||
var p := pool::of::<pooled>();
|
||||
pooled_closed = 0;
|
||||
var made := vector::<*mut pooled>::new();
|
||||
for i in 1..101u {
|
||||
made.append(p.make(pooled { value = i }));
|
||||
}
|
||||
t.expects(p.count() == 100 && made[41][0].value == 42);
|
||||
|
||||
# The odd values, 1 to 99, are unmade, then the rest.
|
||||
for i in 0..made.length {
|
||||
if i % 2 == 0 {
|
||||
p.unmake(made[i]);
|
||||
}
|
||||
}
|
||||
t.expects(pooled_closed == 2500 && p.count() == 50);
|
||||
for i in 0..made.length {
|
||||
if i % 2 == 1 {
|
||||
p.unmake(made[i]);
|
||||
}
|
||||
}
|
||||
t.expects(pooled_closed == 5050 && p.count() == 0);
|
||||
}
|
||||
|
||||
@test def lists_keep_their_nodes_in_a_pool(t: &mut tester): void {
|
||||
# A list asks for one node at a time, each within the pool's blocks, and gives
|
||||
# each back as it is removed.
|
||||
var p := pool::new(64, 8);
|
||||
val alloc: maybe<&mut allocator> = &mut p;
|
||||
{
|
||||
var numbers := list::<u64>::new(alloc);
|
||||
for i in 0..1000u {
|
||||
numbers.push_back(i);
|
||||
}
|
||||
t.expects(p.count() == 1000);
|
||||
for _ in 0..400u {
|
||||
numbers.pop_front();
|
||||
}
|
||||
var total: u64 = 0;
|
||||
for &n in numbers {
|
||||
total += n;
|
||||
}
|
||||
t.expects(p.count() == 600 && total == 419700);
|
||||
}
|
||||
t.expects(p.count() == 0);
|
||||
}
|
||||
@@ -0,0 +1,585 @@
|
||||
# Tests of `std::args`: every form of the syntax, each error and where it is,
|
||||
# the values std's types read, repeats, positional arguments, subcommands, the
|
||||
# help text, and the mistakes in marks that stop the program. The commands are
|
||||
# private to the program, so the walk sees them only by the consent its marks
|
||||
# give.
|
||||
import std::args;
|
||||
import std::io;
|
||||
import std::testing;
|
||||
|
||||
|
||||
@command{ name = "flags", help = "Reads switches and numbers." }
|
||||
struct cli_flags {
|
||||
@option{ short = 'v', help = "Says more." }
|
||||
var verbose: bool;
|
||||
@option{ short = 'q' }
|
||||
var quiet: bool;
|
||||
@option{ short = 'n', value = "N", help = "How many." }
|
||||
var count: i64 = 3;
|
||||
@option{ name = "level", short = 'l' }
|
||||
var depth: i64;
|
||||
@option{ help = "Does nothing." }
|
||||
var dry_run: bool;
|
||||
@argument{ value = "WORD", help = "The words." }
|
||||
var words: vector<strview>;
|
||||
var untouched: i64 = 99;
|
||||
}
|
||||
|
||||
enum cli_colour: u8 {
|
||||
@choice red,
|
||||
@choice{ name = "GREEN", help = "As grass is." } green,
|
||||
@choice light_blue,
|
||||
unmarked,
|
||||
}
|
||||
|
||||
struct cli_heat : args::value {
|
||||
var degrees: f64;
|
||||
}
|
||||
|
||||
def cli_heat::from_argument(text: strview): result<cli_heat, strview> {
|
||||
if text.length < 2 || text[text.length - 1] != 'C' {
|
||||
return "is not a temperature, as `21C`";
|
||||
}
|
||||
return match real::parse::<f64>(text.substr(0, text.length - 1)) {
|
||||
value(v) => cli_heat { degrees = v },
|
||||
error(_) => "is not a temperature, as `21C`",
|
||||
};
|
||||
}
|
||||
|
||||
@command{ name = "values" }
|
||||
struct cli_values {
|
||||
@option var tiny: u8;
|
||||
@option var signed: i8;
|
||||
@option var wide: i64;
|
||||
@option var huge: u64;
|
||||
@option var ratio: f64;
|
||||
@option var small: f32;
|
||||
@option var named: string;
|
||||
@option var file: path;
|
||||
@option var colour: cli_colour = cli_colour::red;
|
||||
@option var heat: maybe<cli_heat>;
|
||||
@option var hues: vector<cli_colour>;
|
||||
}
|
||||
|
||||
@command{ name = "repeats" }
|
||||
struct cli_repeats {
|
||||
@option{ short = 'I', value = "DIR" }
|
||||
var include: vector<strview>;
|
||||
@option{ short = 'v', count = true }
|
||||
var verbosity: u32;
|
||||
@option{ short = 'n' }
|
||||
var number: i32;
|
||||
}
|
||||
|
||||
@command{ name = "places" }
|
||||
struct cli_places {
|
||||
@argument{ value = "FIRST" }
|
||||
var first: strview;
|
||||
@argument{ value = "MIDDLE" }
|
||||
var middle: vector<i64>;
|
||||
@argument{ value = "LAST" }
|
||||
var last: strview;
|
||||
@argument{ value = "MAYBE" }
|
||||
var maybe_one: maybe<strview>;
|
||||
}
|
||||
|
||||
@command{ name = "passes" }
|
||||
struct cli_passes {
|
||||
@option{ short = 'x' }
|
||||
var exact: bool;
|
||||
@argument{ value = "FILE" }
|
||||
var files: vector<strview>;
|
||||
@argument{ value = "ARGUMENT", rest = true, help = "What is passed on." }
|
||||
var passed: vector<strview>;
|
||||
}
|
||||
|
||||
@command{ name = "needs" }
|
||||
struct cli_needs {
|
||||
@option{ short = 'o', value = "OUTPUT", required = true, help = "Where it goes." }
|
||||
var output: strview;
|
||||
@argument{ value = "INPUT" }
|
||||
var input: strview;
|
||||
}
|
||||
|
||||
@command{ name = "host" }
|
||||
struct cli_host {
|
||||
@option{ short = 'h', value = "NAME", help = "The host." }
|
||||
var host: strview;
|
||||
}
|
||||
|
||||
@command{ name = "git", help = "Keeps versions.", version = "git 2.0" }
|
||||
union cli_git {
|
||||
@command{ help = "Names other copies." }
|
||||
var remote: cli_remote;
|
||||
@command
|
||||
var status: cli_status;
|
||||
}
|
||||
|
||||
@command{ help = "Lists, adds, and removes other copies." }
|
||||
struct cli_remote {
|
||||
@option{ short = 'v', help = "Shows each one's address." }
|
||||
var verbose: bool;
|
||||
@argument
|
||||
var action: cli_remote_action;
|
||||
}
|
||||
|
||||
@command
|
||||
union cli_remote_action {
|
||||
@command{ help = "Adds one." }
|
||||
var add: cli_remote_add;
|
||||
@command{ name = "rm", help = "Removes one." }
|
||||
var remove: cli_remote_remove;
|
||||
}
|
||||
|
||||
@command
|
||||
struct cli_remote_add {
|
||||
@option{ help = "Fetches it at once." }
|
||||
var fetch: bool;
|
||||
@argument{ value = "NAME" }
|
||||
var name: strview;
|
||||
@argument{ value = "URL" }
|
||||
var url: strview;
|
||||
}
|
||||
|
||||
@command
|
||||
struct cli_remote_remove {
|
||||
@argument{ value = "NAME" }
|
||||
var name: strview;
|
||||
}
|
||||
|
||||
@command{ help = "Shows what changed." }
|
||||
struct cli_status {
|
||||
@option{ short = 's' }
|
||||
var short_form: bool;
|
||||
}
|
||||
|
||||
@command{ name = "make" }
|
||||
struct cli_make {
|
||||
@option{ short = 'C', value = "DIR" }
|
||||
var directory: strview;
|
||||
@argument{ value = "FILE" }
|
||||
var file: strview;
|
||||
@argument
|
||||
var step: cli_make_step;
|
||||
}
|
||||
|
||||
@command
|
||||
union cli_make_step {
|
||||
@command var build: cli_make_build;
|
||||
@command var clean: cli_status;
|
||||
}
|
||||
|
||||
@command
|
||||
struct cli_make_build {
|
||||
@option{ short = 'j' }
|
||||
var jobs: u8 = 1;
|
||||
}
|
||||
|
||||
# Options several commands share, as a group, which holds a group of its own.
|
||||
@group
|
||||
struct cli_shared {
|
||||
@option{ short = 'O', value = "LEVEL", help = "How much to optimize." }
|
||||
var level: u8 = 2;
|
||||
@option{ short = 'v', help = "Says more." }
|
||||
var verbose: bool;
|
||||
@group
|
||||
var library: cli_library;
|
||||
}
|
||||
|
||||
@group
|
||||
struct cli_library {
|
||||
@option{ name = "std", value = "DIR", required = true, help = "Where the library is." }
|
||||
var directory: strview;
|
||||
@option{ short = 'I', value = "DIR" }
|
||||
var include: vector<strview>;
|
||||
}
|
||||
|
||||
@command{ name = "grouped", help = "Builds with the options it shares." }
|
||||
struct cli_grouped {
|
||||
@option{ short = 'o', value = "OUTPUT", help = "Where it goes." }
|
||||
var output: strview;
|
||||
@group
|
||||
var shared: cli_shared;
|
||||
@option{ short = 'j', value = "N", help = "How many at once." }
|
||||
var jobs: u32 = 1;
|
||||
@argument{ value = "FILE", help = "The files." }
|
||||
var files: vector<strview>;
|
||||
}
|
||||
|
||||
# The commands whose marks are mistaken, which stop the program once read.
|
||||
@command struct cli_two_longs { @option var level: i64; @option{ name = "level" } var depth: i64; }
|
||||
@command struct cli_two_shorts { @option{ short = 'x' } var one: bool; @option{ short = 'x' } var two: bool; }
|
||||
@command struct cli_bad_short { @option{ short = '!' } var bang: bool; }
|
||||
@command struct cli_bad_count { @option{ count = true } var noise: strview; }
|
||||
@command struct cli_bad_rest { @argument{ rest = true } var after: strview; }
|
||||
@command struct cli_two_rests { @argument{ rest = true } var one: vector<strview>; @argument{ rest = true } var two: vector<strview>; }
|
||||
@command struct cli_late_command { @argument var step: cli_make_step; @argument var after: strview; }
|
||||
@command struct cli_many_before { @argument var files: vector<strview>; @argument var step: cli_make_step; }
|
||||
@command union cli_two_commands { @command var one: cli_status; @command{ name = "one" } var two: cli_status; }
|
||||
@command struct cli_group_short { @option{ short = 'v' } var loud: bool; @group var shared: cli_shared; }
|
||||
@command struct cli_group_long { @group var shared: cli_shared; @option{ name = "std" } var other: strview; }
|
||||
|
||||
# The error reading the arguments into a command gives, or one of no kind
|
||||
# where they are read.
|
||||
def cli_error_of<T>(given: span<strview>): args::error where T: zeroable {
|
||||
var read := args::parse::<T>(given) else (wrong) { return wrong; };
|
||||
return args::error { kind = args::error_kind::help_asked, at = 9999 };
|
||||
}
|
||||
|
||||
# The arguments read into flags, or flags of a count of -1 where they are not.
|
||||
def cli_flags_of(given: span<strview>): cli_flags {
|
||||
var read := args::parse::<cli_flags>(given) else (_) { return cli_flags { count = -1 }; };
|
||||
return move(read);
|
||||
}
|
||||
|
||||
@test def options_are_read_by_long_and_short_names(t: &mut tester): void {
|
||||
t.expects(cli_flags_of(["--count", "4"]).count == 4);
|
||||
t.expects(cli_flags_of(["--count=5"]).count == 5);
|
||||
t.expects(cli_flags_of(["-n", "6"]).count == 6);
|
||||
t.expects(cli_flags_of(["-n7"]).count == 7);
|
||||
t.expects(cli_flags_of(["--level", "2"]).depth == 2);
|
||||
t.expects(cli_flags_of(["-l", "8"]).depth == 8);
|
||||
|
||||
val plain := cli_flags_of([]);
|
||||
t.expects(plain.count == 3 && plain.depth == 0 && !plain.verbose && plain.words.length == 0 && plain.untouched == 99);
|
||||
|
||||
# Switches written together, the last of them taking a value.
|
||||
val together := cli_flags_of(["-vq"]);
|
||||
t.expects(together.verbose && together.quiet);
|
||||
val valued := cli_flags_of(["-vn9"]);
|
||||
t.expects(valued.verbose && !valued.quiet && valued.count == 9);
|
||||
val spaced := cli_flags_of(["-qvn", "10"]);
|
||||
t.expects(spaced.verbose && spaced.quiet && spaced.count == 10);
|
||||
|
||||
# A field's `_` is written `-`, and the last of an option written is kept.
|
||||
t.expects(cli_flags_of(["--dry-run"]).dry_run);
|
||||
t.expects(cli_error_of::<cli_flags>(["--dry_run"]).kind == args::error_kind::unknown_option);
|
||||
t.expects(cli_flags_of(["-n", "1", "--count", "2", "-n3"]).count == 3);
|
||||
}
|
||||
|
||||
@test def values_may_begin_with_a_dash_and_positional_arguments_may_be_dashes(t: &mut tester): void {
|
||||
t.expects(cli_flags_of(["--level", "-5"]).depth == -5);
|
||||
t.expects(cli_flags_of(["-n", "-12"]).count == -12);
|
||||
t.expects(cli_flags_of(["--level=-6"]).depth == -6);
|
||||
|
||||
# Options come between positional arguments, which a lone `-` is, and `-` then
|
||||
# a digit, where no short name is a digit.
|
||||
val mixed := cli_flags_of(["one", "-v", "-", "-5", "two"]);
|
||||
t.expects(mixed.verbose && mixed.words.length == 4);
|
||||
t.expects(mixed.words[0] == "one" && mixed.words[1] == "-" && mixed.words[2] == "-5" && mixed.words[3] == "two");
|
||||
|
||||
# After `--`, everything is positional.
|
||||
val ended := cli_flags_of(["a", "--", "-v", "--count", "b"]);
|
||||
t.expects(!ended.verbose && ended.count == 3 && ended.words.length == 4 && ended.words[1] == "-v");
|
||||
|
||||
# `--name=` gives an empty value, which no number is.
|
||||
val empty := cli_error_of::<cli_flags>(["--count="]);
|
||||
t.expects(empty.kind == args::error_kind::invalid_value && empty.text.length == 0);
|
||||
}
|
||||
|
||||
@test def each_error_says_where_it_is(t: &mut tester): void {
|
||||
val unknown := cli_error_of::<cli_flags>(["-v", "--colour", "red"]);
|
||||
t.expects(unknown.kind == args::error_kind::unknown_option && unknown.at == 1 && unknown.text == "--colour");
|
||||
val unknown_short := cli_error_of::<cli_flags>(["-vz"]);
|
||||
t.expects(unknown_short.kind == args::error_kind::unknown_option && unknown_short.at == 0 && unknown_short.name == "-z");
|
||||
|
||||
val missing := cli_error_of::<cli_flags>(["-v", "--count"]);
|
||||
t.expects(missing.kind == args::error_kind::missing_value && missing.at == 2 && missing.name == "--count");
|
||||
val missing_short := cli_error_of::<cli_flags>(["-vn"]);
|
||||
t.expects(missing_short.kind == args::error_kind::missing_value && missing_short.at == 1 && missing_short.name == "-n");
|
||||
|
||||
val invalid := cli_error_of::<cli_flags>(["--count", "ten"]);
|
||||
t.expects(invalid.kind == args::error_kind::invalid_value && invalid.at == 1 && invalid.text == "ten");
|
||||
t.expects(invalid.name == "--count" && invalid.reason == "is not a whole number");
|
||||
val attached := cli_error_of::<cli_flags>(["-nx1"]);
|
||||
t.expects(attached.kind == args::error_kind::invalid_value && attached.at == 0 && attached.text == "x1" && attached.name == "-n");
|
||||
|
||||
val switched := cli_error_of::<cli_flags>(["--verbose=yes"]);
|
||||
t.expects(switched.kind == args::error_kind::switch_given_value && switched.text == "yes" && switched.name == "--verbose");
|
||||
|
||||
val required := cli_error_of::<cli_needs>(["in"]);
|
||||
t.expects(required.kind == args::error_kind::missing_option && required.at == 1 && required.name == "--output");
|
||||
val argument := cli_error_of::<cli_needs>(["-o", "out"]);
|
||||
t.expects(argument.kind == args::error_kind::missing_argument && argument.at == 2 && argument.name == "INPUT");
|
||||
val extra := cli_error_of::<cli_needs>(["-o", "out", "in", "more"]);
|
||||
t.expects(extra.kind == args::error_kind::unexpected_argument && extra.at == 3 && extra.text == "more");
|
||||
|
||||
val command := cli_error_of::<cli_git>(["stats"]);
|
||||
t.expects(command.kind == args::error_kind::unknown_command && command.at == 0 && command.text == "stats");
|
||||
val no_command := cli_error_of::<cli_git>([]);
|
||||
t.expects(no_command.kind == args::error_kind::missing_command && no_command.at == 0);
|
||||
val deeper := cli_error_of::<cli_git>(["remote", "-v"]);
|
||||
t.expects(deeper.kind == args::error_kind::missing_command && deeper.at == 2);
|
||||
|
||||
val helped := cli_error_of::<cli_flags>(["-v", "--help"]);
|
||||
t.expects(helped.kind == args::error_kind::help_asked && helped.at == 1);
|
||||
t.expects(cli_error_of::<cli_flags>(["-vh"]).kind == args::error_kind::help_asked);
|
||||
t.expects(cli_error_of::<cli_git>(["--version"]).kind == args::error_kind::version_asked);
|
||||
t.expects(cli_error_of::<cli_flags>(["--version"]).kind == args::error_kind::unknown_option);
|
||||
}
|
||||
|
||||
@test def errors_say_what_went_wrong(t: &mut tester): void {
|
||||
t.expects(cli_error_of::<cli_values>(["--tiny", "300"]).describe().view() == "`--tiny 300`: 300 is not between 0 and 255.");
|
||||
t.expects(cli_error_of::<cli_flags>(["--colour"]).describe().view() == "`--colour` is not an option.");
|
||||
t.expects(cli_error_of::<cli_flags>(["--count"]).describe().view() == "`--count` needs a value.");
|
||||
t.expects(cli_error_of::<cli_flags>(["-q=1"]).describe().view() == "`-q=1` is not an option.");
|
||||
t.expects(cli_error_of::<cli_flags>(["--quiet=1"]).describe().view() == "`--quiet` takes no value, but is given `1`.");
|
||||
t.expects(cli_error_of::<cli_needs>(["in"]).describe().view() == "`--output` is required.");
|
||||
t.expects(cli_error_of::<cli_needs>(["-o", "out"]).describe().view() == "INPUT is missing.");
|
||||
t.expects(cli_error_of::<cli_places>(["a", "x", "b"]).describe().view() == "MIDDLE `x` is not a whole number.");
|
||||
t.expects(cli_error_of::<cli_needs>(["-o", "o", "a", "b"]).describe().view() == "`b` is more than the arguments taken.");
|
||||
t.expects(cli_error_of::<cli_git>(["stats"]).describe().view() == "`stats` is not a command.");
|
||||
t.expects(cli_error_of::<cli_git>([]).describe().view() == "A command is needed.");
|
||||
}
|
||||
|
||||
@test def numbers_are_read_within_their_ranges(t: &mut tester): void {
|
||||
val read := args::parse::<cli_values>([
|
||||
"--tiny", "255", "--signed=-128", "--wide", "-9223372036854775808", "--huge", "18446744073709551615",
|
||||
"--ratio", "2.5", "--small", "-0.25"
|
||||
]) else (_) { t.expects(false); return; };
|
||||
t.expects(read.tiny == 255 && read.signed == -128 && read.wide == -9223372036854775807 - 1);
|
||||
t.expects(read.huge == 18446744073709551615 && read.ratio == 2.5 && read.small == -0.25);
|
||||
|
||||
# A prefix and `_` between digits are read as the language reads them.
|
||||
val prefixed := args::parse::<cli_values>(["--wide", "0x1_0", "--tiny", "0b11", "--huge", "1_000"]) else (_) { t.expects(false); return; };
|
||||
t.expects(prefixed.wide == 16 && prefixed.tiny == 3 && prefixed.huge == 1000);
|
||||
|
||||
t.expects(cli_error_of::<cli_values>(["--tiny", "256"]).reason == "is not between 0 and 255");
|
||||
t.expects(cli_error_of::<cli_values>(["--tiny", "-1"]).reason == "is not between 0 and 255");
|
||||
t.expects(cli_error_of::<cli_values>(["--signed", "-129"]).reason == "is not between -128 and 127");
|
||||
t.expects(cli_error_of::<cli_values>(["--signed", "128"]).reason == "is not between -128 and 127");
|
||||
t.expects(cli_error_of::<cli_values>(["--wide", "9223372036854775808"]).kind == args::error_kind::invalid_value);
|
||||
t.expects(cli_error_of::<cli_values>(["--huge", "18446744073709551616"]).reason == "is not a whole number");
|
||||
t.expects(cli_error_of::<cli_values>(["--tiny", "0x"]).reason == "is not a whole number");
|
||||
t.expects(cli_error_of::<cli_values>(["--ratio", "much"]).reason == "is not a number");
|
||||
t.expects(cli_error_of::<cli_values>(["--small", "1e39"]).reason == "is too large");
|
||||
}
|
||||
|
||||
@test def text_paths_enums_and_a_programs_own_values_are_read(t: &mut tester): void {
|
||||
val read := args::parse::<cli_values>([
|
||||
"--named", "anything", "--file", "a/b", "--colour", "light-blue", "--heat", "21.5C"
|
||||
]) else (_) { t.expects(false); return; };
|
||||
t.expects(read.named.view() == "anything");
|
||||
t.expects(read.file.view() == path::parse("a/b").value.view());
|
||||
t.expects(read.colour == cli_colour::light_blue);
|
||||
t.expects(read.heat is some(&heat) && heat.degrees == 21.5);
|
||||
t.expects(args::parse::<cli_values>([]).value.heat is none);
|
||||
|
||||
# A member is read by the `name` its mark gives, and an unmarked one not at all.
|
||||
t.expects(args::parse::<cli_values>(["--colour", "GREEN"]).value.colour == cli_colour::green);
|
||||
t.expects(cli_error_of::<cli_values>(["--colour", "green"]).reason == "is not one of the choices");
|
||||
t.expects(cli_error_of::<cli_values>(["--colour", "unmarked"]).kind == args::error_kind::invalid_value);
|
||||
t.expects(cli_error_of::<cli_values>(["--heat", "hot"]).reason == "is not a temperature, as `21C`");
|
||||
t.expects(cli_error_of::<cli_values>(["--file", ""]).reason == "is not a path");
|
||||
|
||||
val listed := args::parse::<cli_values>(["--hues", "red", "--hues", "GREEN"]) else (_) { t.expects(false); return; };
|
||||
t.expects(listed.hues.length == 2 && listed.hues[0] == cli_colour::red && listed.hues[1] == cli_colour::green);
|
||||
}
|
||||
|
||||
@test def options_repeat_into_vectors_and_counts(t: &mut tester): void {
|
||||
val read := args::parse::<cli_repeats>(["-I", "a", "-vvv", "--include=b", "-Ic", "-v"]) else (_) { t.expects(false); return; };
|
||||
t.expects(read.include.length == 3 && read.include[0] == "a" && read.include[1] == "b" && read.include[2] == "c");
|
||||
t.expects(read.verbosity == 4);
|
||||
t.expects(args::parse::<cli_repeats>(["--verbosity", "--verbosity"]).value.verbosity == 2);
|
||||
t.expects(cli_error_of::<cli_repeats>(["--verbosity=2"]).kind == args::error_kind::switch_given_value);
|
||||
|
||||
# A count is no switch to the short names written with it: `-vn5` counts once.
|
||||
val counted := args::parse::<cli_repeats>(["-vn5"]) else (_) { t.expects(false); return; };
|
||||
t.expects(counted.verbosity == 1 && counted.number == 5);
|
||||
}
|
||||
|
||||
@test def positional_arguments_go_to_their_fields_in_turn(t: &mut tester): void {
|
||||
# A vector takes what is left over once the single fields after it have theirs.
|
||||
val read := args::parse::<cli_places>(["a", "1", "2", "3", "z"]) else (_) { t.expects(false); return; };
|
||||
t.expects(read.first == "a" && read.middle.length == 3 && read.middle[2] == 3 && read.last == "z" && read.maybe_one is none);
|
||||
|
||||
val fewest := args::parse::<cli_places>(["a", "z"]) else (_) { t.expects(false); return; };
|
||||
t.expects(fewest.first == "a" && fewest.middle.length == 0 && fewest.last == "z");
|
||||
t.expects(cli_error_of::<cli_places>(["a"]).name == "LAST");
|
||||
|
||||
# What follows `--` goes to the field taking the rest, and only there.
|
||||
val passed := args::parse::<cli_passes>(["x.sakura", "-x", "y.sakura", "--", "-x", "--", "z"]) else (_) { t.expects(false); return; };
|
||||
t.expects(passed.exact && passed.files.length == 2 && passed.files[1] == "y.sakura");
|
||||
t.expects(passed.passed.length == 3 && passed.passed[0] == "-x" && passed.passed[1] == "--" && passed.passed[2] == "z");
|
||||
val none_passed := args::parse::<cli_passes>(["a"]) else (_) { t.expects(false); return; };
|
||||
t.expects(none_passed.files.length == 1 && none_passed.passed.length == 0);
|
||||
}
|
||||
|
||||
@test def subcommands_read_their_own_options_two_deep(t: &mut tester): void {
|
||||
val read := args::parse::<cli_git>(["remote", "-v", "add", "--fetch", "origin", "https://x"]) else (_) { t.expects(false); return; };
|
||||
match read {
|
||||
remote(&r) => {
|
||||
t.expects(r.verbose);
|
||||
match r.action {
|
||||
add(&a) => t.expects(a.fetch && a.name == "origin" && a.url == "https://x");
|
||||
remove(&_) => t.expects(false);
|
||||
}
|
||||
}
|
||||
status(&_) => t.expects(false);
|
||||
}
|
||||
|
||||
val removed := args::parse::<cli_git>(["remote", "rm", "old"]) else (_) { t.expects(false); return; };
|
||||
t.expects(removed is remote(&r) && r.action is remove(&gone) && gone.name == "old" && !r.verbose);
|
||||
t.expects(args::parse::<cli_git>(["status", "-s"]).value is status(&s) && s.short_form);
|
||||
|
||||
# A command's own options come before its subcommand's word, and the
|
||||
# positional arguments before it each take one.
|
||||
val made := args::parse::<cli_make>(["-C", "src", "rules.mk", "build", "-j", "8"]) else (_) { t.expects(false); return; };
|
||||
t.expects(made.directory == "src" && made.file == "rules.mk" && made.step is build(&b) && b.jobs == 8);
|
||||
t.expects(cli_error_of::<cli_make>(["rules.mk", "build", "-C", "x"]).kind == args::error_kind::unknown_option);
|
||||
t.expects(cli_error_of::<cli_make>(["rules.mk"]).kind == args::error_kind::missing_command);
|
||||
}
|
||||
|
||||
@test def the_help_text_is_written_from_the_marks(t: &mut tester): void {
|
||||
t.expects(args::help::<cli_flags>().view() == """
|
||||
usage: flags [options] WORD...
|
||||
|
||||
Reads switches and numbers.
|
||||
|
||||
arguments:
|
||||
WORD... The words.
|
||||
|
||||
options:
|
||||
-v, --verbose Says more.
|
||||
-q, --quiet
|
||||
-n, --count N How many. Default: 3.
|
||||
-l, --level LEVEL Default: 0.
|
||||
--dry-run Does nothing.
|
||||
-h, --help Shows this help.
|
||||
""");
|
||||
|
||||
# The arguments reach a subcommand, whose help is given, and its usage.
|
||||
t.expects(args::help::<cli_git>(["remote", "add", "--help"]).view() == """
|
||||
usage: git remote add [options] NAME URL
|
||||
|
||||
Adds one.
|
||||
|
||||
arguments:
|
||||
NAME
|
||||
URL
|
||||
|
||||
options:
|
||||
--fetch Fetches it at once.
|
||||
-h, --help Shows this help.
|
||||
""");
|
||||
t.expects(args::usage::<cli_git>(["remote"]).view() == "usage: git remote [options] COMMAND ...");
|
||||
t.expects(args::help::<cli_git>(["--help"]).view() == """
|
||||
usage: git [options] COMMAND ...
|
||||
|
||||
Keeps versions.
|
||||
|
||||
commands:
|
||||
remote Names other copies.
|
||||
status Shows what changed.
|
||||
|
||||
options:
|
||||
-h, --help Shows this help.
|
||||
--version Shows the version.
|
||||
""");
|
||||
|
||||
t.expects(args::help::<cli_values>([]).view() == """
|
||||
usage: values [options]
|
||||
|
||||
options:
|
||||
--tiny TINY Default: 0.
|
||||
--signed SIGNED Default: 0.
|
||||
--wide WIDE Default: 0.
|
||||
--huge HUGE Default: 0.
|
||||
--ratio RATIO Default: 0.
|
||||
--small SMALL Default: 0.
|
||||
--named NAMED
|
||||
--file FILE
|
||||
--colour COLOUR Default: red.
|
||||
red
|
||||
GREEN As grass is.
|
||||
light-blue
|
||||
--heat HEAT
|
||||
--hues HUES
|
||||
red
|
||||
GREEN As grass is.
|
||||
light-blue
|
||||
-h, --help Shows this help.
|
||||
""");
|
||||
t.expects(args::usage::<cli_passes>().view() == "usage: passes [options] FILE... [-- ARGUMENT...]");
|
||||
t.expects(args::usage::<cli_places>().view() == "usage: places [options] FIRST MIDDLE... LAST [MAYBE]");
|
||||
}
|
||||
|
||||
@test def help_is_left_to_a_field_taking_its_name(t: &mut tester): void {
|
||||
val read := args::parse::<cli_host>(["-h", "example.org"]) else (_) { t.expects(false); return; };
|
||||
t.expects(read.host == "example.org");
|
||||
t.expects(cli_error_of::<cli_host>(["--help"]).kind == args::error_kind::help_asked);
|
||||
t.expects(args::help::<cli_host>().view() == """
|
||||
usage: host [options]
|
||||
|
||||
options:
|
||||
-h, --host NAME The host.
|
||||
--help Shows this help.
|
||||
""");
|
||||
}
|
||||
|
||||
@test def parse_or_exit_stops_with_the_status_of_what_it_says(t: &mut tester): void {
|
||||
t.expects(!stops(def() { _ = args::parse_or_exit::<cli_flags>(["--help"]); }));
|
||||
t.expects(!stops(def() { _ = args::parse_or_exit::<cli_git>(["--version"]); }));
|
||||
t.expects(stops(def() { _ = args::parse_or_exit::<cli_flags>(["--count", "x"]); }));
|
||||
t.expects(!stops(def() { _ = args::parse_or_exit::<cli_flags>(["-v"]); }));
|
||||
}
|
||||
|
||||
@test def mistaken_marks_stop_the_program_however_it_is_run(t: &mut tester): void {
|
||||
t.expects(stops(def() { _ = args::parse::<cli_two_longs>([]); }));
|
||||
t.expects(stops(def() { _ = args::parse::<cli_two_shorts>(["--help"]); }));
|
||||
t.expects(stops(def() { _ = args::parse::<cli_bad_short>([]); }));
|
||||
t.expects(stops(def() { _ = args::parse::<cli_bad_count>([]); }));
|
||||
t.expects(stops(def() { _ = args::parse::<cli_bad_rest>([]); }));
|
||||
t.expects(stops(def() { _ = args::parse::<cli_two_rests>([]); }));
|
||||
t.expects(stops(def() { _ = args::parse::<cli_late_command>([]); }));
|
||||
t.expects(stops(def() { _ = args::parse::<cli_many_before>([]); }));
|
||||
t.expects(stops(def() { _ = args::parse::<cli_two_commands>([]); }));
|
||||
t.expects(stops(def() { _ = args::parse::<cli_group_short>([]); }));
|
||||
t.expects(stops(def() { _ = args::parse::<cli_group_long>([]); }));
|
||||
t.expects(!stops(def() { _ = args::parse::<cli_flags>([]); }));
|
||||
}
|
||||
|
||||
@test def groups_are_read_as_if_declared_in_place(t: &mut tester): void {
|
||||
val read := args::parse::<cli_grouped>([
|
||||
"-o", "out", "-O1", "--verbose", "--std", "lib", "-Ia", "--include", "b", "-j", "4", "x", "y"
|
||||
]) else (_) { t.expects(false); return; };
|
||||
t.expects(read.output == "out" && read.shared.level == 1 && read.shared.verbose && read.jobs == 4);
|
||||
t.expects(read.shared.library.directory == "lib" && read.shared.library.include.length == 2);
|
||||
t.expects(read.shared.library.include[1] == "b" && read.files.length == 2 && read.files[1] == "y");
|
||||
|
||||
# A group's fields keep their defaults, and its short names are written
|
||||
# together with the command's own.
|
||||
val plain := args::parse::<cli_grouped>(["--std=lib"]) else (_) { t.expects(false); return; };
|
||||
t.expects(plain.shared.level == 2 && !plain.shared.verbose && plain.jobs == 1 && plain.output.length == 0);
|
||||
val together := args::parse::<cli_grouped>(["--std", "lib", "-vj2", "-vO3"]) else (_) { t.expects(false); return; };
|
||||
t.expects(together.shared.verbose && together.jobs == 2 && together.shared.level == 3);
|
||||
|
||||
# Errors name a group's options as they name the command's own.
|
||||
val required := cli_error_of::<cli_grouped>(["x"]);
|
||||
t.expects(required.kind == args::error_kind::missing_option && required.name == "--std");
|
||||
val invalid := cli_error_of::<cli_grouped>(["--std", "lib", "-O", "300"]);
|
||||
t.expects(invalid.kind == args::error_kind::invalid_value && invalid.name == "-O" && invalid.text == "300");
|
||||
val switched := cli_error_of::<cli_grouped>(["--std", "lib", "--verbose=yes"]);
|
||||
t.expects(switched.kind == args::error_kind::switch_given_value && switched.name == "--verbose");
|
||||
t.expects(cli_error_of::<cli_grouped>(["--std", "lib", "--shared"]).kind == args::error_kind::unknown_option);
|
||||
}
|
||||
|
||||
@test def groups_are_shown_in_place_in_the_help_text(t: &mut tester): void {
|
||||
t.expects(args::help::<cli_grouped>().view() == """
|
||||
usage: grouped [options] FILE...
|
||||
|
||||
Builds with the options it shares.
|
||||
|
||||
arguments:
|
||||
FILE... The files.
|
||||
|
||||
options:
|
||||
-o, --output OUTPUT Where it goes.
|
||||
-O, --level LEVEL How much to optimize. Default: 2.
|
||||
-v, --verbose Says more.
|
||||
--std DIR Where the library is. Required.
|
||||
-I, --include DIR
|
||||
-j, --jobs N How many at once. Default: 1.
|
||||
-h, --help Shows this help.
|
||||
""");
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
# 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::containers;
|
||||
import std::io;
|
||||
import system;
|
||||
import std::testing;
|
||||
|
||||
|
||||
# How many counters have been closed, which only those holding a count are.
|
||||
var closed: u64 = 0;
|
||||
|
||||
struct counter : owning, hashable, ordered {
|
||||
var n: u64;
|
||||
}
|
||||
|
||||
def counter::close(&mut this): void {
|
||||
if this.n != 0 {
|
||||
closed++;
|
||||
this.n = 0;
|
||||
}
|
||||
}
|
||||
|
||||
def counter::hash(&this): u64 { return this.n; }
|
||||
|
||||
def counter::equals(&this, other: &counter): bool { return this.n == other.n; }
|
||||
|
||||
def counter::compare(&this, other: &counter): i64 { return this.n as i64 - other.n as i64; }
|
||||
|
||||
# A value that is not closeable itself, but holds one that is.
|
||||
struct holder {
|
||||
var c: counter;
|
||||
}
|
||||
|
||||
def held(n: u64): holder {
|
||||
return holder { c = counter { n = n } };
|
||||
}
|
||||
|
||||
@test def containers_stop_at_an_index_past_their_end(t: &mut tester): void {
|
||||
t.expects(!stops(def() { var v := vector::<i64>::new(); v.append(1); val x := v[0]; v.set(0, 2); v.insert_at(1, 3); v.remove_at(1); }));
|
||||
t.expects(!stops(def() { var i := interner::<i64>::new(); i.intern(1); val x := i[0]; }));
|
||||
|
||||
# Only a program that checks stops at these, which one that does not reads
|
||||
# past what the container holds.
|
||||
if const checking() {
|
||||
t.expects(stops(def() { var v := vector::<i64>::new(); v.append(1); val x := v[1]; }));
|
||||
t.expects(stops(def() { var v := vector::<i64>::new(); v.append(1); v[3] = 2; }));
|
||||
t.expects(stops(def() { var v := vector::<i64>::new(); v.set(0, 1); }));
|
||||
t.expects(stops(def() { var v := vector::<i64>::new(); v.insert_at(1, 1); }));
|
||||
t.expects(stops(def() { var v := vector::<i64>::new(); v.append(1); v.remove_at(1); }));
|
||||
|
||||
t.expects(stops(def() { val s := string::from("ab", nothing {}); val b := s[2]; }));
|
||||
t.expects(stops(def() { val xs: i64[2] = [1, 2]; val view: span<i64> = xs[0:2]; val x := view.at(2); }));
|
||||
t.expects(stops(def() { var xs: i64[2] = [1, 2]; var view: slice<i64> = xs[0:2]; view.at(2) = 3; }));
|
||||
|
||||
t.expects(stops(def() { var d := deque::<i64>::new(); d.push_back(1); val x := d[1]; }));
|
||||
t.expects(stops(def() { var l := list::<i64>::new(); l.push_back(1); val x := l[1]; }));
|
||||
t.expects(stops(def() { var l := list::<i64>::new(); l.insert_at(1, 1); }));
|
||||
t.expects(stops(def() { var l := list::<i64>::new(); l.push_back(1); l.remove_at(1); }));
|
||||
t.expects(stops(def() { var c := chain::<i64>::new(); c.push_back(1); val x := c[1]; }));
|
||||
t.expects(stops(def() { var c := chain::<i64>::new(); c.insert_at(1, 1); }));
|
||||
t.expects(stops(def() { var c := chain::<i64>::new(); c.push_back(1); c.remove_at(1); }));
|
||||
t.expects(stops(def() { var r := runs::<i64>::new(); val x := r.length(1); }));
|
||||
t.expects(stops(def() { var r := runs::<i64>::new(); val id := r.add([1, 2]); val x := r.at(id, 2); }));
|
||||
t.expects(stops(def() { var g := groups::<i64>::new(2); g.count(2); }));
|
||||
t.expects(stops(def() { var w := byte_writer::new(); w.u16(1); w.set_u32(0, 5); }));
|
||||
t.expects(stops(def() { var i := interner::<i64>::new(); i.intern(1); val x := i[1]; }));
|
||||
}
|
||||
}
|
||||
|
||||
@test def containers_stop_where_they_hold_nothing_asked_for(t: &mut tester): void {
|
||||
t.expects(!stops(def() { var s := stack::<i64>::new(); s.push(1); val x := s.peek(); s.pop(); }));
|
||||
t.expects(stops(def() { var g := groups::<i64>::new(1); g.seal(); g.count(0); }));
|
||||
t.expects(!stops(def() { var g := groups::<i64>::new(1); val x := g.of(0); }));
|
||||
t.expects(!stops(def() { var d := dict::<i64, i64>::new(); d.set(1, 2); val x := d[1]; }));
|
||||
|
||||
# Only a program that checks stops at these, which one that does not reads
|
||||
# past what the container holds.
|
||||
if const checking() {
|
||||
t.expects(stops(def() { var s := stack::<i64>::new(); s.pop(); }));
|
||||
t.expects(stops(def() { val s := stack::<i64>::new(); val x := s.peek(); }));
|
||||
t.expects(stops(def() { var q := queue::<i64>::new(); q.pop(); }));
|
||||
t.expects(stops(def() { val q := queue::<i64>::new(); val x := q.peek(); }));
|
||||
t.expects(stops(def() { var d := deque::<i64>::new(); d.pop_front(); }));
|
||||
t.expects(stops(def() { var d := deque::<i64>::new(); d.pop_back(); }));
|
||||
t.expects(stops(def() { val d := deque::<i64>::new(); val x := d.front(); }));
|
||||
t.expects(stops(def() { val d := deque::<i64>::new(); val x := d.back(); }));
|
||||
t.expects(stops(def() { var l := list::<i64>::new(); l.pop_front(); }));
|
||||
t.expects(stops(def() { val l := list::<i64>::new(); val x := l.front(); }));
|
||||
t.expects(stops(def() { val l := list::<i64>::new(); val x := l.back(); }));
|
||||
t.expects(stops(def() { var c := chain::<i64>::new(); c.pop_front(); }));
|
||||
t.expects(stops(def() { var c := chain::<i64>::new(); c.pop_back(); }));
|
||||
t.expects(stops(def() { val c := chain::<i64>::new(); val x := c.front(); }));
|
||||
t.expects(stops(def() { val c := chain::<i64>::new(); val x := c.back(); }));
|
||||
t.expects(stops(def() { val v := vector::<i64>::new(); val x := v.first(); }));
|
||||
t.expects(stops(def() { val v := vector::<i64>::new(); val x := v.last(); }));
|
||||
t.expects(stops(def() { var v := vector::<i64>::new(); v.truncate(); }));
|
||||
t.expects(stops(def() { val h := heap::<i64>::new(); val x := h.peek(); }));
|
||||
t.expects(stops(def() { var h := heap::<i64>::new(); h.pop(); }));
|
||||
t.expects(stops(def() { var g := groups::<i64>::new(1); g.count(0); g.seal(); g.put(0, 1); g.put(0, 2); }));
|
||||
t.expects(stops(def() { var g := groups::<i64>::new(1); g.count(0); g.put(0, 1); }));
|
||||
t.expects(stops(def() { var w := byte_writer::new(); w.byte(1); w.rewind(2); }));
|
||||
|
||||
t.expects(stops(def() { var d := dict::<i64, i64>::new(); d.set(1, 2); val x := d[5]; }));
|
||||
}
|
||||
}
|
||||
|
||||
# The element `get` gives, or -1 where it gives none.
|
||||
def got<T>(found: maybe<&T>): i64 where T: integer {
|
||||
if found is some(element) {
|
||||
return element as i64;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
@test def containers_give_an_element_or_nothing_by_get(t: &mut tester): void {
|
||||
var v := vector::<i64>::new();
|
||||
v.append(4);
|
||||
v.append(5);
|
||||
val read := &v;
|
||||
t.expects(got(read.get(1)) == 5 && got(read.get(2)) == -1);
|
||||
if v.get(0) is some(&mut first) {
|
||||
first = 6;
|
||||
}
|
||||
t.expects(v[0] == 6 && v.get(2) is none);
|
||||
|
||||
val s := string::from("ab", nothing {});
|
||||
t.expects(got(s.get(1)) == 'b' as i64 && got(s.get(2)) == -1);
|
||||
val xs: i64[3] = [1, 2, 3];
|
||||
val part: span<i64> = xs[1:2];
|
||||
t.expects(got(part.get(1)) == 3 && got(part.get(2)) == -1);
|
||||
var ys: i64[3] = [1, 2, 3];
|
||||
var place: slice<i64> = ys[1:2];
|
||||
if place.get(1) is some(&mut last) {
|
||||
last = 9;
|
||||
}
|
||||
t.expects(ys[2] == 9 && place.get(2) is none);
|
||||
|
||||
var d := deque::<i64>::new();
|
||||
d.push_back(7);
|
||||
var l := list::<i64>::new();
|
||||
l.push_back(8);
|
||||
var c := chain::<i64>::new();
|
||||
c.push_back(9);
|
||||
val dr := &d;
|
||||
val lr := &l;
|
||||
val cr := &c;
|
||||
t.expects(got(dr.get(0)) == 7 && got(dr.get(1)) == -1);
|
||||
t.expects(got(lr.get(0)) == 8 && got(lr.get(1)) == -1);
|
||||
t.expects(got(cr.get(0)) == 9 && got(cr.get(1)) == -1);
|
||||
}
|
||||
|
||||
@test def containers_close_what_their_elements_hold(t: &mut tester): void {
|
||||
# A value holding what closes is closed as a local holding it is.
|
||||
var lone := held(1);
|
||||
closed = 0;
|
||||
close(&mut lone);
|
||||
t.expects(closed == 1 && lone.c.n == 0);
|
||||
|
||||
closed = 0;
|
||||
var v := vector::<holder>::new();
|
||||
v.append(held(1)); v.append(held(2)); v.append(held(3)); v.append(held(4));
|
||||
v.remove_at(0);
|
||||
t.expects(closed == 1);
|
||||
v.resize(2);
|
||||
t.expects(closed == 2);
|
||||
v.clear();
|
||||
t.expects(closed == 4);
|
||||
v.append(held(5));
|
||||
v.close();
|
||||
t.expects(closed == 5);
|
||||
|
||||
closed = 0;
|
||||
var s := stack::<holder>::new();
|
||||
s.push(held(1)); s.push(held(2)); s.push(held(3));
|
||||
s.pop();
|
||||
s.resize(1);
|
||||
s.clear();
|
||||
t.expects(closed == 3);
|
||||
|
||||
closed = 0;
|
||||
var q := queue::<holder>::new();
|
||||
q.push(held(1)); q.push(held(2));
|
||||
q.pop();
|
||||
q.clear();
|
||||
var d := deque::<holder>::new();
|
||||
d.push_back(held(1)); d.push_front(held(2)); d.push_back(held(3));
|
||||
d.pop_front();
|
||||
d.pop_back();
|
||||
d.clear();
|
||||
t.expects(closed == 5);
|
||||
|
||||
closed = 0;
|
||||
var l := list::<holder>::new();
|
||||
l.push_back(held(1)); l.push_back(held(2)); l.push_back(held(3));
|
||||
l.pop_front();
|
||||
l.remove_at(1);
|
||||
l.clear();
|
||||
var c := chain::<holder>::new();
|
||||
c.push_back(held(1)); c.push_back(held(2)); c.push_back(held(3));
|
||||
c.pop_back();
|
||||
c.remove_at(0);
|
||||
c.clear();
|
||||
t.expects(closed == 6);
|
||||
|
||||
closed = 0;
|
||||
var m := dict::<i64, holder>::new();
|
||||
m.set(1, held(1)); m.set(2, held(2)); m.set(3, held(3));
|
||||
m.set(1, held(4));
|
||||
t.expects(closed == 1);
|
||||
t.expects(m.remove(&2));
|
||||
m.clear();
|
||||
t.expects(closed == 4);
|
||||
}
|
||||
|
||||
# An interner closes a value it is given that equals one it holds, keeping the
|
||||
# first, and gives that one's ID; what it holds it closes where it is cleared, and
|
||||
# it numbers from 0 again after.
|
||||
@test def sets_close_the_values_they_let_go(t: &mut tester): void {
|
||||
closed = 0;
|
||||
var s := hashset::<counter>::new();
|
||||
for n in 1..7 { t.expects(s.insert(counter { n = n as u64 })); }
|
||||
t.expects(!s.insert(counter { n = 1 }) && s.length == 6 && closed == 1);
|
||||
val two := counter { n = 2 };
|
||||
t.expects(s.remove(&two) && !s.remove(&two) && closed == 2);
|
||||
|
||||
var odd := hashset::<counter>::new();
|
||||
for n in 0..4 { odd.insert(counter { n = (2 * n + 1) as u64 }); }
|
||||
s.intersect_with(&odd);
|
||||
t.expects(s.length == 3 && closed == 4);
|
||||
s.subtract(&odd);
|
||||
t.expects(s.is_empty && closed == 7);
|
||||
for n in 10..13 { s.insert(counter { n = n as u64 }); }
|
||||
s.clear();
|
||||
t.expects(closed == 10 && odd.length == 4);
|
||||
|
||||
var words := hashset::<string>::new();
|
||||
words.insert(string::from("one", nothing {}));
|
||||
words.insert(string::from("two", nothing {}));
|
||||
var more := hashset::<string>::new();
|
||||
more.insert(string::from("two", nothing {}));
|
||||
more.insert(string::from("three", nothing {}));
|
||||
var copied := hashset::<string>::copy_of(&words);
|
||||
copied.union_with(&more);
|
||||
more.close();
|
||||
words.close();
|
||||
val three := string::from("three", nothing {});
|
||||
t.expects(copied.length == 3 && copied.contains(&three) && copied.get(&three).some.view() == "three");
|
||||
}
|
||||
|
||||
@test def interners_keep_the_first_of_equal_values(t: &mut tester): void {
|
||||
closed = 0;
|
||||
var i := interner::<counter>::new();
|
||||
t.expects(i.intern(counter { n = 5 }) == 0 && i.intern(counter { n = 6 }) == 1);
|
||||
t.expects(i.intern(counter { n = 5 }) == 0 && closed == 1 && i.length == 2);
|
||||
val six := counter { n = 6 };
|
||||
t.expects(i.find(&six).some == 1 && i[1].n == 6 && i.contains(&six));
|
||||
i.clear();
|
||||
t.expects(closed == 3 && i.is_empty && i.find(&six) is none);
|
||||
t.expects(i.intern(counter { n = 7 }) == 0);
|
||||
|
||||
# Text is found, and interned, by its view, and copied only where it is new.
|
||||
var words := interner::<string>::new();
|
||||
var ids := vector::<u32>::new();
|
||||
for w in "a b a c b".split(' ' as u8) {
|
||||
ids.append(words.intern_view(w));
|
||||
}
|
||||
val b: strview = "b";
|
||||
val d: strview = "d";
|
||||
t.expects(ids.length == 5 && ids[0] == 0 && ids[1] == 1 && ids[2] == 0 && ids[3] == 2 && ids[4] == 1);
|
||||
t.expects(words.length == 3 && words.find_view(b).some == 1 && words.find_view(d) is none && words[2].view() == "c");
|
||||
var copied := interner::<string>::copy_of(&words);
|
||||
words.close();
|
||||
t.expects(copied.length == 3 && copied.find_view(b).some == 1 && copied[0].view() == "a");
|
||||
}
|
||||
|
||||
# A heap gives its least value first, and closes each value it removes.
|
||||
@test def heaps_give_their_least_value_first(t: &mut tester): void {
|
||||
closed = 0;
|
||||
var h := heap::<counter>::new();
|
||||
val given: u64[6] = [5, 2, 8, 1, 9, 3];
|
||||
for i in 0..6 { h.push(counter { n = given[i] }); }
|
||||
var order := vector::<u64>::new();
|
||||
while !h.is_empty {
|
||||
order.append(h.peek().n);
|
||||
h.pop();
|
||||
}
|
||||
t.expects(order.length == 6 && order[0] == 1 && order[1] == 2 && order[2] == 3 && order[5] == 9 && closed == 6);
|
||||
|
||||
var words := heap::<u64>::new(4, nothing {});
|
||||
for i in 0..100 { words.push(((i * 37) % 101) as u64); }
|
||||
var last: u64 = 0;
|
||||
var rising := true;
|
||||
while !words.is_empty {
|
||||
rising = rising && words.peek() >= last;
|
||||
last = words.peek();
|
||||
words.pop();
|
||||
}
|
||||
t.expects(rising);
|
||||
}
|
||||
|
||||
# Runs are named by IDs from 1, the empty one 0, and rewound to drop the newest.
|
||||
@test def runs_hold_lists_named_by_ids(t: &mut tester): void {
|
||||
var r := runs::<u32>::new();
|
||||
val a := r.add([1, 2, 3]);
|
||||
r.push(7);
|
||||
r.push(8);
|
||||
val b := r.end();
|
||||
t.expects(a == 1 && b == 2 && r.end() == 0 && r.add(span::<u32>::empty()) == 0 && r.count == 3);
|
||||
t.expects(r.length(a) == 3 && r.at(b, 0) == 7 && r.view(a)[2] == 3 && r.length(0) == 0 && r.size == 5);
|
||||
r.rewind(2);
|
||||
t.expects(r.count == 2 && r.add([4]) == 2 && r.at(2, 0) == 4);
|
||||
val copied := runs::<u32>::copy_of(&r);
|
||||
r.clear();
|
||||
t.expects(r.count == 1 && copied.count == 3 && copied.view(1)[1] == 2);
|
||||
|
||||
closed = 0;
|
||||
var held := runs::<counter>::new();
|
||||
held.push(counter { n = 1 });
|
||||
held.push(counter { n = 2 });
|
||||
val id := held.end();
|
||||
held.push(counter { n = 3 });
|
||||
held.rewind(1);
|
||||
t.expects(id == 1 && closed == 3 && held.count == 1);
|
||||
}
|
||||
|
||||
# Groups put each element after those of its key put before it, once counted.
|
||||
@test def groups_gather_elements_by_key(t: &mut tester): void {
|
||||
var g := groups::<u32>::new(4);
|
||||
val keys: u32[6] = [3, 0, 3, 1, 3, 0];
|
||||
for i in 0..6 { g.count(keys[i]); }
|
||||
g.seal();
|
||||
for i in 0..6 { g.put(keys[i], i as u32); }
|
||||
t.expects(g.keys == 4 && g.size == 6 && g.length(3) == 3 && g.length(2) == 0);
|
||||
t.expects(g.of(3)[0] == 0 && g.of(3)[1] == 2 && g.of(3)[2] == 4 && g.of(0)[1] == 5 && g.of(1)[0] == 3);
|
||||
g.reset(2);
|
||||
g.count(1, 2);
|
||||
t.expects(!g.is_sealed && g.length(1) == 2 && g.keys == 2 && g.of(1).length == 0);
|
||||
g.seal();
|
||||
g.put(1, 9);
|
||||
t.expects(g.of(1)[0] == 9 && g.of(1).length == 2);
|
||||
}
|
||||
|
||||
# An allocator that never has memory to give.
|
||||
struct starved : allocator {}
|
||||
|
||||
def starved::acquire(&mut this, size: u64, align: u64): *mut u8 { return null; }
|
||||
|
||||
def starved::dispose(&mut this, addr: *mut u8, size: u64): void {}
|
||||
|
||||
def starved::resize(&mut this, addr: *mut u8, old: u64, size: u64, align: u64): *mut u8 { return null; }
|
||||
|
||||
# Each container is given an allocator with nothing to give, named as the
|
||||
# `maybe<&mut allocator>` the overloads of `new` take.
|
||||
@test def an_allocator_that_gives_no_memory_stops_the_program(t: &mut tester): void {
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var v := vector::<i64>::new(alloc); v.append(1); }));
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var s := string::new(alloc); s.push('x' as u8); }));
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var d := dict::<i64, i64>::new(alloc); d.set(1, 2); }));
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var h := hashset::<i64>::new(alloc); h.insert(1); }));
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var i := interner::<i64>::new(alloc); i.intern(1); }));
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var h := heap::<i64>::new(alloc); h.push(1); }));
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var r := runs::<i64>::new(alloc); }));
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var g := groups::<i64>::new(4, alloc); }));
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var w := byte_writer::new(alloc); w.byte(1); }));
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var l := list::<i64>::new(alloc); l.push_back(1); }));
|
||||
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var q := queue::<i64>::new(alloc); q.push(1); }));
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
# Tests of the owners shared by every copy: `rc`, counted plainly, and `arc`,
|
||||
# counted atomically, with the weak references that do not keep their values.
|
||||
# Each closes what it holds exactly once, where its last owner closes.
|
||||
import std::containers;
|
||||
import std::testing;
|
||||
import std::thread;
|
||||
|
||||
|
||||
# How many values the tests gave owners have been closed, from any thread.
|
||||
var owned_closed: atomic<u64>;
|
||||
|
||||
struct owned : owning {
|
||||
var mark: u64;
|
||||
}
|
||||
|
||||
def owned::close(&mut this): void {
|
||||
if this.mark != 0 {
|
||||
_ = owned_closed.fetch_add(1);
|
||||
this.mark = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@test def counted_owners_and_maybe_owners_are_one_word(t: &mut tester): void {
|
||||
t.expects(size_of::<rc<owned>>() == 8 && size_of::<maybe<rc<owned>>>() == 8);
|
||||
t.expects(size_of::<arc<owned>>() == 8 && size_of::<maybe<arc<owned>>>() == 8);
|
||||
}
|
||||
|
||||
@test def rc_copies_share_one_value_the_last_closes(t: &mut tester): void {
|
||||
val before := owned_closed.load();
|
||||
var first := rc::<owned>::new(owned { mark = 1 });
|
||||
var weak := first.weak();
|
||||
{
|
||||
var second := copy(&first);
|
||||
second.get().mark = 5;
|
||||
t.expects(first.count() == 2 && first.get().mark == 5);
|
||||
}
|
||||
t.expects(first.count() == 1 && owned_closed.load() == before);
|
||||
if weak.lock() is some(&locked) {
|
||||
t.expects(locked.count() == 2 && locked.get().mark == 5);
|
||||
} else {
|
||||
t.expects(false);
|
||||
}
|
||||
|
||||
var weaker := copy(&weak);
|
||||
first.close();
|
||||
t.expects(owned_closed.load() == before + 1);
|
||||
t.expects(!(weak.lock() is some) && !(weaker.lock() is some));
|
||||
|
||||
# Moving an owner moves the count's claim with it.
|
||||
var moved_from := rc::<owned>::new(owned { mark = 7 });
|
||||
var moved_to := move(&mut moved_from);
|
||||
moved_from.close();
|
||||
t.expects(moved_to.count() == 1 && owned_closed.load() == before + 1);
|
||||
moved_to.close();
|
||||
t.expects(owned_closed.load() == before + 2);
|
||||
}
|
||||
|
||||
@test def arc_copies_are_counted_from_many_threads(t: &mut tester): void {
|
||||
val before := owned_closed.load();
|
||||
var shared := arc::<owned>::new(owned { mark = 9 });
|
||||
val weak := shared.weak();
|
||||
val from: &arc<owned> = &shared;
|
||||
var workers := vector::<thread::handle<void>>::new();
|
||||
for _ in 0..4u {
|
||||
var started := thread::spawn(def() {
|
||||
for _ in 0..2000u {
|
||||
val held := copy(from);
|
||||
if held.get().mark != 9 { return; }
|
||||
}
|
||||
}) else (e) { t.expects(false); return; };
|
||||
workers.append(move(&mut started));
|
||||
}
|
||||
for i in 0..workers.length {
|
||||
workers[i].join();
|
||||
}
|
||||
t.expects(shared.count() == 1 && owned_closed.load() == before);
|
||||
|
||||
var last := copy(&shared);
|
||||
shared.close();
|
||||
t.expects(last.count() == 1 && owned_closed.load() == before);
|
||||
if weak.lock() is some(&locked) {
|
||||
t.expects(locked.get().mark == 9);
|
||||
}
|
||||
last.close();
|
||||
t.expects(owned_closed.load() == before + 1 && !(weak.lock() is some));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
# JSON's conformance, by Nicolas Seriot's JSONTestSuite, whose parsing cases are in
|
||||
# `tests/json/parsing` under its MIT license. Each `y_` case must be accepted, and each
|
||||
# `n_` case refused. RFC 8259 leaves the `i_` cases to the parser.
|
||||
import std::io;
|
||||
import std::json;
|
||||
import std::testing;
|
||||
|
||||
|
||||
# The `i_` cases that are accepted: numbers too large or too small for any type,
|
||||
# which reading them as one refuses, and nesting within the limit. Every other is
|
||||
# refused: text that is not UTF-8, half of a surrogate pair, UTF-16, and a byte
|
||||
# order mark before the value.
|
||||
const accepted: span<strview> = [
|
||||
"i_number_double_huge_neg_exp.json",
|
||||
"i_number_huge_exp.json",
|
||||
"i_number_neg_int_huge_exp.json",
|
||||
"i_number_pos_double_huge_exp.json",
|
||||
"i_number_real_neg_overflow.json",
|
||||
"i_number_real_pos_overflow.json",
|
||||
"i_number_real_underflow.json",
|
||||
"i_number_too_big_neg_int.json",
|
||||
"i_number_too_big_pos_int.json",
|
||||
"i_number_very_big_negative_int.json",
|
||||
"i_structure_500_nested_arrays.json",
|
||||
];
|
||||
|
||||
def is_accepted(name: strview): bool {
|
||||
for each in accepted {
|
||||
if each == name {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@test def json_conforms_to_its_test_suite(t: &mut tester): void {
|
||||
val folder := path::parse("tests/json/parsing") else (_) {
|
||||
t.expects(false);
|
||||
return;
|
||||
};
|
||||
var listing := io::directory::open(&folder) else (e) {
|
||||
print("The suite is read from `tests/json/parsing`, so the tests run from the root of the repository.\n");
|
||||
t.expects(false);
|
||||
return;
|
||||
};
|
||||
|
||||
var checked: u64 = 0;
|
||||
while listing.next() is some(each) {
|
||||
val name: strview = each.name;
|
||||
if !name.ends_with(".json") {
|
||||
continue;
|
||||
}
|
||||
|
||||
val at := folder.join(name);
|
||||
val text := io::read_file(&at) else (_) {
|
||||
t.expects(false);
|
||||
continue;
|
||||
};
|
||||
val parsed := json::parse(text.view()) is value;
|
||||
val wanted := name[0] == 'y' || (name[0] == 'i' && is_accepted(name));
|
||||
if parsed != wanted {
|
||||
print($"{name} is {parsed ? "accepted" : "refused"}\n");
|
||||
}
|
||||
t.expects(parsed == wanted);
|
||||
checked++;
|
||||
}
|
||||
t.expects(checked == 318);
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
# Tests of `std::json`: its text, the reader, the document, and the writer.
|
||||
import std::io;
|
||||
import std::json;
|
||||
import std::testing;
|
||||
import system;
|
||||
|
||||
|
||||
# Whether parsing the text fails with the kind of error, at the line and column.
|
||||
def fails_at(text: strview, kind: json::error_kind, line: u32, column: u32): bool {
|
||||
match json::parse(text) {
|
||||
value(&_) => return false;
|
||||
error(e) => return e.kind == kind && e.line == line && e.column == column;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
# The text a document's root is written again as, on one line.
|
||||
def rewritten(text: strview): string {
|
||||
val doc := json::parse(text) else (e) { return e.describe(); };
|
||||
var out := json::writer::new();
|
||||
json::encode(&doc.root, &mut out);
|
||||
val written := out.finish() else (e) { return e.describe(); };
|
||||
return string::from(written, nothing {});
|
||||
}
|
||||
|
||||
# The bits of a float, which tell `-0` from `0` and compare exactly.
|
||||
def bits(x: f64): u64 {
|
||||
var copy: f64 = x;
|
||||
return *(((©) as *f64) as *u64);
|
||||
}
|
||||
|
||||
@test def json_escapes_text_and_checks_utf8(t: &mut tester): void {
|
||||
var out := string::new(nothing {});
|
||||
t.expects(json::escape("plain é \"quoted\" back\\slash\n\t\x01\x1F", &mut out));
|
||||
t.expects(out.view() == "plain é \\\"quoted\\\" back\\\\slash\\n\\t\\u0001\\u001f");
|
||||
|
||||
var back := string::new(nothing {});
|
||||
json::unescape("a\\u00e9\\ud83d\\ude00\\n\\/\\\\\\\"\\b\\f\\r\\t", &mut back);
|
||||
t.expects(back.view() == "aé😀\n/\\\"\x08\x0C\r\t");
|
||||
|
||||
# Overlong forms, surrogates, and characters past U+10FFFF are not UTF-8.
|
||||
t.expects(json::is_utf8("é😀\xEF\xBF\xBF\xF4\x8F\xBF\xBF"));
|
||||
t.expects(!json::is_utf8("\xC0\x80") && !json::is_utf8("\xE0\x80\x80") && !json::is_utf8("\xED\xA0\x80"));
|
||||
t.expects(!json::is_utf8("\xF4\x90\x80\x80") && !json::is_utf8("\xE2\x82") && !json::is_utf8("\x80"));
|
||||
|
||||
var cut := string::new(nothing {});
|
||||
t.expects(!json::escape("ok\xFFno", &mut cut));
|
||||
t.expects(cut.view() == "ok");
|
||||
}
|
||||
|
||||
@test def json_reader_gives_tokens(t: &mut tester): void {
|
||||
var tokens := json::reader::new(" {\"a\\n\": [1, -2.5e3, true, false, null, \"x\"]} ");
|
||||
var kinds := string::new(nothing {});
|
||||
while tokens.next() is some(read) {
|
||||
kinds.append($"{read.kind}:{read.view} ");
|
||||
}
|
||||
t.expects(tokens.error is none);
|
||||
t.expects(kinds.view() == "begin_object:{ key:a\\n begin_array:[ number:1 number:-2.5e3 boolean:true boolean:false empty:null text:x end_array:] end_object:} ");
|
||||
|
||||
# A key's escapes are left for `unescape`, and the token says it holds some.
|
||||
var keyed := json::reader::new("{\"a\\n\": 1}");
|
||||
_ = keyed.next();
|
||||
val key := keyed.next().some;
|
||||
t.expects(key.kind == json::token_kind::key && key.escaped && key.offset == 1);
|
||||
|
||||
# Skipping a value reads past everything it holds.
|
||||
var skim := json::reader::new("{\"params\": {\"deep\": [1, [2, {}]]}, \"method\": \"m\"}");
|
||||
_ = skim.next();
|
||||
_ = skim.next();
|
||||
t.expects(skim.skip());
|
||||
t.expects(skim.next().some.view == "method" && skim.next().some.view == "m");
|
||||
}
|
||||
|
||||
@test def json_reader_stops_at_the_first_error(t: &mut tester): void {
|
||||
var tokens := json::reader::new("[1, 2,]");
|
||||
var count := 0;
|
||||
while tokens.next() is some(_) {
|
||||
count++;
|
||||
}
|
||||
t.expects(count == 3);
|
||||
t.expects(tokens.error.some.kind == json::error_kind::unexpected_byte && tokens.error.some.column == 7);
|
||||
t.expects(tokens.next() is none);
|
||||
}
|
||||
|
||||
@test def json_nesting_is_limited(t: &mut tester): void {
|
||||
t.expects(json::parse("[[[1]]]", 3) is value);
|
||||
match json::parse("[[[[1]]]]", 3) {
|
||||
value(&_) => t.expects(false);
|
||||
error(e) => t.expects(e.kind == json::error_kind::too_deep && e.column == 4);
|
||||
}
|
||||
|
||||
# Past 512 levels, a reader given a higher limit keeps what is open elsewhere.
|
||||
var deep := string::new(nothing {});
|
||||
for _ in 0..600 { deep.append("[{\"k\":"); }
|
||||
deep.append("1");
|
||||
for _ in 0..600 { deep.append("}]"); }
|
||||
t.expects(json::parse(deep.view()) is error);
|
||||
t.expects(json::parse(deep.view(), 1200) is value);
|
||||
}
|
||||
|
||||
@test def json_parse_errors_say_where(t: &mut tester): void {
|
||||
t.expects(fails_at("", json::error_kind::unexpected_end, 1, 1));
|
||||
t.expects(fails_at("{\"a\": 1,\n \"b\" 2}", json::error_kind::unexpected_byte, 2, 6));
|
||||
t.expects(fails_at("[1, 2", json::error_kind::unexpected_end, 1, 6));
|
||||
t.expects(fails_at("[01]", json::error_kind::invalid_number, 1, 2));
|
||||
t.expects(fails_at("[1.]", json::error_kind::invalid_number, 1, 2));
|
||||
t.expects(fails_at("[.5]", json::error_kind::unexpected_byte, 1, 2));
|
||||
t.expects(fails_at("[-]", json::error_kind::invalid_number, 1, 2));
|
||||
t.expects(fails_at("[1e]", json::error_kind::invalid_number, 1, 2));
|
||||
t.expects(fails_at("[\"a\\x\"]", json::error_kind::invalid_escape, 1, 4));
|
||||
t.expects(fails_at("[\"\\ud800\"]", json::error_kind::invalid_escape, 1, 3));
|
||||
t.expects(fails_at("[\"\\udc00\"]", json::error_kind::invalid_escape, 1, 3));
|
||||
t.expects(fails_at("[\"tab\there\"]", json::error_kind::unexpected_byte, 1, 6));
|
||||
t.expects(fails_at("[\"\xC0\x80\"]", json::error_kind::invalid_utf8, 1, 3));
|
||||
t.expects(fails_at("{\"a\": tru}", json::error_kind::unexpected_byte, 1, 7));
|
||||
t.expects(fails_at("[nul", json::error_kind::unexpected_end, 1, 2));
|
||||
t.expects(fails_at("{} {}", json::error_kind::trailing_text, 1, 4));
|
||||
t.expects(fails_at("[1,]", json::error_kind::unexpected_byte, 1, 4));
|
||||
t.expects(fails_at("{\"a\":1,}", json::error_kind::unexpected_byte, 1, 8));
|
||||
t.expects(fails_at("NaN", json::error_kind::unexpected_byte, 1, 1));
|
||||
|
||||
val failed := json::parse("[1,\n x]") else (e) {
|
||||
t.expects(e.describe().view() == "2:3: A byte stands where JSON allows none of its kind.");
|
||||
return;
|
||||
};
|
||||
t.expects(false);
|
||||
}
|
||||
|
||||
@test def json_documents_keep_every_member(t: &mut tester): void {
|
||||
val doc := json::parse("{\"id\": 1, \"name\": \"a\", \"id\": 2, \"n\\u0061me\": \"b\", \"id\": 3}") else (e) {
|
||||
t.expects(false);
|
||||
return;
|
||||
};
|
||||
val root := doc.root;
|
||||
t.expects(root.kind == json::kind::object && root.length == 5);
|
||||
t.expects(root.get("id").some.as_i64().value == 1);
|
||||
t.expects(root.get("missing") is none);
|
||||
|
||||
var ids: i64 = 0;
|
||||
for each in root.get_all("id") {
|
||||
ids = ids * 10 + each.as_i64().value;
|
||||
}
|
||||
t.expects(ids == 123);
|
||||
|
||||
# Escaped names are found by their decoded text, and every member is given in order.
|
||||
var names := string::new(nothing {});
|
||||
for each in root.get_all("name") {
|
||||
names.append(each.as_text().value);
|
||||
}
|
||||
t.expects(names.view() == "ab");
|
||||
var keys := string::new(nothing {});
|
||||
for each in root.members() {
|
||||
keys.append(each.key);
|
||||
keys.push(' ');
|
||||
}
|
||||
t.expects(keys.view() == "id name id name id ");
|
||||
}
|
||||
|
||||
@test def json_values_are_read_by_kind(t: &mut tester): void {
|
||||
val doc := json::parse("[null, true, false, 0, \"s\", [1, 2], {\"k\": [3]}]") else (e) {
|
||||
t.expects(false);
|
||||
return;
|
||||
};
|
||||
val root := doc.root;
|
||||
t.expects(root.length == 7 && root.at(7) is none && root.get("k") is none);
|
||||
t.expects(root.at(0).some.is_null && root.at(1).some.as_bool().value && !root.at(2).some.as_bool().value);
|
||||
t.expects(root.at(4).some.as_text().value == "s" && root.at(4).some.length == 0);
|
||||
t.expects(root.at(6).some.get("k").some.at(0).some.as_u64().value == 3);
|
||||
|
||||
var total: i64 = 0;
|
||||
for item in root.at(5).some.elements() {
|
||||
total += item.as_i64().value;
|
||||
}
|
||||
t.expects(total == 3);
|
||||
|
||||
# A value of the wrong kind says where it is.
|
||||
match root.at(4).some.as_i64() {
|
||||
value(_) => t.expects(false);
|
||||
error(e) => t.expects(e.kind == json::error_kind::wrong_kind && e.line == 1 && e.column == 24);
|
||||
}
|
||||
t.expects(root.at(0).some.as_bool() is error && root.as_text() is error);
|
||||
t.expects(root.at(4).some.elements().next() is none && root.members().next() is none);
|
||||
}
|
||||
|
||||
@test def json_integers_read_exactly(t: &mut tester): void {
|
||||
val doc := json::parse("""
|
||||
[1e3, 1.50e1, 1.5, 1e-1, -0, 0e99999, 9223372036854775807, -9223372036854775808,
|
||||
9223372036854775808, 18446744073709551615, 18446744073709551616, -1, 12.000, 1e19, 1e20]
|
||||
""") else (e) {
|
||||
t.expects(false);
|
||||
return;
|
||||
};
|
||||
val at := doc.root;
|
||||
t.expects(at.at(0).some.as_i64().value == 1000 && at.at(1).some.as_i64().value == 15);
|
||||
t.expects(at.at(2).some.as_i64().error.kind == json::error_kind::wrong_kind);
|
||||
t.expects(at.at(3).some.as_i64().error.kind == json::error_kind::wrong_kind);
|
||||
t.expects(at.at(4).some.as_u64().value == 0 && at.at(5).some.as_i64().value == 0);
|
||||
t.expects(at.at(6).some.as_i64().value == 9223372036854775807);
|
||||
t.expects(at.at(7).some.as_i64().value == -9223372036854775807 - 1);
|
||||
t.expects(at.at(8).some.as_i64().error.kind == json::error_kind::out_of_range);
|
||||
t.expects(at.at(8).some.as_u64().value == 9223372036854775808);
|
||||
t.expects(at.at(9).some.as_u64().value == 18446744073709551615);
|
||||
t.expects(at.at(10).some.as_u64().error.kind == json::error_kind::out_of_range);
|
||||
t.expects(at.at(11).some.as_u64().error.kind == json::error_kind::out_of_range && at.at(11).some.as_i64().value == -1);
|
||||
t.expects(at.at(12).some.as_i64().value == 12);
|
||||
t.expects(at.at(13).some.as_u64().value == 10000000000000000000 && at.at(14).some.as_u64() is error);
|
||||
}
|
||||
|
||||
@test def json_floats_read_back_exactly(t: &mut tester): void {
|
||||
const written: span<f64> = [0.1, 5e-324, 2.2250738585072014e-308, 1.7976931348623157e308, 9007199254740993.0,
|
||||
-0.0, 1e21, 1e-7, 123456789012345680000.0, 0.30000000000000004, 3.0, -2.5e-300];
|
||||
var out := json::writer::new();
|
||||
out.begin_array();
|
||||
for x in written {
|
||||
out.real(x);
|
||||
}
|
||||
out.end_array();
|
||||
val text := out.finish() else (e) {
|
||||
t.expects(false);
|
||||
return;
|
||||
};
|
||||
|
||||
val doc := json::parse(text) else (e) {
|
||||
t.expects(false);
|
||||
return;
|
||||
};
|
||||
for index, x in written {
|
||||
t.expects(bits(doc.root.at(index).some.as_f64().value) == bits(x));
|
||||
}
|
||||
t.expects(doc.root.at(4).some.as_f64().value == 9007199254740992.0);
|
||||
|
||||
val huge := json::parse("[1e400, 1e-400]") else (e) {
|
||||
t.expects(false);
|
||||
return;
|
||||
};
|
||||
t.expects(huge.root.at(0).some.as_f64().error.kind == json::error_kind::out_of_range);
|
||||
t.expects(huge.root.at(1).some.as_f64().value == 0.0);
|
||||
}
|
||||
|
||||
@test def json_writer_writes_compactly_and_indented(t: &mut tester): void {
|
||||
var out := json::writer::new();
|
||||
out.begin_object();
|
||||
out.member("jsonrpc"); out.text("2.0");
|
||||
out.member("id"); out.unsigned(7);
|
||||
out.member("result");
|
||||
out.begin_array();
|
||||
out.signed(-12); out.boolean(false); out.empty(); out.begin_object(); out.end_object(); out.begin_array(); out.end_array();
|
||||
out.end_array();
|
||||
out.end_object();
|
||||
t.expects(out.finish().value == "{\"jsonrpc\":\"2.0\",\"id\":7,\"result\":[-12,false,null,{},[]]}");
|
||||
|
||||
var pretty := json::writer::indented(2);
|
||||
pretty.begin_object();
|
||||
pretty.member("a"); pretty.begin_array(); pretty.signed(1); pretty.signed(2); pretty.end_array();
|
||||
pretty.member("b"); pretty.begin_object(); pretty.end_object();
|
||||
pretty.end_object();
|
||||
t.expects(pretty.finish().value == "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}");
|
||||
|
||||
# A writer is emptied to write another value.
|
||||
out.clear();
|
||||
out.text("again");
|
||||
t.expects(out.finish().value == "\"again\"");
|
||||
|
||||
# The extremes of the integers write as they are.
|
||||
out.clear();
|
||||
out.begin_array(); out.signed(-9223372036854775807 - 1); out.unsigned(18446744073709551615); out.signed(0); out.end_array();
|
||||
t.expects(out.finish().value == "[-9223372036854775808,18446744073709551615,0]");
|
||||
}
|
||||
|
||||
# A stream that takes only so many bytes, then fails, as a full disk does.
|
||||
struct refusing : writable {
|
||||
var left: u64;
|
||||
}
|
||||
|
||||
def refusing::write(&mut this, data: span<u8>): result<void, io_error> {
|
||||
if data.length > this.left {
|
||||
return io_error::no_space;
|
||||
}
|
||||
this.left -= data.length;
|
||||
return;
|
||||
}
|
||||
|
||||
# Writes a document larger than a writer holds before it passes its text on.
|
||||
def write_records(out: &mut json::writer): void {
|
||||
out.begin_array();
|
||||
for i in 0..3000 {
|
||||
out.begin_object();
|
||||
out.member("n"); out.unsigned(i as u64);
|
||||
out.member("name"); out.text("élément");
|
||||
out.end_object();
|
||||
}
|
||||
out.end_array();
|
||||
}
|
||||
|
||||
@test def json_writer_passes_its_text_to_a_stream(t: &mut tester): void {
|
||||
var whole := json::writer::indented(2);
|
||||
write_records(&mut whole);
|
||||
val text := whole.finish() else (_) { t.expects(false); return; };
|
||||
|
||||
var said := string::new(nothing {});
|
||||
var streamed := json::writer::to(&mut said, 2);
|
||||
write_records(&mut streamed);
|
||||
t.expects(said.length >= 16384 && said.length < text.length);
|
||||
val rest := streamed.finish() else (_) { t.expects(false); return; };
|
||||
t.expects(rest.length == 0 && said.view() == text);
|
||||
|
||||
# A typed value, through a writer that holds what it is given in turn.
|
||||
var numbers := vector::<u64>::new();
|
||||
for i in 0..5000 {
|
||||
numbers.append((i * 7) as u64);
|
||||
}
|
||||
val expected := json::to_text(&numbers) else (_) { t.expects(false); return; };
|
||||
var buffered := string::new(nothing {});
|
||||
{
|
||||
var out := io::writer_of(&mut buffered);
|
||||
json::write_to(&numbers, &mut out) else (_) { t.expects(false); return; };
|
||||
_ = out.flush();
|
||||
}
|
||||
t.expects(buffered.view() == expected.view() && buffered.length > 16384);
|
||||
|
||||
# A stream that fails is kept as its failure, and what is written after is let go.
|
||||
var refused := refusing { left = 10 };
|
||||
var failing := json::writer::to(&mut refused);
|
||||
write_records(&mut failing);
|
||||
t.expects(failing.finish().error.kind == json::error_kind::not_written && refused.left == 10);
|
||||
t.expects(json::write_to(&numbers, &mut refused).error.kind == json::error_kind::not_written);
|
||||
}
|
||||
|
||||
@test def json_writer_keeps_failures_in_the_data(t: &mut tester): void {
|
||||
var out := json::writer::new();
|
||||
out.begin_array();
|
||||
out.real(1.0 / 0.0);
|
||||
out.real(0.0 / 0.0);
|
||||
out.text("ok\xFF");
|
||||
out.end_array();
|
||||
match out.finish() {
|
||||
value(_) => t.expects(false);
|
||||
error(e) => t.expects(e.kind == json::error_kind::not_finite && e.line == 0);
|
||||
}
|
||||
t.expects(out._text.view() == "[null,null,null]");
|
||||
|
||||
out.clear();
|
||||
out.begin_object();
|
||||
out.member("\xC0\x80");
|
||||
out.signed(1);
|
||||
out.end_object();
|
||||
t.expects(out.finish().error.kind == json::error_kind::invalid_utf8);
|
||||
t.expects(out._text.view() == "{\"\":1}");
|
||||
}
|
||||
|
||||
@test def json_writer_writes_text_lossily_where_asked(t: &mut tester): void {
|
||||
# Each byte that breaks UTF-8 is the escape of U+FFFD, a sequence cut short a
|
||||
# byte at a time, and the escapes and characters around it are as ever.
|
||||
var whole := string::new(nothing {});
|
||||
t.expects(!json::escape("a\xC0\x80b\xE2\x82 é\x08", &mut whole, true));
|
||||
t.expects(whole.view() == "a\\ufffd\\ufffdb\\ufffd\\ufffd é\\b");
|
||||
var plain := string::new(nothing {});
|
||||
t.expects(json::escape("é\n", &mut plain, true) && plain.view() == "é\\n");
|
||||
|
||||
# A lossy writer keeps no failure, in members' names or strings.
|
||||
var out := json::writer::new();
|
||||
out.set_lossy(true);
|
||||
out.begin_object();
|
||||
out.member("k\xFF");
|
||||
out.text("ok\xFF");
|
||||
out.end_object();
|
||||
t.expects(out.finish().value == "{\"k\\ufffd\":\"ok\\ufffd\"}");
|
||||
|
||||
# Emptied, it stays lossy, and made strict again, it keeps the failure.
|
||||
out.clear();
|
||||
out.text("\xFF");
|
||||
t.expects(out.finish().value == "\"\\ufffd\"");
|
||||
out.clear();
|
||||
out.set_lossy(false);
|
||||
out.text("\xFF");
|
||||
t.expects(out.finish().error.kind == json::error_kind::invalid_utf8);
|
||||
}
|
||||
|
||||
@test def json_writer_writes_text_already_written(t: &mut tester): void {
|
||||
# Text already written is a value, with the commas and names around it, and
|
||||
# keeps its own spacing.
|
||||
var out := json::writer::new();
|
||||
out.begin_object();
|
||||
out.member("jsonrpc"); out.text("2.0");
|
||||
out.member("id"); out.raw("\"a\"");
|
||||
out.member("result");
|
||||
out.begin_array(); out.raw("{\"x\": [1, 2]}"); out.raw("null"); out.end_array();
|
||||
out.end_object();
|
||||
t.expects(out.finish().value == "{\"jsonrpc\":\"2.0\",\"id\":\"a\",\"result\":[{\"x\": [1, 2]},null]}");
|
||||
|
||||
var pretty := json::writer::indented(2);
|
||||
pretty.begin_array(); pretty.raw("{\"a\":1}"); pretty.signed(2); pretty.end_array();
|
||||
t.expects(pretty.finish().value == "[\n {\"a\":1},\n 2\n]");
|
||||
|
||||
out.clear();
|
||||
out.raw("[]");
|
||||
t.expects(out.finish().value == "[]");
|
||||
}
|
||||
|
||||
@test def json_documents_are_written_again_whole(t: &mut tester): void {
|
||||
val text: strview = "{\"a\":[1,-2,1.5,18446744073709551615,\"t\\u00e9\\n\",null,true,{}],\"b\":{\"c\":[]},\"a\":0}";
|
||||
val once := rewritten(text);
|
||||
t.expects(once.view() == "{\"a\":[1,-2,1.5,18446744073709551615,\"té\\n\",null,true,{}],\"b\":{\"c\":[]},\"a\":0}");
|
||||
val twice := rewritten(once.view());
|
||||
t.expects(twice.view() == once.view());
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2016 Nicolas Seriot
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1 @@
|
||||
[123.456e-789]
|
||||
@@ -0,0 +1 @@
|
||||
[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]
|
||||
@@ -0,0 +1 @@
|
||||
[-1e+9999]
|
||||
@@ -0,0 +1 @@
|
||||
[1.5e+9999]
|
||||
@@ -0,0 +1 @@
|
||||
[-123123e100000]
|
||||
@@ -0,0 +1 @@
|
||||
[123123e100000]
|
||||
@@ -0,0 +1 @@
|
||||
[123e-10000000]
|
||||
@@ -0,0 +1 @@
|
||||
[-123123123123123123123123123123]
|
||||
@@ -0,0 +1 @@
|
||||
[100000000000000000000]
|
||||
@@ -0,0 +1 @@
|
||||
[-237462374673276894279832749832423479823246327846]
|
||||
@@ -0,0 +1 @@
|
||||
{"\uDFAA":0}
|
||||
@@ -0,0 +1 @@
|
||||
["\uDADA"]
|
||||
@@ -0,0 +1 @@
|
||||
["\uD888\u1234"]
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
["譌・ム淫"]
|
||||
@@ -0,0 +1 @@
|
||||
["���"]
|
||||
@@ -0,0 +1 @@
|
||||
["\uD800\n"]
|
||||
@@ -0,0 +1 @@
|
||||
["\uDd1ea"]
|
||||
@@ -0,0 +1 @@
|
||||
["\uD800\uD800\n"]
|
||||
@@ -0,0 +1 @@
|
||||
["\ud800"]
|
||||
@@ -0,0 +1 @@
|
||||
["\ud800abc"]
|
||||
@@ -0,0 +1 @@
|
||||
["�"]
|
||||
@@ -0,0 +1 @@
|
||||
["\uDd1e\uD834"]
|
||||
@@ -0,0 +1 @@
|
||||
["И"]
|
||||
@@ -0,0 +1 @@
|
||||
["\uDFAA"]
|
||||
@@ -0,0 +1 @@
|
||||
["�"]
|
||||
@@ -0,0 +1 @@
|
||||
["����"]
|
||||
@@ -0,0 +1 @@
|
||||
["��"]
|
||||
@@ -0,0 +1 @@
|
||||
["�ソソソソ"]
|
||||
@@ -0,0 +1 @@
|
||||
["�"]
|
||||
@@ -0,0 +1 @@
|
||||
["��"]
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -0,0 +1 @@
|
||||
[1 true]
|
||||
@@ -0,0 +1 @@
|
||||
[a�]
|
||||
@@ -0,0 +1 @@
|
||||
["": 1]
|
||||
@@ -0,0 +1 @@
|
||||
[""],
|
||||
@@ -0,0 +1 @@
|
||||
[,1]
|
||||
@@ -0,0 +1 @@
|
||||
[1,,2]
|
||||
@@ -0,0 +1 @@
|
||||
["x",,]
|
||||
@@ -0,0 +1 @@
|
||||
["x"]]
|
||||
@@ -0,0 +1 @@
|
||||
["",]
|
||||
@@ -0,0 +1 @@
|
||||
["x"
|
||||
@@ -0,0 +1 @@
|
||||
[x
|
||||
@@ -0,0 +1 @@
|
||||
[3[4]]
|
||||
@@ -0,0 +1 @@
|
||||
[�]
|
||||
@@ -0,0 +1 @@
|
||||
[1:2]
|
||||
@@ -0,0 +1 @@
|
||||
[,]
|
||||
@@ -0,0 +1 @@
|
||||
[-]
|
||||
@@ -0,0 +1 @@
|
||||
[ , ""]
|
||||
@@ -0,0 +1,3 @@
|
||||
["a",
|
||||
4
|
||||
,1,
|
||||
@@ -0,0 +1 @@
|
||||
[1,]
|
||||
@@ -0,0 +1 @@
|
||||
[1,,]
|
||||
@@ -0,0 +1 @@
|
||||
["a"\f]
|
||||
@@ -0,0 +1 @@
|
||||
[*]
|
||||
@@ -0,0 +1 @@
|
||||
[""
|
||||
@@ -0,0 +1 @@
|
||||
[1,
|
||||
@@ -0,0 +1,3 @@
|
||||
[1,
|
||||
1
|
||||
,1
|
||||
@@ -0,0 +1 @@
|
||||
[{}
|
||||
@@ -0,0 +1 @@
|
||||
[fals]
|
||||
@@ -0,0 +1 @@
|
||||
[nul]
|
||||
@@ -0,0 +1 @@
|
||||
[tru]
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
[++1234]
|
||||
@@ -0,0 +1 @@
|
||||
[+1]
|
||||
@@ -0,0 +1 @@
|
||||
[+Inf]
|
||||
@@ -0,0 +1 @@
|
||||
[-01]
|
||||
@@ -0,0 +1 @@
|
||||
[-1.0.]
|
||||
@@ -0,0 +1 @@
|
||||
[-2.]
|
||||
@@ -0,0 +1 @@
|
||||
[-NaN]
|
||||
@@ -0,0 +1 @@
|
||||
[.-1]
|
||||
@@ -0,0 +1 @@
|
||||
[.2e-3]
|
||||
@@ -0,0 +1 @@
|
||||
[0.1.2]
|
||||
@@ -0,0 +1 @@
|
||||
[0.3e+]
|
||||
@@ -0,0 +1 @@
|
||||
[0.3e]
|
||||
@@ -0,0 +1 @@
|
||||
[0.e1]
|
||||
@@ -0,0 +1 @@
|
||||
[0E+]
|
||||
@@ -0,0 +1 @@
|
||||
[0E]
|
||||
@@ -0,0 +1 @@
|
||||
[0e+]
|
||||
@@ -0,0 +1 @@
|
||||
[0e]
|
||||
@@ -0,0 +1 @@
|
||||
[1.0e+]
|
||||
@@ -0,0 +1 @@
|
||||
[1.0e-]
|
||||
@@ -0,0 +1 @@
|
||||
[1.0e]
|
||||
@@ -0,0 +1 @@
|
||||
[1 000.0]
|
||||
@@ -0,0 +1 @@
|
||||
[1eE2]
|
||||
@@ -0,0 +1 @@
|
||||
[2.e+3]
|
||||
@@ -0,0 +1 @@
|
||||
[2.e-3]
|
||||
Loaded 100 of 1625 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user