Initial Commit
This commit is contained in:
789 files changed
+149185
No files matched your search
@@ -0,0 +1,241 @@
|
||||
# Tests of the memory `core` gives: a block of the heap keeps what it holds
|
||||
# through resizing; blocks of every class, small, carved from chunks, and
|
||||
# mapped on their own, hold what's written to them and come back zeroed where
|
||||
# they're asked to be, and keep what they hold through resizing from each
|
||||
# class to the next; and threads allocating, resizing, and releasing at once,
|
||||
# blocks the others made among them, keep what each block holds. The
|
||||
# allocators of std, an arena and a pool, are tested there.
|
||||
import std::math;
|
||||
import std::testing;
|
||||
import std::thread;
|
||||
|
||||
|
||||
@test def uncleared_memory_keeps_what_it_holds_through_resizing(t: &mut tester): void {
|
||||
val block := raw_allocate(64) as *mut u64;
|
||||
for i in 0..8u { block[i] = i * 11; }
|
||||
val grown := raw_resize(block as *mut u8, 8192) as *mut u64;
|
||||
var same := true;
|
||||
for i in 0..8u { same = same && grown[i] == i * 11; }
|
||||
val shrunk := raw_resize(grown as *mut u8, 16) as *mut u64;
|
||||
t.expects(same && shrunk[1] == 11);
|
||||
raw_release(shrunk as *mut u8);
|
||||
}
|
||||
|
||||
# Writes a block's bytes of a seed: each of its first 64, then every 16th, as
|
||||
# far as it reaches, the same whatever its size, so what it holds is checked
|
||||
# as far as a block it's resized to reaches. Blocks are aligned to 16 bytes, so
|
||||
# two that overlap share a byte written.
|
||||
def stamp(at: *mut u8, size: u64, seed: u64): void {
|
||||
var i: u64 = 0;
|
||||
while i < size {
|
||||
at[i] = ((i * 7 + seed * 13) & 0xFF) as u8;
|
||||
i += i < 64 ? 1 : 16;
|
||||
}
|
||||
}
|
||||
|
||||
# Whether a block holds what `stamp` wrote of a seed, as far as the size.
|
||||
def holds_stamp(at: *u8, size: u64, seed: u64): bool {
|
||||
var i: u64 = 0;
|
||||
while i < size {
|
||||
return false if at[i] != ((i * 7 + seed * 13) & 0xFF) as u8;
|
||||
i += i < 64 ? 1 : 16;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
def all_zero(at: *u8, size: u64): bool {
|
||||
for i in 0..size {
|
||||
return false if at[i] != 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
def next_random(r: u64): u64 {
|
||||
return math::wrapping_add(math::wrapping_mul(r, 6364136223846793005), 1442695040888963407);
|
||||
}
|
||||
|
||||
# A size of a number, as likely of each kind: small; carved from chunks; about
|
||||
# the largest carved, a block's header past it or not; or mapped on its own.
|
||||
def block_size_from(r: u64): u64 {
|
||||
val pick := r >> 33;
|
||||
val kind := pick % 4;
|
||||
if kind == 0 {
|
||||
return 1 + pick % 2047;
|
||||
}
|
||||
if kind == 1 {
|
||||
return 2048 + pick % 260000;
|
||||
}
|
||||
if kind == 2 {
|
||||
return 262100 + pick % 64;
|
||||
}
|
||||
return 262200 + pick % 400000;
|
||||
}
|
||||
|
||||
@test def blocks_of_every_size_hold_what_is_written_and_come_back_zeroed(t: &mut tester): void {
|
||||
# About each edge of the classes, and a block's header of 16 bytes before
|
||||
# the largest carved, 256 KiB.
|
||||
val sizes: u64[26] = [
|
||||
1, 15, 16, 17, 255, 256, 257, 1000, 2032, 2033, 2049, 2560, 2561, 4096, 4097, 50000, 65536, 65537,
|
||||
262127, 262128, 262129, 262144, 300000, 1048576, 1048577, 3000000,
|
||||
];
|
||||
var written := true;
|
||||
var cleared := true;
|
||||
for k in 0..26u {
|
||||
val size := sizes[k];
|
||||
val at := raw_allocate(size);
|
||||
stamp(at, size, k);
|
||||
written = written && holds_stamp(at, size, k);
|
||||
# Every byte written, so a block reused is seen cleared.
|
||||
for i in 0..size { at[i] = 0xFF; }
|
||||
raw_release(at);
|
||||
val again := raw_allocate_zeroed(size);
|
||||
cleared = cleared && all_zero(again, size);
|
||||
raw_release(again);
|
||||
}
|
||||
t.expects(written);
|
||||
t.expects(cleared);
|
||||
}
|
||||
|
||||
@test def blocks_keep_what_they_hold_resized_through_every_class(t: &mut tester): void {
|
||||
var size: u64 = 1;
|
||||
var at := raw_allocate(size);
|
||||
stamp(at, size, 5);
|
||||
var kept := true;
|
||||
while size < 3000000 {
|
||||
val grown := size + size / 4 + 1;
|
||||
at = raw_resize(at, grown);
|
||||
kept = kept && holds_stamp(at, size, 5);
|
||||
stamp(at, grown, 5);
|
||||
size = grown;
|
||||
}
|
||||
while size > 1 {
|
||||
val shrunk := size - size / 4 - 1;
|
||||
at = raw_resize(at, shrunk);
|
||||
kept = kept && holds_stamp(at, shrunk, 5);
|
||||
size = shrunk;
|
||||
}
|
||||
raw_release(at);
|
||||
t.expects(kept);
|
||||
}
|
||||
|
||||
# What a thread churning blocks is given: its seed, where the blocks it's
|
||||
# given and leaves are, from which, and where it says how many it found
|
||||
# changed.
|
||||
struct churn_job {
|
||||
var seed: u64;
|
||||
var blocks: *mut u64; # A pointer and size of each block.
|
||||
var first: u64; # The first of the 32 it's given.
|
||||
var wrong: *mut u64;
|
||||
}
|
||||
|
||||
# Releases the 32 blocks a thread is given, which another thread made, then
|
||||
# allocates, resizes, and releases its own at random, 32 at once, checking
|
||||
# each as it's let go of, and leaves its last for another thread to release,
|
||||
# marked of 1000 past where each is.
|
||||
def churn(job: churn_job): void {
|
||||
var wrong: u64 = 0;
|
||||
for k in 0..32u {
|
||||
val slot := (job.first + k) * 2;
|
||||
val given := job.blocks[slot] as *mut u8;
|
||||
if !holds_stamp(given, job.blocks[slot + 1], k) {
|
||||
wrong++;
|
||||
}
|
||||
raw_release(given);
|
||||
}
|
||||
|
||||
var at: u64[32];
|
||||
var size: u64[32];
|
||||
var seed: u64[32];
|
||||
for k in 0..32u {
|
||||
at[k] = 0;
|
||||
size[k] = 0;
|
||||
seed[k] = 0;
|
||||
}
|
||||
var r := job.seed;
|
||||
for round in 0..2000u {
|
||||
r = next_random(r);
|
||||
val k := (r >> 40) % 32;
|
||||
if at[k] != 0 {
|
||||
if !holds_stamp(at[k] as *u8, size[k], seed[k]) {
|
||||
wrong++;
|
||||
}
|
||||
if (r >> 20) % 4 == 0 {
|
||||
# Resized, it keeps what it held as far as it reaches.
|
||||
val resized := block_size_from(next_random(r));
|
||||
val moved := raw_resize(at[k] as *mut u8, resized);
|
||||
if !holds_stamp(moved, math::min(size[k], resized), seed[k]) {
|
||||
wrong++;
|
||||
}
|
||||
stamp(moved, resized, seed[k]);
|
||||
at[k] = moved as u64;
|
||||
size[k] = resized;
|
||||
continue;
|
||||
}
|
||||
raw_release(at[k] as *mut u8);
|
||||
}
|
||||
size[k] = block_size_from(r);
|
||||
seed[k] = round;
|
||||
val made := (r >> 8) % 2 == 0 ? raw_allocate(size[k]) : raw_allocate_zeroed(size[k]);
|
||||
stamp(made, size[k], seed[k]);
|
||||
at[k] = made as u64;
|
||||
}
|
||||
|
||||
for k in 0..32u {
|
||||
if at[k] == 0 {
|
||||
size[k] = 100;
|
||||
at[k] = raw_allocate(100) as u64;
|
||||
}
|
||||
else {
|
||||
if !holds_stamp(at[k] as *u8, size[k], seed[k]) {
|
||||
wrong++;
|
||||
}
|
||||
}
|
||||
stamp(at[k] as *mut u8, size[k], 1000 + k);
|
||||
val slot := (job.first + k) * 2;
|
||||
job.blocks[slot] = at[k];
|
||||
job.blocks[slot + 1] = size[k];
|
||||
}
|
||||
job.wrong[job.first / 32] = wrong;
|
||||
}
|
||||
|
||||
@test def threads_allocating_at_once_keep_what_each_block_holds(t: &mut tester): void {
|
||||
val threads: u64 = 8;
|
||||
val blocks := raw_allocate_zeroed(threads * 32 * 16) as *mut u64;
|
||||
val wrong := raw_allocate_zeroed(threads * 8) as *mut u64;
|
||||
var r: u64 = 99;
|
||||
for k in 0..threads * 32 {
|
||||
r = next_random(r);
|
||||
val size := block_size_from(r);
|
||||
val made := raw_allocate(size);
|
||||
stamp(made, size, k % 32);
|
||||
blocks[k * 2] = made as u64;
|
||||
blocks[k * 2 + 1] = size;
|
||||
}
|
||||
|
||||
var running := vector::<thread::handle<void>>::new();
|
||||
for i in 0..threads {
|
||||
val job := churn_job{ seed = i * 1000 + 7, blocks = blocks, first = i * 32, wrong = wrong };
|
||||
running.append(thread::spawn_with(churn, job).expect("A thread starts."));
|
||||
}
|
||||
for i in 0..running.length {
|
||||
running[i].join();
|
||||
}
|
||||
|
||||
# The blocks each left, released by this thread.
|
||||
var left: u64 = 0;
|
||||
for k in 0..threads * 32 {
|
||||
val made := blocks[k * 2] as *mut u8;
|
||||
if !holds_stamp(made, blocks[k * 2 + 1], 1000 + k % 32) {
|
||||
left++;
|
||||
}
|
||||
raw_release(made);
|
||||
}
|
||||
var found: u64 = 0;
|
||||
for i in 0..threads {
|
||||
found += wrong[i];
|
||||
}
|
||||
t.expects(found == 0);
|
||||
t.expects(left == 0);
|
||||
raw_release(blocks as *mut u8);
|
||||
raw_release(wrong as *mut u8);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
# Tests of atomics: each operation at each width, of integers, `bool`, enums,
|
||||
# and pointers, the orders that make no sense stopping the program, and two
|
||||
# processes adding to memory they share, which loses nothing only where every
|
||||
# addition is one step.
|
||||
|
||||
import system;
|
||||
import std::testing;
|
||||
|
||||
|
||||
# Whether running the function stops the program. It runs in a copy of the
|
||||
# program that writes nothing, so that this one goes on and the report of the
|
||||
# stop is not mixed into the tests'.
|
||||
def stops_atomically(run: def(): void): bool {
|
||||
when os == windows {
|
||||
val stopped := copied(run);
|
||||
return !(stopped.exited && stopped.code == 0);
|
||||
}
|
||||
val child := fork();
|
||||
if child == 0 {
|
||||
val out: fd = fd::stdout;
|
||||
val err: fd = fd::stderr;
|
||||
out.close();
|
||||
err.close();
|
||||
run();
|
||||
exit(0);
|
||||
}
|
||||
var status: process_status;
|
||||
return wait(child, &mut status) >= 0 && !(status.exited && status.code == 0);
|
||||
}
|
||||
|
||||
# Works every operation on an atomic of `T`, given a value below another, compared
|
||||
# as `T` is, where of an unsigned type the higher has its top bit set, so that
|
||||
# comparing it as signed would order them the other way, and the least and
|
||||
# greatest of `T`.
|
||||
def operations_of<T>(t: &mut tester, low: T, high: T, least: T, most: T): void where T: integer, lockfree {
|
||||
var a := atomic::<T>::new(low);
|
||||
t.expects(a.load() == low);
|
||||
a.store(high);
|
||||
t.expects(a.load() == high);
|
||||
t.expects(a.exchange(low) == high && a.load() == low);
|
||||
|
||||
# Adding and subtracting wrap.
|
||||
a.store(most);
|
||||
t.expects(a.fetch_add(1) == most && a.load() == least);
|
||||
t.expects(a.fetch_sub(1) == least && a.load() == most);
|
||||
a.store(low);
|
||||
t.expects(a.fetch_add(high) == low);
|
||||
val sum := a.load();
|
||||
t.expects(a.fetch_sub(high) == sum && a.load() == low);
|
||||
|
||||
# Bits, against the operators.
|
||||
a.store(high);
|
||||
t.expects(a.fetch_and(low) == high && a.load() == (high & low));
|
||||
a.store(high);
|
||||
t.expects(a.fetch_or(low) == high && a.load() == (high | low));
|
||||
a.store(high);
|
||||
t.expects(a.fetch_xor(low) == high && a.load() == (high ^ low));
|
||||
|
||||
# The least and greatest, compared as `T` is.
|
||||
a.store(low);
|
||||
t.expects(a.fetch_min(high) == low && a.load() == low);
|
||||
t.expects(a.fetch_max(high) == low && a.load() == high);
|
||||
t.expects(a.fetch_max(low) == high && a.load() == high);
|
||||
t.expects(a.fetch_min(low) == high && a.load() == low);
|
||||
|
||||
# A compare-exchange writes where it finds what it expects, and otherwise gives
|
||||
# what it found.
|
||||
match a.compare_exchange(low, high) {
|
||||
value(found) => t.expects(found == low && a.load() == high);
|
||||
error(_) => t.expects(false);
|
||||
}
|
||||
match a.compare_exchange(low, most, order::acq_rel, order::acquire) {
|
||||
value(_) => t.expects(false);
|
||||
error(found) => t.expects(found == high && a.load() == high);
|
||||
}
|
||||
match a.compare_exchange_weak(high, least, order::release, order::relaxed) {
|
||||
value(found) => t.expects(found == high && a.load() == least);
|
||||
error(_) => t.expects(false);
|
||||
}
|
||||
}
|
||||
|
||||
@test def every_operation_works_at_every_width(t: &mut tester): void {
|
||||
operations_of::<u8>(t, 100, 200, 0, 255);
|
||||
operations_of::<i8>(t, -56, 100, -128, 127);
|
||||
operations_of::<u16>(t, 0x1234, 0xF00D, 0, 0xFFFF);
|
||||
operations_of::<i16>(t, -4000, 0x1234, -32768, 32767);
|
||||
operations_of::<u32>(t, 7, 0x80000001, 0, 0xFFFFFFFF);
|
||||
operations_of::<i32>(t, -2000000000, 2000000000, -2147483648, 2147483647);
|
||||
operations_of::<u64>(t, 3, 0x8000000000000003, 0, 0xFFFFFFFFFFFFFFFF);
|
||||
operations_of::<i64>(t, -0x7000000000000000, 0x7000000000000000, -0x7FFFFFFFFFFFFFFF - 1, 0x7FFFFFFFFFFFFFFF);
|
||||
}
|
||||
|
||||
@test def every_order_is_taken_where_it_makes_sense(t: &mut tester): void {
|
||||
var a := atomic::<u32>::new(1);
|
||||
for how in [order::relaxed, order::acquire, order::seq_cst] {
|
||||
t.expects(a.load(how) == 1);
|
||||
}
|
||||
for how in [order::relaxed, order::release, order::seq_cst] {
|
||||
a.store(2, how);
|
||||
t.expects(a.load() == 2);
|
||||
}
|
||||
for how in [order::relaxed, order::acquire, order::release, order::acq_rel, order::seq_cst] {
|
||||
t.expects(a.fetch_add(1, how) == 2 && a.exchange(2, how) == 3);
|
||||
fence(how);
|
||||
}
|
||||
t.expects(a.compare_exchange(2, 5, order::seq_cst, order::seq_cst) is value);
|
||||
t.expects(a.compare_exchange(5, 6, order::acq_rel, order::acquire) is value);
|
||||
t.expects(a.compare_exchange(6, 7, order::release, order::relaxed) is value);
|
||||
t.expects(a.compare_exchange(0, 8, order::relaxed, order::relaxed) is error);
|
||||
t.expects(a.load() == 7);
|
||||
}
|
||||
|
||||
enum light { red, amber, green }
|
||||
|
||||
@test def bools_enums_and_pointers_are_atomic(t: &mut tester): void {
|
||||
var flag := atomic::<bool>::new(false);
|
||||
t.expects(!flag.exchange(true) && flag.load());
|
||||
t.expects(flag.compare_exchange(true, false) is value && !flag.load());
|
||||
t.expects(flag.compare_exchange(true, true) is error);
|
||||
|
||||
var lamp := atomic::<light>::new(light::red);
|
||||
lamp.store(light::green);
|
||||
t.expects(lamp.exchange(light::amber) == light::green);
|
||||
match lamp.compare_exchange(light::red, light::green) {
|
||||
value(_) => t.expects(false);
|
||||
error(found) => t.expects(found == light::amber);
|
||||
}
|
||||
|
||||
val block := raw_allocate(16);
|
||||
var at := atomic::<*mut u8>::new(null);
|
||||
t.expects(at.exchange(block) == null && at.load() == block);
|
||||
t.expects(at.compare_exchange(block, block + 8) is value && at.load() == block + 8);
|
||||
raw_release(block);
|
||||
}
|
||||
|
||||
@test def orders_that_make_no_sense_stop_the_program(t: &mut tester): void {
|
||||
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.load(order::release); }));
|
||||
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.load(order::acq_rel); }));
|
||||
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); a.store(1, order::acquire); }));
|
||||
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); a.store(1, order::acq_rel); }));
|
||||
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::seq_cst, order::release); }));
|
||||
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::seq_cst, order::acq_rel); }));
|
||||
# A failure no stronger than what the success reads.
|
||||
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::relaxed, order::acquire); }));
|
||||
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::release, order::acquire); }));
|
||||
t.expects(stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::acq_rel, order::seq_cst); }));
|
||||
t.expects(!stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.compare_exchange(0, 1, order::acq_rel, order::acquire); }));
|
||||
t.expects(!stops_atomically(def() { var a := atomic::<u64>::new(0); _ = a.load(order::acquire); a.store(1, order::release); }));
|
||||
}
|
||||
|
||||
# How many times each process adds.
|
||||
const contended: u64 = 1000000;
|
||||
|
||||
# Sharing a page between processes takes `fork` and `mmap`, which Linux has.
|
||||
when os == linux {
|
||||
@test def two_processes_adding_to_memory_they_share_lose_nothing(t: &mut tester): void {
|
||||
# A page both processes keep after `fork`, rather than a copy each.
|
||||
val page := system::linux::syscall(9, 0, 4096, 3, 0x21, 0xFFFFFFFFFFFFFFFF, 0);
|
||||
t.expects(page > 0);
|
||||
return if page <= 0;
|
||||
val sum := page as u64 as *mut atomic<u64>;
|
||||
val tries := (page as u64 + 8) as *mut atomic<u32>;
|
||||
val bits := (page as u64 + 16) as *mut atomic<u16>;
|
||||
val most := (page as u64 + 24) as *mut atomic<i32>;
|
||||
|
||||
val child := fork();
|
||||
val own: u64 = child == 0 ? 1 : 2;
|
||||
for i in 0..contended {
|
||||
_ = sum[0].fetch_add(1);
|
||||
# A loop of compare-exchanges adds as well, trying again where the other
|
||||
# process wrote first.
|
||||
var seen := tries[0].load(order::relaxed);
|
||||
while true {
|
||||
match tries[0].compare_exchange_weak(seen, seen + 1, order::acq_rel, order::relaxed) {
|
||||
value(_) => break;
|
||||
error(found) => seen = found;
|
||||
}
|
||||
}
|
||||
_ = most[0].fetch_max((i * 2 + own) as i32);
|
||||
if i % 1000 == 0 {
|
||||
_ = bits[0].fetch_or((1 << (own * 4 + i / 1000 % 4)) as u16);
|
||||
}
|
||||
}
|
||||
if child == 0 {
|
||||
exit(0);
|
||||
}
|
||||
var status: process_status;
|
||||
t.expects(wait(child, &mut status) >= 0 && status.exited && status.code == 0);
|
||||
t.expects(sum[0].load() == 2 * contended);
|
||||
t.expects(tries[0].load() == 2 * contended as u32);
|
||||
t.expects(bits[0].load() == 0xFF0);
|
||||
t.expects(most[0].load() == ((contended - 1) * 2 + 2) as i32);
|
||||
_ = system::linux::syscall(11, page as u64, 4096, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
# 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 system;
|
||||
import std::testing;
|
||||
import std::containers;
|
||||
|
||||
|
||||
# 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; }
|
||||
|
||||
@test def vectors_grow_by_elements_left_undefined(t: &mut tester): void {
|
||||
var v := vector::<u64>::new();
|
||||
v.append(1);
|
||||
v.extend_undefined(1000);
|
||||
t.expects(v.length == 1001 && v[0] == 1);
|
||||
for i in 1..v.length {
|
||||
v[i] = i;
|
||||
}
|
||||
t.expects(v[1000] == 1000);
|
||||
|
||||
var zeroed := vector::<u64>::new();
|
||||
zeroed.resize(5000);
|
||||
var sum: u64 = 0;
|
||||
for &each in zeroed {
|
||||
sum += each;
|
||||
}
|
||||
t.expects(zeroed.length == 5000 && sum == 0);
|
||||
}
|
||||
|
||||
# A set closes a value where it lets it go: one it is given and already holds, one
|
||||
# removed, and one another set leaves or takes out, while what it copies in is its
|
||||
# own, so the set copied from closes only its own.
|
||||
# A vector reads its ends, removes its last, grows by copies, and sorts, closing
|
||||
# only what it removes, and moving what it sorts without closing or copying it.
|
||||
@test def vectors_read_their_ends_and_sort_what_they_hold(t: &mut tester): void {
|
||||
closed = 0;
|
||||
var v := vector::<counter>::new();
|
||||
for n in 1..4 { v.append(counter { n = n as u64 }); }
|
||||
t.expects(v.first.n == 1 && v.last.n == 3);
|
||||
v.last.n = 9;
|
||||
v.truncate();
|
||||
t.expects(closed == 1 && v.length == 2 && v.last.n == 2);
|
||||
|
||||
# Many are sorted by merging runs, and those an order leaves equal keep theirs.
|
||||
closed = 0;
|
||||
var many := vector::<counter>::new();
|
||||
for i in 0..40 { many.append(counter { n = ((i * 17) % 41 + 1) as u64 }); }
|
||||
many.sort();
|
||||
var sorted := true;
|
||||
for i in 1..many.length { sorted = sorted && many[i - 1].n < many[i].n; }
|
||||
t.expects(sorted && closed == 0);
|
||||
many.sort_by(def(a: &counter, b: &counter): bool { return a.n % 2 < b.n % 2; });
|
||||
t.expects(many[0].n == 2 && many[1].n == 4 && many[20].n == 1 && closed == 0);
|
||||
many.clear();
|
||||
t.expects(closed == 40);
|
||||
|
||||
var texts := vector::<string>::new();
|
||||
val more: string[2] = [string::from("b", nothing {}), string::from("a", nothing {})];
|
||||
texts.extend(more[:]);
|
||||
texts.resize(4, string::from("z", nothing {}));
|
||||
texts.sort();
|
||||
t.expects(texts.length == 4 && texts[0].span == "a" && texts[3].span == "z" && more[0].span == "b");
|
||||
|
||||
var numbers := vector::<u32>::new();
|
||||
numbers.resize(3, 0xFFFFFFFF);
|
||||
numbers.extend([4, 2]);
|
||||
numbers.sort();
|
||||
val view := numbers.span;
|
||||
t.expects(numbers.first == 2 && view.lower_bound(&4) == 1 && view.upper_bound(&4) == 2 && view.lower_bound(&5) == 2);
|
||||
t.expects(view.partition_point(def(x: &u32): bool { return x < 0xFFFFFFFF; }) == 2);
|
||||
|
||||
var d := dict::<u32, string>::new();
|
||||
d.set(1, string::from("one", nothing {}));
|
||||
t.expects(d.get_or(&1, string::new(nothing {})).span == "one" && d.get_or(&2, string::from("none", nothing {})).span == "none");
|
||||
}
|
||||
|
||||
@test def bytes_compare_flags_change_and_digits_read_in_any_base(t: &mut tester): void {
|
||||
val a: strview = "abc";
|
||||
val b: strview = "abd";
|
||||
t.expects(memcmp(a.data, b.data, 3) < 0 && memcmp(b.data, a.data, 3) > 0 && memcmp(a.data, a.data, 3) == 0);
|
||||
|
||||
var f: flags32<target> = 0;
|
||||
f.set(3, true);
|
||||
t.expects(f.get(3 as u8) && !f.get(4 as u8));
|
||||
f.set(3, false);
|
||||
t.expects(!f.get(3 as u8) && f == 0);
|
||||
t.expects(f.with(5, true).get(5 as u8) && !f.get(5 as u8));
|
||||
f.set(target::fields);
|
||||
t.expects(f.get(target::fields) && !f.with(4, false).get(target::fields));
|
||||
|
||||
t.expects(('2' as u8).is_base_digit(3) && !('3' as u8).is_base_digit(3) && !('9' as u8).is_base_digit(3));
|
||||
t.expects(('z' as u8).is_base_digit(36) && ('F' as u8).is_base_digit(16) && !('g' as u8).is_base_digit(16));
|
||||
}
|
||||
|
||||
@test def tuples_hold_a_value_of_each_type_and_close_what_closes(t: &mut tester): void {
|
||||
var pair := tuple::of(3, string::from("three", nothing {}));
|
||||
pair.at::<0>() += 1;
|
||||
t.expects(pair.items[0] == 4 && pair.at::<1>().span == "three" && pair.items.length == 2);
|
||||
|
||||
val before := closed;
|
||||
{
|
||||
val held := tuple::of(counter { n = 1 }, 5 as u8, counter { n = 2 });
|
||||
t.expects(held.at::<2>().n == 2 && closed == before);
|
||||
}
|
||||
t.expects(closed == before + 2);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
# Tests of `function`, which holds one callable of a signature, whatever its type,
|
||||
# and owns it: each kind of callable it holds, in its buffer or a box, signatures of
|
||||
# every shape, closing what it holds exactly once, holding nothing, lending what it
|
||||
# holds by its type, and being handed to another thread.
|
||||
|
||||
import std::testing;
|
||||
import std::thread;
|
||||
|
||||
|
||||
# How many callables the tests gave functions have been closed, from any thread.
|
||||
var callables_closed: atomic<u64>;
|
||||
|
||||
# A functor of two words counting its calls, closed once where it holds a mark.
|
||||
struct call_counter : invokable<def(i64): i64>, owning {
|
||||
var mark: u64;
|
||||
var calls: u64;
|
||||
}
|
||||
|
||||
def call_counter::invoke(&mut this, x: i64): i64 {
|
||||
this.calls++;
|
||||
return x + this.calls as i64;
|
||||
}
|
||||
|
||||
def call_counter::close(&mut this): void {
|
||||
if this.mark != 0 {
|
||||
_ = callables_closed.fetch_add(1);
|
||||
this.mark = 0;
|
||||
}
|
||||
}
|
||||
|
||||
# Functors of 8, 24 and 25 bytes, the last too large for a function's buffer.
|
||||
struct one_word : invokable<def(): u64> { var word: u64; }
|
||||
def one_word::invoke(&mut this): u64 { return this.word; }
|
||||
|
||||
struct three_words : invokable<def(): u64> { var bytes: u8[24]; }
|
||||
def three_words::invoke(&mut this): u64 { return this.bytes[0] as u64 + this.bytes[23] as u64; }
|
||||
|
||||
struct past_three_words : invokable<def(): u64> { var bytes: u8[25]; }
|
||||
def past_three_words::invoke(&mut this): u64 { return this.bytes[0] as u64 + this.bytes[24] as u64; }
|
||||
|
||||
# A functor in a box, closed once where it holds a mark, as a large one held is.
|
||||
struct large_counter : invokable<def(): u64>, owning {
|
||||
var mark: u64;
|
||||
var calls: u64;
|
||||
var pad: u64[4];
|
||||
}
|
||||
|
||||
def large_counter::invoke(&mut this): u64 {
|
||||
this.calls++;
|
||||
return this.calls;
|
||||
}
|
||||
|
||||
def large_counter::close(&mut this): void {
|
||||
if this.mark != 0 {
|
||||
_ = callables_closed.fetch_add(1);
|
||||
this.mark = 0;
|
||||
}
|
||||
}
|
||||
|
||||
struct held_point { var x: f64; var y: f64; }
|
||||
def held_point::sum(&this): f64 { return this.x + this.y; }
|
||||
def held_point::origin(): held_point { return held_point {}; }
|
||||
|
||||
def twice_given(x: i64): i64 { return x * 2; }
|
||||
def added_up(xs: i64...): i64 { var total: i64 = 0; for x in xs { total += x; } return total; }
|
||||
def nothing_given(): u64 { return 7; }
|
||||
def four_given(a: u8, b: u16, c: u32, d: u64): u64 { return a as u64 + b as u64 + c as u64 + d; }
|
||||
def larger_of(a: &i64, b: &i64): &i64 {
|
||||
val x: i64 = a;
|
||||
val y: i64 = b;
|
||||
return x > y ? a : b;
|
||||
}
|
||||
|
||||
# A lambda using no locals, which may outlive the function making it.
|
||||
def lambda_using_none(): function<def(i64): i64> {
|
||||
return function::new(def(x: i64): i64 => x - 1);
|
||||
}
|
||||
|
||||
@test def functions_are_four_words_holding_any_callable(t: &mut tester): void {
|
||||
t.expects(size_of::<function<def(i64): i64>>() == 32 && size_of::<function<def(): void>>() == 32);
|
||||
|
||||
val named: function<def(i64): i64> = function::new(twice_given);
|
||||
t.expects(named(21) == 42);
|
||||
|
||||
# A method taken through its type takes its receiver first.
|
||||
val method: function<def(&held_point): f64> = function::new(held_point::sum);
|
||||
val p := held_point { x = 1.5, y = 2.0 };
|
||||
t.expects(method(&p) == 3.5);
|
||||
val made: function<def(): held_point> = function::new(held_point::origin);
|
||||
t.expects(made().x == 0.0);
|
||||
|
||||
# A lambda refers to the locals it uses, which change under it.
|
||||
var by := 10;
|
||||
val lambda: function<def(i64): i64> = function::new(def(x: i64): i64 => x + by);
|
||||
t.expects(lambda(1) == 11);
|
||||
by = 20;
|
||||
t.expects(lambda(1) == 21);
|
||||
|
||||
val kept := lambda_using_none();
|
||||
t.expects(kept(5) == 4);
|
||||
}
|
||||
|
||||
@test def functions_hold_small_functors_in_place_and_large_ones_in_a_box(t: &mut tester): void {
|
||||
var bytes: u8[25];
|
||||
bytes[0] = 1;
|
||||
bytes[23] = 2;
|
||||
bytes[24] = 3;
|
||||
val one: function<def(): u64> = function::new(one_word { word = 9 });
|
||||
var three: three_words;
|
||||
three.bytes[0] = 1;
|
||||
three.bytes[23] = 2;
|
||||
val in_place: function<def(): u64> = function::new(three);
|
||||
val boxed: function<def(): u64> = function::new(past_three_words { bytes = bytes });
|
||||
t.expects(one() == 9 && in_place() == 3 && boxed() == 4);
|
||||
|
||||
# What a functor changes as it is called stays changed, in place or boxed.
|
||||
val counting: function<def(i64): i64> = function::new(call_counter {});
|
||||
t.expects(counting(10) == 11 && counting(10) == 12);
|
||||
val large: function<def(): u64> = function::new(large_counter {});
|
||||
t.expects(large() == 1 && large() == 2 && large() == 3);
|
||||
}
|
||||
|
||||
@test def functions_call_a_functor_referred_to_where_it_is(t: &mut tester): void {
|
||||
var counter := call_counter {};
|
||||
{
|
||||
val referring: function<def(i64): i64> = function::new(&mut counter);
|
||||
t.expects(referring(0) == 1 && referring(0) == 2);
|
||||
}
|
||||
t.expects(counter.calls == 2);
|
||||
}
|
||||
|
||||
@test def functions_take_signatures_of_every_shape(t: &mut tester): void {
|
||||
val none: function<def(): u64> = function::new(nothing_given);
|
||||
val four: function<def(u8, u16, u32, u64): u64> = function::new(four_given);
|
||||
t.expects(none() == 7 && four(1, 2, 3, 4) == 10);
|
||||
|
||||
# References are given and given back.
|
||||
val larger: function<def(&i64, &i64): &i64> = function::new(larger_of);
|
||||
val a: i64 = 3;
|
||||
val b: i64 = 8;
|
||||
val got: i64 = larger(&a, &b);
|
||||
t.expects(got == 8);
|
||||
|
||||
# What gives nothing, which a lambda appending to a vector does.
|
||||
var seen := vector::<i64>::new();
|
||||
val keep: function<def(i64): void> = function::new(def(x: i64) { seen.append(x); });
|
||||
keep(4);
|
||||
keep(5);
|
||||
t.expects(seen.length == 2 && seen[1] == 5);
|
||||
|
||||
# A variadic signature takes any number of arguments, or a view of them.
|
||||
val sum: function<def(i64...): i64> = function::new(added_up);
|
||||
val more: i64[3] = [4, 5, 6];
|
||||
t.expects(sum() == 0 && sum(1, 2, 3) == 6 && sum(...more) == 15);
|
||||
}
|
||||
|
||||
@test def functions_close_what_they_hold_once(t: &mut tester): void {
|
||||
val before := callables_closed.load();
|
||||
{
|
||||
val f: function<def(i64): i64> = function::new(call_counter { mark = 1 });
|
||||
val g: function<def(): u64> = function::new(large_counter { mark = 1 });
|
||||
}
|
||||
t.expects(callables_closed.load() == before + 2);
|
||||
|
||||
# Written over, what it held closes; moved from, it holds nothing to close.
|
||||
var f: function<def(i64): i64> = function::new(call_counter { mark = 1 });
|
||||
f = function::new(call_counter { mark = 2 });
|
||||
t.expects(callables_closed.load() == before + 3);
|
||||
var moved := move(&mut f);
|
||||
f.close();
|
||||
t.expects(callables_closed.load() == before + 3);
|
||||
moved.close();
|
||||
moved.close();
|
||||
t.expects(callables_closed.load() == before + 4);
|
||||
|
||||
# A vector of them grows by moving them, and closes each once.
|
||||
{
|
||||
var many := vector::<function<def(): u64>>::new();
|
||||
for i in 0..40u {
|
||||
many.append(function::new(large_counter { mark = i + 1 }));
|
||||
}
|
||||
t.expects(many[39]() == 1);
|
||||
}
|
||||
t.expects(callables_closed.load() == before + 44);
|
||||
}
|
||||
|
||||
@test def empty_functions_hold_nothing_and_stop_where_called(t: &mut tester): void {
|
||||
var empty: function<def(): void>;
|
||||
t.expects(!empty.holds());
|
||||
empty = function::new(def() {});
|
||||
t.expects(empty.holds());
|
||||
val moved := move(&mut empty);
|
||||
t.expects(!empty.holds() && moved.holds());
|
||||
t.expects(stops(def() { var none: function<def(i64): i64>; _ = none(1); }));
|
||||
}
|
||||
|
||||
@test def functions_lend_what_they_hold_by_its_type(t: &mut tester): void {
|
||||
val counting: function<def(i64): i64> = function::new(call_counter { calls = 5 });
|
||||
_ = counting(0);
|
||||
if counting.get::<call_counter>() is some(&held) {
|
||||
t.expects(held.calls == 6);
|
||||
} else {
|
||||
t.expects(false);
|
||||
}
|
||||
t.expects(!(counting.get::<def(i64): i64>() is some));
|
||||
|
||||
val large: function<def(): u64> = function::new(large_counter {});
|
||||
_ = large();
|
||||
if large.get::<large_counter>() is some(&held) {
|
||||
t.expects(held.calls == 1);
|
||||
} else {
|
||||
t.expects(false);
|
||||
}
|
||||
t.expects(!(large.get::<one_word>() is some));
|
||||
|
||||
var empty: function<def(): u64>;
|
||||
t.expects(!(empty.get::<large_counter>() is some));
|
||||
}
|
||||
|
||||
# Calls a function given to a thread, which then owns it.
|
||||
def call_given(f: function<def(): u64>): void {
|
||||
_ = f();
|
||||
_ = f();
|
||||
}
|
||||
|
||||
@test def functions_are_handed_to_other_threads(t: &mut tester): void {
|
||||
val before := callables_closed.load();
|
||||
var counting: function<def(): u64> = function::new(large_counter { mark = 1 });
|
||||
var thread := thread::spawn_with(call_given, move(&mut counting)) else {
|
||||
t.expects(false);
|
||||
return;
|
||||
};
|
||||
thread.join();
|
||||
t.expects(!counting.holds() && callables_closed.load() == before + 1);
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
# Tests of generics given constants, and of what calls infer. A constant parameter is
|
||||
# given a value of its type, worked out while checking, and instances given equal values
|
||||
# are one instance. Calls infer constants from the lengths of fixed arrays and the
|
||||
# arguments of other instances, and infer type arguments from bounds, the type expected
|
||||
# of their result, array literals, functions named as values, and the arguments around
|
||||
# one that needs another's type first.
|
||||
import std::testing;
|
||||
import std::containers;
|
||||
|
||||
|
||||
# A buffer of a number of elements its type gives.
|
||||
struct buffer<T, const N: u64> where T: zeroable {
|
||||
var items: T[N];
|
||||
}
|
||||
|
||||
def buffer<T, N>::capacity(&this): u64 { return N; }
|
||||
|
||||
def buffer<T, const N: u64>::filled(value: T): buffer<T, N> {
|
||||
var made: buffer<T, N>;
|
||||
for i in 0..N { made.items[i] = value; }
|
||||
return made;
|
||||
}
|
||||
|
||||
const four_of: u64 = 4;
|
||||
|
||||
@test def constants_tell_instances_apart(t: &mut tester): void {
|
||||
var b: buffer<i64, 4>;
|
||||
val c: buffer<i64, four_of> = buffer::<i64, 2 + 2>::filled(7);
|
||||
b = c;
|
||||
t.expects(b.capacity() == 4 && b.items.length == 4 && b.items[3] == 7);
|
||||
t.expects(name_of::<buffer<u8, 16>>() == "buffer<u8, 16>");
|
||||
t.expects(name_of::<buffer<u16, four_of * 2>>() == "buffer<u16, 8>");
|
||||
}
|
||||
|
||||
enum color { red, green, blue }
|
||||
struct spot { var x: i64; var y: i64 = 7; }
|
||||
union figure { var circle: f64; var square: f64; }
|
||||
const origin: spot = spot { x = 1 };
|
||||
const table: i64[3] = [10, 20, 30];
|
||||
|
||||
struct labelled<const NAME: strview> {}
|
||||
def labelled<NAME>::name(&this): strview { return NAME; }
|
||||
|
||||
struct painted<const C: color> {}
|
||||
def painted<C>::color(&this): color { return C; }
|
||||
|
||||
struct placed<const P: spot> {}
|
||||
def placed<P>::sum(&this): i64 { return P.x + P.y; }
|
||||
|
||||
struct flagged<const B: bool> {}
|
||||
def flagged<B>::on(&this): bool {
|
||||
if const B {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
struct scaled<const F: f64> {}
|
||||
def scaled<F>::times(&this, x: f64): f64 { return x * F; }
|
||||
|
||||
struct drawn<const S: figure> {}
|
||||
def drawn<S>::size(&this): f64 {
|
||||
if S is circle(r) {
|
||||
return r;
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
def double(x: i64): i64 { return x * 2; }
|
||||
def triple(x: i64): i64 { return x * 3; }
|
||||
struct applied<const F: def(i64): i64> {}
|
||||
def applied<F>::run(&this, x: i64): i64 { return F(x); }
|
||||
|
||||
struct indexed<const XS: i64[3]> {}
|
||||
def indexed<XS>::second(&this): i64 { return XS[1]; }
|
||||
|
||||
struct aimed<const R: &i64[3]> {}
|
||||
def aimed<R>::last(&this): i64 { return R[2]; }
|
||||
|
||||
struct keeper<T, const V: T> {}
|
||||
def keeper<T, V>::get(&this): T { return V; }
|
||||
|
||||
@test def constants_are_values_of_every_kind(t: &mut tester): void {
|
||||
t.expects(labelled::<"hello"> {}.name() == "hello");
|
||||
t.expects(painted::<color::green> {}.color() == color::green);
|
||||
|
||||
# A struct is the same constant as another holding the same fields, its defaults
|
||||
# included, however each is written.
|
||||
val here: placed<spot { x = 1, y = 7 }> = placed::<origin> {};
|
||||
t.expects(here.sum() == 8);
|
||||
|
||||
t.expects(flagged::<true> {}.on() && !flagged::<(1 > 2)> {}.on());
|
||||
t.expects(scaled::<1.5> {}.times(2.0) == 3.0);
|
||||
t.expects(drawn::<figure { circle = 2.5 }> {}.size() == 2.5);
|
||||
t.expects(applied::<double> {}.run(5) == 10 && applied::<triple> {}.run(5) == 15);
|
||||
t.expects(indexed::<table> {}.second() == 20 && indexed::<[4, 5, 6]> {}.second() == 5);
|
||||
t.expects(aimed::<&table> {}.last() == 30);
|
||||
t.expects(keeper::<u8, 200> {}.get() == 200 && keeper::<strview, "x"> {}.get() == "x");
|
||||
}
|
||||
|
||||
def summed<const N: u64>(xs: &i64[N]): i64 {
|
||||
var sum: i64 = 0;
|
||||
for x in xs { sum += x; }
|
||||
return sum;
|
||||
}
|
||||
|
||||
def grown<T, const N: u64>(xs: &T[N], last: T): T[N + 1] where T: zeroable {
|
||||
var out: T[N + 1];
|
||||
for i, x in xs { out[i] = x; }
|
||||
out[N] = last;
|
||||
return out;
|
||||
}
|
||||
|
||||
def capacity_of<T, const N: u64>(b: &buffer<T, N>): u64 where T: zeroable { return N; }
|
||||
|
||||
def widened<T, const N: u64>(b: &buffer<T, N>): buffer<T, N * 2> where T: zeroable {
|
||||
var out: buffer<T, N * 2>;
|
||||
for i, x in b.items {
|
||||
out.items[i] = x;
|
||||
out.items[i + N] = x;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
type grid_of<const N: u64> = i64[N][N];
|
||||
|
||||
@test def constants_are_inferred_from_what_is_given(t: &mut tester): void {
|
||||
val xs: i64[3] = [1, 2, 3];
|
||||
t.expects(summed(&xs) == 6 && summed::<2>(&[5, 6]) == 11);
|
||||
|
||||
val ys := grown(&xs, 4);
|
||||
t.expects(ys.length == 4 && ys[3] == 4);
|
||||
|
||||
val b := buffer::<i64, 3>::filled(9);
|
||||
val w := widened(&b);
|
||||
t.expects(capacity_of(&b) == 3 && capacity_of(&w) == 6 && w.items[5] == 9);
|
||||
|
||||
val sq: grid_of<2> = [[1, 2], [3, 4]];
|
||||
t.expects(sq[1][0] == 3);
|
||||
}
|
||||
|
||||
def doubled<const N: u64>(): u64 { return N * 2; }
|
||||
const twelve: u64 = doubled::<6>();
|
||||
|
||||
def described<const N: u64>(): strview {
|
||||
if const N > 2 {
|
||||
return "many";
|
||||
}
|
||||
return "few";
|
||||
}
|
||||
|
||||
@test def constants_are_known_while_compiling(t: &mut tester): void {
|
||||
t.expects(twelve == 12);
|
||||
t.expects(described::<1>() == "few" && described::<5>() == "many");
|
||||
}
|
||||
|
||||
# What a container's elements are, as a bound gives it.
|
||||
def leading<C, T>(c: &C): maybe<T> where C: iterable<T> {
|
||||
for x in c {
|
||||
return x;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
struct wrapped<T> { var value: T; }
|
||||
def wrapped<T>::new(value: T): wrapped<T> { return wrapped::<T> { value = value }; }
|
||||
|
||||
def itself<T>(x: T): T { return x; }
|
||||
def apply<T, U>(f: def(T): U, x: T): U { return f(x); }
|
||||
|
||||
def sum_of<T>(xs: span<T>): T where T: numeric, zeroable {
|
||||
var all: T;
|
||||
for x in xs { all += x; }
|
||||
return all;
|
||||
}
|
||||
|
||||
def made_empty<T>(): vector<T> { return vector::<T>::new(); }
|
||||
def pick<T>(a: T, b: T): T { return b; }
|
||||
def latter<T, U>(a: T, b: U): U { return b; }
|
||||
|
||||
@test def calls_infer_what_their_arguments_do_not_give(t: &mut tester): void {
|
||||
var xs := vector::<i64>::new();
|
||||
xs.append(4);
|
||||
t.expects(leading(&xs) is some(got) && got == 4);
|
||||
|
||||
# A generic type's own static method infers the type's arguments too.
|
||||
val b := wrapped::new(5);
|
||||
val c: wrapped<u8> = wrapped::new(5);
|
||||
var v: vector<i64> = vector::new();
|
||||
v.append(1);
|
||||
t.expects(b.value == 5 && c.value == 5 && v.length == 1);
|
||||
|
||||
# A generic function labelled as a value is the instance the type expected gives.
|
||||
val f: def(i64): i64 = itself;
|
||||
t.expects(f(4) == 4 && apply(itself, 3) == 3 && apply(double, 3) == 6);
|
||||
|
||||
t.expects(sum_of([1, 2, 3]) == 6 && sum_of([1.5, 2.5]) == 4.0);
|
||||
|
||||
# An argument needing another's type is checked once the other gives it.
|
||||
var given := vector::<u8>::new();
|
||||
given.append(1);
|
||||
val picked := pick(made_empty(), move(given));
|
||||
t.expects(picked.length == 1);
|
||||
|
||||
# Type arguments written are the first ones, and the call infers the rest.
|
||||
t.expects(latter::<i64>(1, true));
|
||||
}
|
||||
|
||||
# Says only whether a number is even, failing with the number otherwise.
|
||||
def even_only(n: u64): result<void, u64> {
|
||||
if n % 2 != 0 { return n; }
|
||||
return;
|
||||
}
|
||||
|
||||
@test def void_is_given_to_std_generics_as_any_type(t: &mut tester): void {
|
||||
# Owners, containers, and results hold `void`, its one value taking no bytes.
|
||||
val held := box::<void>::new(void {});
|
||||
t.expects(held.holds());
|
||||
var shared := rc::<void>::new(void {});
|
||||
val also := copy(&shared);
|
||||
t.expects(shared.count() == 2);
|
||||
var marks := vector::<void>::new();
|
||||
for _ in 0..5u { marks.append(void {}); }
|
||||
t.expects(marks.length == 5 && size_of::<void>() == 0);
|
||||
|
||||
# A `maybe<void>` tells a value missing from the value of `void`.
|
||||
var seen: maybe<void> = nothing {};
|
||||
t.expects(!(seen is some));
|
||||
seen = void {};
|
||||
t.expects(seen is some);
|
||||
|
||||
# A result of `void` says only whether something failed.
|
||||
t.expects(even_only(4) is value && even_only(3) is error);
|
||||
var failed: u64 = 0;
|
||||
even_only(7) else (n) { failed = n; };
|
||||
t.expects(failed == 7);
|
||||
|
||||
# A function giving nothing is held, and called, as one giving any type.
|
||||
var count := 0;
|
||||
val f: function<def(): void> = function::new(def() { count++; });
|
||||
f();
|
||||
f();
|
||||
t.expects(count == 2);
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
# Tests of iterating what an iterator gives by value: each element is the loop's own,
|
||||
# closed where each pass of the body ends, however the pass ends.
|
||||
import std::containers;
|
||||
import std::testing;
|
||||
|
||||
|
||||
# How many lines holding a number have been closed.
|
||||
var lines_closed: u64 = 0;
|
||||
|
||||
struct line : owning {
|
||||
var n: u64;
|
||||
}
|
||||
|
||||
def line::close(&mut this): void {
|
||||
if this.n != 0 {
|
||||
lines_closed++;
|
||||
this.n = 0;
|
||||
}
|
||||
}
|
||||
|
||||
# Gives lines numbered from how many are left down to 1, each a new value.
|
||||
struct lines : iter<line> {
|
||||
var left: u64;
|
||||
}
|
||||
|
||||
def lines::next(&mut this): maybe<line> {
|
||||
if this.left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
this.left--;
|
||||
return line { n = this.left + 1 };
|
||||
}
|
||||
|
||||
# Gives words numbered down to 0, each a new string, as a reader gives its lines.
|
||||
struct words : iter<string> {
|
||||
var left: u64;
|
||||
}
|
||||
|
||||
def words::next(&mut this): maybe<string> {
|
||||
if this.left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
this.left--;
|
||||
return $"word {this.left}";
|
||||
}
|
||||
|
||||
# The first line numbered no more than the limit, the rest skipped by `continue`.
|
||||
def first_within(limit: u64): u64 {
|
||||
for each in (lines { left = 5 }) {
|
||||
if each.n > limit {
|
||||
continue;
|
||||
}
|
||||
return each.n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@test def iterators_give_elements_the_loop_owns(t: &mut tester): void {
|
||||
lines_closed = 0;
|
||||
var total: u64 = 0;
|
||||
for each in (lines { left = 4 }) {
|
||||
total += each.n;
|
||||
}
|
||||
t.expects(total == 10 && lines_closed == 4);
|
||||
|
||||
# 5, then 4 by `continue`, then 3, then 2 by `break`, and 1 never given.
|
||||
lines_closed = 0;
|
||||
for each in (lines { left = 5 }) {
|
||||
if each.n == 4 {
|
||||
continue;
|
||||
}
|
||||
if each.n == 2 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
t.expects(lines_closed == 4);
|
||||
|
||||
# 5 and 4 by `continue`, and 3 by `return`.
|
||||
lines_closed = 0;
|
||||
t.expects(first_within(3) == 3 && lines_closed == 3);
|
||||
|
||||
lines_closed = 0;
|
||||
for _ in (lines { left = 3 }) {}
|
||||
t.expects(lines_closed == 3);
|
||||
|
||||
# An iterator variable is advanced where it is, so a second loop goes on from there.
|
||||
lines_closed = 0;
|
||||
var walk := lines { left = 4 };
|
||||
for each in walk {
|
||||
if each.n == 3 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
var rest: u64 = 0;
|
||||
for each in walk {
|
||||
rest += each.n;
|
||||
}
|
||||
t.expects(rest == 3 && lines_closed == 4);
|
||||
}
|
||||
|
||||
@test def iterators_give_strings_the_loop_owns(t: &mut tester): void {
|
||||
var joined := string::new(nothing {});
|
||||
for word in (words { left = 3 }) {
|
||||
joined.append(word.span);
|
||||
joined.append(";");
|
||||
}
|
||||
t.expects(joined.span == "word 2;word 1;word 0;");
|
||||
|
||||
var counted := 0u;
|
||||
for word in (words { left = 100 }) {
|
||||
counted += word.length;
|
||||
}
|
||||
t.expects(counted == 690);
|
||||
}
|
||||
|
||||
@test def loops_refer_to_what_they_walk(t: &mut tester): void {
|
||||
# Elements an array holds, or an iterator gives by reference, are referred to by
|
||||
# `for x`, neither copied nor closed by the loop.
|
||||
lines_closed = 0;
|
||||
var kept: line[2];
|
||||
kept[0] = line { n = 1 };
|
||||
kept[1] = line { n = 2 };
|
||||
var sum: u64 = 0;
|
||||
for &each in kept {
|
||||
sum += each.n;
|
||||
}
|
||||
t.expects(sum == 3 && lines_closed == 0);
|
||||
|
||||
var texts := vector::<string>::new();
|
||||
texts.append(string::from("ab", nothing {}));
|
||||
texts.append(string::from("cde", nothing {}));
|
||||
var length: u64 = 0;
|
||||
for &text in texts.span {
|
||||
length += text.length;
|
||||
}
|
||||
t.expects(length == 5 && texts.length == 2);
|
||||
}
|
||||
|
||||
# The numbers 1 to 6, which the tests of adapters and consumers walk.
|
||||
def six(): vector<u64> {
|
||||
var made := vector::<u64>::new();
|
||||
for i in 1..=6u {
|
||||
made.append(i);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# The text of what an iterator gives, separated by spaces.
|
||||
def spaced<T, I>(it: I): string where I: iter<T> {
|
||||
return it.to_string(" ");
|
||||
}
|
||||
|
||||
@test def adapters_make_iterators_of_iterators(t: &mut tester): void {
|
||||
val v := six();
|
||||
t.expects(spaced(v.iter().map(def(x): u64 => x * 10)).span == "10 20 30 40 50 60");
|
||||
t.expects(spaced(v.iter().filter(def(x) => x % 2 == 0)).span == "2 4 6");
|
||||
t.expects(spaced(v.iter().filter_map(def(x): maybe<u64> => x % 3 == 0 ? something::<u64>(x / 3) : nothing {})).span == "1 2");
|
||||
t.expects(spaced(v.iter().enumerate().map(def(p): u64 => p.first * 10 + p.second)).span == "1 12 23 34 45 56");
|
||||
t.expects(spaced(v.iter().zip(v.iter().skip(1)).map(def(p): u64 => p.first * p.second)).span == "2 6 12 20 30");
|
||||
t.expects(spaced(v.iter().take(2).chain(v.iter().skip(4))).span == "1 2 5 6");
|
||||
t.expects(spaced(v.iter().take_while(def(x) => x < 4)).span == "1 2 3");
|
||||
t.expects(spaced(v.iter().skip_while(def(x) => x < 4)).span == "4 5 6");
|
||||
t.expects(spaced(v.iter().step(2)).span == "1 3 5");
|
||||
t.expects(spaced(v.iter().rev()).span == "6 5 4 3 2 1");
|
||||
t.expects(spaced(v.iter().take(3).flat_map(def(x) => 0..x)).span == "0 0 1 0 1 2");
|
||||
t.expects(spaced(v.iter().copied().map(def(x: u64): u64 => x + 1)).span == "2 3 4 5 6 7");
|
||||
|
||||
var seen: u64 = 0;
|
||||
t.expects(v.iter().inspect(def(x) { seen += x; }).count() == 6 && seen == 21);
|
||||
|
||||
var looked := v.iter().peekable();
|
||||
t.expects(looked.peek() is some(first) && first == 1);
|
||||
t.expects(spaced(looked).span == "1 2 3 4 5 6");
|
||||
}
|
||||
|
||||
@test def adapters_take_the_edges(t: &mut tester): void {
|
||||
val v := six();
|
||||
val none := vector::<u64>::new();
|
||||
t.expects(none.iter().map(def(x): u64 => x).count() == 0 && none.iter().rev().count() == 0);
|
||||
t.expects(v.iter().take(0).count() == 0 && v.iter().skip(9).count() == 0);
|
||||
t.expects(spaced(v.iter().step(1)).span == "1 2 3 4 5 6");
|
||||
t.expects(v.iter().zip(v.iter().take(2)).count() == 2 && v.iter().take(1).zip(v.iter()).count() == 1);
|
||||
|
||||
# Walking from both ends gives each element once, until the ends meet.
|
||||
var both := v.iter();
|
||||
var taken := string::new(nothing {});
|
||||
while true {
|
||||
val front := both.next();
|
||||
if front is some(a) {
|
||||
taken.append($"{a}<");
|
||||
}
|
||||
val back := both.next_back();
|
||||
if back is some(b) {
|
||||
taken.append($">{b}");
|
||||
}
|
||||
break if both.remaining() == 0;
|
||||
}
|
||||
t.expects(taken.span == "1<>62<>53<>4");
|
||||
t.expects(both.next() is not some(_) && both.next_back() is not some(_));
|
||||
}
|
||||
|
||||
@test def consumers_walk_to_the_end(t: &mut tester): void {
|
||||
val v := six();
|
||||
t.expects(v.iter().count() == 6 && v.iter().copied().sum() == 21 && v.iter().copied().product() == 720);
|
||||
t.expects(v.iter().fold(100u, def(a: u64, x: &u64): u64 => a - x) == 79);
|
||||
t.expects((v.iter().copied().reduce(def(a: u64, b: u64): u64 => a * b) else 0) == 720);
|
||||
t.expects(v.iter().any(def(x) => x > 5) && !v.iter().any(def(x) => x > 6));
|
||||
t.expects(v.iter().all(def(x) => x > 0) && !v.iter().all(def(x) => x > 1));
|
||||
t.expects((v.iter().copied().find(def(x) => x > 3) else 0) == 4);
|
||||
t.expects((v.iter().position(def(x) => x > 3) else 99) == 3 && v.iter().position(def(x) => x > 9) is not some(_));
|
||||
t.expects((v.iter().copied().min() else 0) == 1 && (v.iter().copied().max() else 0) == 6);
|
||||
t.expects((v.iter().copied().min_by(def(a, b) => a > b) else 0) == 6);
|
||||
t.expects((v.iter().copied().max_by_key(def(x): u64 => (x * 7) % 5) else 0) == 2);
|
||||
t.expects((v.iter().copied().min_by_key(def(x): u64 => (x * 7) % 5) else 0) == 5);
|
||||
t.expects((v.iter().copied().last() else 0) == 6 && (v.iter().copied().nth(2) else 0) == 3);
|
||||
t.expects(v.iter().nth(6) is not some(_));
|
||||
|
||||
val none := vector::<u64>::new();
|
||||
t.expects(none.iter().copied().sum() == 0 && none.iter().copied().min() is not some(_));
|
||||
t.expects(none.iter().copied().reduce(def(a: u64, b: u64): u64 => a + b) is not some(_));
|
||||
|
||||
val doubled := v.iter().map(def(x): u64 => x * 2).to_vector();
|
||||
t.expects(doubled.length == 6 && doubled[5] == 12);
|
||||
|
||||
var into := vector::<u64>::new();
|
||||
into.append(0);
|
||||
v.iter().copied().into(&mut into);
|
||||
t.expects(into.length == 7 && into[6] == 6);
|
||||
|
||||
var walked: u64 = 0;
|
||||
v.iter().for_each(def(x) { walked += x; });
|
||||
t.expects(walked == 21);
|
||||
}
|
||||
|
||||
# How many `ticket`s holding a number have been closed.
|
||||
var tickets_closed: u64 = 0;
|
||||
|
||||
struct ticket : owning {
|
||||
var n: u64;
|
||||
}
|
||||
|
||||
def ticket::close(&mut this): void {
|
||||
if this.n != 0 {
|
||||
tickets_closed++;
|
||||
this.n = 0;
|
||||
}
|
||||
}
|
||||
|
||||
# Gives tickets numbered from how many are left down to 1, each a new value, and
|
||||
# counts how many times it is closed itself, which one moved from is not.
|
||||
var ticket_sources_closed: u64 = 0;
|
||||
|
||||
struct tickets : owning, iter<ticket> {
|
||||
var left: u64;
|
||||
var live: bool;
|
||||
}
|
||||
|
||||
def tickets::next(&mut this): maybe<ticket> {
|
||||
return nothing {} if this.left == 0;
|
||||
this.left--;
|
||||
return ticket { n = this.left + 1 };
|
||||
}
|
||||
|
||||
def tickets::close(&mut this): void {
|
||||
if this.live {
|
||||
ticket_sources_closed++;
|
||||
this.live = false;
|
||||
}
|
||||
}
|
||||
|
||||
@test def adapters_close_what_they_own_once(t: &mut tester): void {
|
||||
tickets_closed = 0;
|
||||
ticket_sources_closed = 0;
|
||||
val total := (tickets { left = 4, live = true }).map(def(x: ticket): u64 => x.n).sum();
|
||||
t.expects(total == 10 && tickets_closed == 4 && ticket_sources_closed == 1);
|
||||
|
||||
tickets_closed = 0;
|
||||
ticket_sources_closed = 0;
|
||||
val kept := (tickets { left = 5, live = true }).filter(def(x) => x.n % 2 == 1).take(2).to_vector();
|
||||
t.expects(kept.length == 2 && kept[0].n == 5 && kept[1].n == 3);
|
||||
t.expects(tickets_closed == 1 && ticket_sources_closed == 1);
|
||||
|
||||
tickets_closed = 0;
|
||||
ticket_sources_closed = 0;
|
||||
var found := (tickets { left = 3, live = true }).enumerate().find(def(p) => p.second.n == 2);
|
||||
t.expects(found is some(&p) && p.first == 1);
|
||||
t.expects(tickets_closed == 1 && ticket_sources_closed == 1);
|
||||
}
|
||||
|
||||
type view_cursor = span<u64>::iterator;
|
||||
type view_filter = filtered<&u64, span<u64>::iterator, def(& &u64): bool>;
|
||||
type list_map = mapped<&u64, u64, list<u64>::iterator, def(&u64): u64>;
|
||||
|
||||
# Whether a view's cursor knows how many it has left, which it does.
|
||||
def view_is_sized(): bool { if const view_cursor is sized_iterator<&u64> { return true; } return false; }
|
||||
|
||||
# Whether filtering it knows, which it does not.
|
||||
def filter_is_sized(): bool { if const view_filter is sized_iterator<&u64> { return true; } return false; }
|
||||
|
||||
# Whether mapping a list's cursor walks backward, which it does not.
|
||||
def list_map_is_backward(): bool { if const list_map is backward_iterator<u64> { return true; } return false; }
|
||||
|
||||
@test def adapters_stay_sized_and_backward_as_what_they_adapt(t: &mut tester): void {
|
||||
var v := six();
|
||||
val view := v.span;
|
||||
t.expects(view.iter().map(def(x): u64 => x).remaining() == 6);
|
||||
t.expects(view.iter().zip(view.iter().skip(2)).remaining() == 4);
|
||||
t.expects(view.iter().enumerate().rev().next() is some(p) && p.first == 5 && p.second == 6);
|
||||
t.expects(view.iter().step(4).remaining() == 2 && view.iter().take(10).remaining() == 6);
|
||||
t.expects(view.iter().chain(view.iter()).remaining() == 12);
|
||||
t.expects(view.iter().filter(def(x) => x > 2).rev().next() is some(last) && last == 6);
|
||||
t.expects(view_is_sized() && !filter_is_sized() && !list_map_is_backward());
|
||||
}
|
||||
|
||||
# An enum with values no member has between its members', and one value two
|
||||
# members share.
|
||||
enum shade: i8 { deep = -3, dim, bright = 2, glare, plain = -2 }
|
||||
|
||||
@test def ranges_are_values(t: &mut tester): void {
|
||||
t.expects(spaced(0..5).span == "0 1 2 3 4" && spaced(0..=5).span == "0 1 2 3 4 5");
|
||||
t.expects(spaced((0..=5).rev()).span == "5 4 3 2 1 0" && spaced((0..20).step(5)).span == "0 5 10 15");
|
||||
t.expects((1..=100).sum() == 5050 && (3..10).length == 7 && (3..=10).length == 8);
|
||||
t.expects((5..2).count() == 0 && (5..=5).count() == 1 && (5..=4).count() == 0);
|
||||
|
||||
val r: range<u8> = 250..=255;
|
||||
t.expects(r.length == 6 && r.contains(255) && !r.contains(249));
|
||||
val first: u8 = 250;
|
||||
val last: u8 = 255;
|
||||
var top := first..=last;
|
||||
var counted: u64 = 0;
|
||||
while top.next() is some(x) {
|
||||
counted++;
|
||||
}
|
||||
t.expects(counted == 6);
|
||||
val low: i8 = -128;
|
||||
val high: i8 = 127;
|
||||
t.expects((low..=high).count() == 256 && (-3..3).sum() == -3);
|
||||
t.expects((0xFFFFFFFFFFFFFFFDu..=0xFFFFFFFFFFFFFFFFu).count() == 3);
|
||||
|
||||
var walk := 0..10u;
|
||||
t.expects(walk.nth(3) is some(x) && x == 3 && walk.next() is some(y) && y == 4);
|
||||
t.expects(walk.nth(9) is not some(_) && walk.is_empty());
|
||||
|
||||
var sum: u64 = 0;
|
||||
for i in 0..=4u {
|
||||
sum += i;
|
||||
}
|
||||
for i in last..=last {
|
||||
sum += i as u64;
|
||||
}
|
||||
t.expects(sum == 265);
|
||||
}
|
||||
|
||||
@test def ranges_count_through_the_members_of_enums(t: &mut tester): void {
|
||||
# Each value once, in order, passing over those no member has.
|
||||
t.expects(spaced(shade::deep..=shade::glare).span == "deep dim bright glare");
|
||||
t.expects(spaced((shade::deep..shade::glare).rev()).span == "bright dim deep");
|
||||
t.expects(spaced((shade::deep..=shade::glare).step(2)).span == "deep bright");
|
||||
val shades := shade::dim..=shade::glare;
|
||||
t.expects(shades.length == 3 && shades.contains(shade::bright) && !shades.contains(shade::deep));
|
||||
t.expects((shade::glare..shade::deep).count() == 0 && (shade::plain..=shade::dim).count() == 1);
|
||||
|
||||
var along := shade::deep..=shade::glare;
|
||||
t.expects(along.nth(2) is some(s) && s == shade::bright && along.remaining() == 1);
|
||||
t.expects(along.next_back() is some(last) && last == shade::glare && along.is_empty());
|
||||
|
||||
var walked := 0;
|
||||
for s in shade::deep..shade::glare {
|
||||
walked = walked * 10 + (s as i64 + 4);
|
||||
}
|
||||
t.expects(walked == 126);
|
||||
}
|
||||
|
||||
@test def text_is_walked_lazily(t: &mut tester): void {
|
||||
val text: strview = "a,,b,c";
|
||||
t.expects(text.split(',').to_string("|").span == "a||b|c" && text.split(',').rev().to_string("|").span == "c|b||a");
|
||||
t.expects("".split(',').count() == 1 && ",".split(',').count() == 2);
|
||||
val parts := text.split(',').to_vector();
|
||||
t.expects(parts.length == 4 && parts[3] == "c");
|
||||
|
||||
val doc: strview = "one\r\ntwo\n\nthree\n";
|
||||
t.expects(doc.lines().to_string("|").span == "one|two||three");
|
||||
t.expects("".lines().count() == 0 && "x".lines().count() == 1 && "\n".lines().count() == 1);
|
||||
t.expects(" hello wide\tworld \n".words().to_string("|").span == "hello|wide|world" && " \t".words().count() == 0);
|
||||
|
||||
val utf: strview = "aé€😀";
|
||||
t.expects(utf.chars().map(def(c): u64 => c as u64).to_string(" ").span == "97 233 8364 128512");
|
||||
var bad: u8[6] = [0x61, 0xC3, 0x28, 0xFF, 0xE2, 0x82];
|
||||
val broken: strview = strview::over(&bad[0] as *u8, 6);
|
||||
t.expects(broken.chars().map(def(c): u64 => c as u64).to_string(" ").span == "97 65533 40 65533 65533 65533");
|
||||
var overlong: u8[2] = [0xC0, 0x80];
|
||||
val long: strview = strview::over(&overlong[0] as *u8, 2);
|
||||
t.expects(long.chars().count() == 2);
|
||||
}
|
||||
|
||||
@test def containers_are_made_of_iterators(t: &mut tester): void {
|
||||
var d := dict::<u64, u64>::new();
|
||||
d.set(1, 10);
|
||||
d.set(2, 20);
|
||||
d.set(3, 30);
|
||||
t.expects(d.keys().copied().sum() == 6 && d.values().copied().sum() == 60 && d.keys().remaining() == 3);
|
||||
|
||||
val squares := dict::from((0..4u).map(def(i: u64): pair<u64, u64> => pair::<u64, u64> { first = i, second = i * i }));
|
||||
t.expects(squares.length == 4 && squares[3] == 9);
|
||||
(5..7u).map(def(i: u64): pair<u64, u64> => pair::<u64, u64> { first = i, second = i }).into(&mut d);
|
||||
t.expects(d.length == 5 && d[6] == 6);
|
||||
|
||||
var v := vector::from((0..10u).filter(def(x) => x % 3 != 0));
|
||||
t.expects(v.iter().to_string(" ").span == "1 2 4 5 7 8");
|
||||
val taken := v.drain(2..5).to_vector();
|
||||
t.expects(taken.iter().to_string(" ").span == "4 5 7" && v.iter().to_string(" ").span == "1 2 8");
|
||||
|
||||
tickets_closed = 0;
|
||||
var held := vector::<ticket>::new();
|
||||
for i in 1..=5u {
|
||||
held.append(ticket { n = i });
|
||||
}
|
||||
{
|
||||
var some_of := held.drain(1..=3);
|
||||
t.expects(some_of.remaining() == 3);
|
||||
t.expects(some_of.next_back() is some(x) && x.n == 4);
|
||||
}
|
||||
t.expects(tickets_closed == 3 && held.length == 2 && held[1].n == 5);
|
||||
|
||||
var joined := string::new(nothing {});
|
||||
"a b c".split(' ').into(&mut joined);
|
||||
t.expects(joined.span == "abc");
|
||||
|
||||
var c := chain::<u64>::new();
|
||||
c.push_back(1);
|
||||
c.push_back(2);
|
||||
c.push_back(3);
|
||||
val read := &c;
|
||||
t.expects(read.iter().rev().copied().to_string(" ").span == "3 2 1" && read.iter().remaining() == 3);
|
||||
var l := list::<u64>::new();
|
||||
l.push_front(5);
|
||||
l.push_front(6);
|
||||
val lread := &l;
|
||||
t.expects(lread.iter().copied().sum() == 11 && lread.iter().remaining() == 2);
|
||||
}
|
||||
|
||||
# A ring over a fixed array, as `deque` is, which writes no iterator of its own:
|
||||
# core's walk it through its `at`.
|
||||
struct ring : indexable<u64, u64>, assignable<u64, u64>, iterable<u64> {
|
||||
var items: u64[5];
|
||||
var head: u64;
|
||||
var count: u64;
|
||||
}
|
||||
|
||||
def ring::at(&this, i: u64): &u64 { return &this.items[(this.head + i) % 5]; }
|
||||
def ring::at(&mut this, i: u64): &mut u64 { return &mut this.items[(this.head + i) % 5]; }
|
||||
|
||||
type ring::iterator = positions_iterator<ring, u64>;
|
||||
type ring::mutator = position_mutator<ring, u64>;
|
||||
|
||||
def ring::iter(&this): positions_iterator<ring, u64> {
|
||||
return positions_iterator::<ring, u64>::over(this, this.count);
|
||||
}
|
||||
|
||||
def ring::iter(&mut this): position_mutator<ring, u64> {
|
||||
return position_mutator::<ring, u64>::over(this, this.count);
|
||||
}
|
||||
|
||||
# The first element of whatever is iterable, through the iterator its bound names.
|
||||
def first_walked<C>(c: &C): u64 where C: iterable<u64> {
|
||||
var walk: C::iterator = c.iter();
|
||||
return walk.next() is some(x) ? x : 0;
|
||||
}
|
||||
|
||||
# Adds to each of the first elements of whatever is written by position.
|
||||
def add_each<C>(c: &mut C, count: u64, n: u64): void where C: assignable<u64, u64> {
|
||||
for i in 0..count {
|
||||
c[i] += n;
|
||||
}
|
||||
}
|
||||
|
||||
@test def containers_indexed_by_position_need_no_iterators(t: &mut tester): void {
|
||||
var r := ring { items = [30, 40, 0, 10, 20], head = 3, count = 4 };
|
||||
val read := &r;
|
||||
t.expects(read.iter().to_string(" ").span == "10 20 30 40" && read.iter().rev().to_string(" ").span == "40 30 20 10");
|
||||
t.expects(read.iter().remaining() == 4 && read.iter().skip(1).remaining() == 3 && first_walked(read) == 10);
|
||||
|
||||
var weighed: u64 = 0;
|
||||
for i, x in r {
|
||||
weighed += (i + 1) * x;
|
||||
}
|
||||
t.expects(weighed == 300);
|
||||
|
||||
for &mut x in r {
|
||||
x += 1;
|
||||
}
|
||||
var writes := r.iter();
|
||||
if writes.next_back() is some(&mut last) {
|
||||
last = 0;
|
||||
}
|
||||
t.expects(read.iter().to_string(" ").span == "11 21 31 0" && writes.remaining() == 3);
|
||||
add_each(&mut r, r.count, 5);
|
||||
t.expects(read.iter().to_string(" ").span == "16 26 36 5");
|
||||
|
||||
# The same iterators walk a container that lends its own.
|
||||
var v := vector::<u64>::new();
|
||||
v.append(1);
|
||||
v.append(2);
|
||||
v.append(3);
|
||||
var each := position_mutator::<vector<u64>, u64>::over(&mut v, v.length);
|
||||
while each.next() is some(&mut x) {
|
||||
x *= 10;
|
||||
}
|
||||
add_each(&mut v, v.length, 1);
|
||||
t.expects(positions_iterator::<vector<u64>, u64>::over(&v, v.length).to_string(" ").span == "11 21 31");
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
# Runs the tests of `core` and `system`, from the root of the repository, where
|
||||
# the tests that read files find them, with the standard library's repository
|
||||
# beside this one. `blossom test` runs them as `sakurac.core`, or:
|
||||
#
|
||||
# sakurac run --lib std=../std tests/core/*.sakura
|
||||
#
|
||||
# Add `-- --only TEXT` to run those whose name holds the text, and `-- --here` to
|
||||
# run them in one program, as a debugger wants. Built with `sakura build`, they run
|
||||
# as an executable the same way.
|
||||
import std::io;
|
||||
import std::process;
|
||||
import system;
|
||||
import std::testing;
|
||||
|
||||
def main(args: span<strview>): void {
|
||||
exit(tester::run(args));
|
||||
}
|
||||
|
||||
# Whether running the function stops the program. It runs in a copy of the program
|
||||
# that writes nothing, so that this one goes on and the report of the stop is not
|
||||
# mixed into the tests'.
|
||||
def stops(run: def(): void): bool {
|
||||
when os == windows {
|
||||
val stopped := copied(run);
|
||||
return !(stopped.exited && stopped.code == 0);
|
||||
}
|
||||
val child := fork();
|
||||
if child == 0 {
|
||||
val out: fd = fd::stdout;
|
||||
val err: fd = fd::stderr;
|
||||
out.close();
|
||||
err.close();
|
||||
run();
|
||||
exit(0);
|
||||
}
|
||||
var status: process_status;
|
||||
return wait(child, &mut status) >= 0 && !(status.exited && status.code == 0);
|
||||
}
|
||||
|
||||
# Windows cannot copy a program as it runs, as `system::fork` does, so what the tests
|
||||
# run in a copy of their own runs there in a copy started again, as `std::testing`
|
||||
# starts the copy each test runs in.
|
||||
when os == windows {
|
||||
# The variable a copy is given, listing how the copies before it stopped.
|
||||
val copy_variable: strview = "SAKURA_TEST_COPY";
|
||||
|
||||
# How many functions `copied` has been asked to run, in this program or a copy,
|
||||
# and how the copies running each stopped, as `exited,code,signal;` each.
|
||||
var copies_asked: u64 = 0;
|
||||
var copies_seen: string = string::new(nothing{});
|
||||
|
||||
# Runs a function in a copy of the program, giving how the copy stopped. The
|
||||
# copy runs the test that asked again, writing nothing, and is told how each
|
||||
# copy before it stopped, which it gives where it is asked for them, so it goes
|
||||
# the way the test went here, though a check that fails asks again. It runs the
|
||||
# function asked for after them, then exits with zero.
|
||||
def copied(run: def(): void): system::process_status {
|
||||
copies_asked++;
|
||||
if process::variable(copy_variable) is some(given) {
|
||||
if replayed(given, copies_asked) is some(status) {
|
||||
return status;
|
||||
}
|
||||
run();
|
||||
system::exit(0);
|
||||
}
|
||||
|
||||
var device := path::parse(system::null_device) else (_) { return system::process_status {}; };
|
||||
var quiet := io::file::open(&device, open_flags::write) else (_) { return system::process_status {}; };
|
||||
val copy := system::respawn($"{copy_variable}={copies_seen.span}".span, system::fd::stdin, quiet.handle, quiet.handle);
|
||||
var status := system::process_status { exited = true, code = -1 };
|
||||
if copy > 0 {
|
||||
_ = system::wait(copy, &mut status);
|
||||
}
|
||||
copies_seen.append($"{status.exited ? 1 : 0},{status.code},{status.signal};".span);
|
||||
return status;
|
||||
}
|
||||
|
||||
# How the copy running the function asked for at a count stopped, as a copy's
|
||||
# variable lists it, or nothing for the one after those it lists.
|
||||
def replayed(given: strview, count: u64): maybe<system::process_status> {
|
||||
var seen := 0u;
|
||||
for entry in given.split(';') {
|
||||
if entry.length == 0 {
|
||||
continue;
|
||||
}
|
||||
seen++;
|
||||
if seen == count {
|
||||
val parts := entry.split(',').to_vector();
|
||||
return system::process_status {
|
||||
exited = parts[0] == "1",
|
||||
code = number_in(parts[1]) as i32,
|
||||
signal = number_in(parts[2]) as i32
|
||||
};
|
||||
}
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
# The integer text says, or zero where it says none.
|
||||
def number_in(text: strview): i64 {
|
||||
if integer::parse::<i64>(text) is value(number) {
|
||||
return number;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
# A directory files may be made in for a while, as the system's `TEMP` names it.
|
||||
def temporary(): strview {
|
||||
return process::variable("TEMP") else { return process::variable("TMP") else { return "."; }; };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
# Tests of std's memory routines against the same work done a byte at a time:
|
||||
# every length up to past where they work 16 bytes at a time, buffers that
|
||||
# overlap either way, and bytes differing at every place.
|
||||
|
||||
import std::math;
|
||||
import std::testing;
|
||||
|
||||
# Fills a buffer with bytes that differ from place to place, its state wrapping
|
||||
# as it's mixed.
|
||||
def scramble(at: *mut u8, count: u64, seed: u64): void {
|
||||
var state := math::wrapping_add(math::wrapping_mul(seed, 0x9E3779B97F4A7C15), 1);
|
||||
for i in 0..count {
|
||||
state = state ^ (state << 13);
|
||||
state = state ^ (state >> 7);
|
||||
state = state ^ (state << 17);
|
||||
at[i] = (state & 0xFF) as u8;
|
||||
}
|
||||
}
|
||||
|
||||
# Whether two buffers hold the same bytes.
|
||||
def same_bytes(a: *u8, b: *u8, count: u64): bool {
|
||||
for i in 0..count {
|
||||
return false if a[i] != b[i];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@test def copies_agree_with_bytes_where_buffers_overlap_or_not(t: &mut tester): void {
|
||||
val room: u64 = 256;
|
||||
val made := raw_allocate(room);
|
||||
val want := raw_allocate(room);
|
||||
for length in 0..101u {
|
||||
for from in 0..40u {
|
||||
for to in 0..40u {
|
||||
scramble(made, room, length * 131 + from * 7 + to);
|
||||
scramble(want, room, length * 131 + from * 7 + to);
|
||||
# The bytes copied, as `memmove` gives them: read whole before any is written.
|
||||
var held: u8[128];
|
||||
for i in 0..length {
|
||||
held[i] = want[64 + from + i];
|
||||
}
|
||||
for i in 0..length {
|
||||
want[64 + to + i] = held[i];
|
||||
}
|
||||
memcpy(made + 64 + to, made + 64 + from, length);
|
||||
t.expects(same_bytes(made, want, room));
|
||||
}
|
||||
}
|
||||
}
|
||||
raw_release(made);
|
||||
raw_release(want);
|
||||
}
|
||||
|
||||
@test def setting_agrees_with_bytes(t: &mut tester): void {
|
||||
val room: u64 = 160;
|
||||
val made := raw_allocate(room);
|
||||
val want := raw_allocate(room);
|
||||
for length in 0..101u {
|
||||
for at in 0..20u {
|
||||
scramble(made, room, length + at);
|
||||
scramble(want, room, length + at);
|
||||
for i in 0..length {
|
||||
want[at + i] = 0xA5;
|
||||
}
|
||||
memset(made + at, 0xA5, length);
|
||||
t.expects(same_bytes(made, want, room));
|
||||
}
|
||||
}
|
||||
raw_release(made);
|
||||
raw_release(want);
|
||||
}
|
||||
|
||||
@test def comparing_agrees_with_bytes(t: &mut tester): void {
|
||||
val a := raw_allocate(128);
|
||||
val b := raw_allocate(128);
|
||||
for length in 0..101u {
|
||||
scramble(a, 128, length);
|
||||
for i in 0..128u {
|
||||
b[i] = a[i];
|
||||
}
|
||||
t.expects(memcmp(a, b, length) == 0);
|
||||
for place in 0..length {
|
||||
for other in [0 as u8, 0x7F, 0x80, 0xFF] {
|
||||
b[place] = other;
|
||||
val want: i64 = a[place] == other ? 0 : (a[place] < other ? -1 : 1);
|
||||
t.expects(memcmp(a, b, length) == want);
|
||||
}
|
||||
b[place] = a[place];
|
||||
}
|
||||
}
|
||||
raw_release(a);
|
||||
raw_release(b);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
# Tests of operators as calls of the methods that give them: each alone, between
|
||||
# operands of different types, through compound assignment, and in generic code by
|
||||
# the traits of std and those a program composes of them.
|
||||
import std::testing;
|
||||
|
||||
|
||||
# A length of time, which adds to another, scales by a number, and divides into a ratio.
|
||||
struct stretch : additive, ordered {
|
||||
var ns: i64;
|
||||
}
|
||||
|
||||
def stretch::equals(&this, other: &stretch): bool { return this.ns == other.ns; }
|
||||
def stretch::compare(&this, other: &stretch): i64 { return this.ns - other.ns; }
|
||||
def stretch::add(&this, other: &stretch): stretch { return stretch { ns = this.ns + other.ns }; }
|
||||
def stretch::sub(&this, other: &stretch): stretch { return stretch { ns = this.ns - other.ns }; }
|
||||
def stretch::negate(&this): stretch { return stretch { ns = -this.ns }; }
|
||||
def stretch::mul(&this, by: &i64): stretch { return stretch { ns = this.ns * by }; }
|
||||
def stretch::mul(&this, by: &f64): stretch { return stretch { ns = (this.ns as f64 * by) as i64 }; }
|
||||
def stretch::div(&this, by: &i64): stretch { return stretch { ns = this.ns / by }; }
|
||||
def stretch::div(&this, by: &stretch): f64 { return this.ns as f64 / by.ns as f64; }
|
||||
|
||||
# A moment, which moves by a length of time, and is a length of time from another.
|
||||
struct moment : ordered {
|
||||
var ns: i64;
|
||||
}
|
||||
|
||||
def moment::equals(&this, other: &moment): bool { return this.ns == other.ns; }
|
||||
def moment::compare(&this, other: &moment): i64 { return this.ns - other.ns; }
|
||||
def moment::add(&this, by: &stretch): moment { return moment { ns = this.ns + by.ns }; }
|
||||
def moment::sub(&this, by: &stretch): moment { return moment { ns = this.ns - by.ns }; }
|
||||
def moment::sub(&this, since: &moment): stretch { return stretch { ns = this.ns - since.ns }; }
|
||||
|
||||
# A vector, which a number scales from either side.
|
||||
struct arrow : additive {
|
||||
var x: f64;
|
||||
var y: f64;
|
||||
}
|
||||
|
||||
def arrow::equals(&this, other: &arrow): bool { return this.x == other.x && this.y == other.y; }
|
||||
def arrow::add(&this, other: &arrow): arrow { return arrow { x = this.x + other.x, y = this.y + other.y }; }
|
||||
def arrow::sub(&this, other: &arrow): arrow { return arrow { x = this.x - other.x, y = this.y - other.y }; }
|
||||
def arrow::negate(&this): arrow { return arrow { x = -this.x, y = -this.y }; }
|
||||
def arrow::mul(&this, by: &f64): arrow { return arrow { x = this.x * by, y = this.y * by }; }
|
||||
def arrow::mul(&this, with: &arrow): f64 { return this.x * with.x + this.y * with.y; }
|
||||
def f64::mul(&this, of: &arrow): arrow { return of * this; }
|
||||
|
||||
# How often a ledger was added to, which only adds.
|
||||
var ledgers_added: u64 = 0;
|
||||
|
||||
struct ledger {
|
||||
var sum: i64;
|
||||
}
|
||||
|
||||
def ledger::add(&this, other: &ledger): ledger {
|
||||
ledgers_added++;
|
||||
return ledger { sum = this.sum + other.sum };
|
||||
}
|
||||
|
||||
# What holds a ledger behind a property.
|
||||
struct purse {
|
||||
var kept: ledger;
|
||||
}
|
||||
|
||||
var purse::all: ledger {
|
||||
get => this.kept;
|
||||
set => this.kept = value;
|
||||
}
|
||||
|
||||
# What scales by an `S`, beside adding: a trait of a program's own, composing std's.
|
||||
trait stretches<S> : additive {
|
||||
def mul(&this, by: &S): self;
|
||||
}
|
||||
|
||||
def blend<V, S>(a: V, b: V, t: S): V where V: stretches<S> {
|
||||
return a + (b - a) * t;
|
||||
}
|
||||
|
||||
def gathered<T>(items: span<T>, from: T): T where T: addable {
|
||||
var all := from;
|
||||
for &each in items { all += each; }
|
||||
return all;
|
||||
}
|
||||
|
||||
def mirrored<T>(a: T, b: T): T where T: additive {
|
||||
return a == b ? a : -(a - b);
|
||||
}
|
||||
|
||||
def product_of<T>(a: T, b: T): T where T: multiplicative {
|
||||
return a * b;
|
||||
}
|
||||
|
||||
def shared_out<T>(whole: T, by: T): T where T: divisible, modular, addable {
|
||||
return whole / by + whole % by;
|
||||
}
|
||||
|
||||
def second(count: i64): stretch { return stretch { ns = count * 1000000000 }; }
|
||||
|
||||
const long_pause: stretch = second(1) + second(2) * 3 - -second(1);
|
||||
|
||||
@test def an_operator_is_a_call_of_its_method(t: &mut tester): void {
|
||||
val a := stretch { ns = 250 };
|
||||
val b := stretch { ns = 100 };
|
||||
t.expects((a + b).ns == 350 && (a - b).ns == 150 && (-a).ns == -250);
|
||||
t.expects(a + b == b + a && a - b > b - a && a + b - b == a);
|
||||
|
||||
# One with only `add` has `+`, and nothing else.
|
||||
ledgers_added = 0;
|
||||
val one := ledger { sum = 1 };
|
||||
t.expects((one + one + one).sum == 3 && ledgers_added == 2);
|
||||
}
|
||||
|
||||
@test def operands_and_results_are_what_the_method_declares(t: &mut tester): void {
|
||||
val began := moment { ns = 100 };
|
||||
val now := moment { ns = 350 };
|
||||
val waited: stretch = now - began;
|
||||
val due: moment = began + waited * 2;
|
||||
t.expects(waited.ns == 250 && due.ns == 600 && (due - waited).ns == 350);
|
||||
|
||||
# A constant takes the type of the parameter it is given to, and of two
|
||||
# overloads the one it is alone.
|
||||
t.expects((waited * 2).ns == 500 && (waited * 0.5).ns == 125 && (waited / 5).ns == 50);
|
||||
val count: u8 = 3;
|
||||
t.expects((waited * count as i64).ns == 750);
|
||||
|
||||
# A result of a third type.
|
||||
val ratio: f64 = (waited * 3) / waited;
|
||||
t.expects(ratio == 3.0 && arrow { x = 1.0, y = 2.0 } * arrow { x = 3.0, y = 4.0 } == 11.0);
|
||||
|
||||
# References are read through, on either side.
|
||||
val later: &moment = &due;
|
||||
val by: &stretch = &waited;
|
||||
t.expects((later - by).ns == 350 && (later - began).ns == 500 && (by + by).ns == 500);
|
||||
}
|
||||
|
||||
@test def a_number_on_the_left_asks_its_own_type(t: &mut tester): void {
|
||||
val v := arrow { x = 1.5, y = 2.0 };
|
||||
val a := v * 2.0;
|
||||
val b := 2.0 * v;
|
||||
val scale := 4.0;
|
||||
t.expects(a == b && a.x == 3.0 && (scale * v).y == 8.0 && (0.5 * v * 2.0) == v);
|
||||
|
||||
# The number is still the number it was: its own methods are beside the program's.
|
||||
t.expects(2.5.mul(&2.0) == 5.0 && 2.5 * 2.0 == 5.0 && scale.mul(&scale) == 16.0);
|
||||
t.expects(2.5 is numeric && 2.5 is multiplicative && product_of(1.5, 4.0) == 6.0);
|
||||
}
|
||||
|
||||
@test def compound_assignment_writes_what_the_method_gives(t: &mut tester): void {
|
||||
var due := moment { ns = 100 };
|
||||
due += stretch { ns = 50 };
|
||||
due -= stretch { ns = 20 };
|
||||
t.expects(due.ns == 130);
|
||||
|
||||
var waited := stretch { ns = 10 };
|
||||
waited += waited;
|
||||
waited *= 3;
|
||||
waited /= 4;
|
||||
t.expects(waited.ns == 15);
|
||||
|
||||
# Through a property, an element, and a reference.
|
||||
ledgers_added = 0;
|
||||
var held := purse { kept = ledger { sum = 2 } };
|
||||
held.all += ledger { sum = 5 };
|
||||
var many := [ledger { sum = 1 }, ledger { sum = 10 }];
|
||||
many[1] += many[0];
|
||||
val through: &mut ledger = &mut many[0];
|
||||
through += held.kept;
|
||||
t.expects(held.kept.sum == 7 && many[1].sum == 11 && many[0].sum == 8 && ledgers_added == 3);
|
||||
}
|
||||
|
||||
@test def generic_code_has_operators_through_its_bounds(t: &mut tester): void {
|
||||
val low := arrow { x = 0.0, y = 0.0 };
|
||||
val high := arrow { x = 2.0, y = 4.0 };
|
||||
t.expects(blend(1.0, 3.0, 0.5) == 2.0 && blend(low, high, 0.5) == arrow { x = 1.0, y = 2.0 });
|
||||
|
||||
t.expects(gathered([1, 2, 3][0:3], 0) == 6 && gathered([1.5, 2.5][0:2], 0.0) == 4.0);
|
||||
t.expects(gathered([second(1), second(2)][0:2], second(0)) == second(3));
|
||||
t.expects(mirrored(7, 3) == -4 && mirrored(second(5), second(2)) == second(-3) && mirrored(high, high) == high);
|
||||
t.expects(product_of(3, 4) == 12 && shared_out(17, 5) == 5 && shared_out(7.5, 2.0) == 5.25);
|
||||
|
||||
# What satisfies which: numbers all of them, and a type what it declares.
|
||||
t.expects(1 is additive && 1 is multiplicative && 1 is numeric && 1.5 is divisible && 1 is modular);
|
||||
t.expects(second(1) is additive && second(1) is addable && !(second(1) is numeric));
|
||||
t.expects(high is additive && !(high is multiplicative) && !(true is addable) && !(moment { ns = 0 } is addable));
|
||||
}
|
||||
|
||||
@test def operators_of_methods_make_constants(t: &mut tester): void {
|
||||
t.expects(long_pause == second(8));
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
# Tests of `core`'s owner of heap memory, `box`, owned alone, which closes what
|
||||
# it holds exactly once. `rc` and `arc`, owned by every copy, are std's, and
|
||||
# tested there.
|
||||
|
||||
import std::testing;
|
||||
|
||||
|
||||
# How many values the tests gave boxes have been closed.
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
struct linked {
|
||||
var value: u64;
|
||||
var next: maybe<box<linked>>;
|
||||
}
|
||||
|
||||
@test def boxes_and_maybe_boxes_are_one_word(t: &mut tester): void {
|
||||
t.expects(size_of::<box<owned>>() == 8 && size_of::<maybe<box<owned>>>() == 8);
|
||||
val none_held: maybe<box<owned>> = nothing {};
|
||||
t.expects(!(none_held is some));
|
||||
}
|
||||
|
||||
@test def a_box_closes_its_value_once(t: &mut tester): void {
|
||||
val before := owned_closed.load();
|
||||
{
|
||||
var a := box::<owned>::new(owned { mark = 1 });
|
||||
a.get().mark = 2;
|
||||
t.expects(a.holds() && a.get().mark == 2);
|
||||
|
||||
# Moving leaves the box moved from empty, so it closes nothing.
|
||||
var b := move(&mut a);
|
||||
t.expects(!a.holds() && b.holds() && b.get().mark == 2);
|
||||
a.close();
|
||||
t.expects(owned_closed.load() == before);
|
||||
|
||||
# Taking the value leaves the box empty and the value its taker's.
|
||||
val taken := b.take();
|
||||
t.expects(!b.holds() && taken.mark == 2 && owned_closed.load() == before);
|
||||
}
|
||||
t.expects(owned_closed.load() == before + 1);
|
||||
|
||||
{
|
||||
val c := box::<owned>::new(owned { mark = 3 });
|
||||
}
|
||||
t.expects(owned_closed.load() == before + 2);
|
||||
}
|
||||
|
||||
@test def boxes_link_a_list_closed_with_its_front(t: &mut tester): void {
|
||||
var front: maybe<box<linked>> = nothing {};
|
||||
for i in 0..100u {
|
||||
front = box::<linked>::new(linked { value = i, next = move(&mut front) });
|
||||
}
|
||||
var total: u64 = 0;
|
||||
var count: u64 = 0;
|
||||
var at: maybe<&linked> = nothing {};
|
||||
if front is some(&first) { at = first.get(); }
|
||||
while at is some(&each) {
|
||||
total += each.value;
|
||||
count++;
|
||||
at = nothing {};
|
||||
if each.next is some(&next) { at = next.get(); }
|
||||
}
|
||||
t.expects(total == 4950 && count == 100);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
# Tests of what is closed where its scope ends: a type naming `owning`, and what holds
|
||||
# one, which is `closeable`. A `close` alone is only a method, and a reference or a
|
||||
# pointer owns nothing.
|
||||
import std::testing;
|
||||
|
||||
|
||||
# How many values holding a number have been closed.
|
||||
var shut: u64 = 0;
|
||||
|
||||
struct named : owning {
|
||||
var n: u64;
|
||||
}
|
||||
|
||||
def named::close(&mut this): void {
|
||||
if this.n != 0 {
|
||||
shut++;
|
||||
this.n = 0;
|
||||
}
|
||||
}
|
||||
|
||||
struct shaped {
|
||||
var n: u64;
|
||||
}
|
||||
|
||||
def shaped::close(&mut this): void {
|
||||
if this.n != 0 {
|
||||
shut++;
|
||||
this.n = 0;
|
||||
}
|
||||
}
|
||||
|
||||
struct wraps {
|
||||
var inner: named;
|
||||
}
|
||||
|
||||
def kind<T>(): span<u8> {
|
||||
if const T is owning { return "owning"; }
|
||||
if const T is closeable { return "closeable"; }
|
||||
return "plain";
|
||||
}
|
||||
|
||||
@test def only_what_names_owning_is_closed(t: &mut tester): void {
|
||||
t.expects(kind::<named>() == "owning" && kind::<wraps>() == "closeable" && kind::<named[2]>() == "closeable");
|
||||
t.expects(kind::<shaped>() == "plain" && kind::<&mut named>() == "plain" && kind::<*mut named>() == "plain");
|
||||
|
||||
shut = 0;
|
||||
{
|
||||
val a := named { n = 1 };
|
||||
val b := shaped { n = 1 };
|
||||
val c := wraps { inner = named { n = 1 } };
|
||||
}
|
||||
t.expects(shut == 2);
|
||||
|
||||
# A `close` is still called by hand, through a reference too.
|
||||
var d := shaped { n = 1 };
|
||||
val through: &mut shaped = &mut d;
|
||||
through.close();
|
||||
t.expects(shut == 3 && d.n == 0);
|
||||
}
|
||||
|
||||
# Gives values counting down to one, then nothing.
|
||||
struct countdown {
|
||||
var left: u64;
|
||||
}
|
||||
|
||||
def countdown::next(&mut this): maybe<named> {
|
||||
if this.left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
this.left--;
|
||||
return named { n = this.left + 1 };
|
||||
}
|
||||
|
||||
def first_of(from: &mut countdown): named {
|
||||
if from.next() is some(got) {
|
||||
return got;
|
||||
}
|
||||
return named {};
|
||||
}
|
||||
|
||||
@test def union_fields_are_taken_from_what_a_call_made(t: &mut tester): void {
|
||||
# Named by value, each is taken out of what the call gave, and closed once, where the
|
||||
# turn ends, a `continue` goes on, or a `break` leaves.
|
||||
shut = 0;
|
||||
var from := countdown { left = 5 };
|
||||
var seen: u64 = 0;
|
||||
while from.next() is some(got) {
|
||||
if got.n == 4 {
|
||||
continue;
|
||||
}
|
||||
seen += got.n;
|
||||
if got.n == 2 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
t.expects(seen == 10 && shut == 4);
|
||||
|
||||
from.left = 1;
|
||||
if from.next() is some(got) {
|
||||
seen += got.n;
|
||||
}
|
||||
from.left = 1;
|
||||
match from.next() {
|
||||
some(got) => seen += got.n;
|
||||
else => {}
|
||||
}
|
||||
t.expects(seen == 12 && shut == 6);
|
||||
|
||||
# Given away, by `return` or as an arm's value, it is closed by what took it.
|
||||
from.left = 2;
|
||||
{
|
||||
val kept := first_of(&mut from);
|
||||
val also: named = match from.next() {
|
||||
some(got) => got,
|
||||
else => named {},
|
||||
};
|
||||
t.expects(kept.n == 2 && also.n == 1 && shut == 6);
|
||||
}
|
||||
t.expects(shut == 8);
|
||||
|
||||
# `is not` gives it to the rest of the block.
|
||||
from.left = 1;
|
||||
{
|
||||
if from.next() is not some(got) {
|
||||
return;
|
||||
}
|
||||
t.expects(got.n == 1 && shut == 8);
|
||||
}
|
||||
t.expects(shut == 9);
|
||||
}
|
||||
|
||||
@test def a_while_closes_what_its_condition_made_each_turn(t: &mut tester): void {
|
||||
# Named in place, each value is still the one the call gave, closed before the
|
||||
# condition makes the next.
|
||||
shut = 0;
|
||||
var from := countdown { left = 4 };
|
||||
var seen: u64 = 0;
|
||||
while from.next() is some(&got) {
|
||||
if got.n == 3 {
|
||||
continue;
|
||||
}
|
||||
seen += got.n;
|
||||
}
|
||||
t.expects(seen == 7 && shut == 4);
|
||||
}
|
||||
|
||||
@test def names_are_given_where_their_test_holds(t: &mut tester): void {
|
||||
# What the left of `&&` names is the right's to use, and of the branch, and each value
|
||||
# a test takes is closed once, whichever tests a short circuit leaves unrun.
|
||||
shut = 0;
|
||||
var from := countdown { left = 3 };
|
||||
var seen: u64 = 0;
|
||||
if from.next() is some(a) && from.next() is some(b) && a.n > b.n {
|
||||
seen = a.n * 10 + b.n;
|
||||
}
|
||||
t.expects(seen == 32 && shut == 2);
|
||||
if from.next() is some(a) && from.next() is some(b) {
|
||||
seen = 0;
|
||||
}
|
||||
t.expects(seen == 32 && shut == 3);
|
||||
|
||||
# `||` gives its right what an `is not` test names, and `!` turns a test around.
|
||||
from.left = 2;
|
||||
val small := from.next() is not some(c) || c.n < 3;
|
||||
t.expects(small && shut == 4);
|
||||
from.left = 1;
|
||||
{
|
||||
if !(from.next() is some(d)) {
|
||||
seen = 0;
|
||||
} else {
|
||||
seen = d.n;
|
||||
}
|
||||
}
|
||||
t.expects(seen == 1 && shut == 5);
|
||||
|
||||
# A guard gives the rest of the block what it names.
|
||||
from.left = 2;
|
||||
{
|
||||
if from.next() is not some(e) || from.next() is not some(f) {
|
||||
return;
|
||||
}
|
||||
seen = e.n * 10 + f.n;
|
||||
}
|
||||
t.expects(seen == 21 && shut == 7);
|
||||
}
|
||||
|
||||
@test def bindings_holding_values_are_moved_from(t: &mut tester): void {
|
||||
# A value a binding took is its own, so it is moved on, and the binding then closes
|
||||
# nothing, as a `var` moved from does.
|
||||
shut = 0;
|
||||
var from := countdown { left = 2 };
|
||||
{
|
||||
var kept := vector::<named>::new();
|
||||
while from.next() is some(got) {
|
||||
kept.append(move(got));
|
||||
}
|
||||
from.left = 1;
|
||||
match from.next() {
|
||||
some(got) => kept.append(move(got));
|
||||
else => {}
|
||||
}
|
||||
from.left = 2;
|
||||
for each in from {
|
||||
kept.append(move(each));
|
||||
}
|
||||
t.expects(kept.length == 5 && shut == 0);
|
||||
}
|
||||
t.expects(shut == 5);
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
# Tests of what references and pointers satisfy. A reference satisfies the traits of
|
||||
# what it refers to, called through it, so a generic given one borrows what it would
|
||||
# otherwise own, and it is compared and hashed as what it refers to. A pointer is an
|
||||
# address: it is compared and hashed as one, and what it points at is reached by
|
||||
# dereferencing it.
|
||||
import std::containers;
|
||||
import std::testing;
|
||||
|
||||
|
||||
# Something written to, a number at a time.
|
||||
trait sink {
|
||||
def put(&mut this, n: u64): void;
|
||||
def put_twice(&mut this, n: u64): void { this.put(n); this.put(n); }
|
||||
}
|
||||
|
||||
# Something whose size is read.
|
||||
trait sized {
|
||||
def size(&this): u64;
|
||||
}
|
||||
|
||||
# How many tallies holding a count have been closed.
|
||||
var tallies_closed: u64 = 0;
|
||||
|
||||
struct tally : sink, sized, owning {
|
||||
var n: u64;
|
||||
}
|
||||
|
||||
def tally::put(&mut this, n: u64): void { this.n += n; }
|
||||
def tally::size(&this): u64 { return this.n; }
|
||||
|
||||
def tally::close(&mut this): void {
|
||||
if this.n != 0 {
|
||||
tallies_closed++;
|
||||
this.n = 0;
|
||||
}
|
||||
}
|
||||
|
||||
# A sink that passes each number on to what it holds, owned or borrowed, and closes
|
||||
# it where it owns what closes.
|
||||
struct relay<S> : sink where S: sink {
|
||||
var to: S;
|
||||
}
|
||||
|
||||
def relay<S>::put(&mut this, n: u64): void {
|
||||
this.to.put(n);
|
||||
}
|
||||
|
||||
# Puts a number through a reference to the trait, made from the field.
|
||||
def relay<S>::put_through_trait(&mut this, n: u64): void {
|
||||
val to: &mut sink = &mut this.to;
|
||||
to.put(n);
|
||||
}
|
||||
|
||||
def relay_to<S>(to: S): relay<S> where S: sink {
|
||||
return relay::<S> { to = move(to) };
|
||||
}
|
||||
|
||||
def size_of_it<T>(it: T): u64 where T: sized {
|
||||
return it.size();
|
||||
}
|
||||
|
||||
# How many times a mark has been hashed by its own `hash`.
|
||||
var marks_hashed: u64 = 0;
|
||||
|
||||
struct mark : ordered, hashable {
|
||||
var n: u64;
|
||||
}
|
||||
|
||||
def mark::equals(&this, other: &mark): bool { return this.n == other.n; }
|
||||
def mark::compare(&this, other: &mark): i64 { return this.n as i64 - other.n as i64; }
|
||||
|
||||
def mark::hash(&this): u64 {
|
||||
marks_hashed++;
|
||||
return this.n;
|
||||
}
|
||||
|
||||
# Something holding a field named as one of a pointer's own methods.
|
||||
struct slot {
|
||||
var hash: u64;
|
||||
}
|
||||
|
||||
def larger<T>(a: T, b: T): T where T: ordered {
|
||||
if a < b { return b; }
|
||||
return a;
|
||||
}
|
||||
|
||||
def same<T>(a: T, b: T): bool where T: equatable {
|
||||
return a == b && a.equals(&b);
|
||||
}
|
||||
|
||||
def total<C>(items: C): u64 where C: iterable<u64> {
|
||||
var sum: u64 = 0;
|
||||
for &each in items {
|
||||
sum += each;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
def first_and_last<C>(items: C, count: u64): u64 where C: indexable<u64, u64> {
|
||||
return items[0] * 10 + items.at(count - 1);
|
||||
}
|
||||
|
||||
# How many elements lie between two pointers, by moving one along, as pointers do.
|
||||
def elements_between<P>(first: P, last: P): i64 where P: pointer {
|
||||
var at := first;
|
||||
at += 1;
|
||||
return last - at + 1;
|
||||
}
|
||||
|
||||
def no_pointer<P>(): P where P: pointer {
|
||||
var made: P;
|
||||
return made;
|
||||
}
|
||||
|
||||
def addressed<T>(): span<u8> {
|
||||
if const T is pointer { return "pointer"; }
|
||||
return "not";
|
||||
}
|
||||
|
||||
# Puts a value in a slot, whatever it is: given a reference, the slot refers anew.
|
||||
def put_in<T>(slot: &mut T, value: T): void {
|
||||
slot = value;
|
||||
}
|
||||
|
||||
def what<S>(): span<u8> {
|
||||
if const S is owning { return "owning"; }
|
||||
if const S is closeable { return "closeable"; }
|
||||
if const S is sink { return "sink"; }
|
||||
return "neither";
|
||||
}
|
||||
|
||||
@test def references_satisfy_what_they_refer_to(t: &mut tester): void {
|
||||
var kept := tally { n = 1 };
|
||||
var by_reference := relay_to(&mut kept);
|
||||
by_reference.put(2);
|
||||
by_reference.put_through_trait(3);
|
||||
t.expects(kept.n == 6);
|
||||
|
||||
# A pointer satisfies nothing of what it points at, but a reference through it does.
|
||||
var by_pointer := relay_to(&mut through((&mut kept) as *mut tally));
|
||||
by_pointer.put(4);
|
||||
by_pointer.put_through_trait(5);
|
||||
t.expects(kept.n == 15);
|
||||
|
||||
val as_trait: &mut sink = &mut kept;
|
||||
var by_trait := relay_to(as_trait);
|
||||
by_trait.put(6);
|
||||
by_trait.put_through_trait(7);
|
||||
t.expects(kept.n == 28);
|
||||
|
||||
# Relays nest, each borrowing the one inside it.
|
||||
var inner := relay_to(&mut kept);
|
||||
var outer := relay_to(&mut inner);
|
||||
outer.put(2);
|
||||
outer.put_through_trait(1);
|
||||
t.expects(kept.n == 31);
|
||||
|
||||
# Read through a reference that only reads, since `size` takes `&this`.
|
||||
t.expects(size_of_it(&kept) == 31 && size_of_it(&through((&kept) as *tally)) == 31);
|
||||
}
|
||||
|
||||
@test def references_take_the_types_their_referents_give(t: &mut tester): void {
|
||||
# A trait asking for types is satisfied through a reference with the referent's, as
|
||||
# `iterable` asks for an `iterator`, and an `@optional` method writing is not asked
|
||||
# of a reference that only reads.
|
||||
var numbers := vector::<u64>::new();
|
||||
numbers.append(4);
|
||||
numbers.append(5);
|
||||
numbers.append(6);
|
||||
val viewed: &vector<u64> = &numbers;
|
||||
t.expects(total(&viewed) == 15 && total(&mut numbers) == 15 && total(numbers.span) == 15);
|
||||
t.expects(first_and_last(&viewed, 3) == 46 && first_and_last(&numbers, 2) == 45);
|
||||
}
|
||||
|
||||
@test def references_close_nothing_they_refer_to(t: &mut tester): void {
|
||||
t.expects(what::<tally>() == "owning");
|
||||
t.expects(what::<relay<tally>>() == "closeable");
|
||||
t.expects(what::<&mut tally>() == "sink" && what::<*mut tally>() == "neither");
|
||||
t.expects(what::<relay<&mut tally>>() == "sink");
|
||||
|
||||
tallies_closed = 0;
|
||||
var lent := tally { n = 1 };
|
||||
{
|
||||
var borrowed := relay_to(&mut lent);
|
||||
borrowed.put(1);
|
||||
}
|
||||
t.expects(tallies_closed == 0 && lent.n == 2);
|
||||
{
|
||||
var owned := relay_to(tally { n = 1 });
|
||||
owned.put(1);
|
||||
}
|
||||
t.expects(tallies_closed == 1);
|
||||
|
||||
# Never closed itself, a reference still has `close` called through it on what it
|
||||
# refers to, as a reference to the trait does, and what a pointer points at.
|
||||
tallies_closed = 0;
|
||||
var shut := tally { n = 1 };
|
||||
val by_reference: &mut tally = &mut shut;
|
||||
by_reference.close();
|
||||
var pointed := tally { n = 1 };
|
||||
(*((&mut pointed) as *mut tally)).close();
|
||||
var traited := tally { n = 1 };
|
||||
val by_trait: &mut owning = &mut traited;
|
||||
by_trait.close();
|
||||
t.expects(tallies_closed == 3 && shut.n == 0 && pointed.n == 0 && traited.n == 0);
|
||||
}
|
||||
|
||||
# A condition is the `bool` a reference refers to, and a ternary's branches are the
|
||||
# values theirs refer to where only one of them is a reference.
|
||||
def read_through(flag: &mut bool, by: &u64): u64 {
|
||||
var total: u64 = 0;
|
||||
if flag {
|
||||
total += 1;
|
||||
}
|
||||
while flag {
|
||||
flag = false;
|
||||
total += 10;
|
||||
}
|
||||
total += flag ? 0 : 100;
|
||||
return total + (flag ? 0 : by);
|
||||
}
|
||||
|
||||
@test def conditions_read_through_references(t: &mut tester): void {
|
||||
var flag := true;
|
||||
val by: u64 = 1000;
|
||||
t.expects(read_through(&mut flag, &by) == 1111 && !flag);
|
||||
|
||||
# `_` names nothing, so a test naming it stands anywhere a `bool` does.
|
||||
val held: maybe<u64> = 4;
|
||||
val empty: maybe<u64> = nothing {};
|
||||
t.expects(held is some(_) && !(empty is some(_)) && (empty is some(_) || held.some == 4));
|
||||
}
|
||||
|
||||
@test def references_compare_what_they_refer_to(t: &mut tester): void {
|
||||
var one := mark { n = 1 };
|
||||
var two := mark { n = 2 };
|
||||
var also := mark { n = 2 };
|
||||
t.expects(larger(&one, &two).n == 2 && larger(&two, &one).n == 2);
|
||||
t.expects(same(&two, &also) && !same(&one, &two));
|
||||
|
||||
var x: i32 = 4;
|
||||
val by_reference: &i32 = &x;
|
||||
t.expects(larger(by_reference, &x) == 4 && hash(&by_reference) == hash(&x));
|
||||
|
||||
# Keys and elements that are references are found by what they refer to.
|
||||
marks_hashed = 0;
|
||||
var counts := dict::<&mark, u64>::new();
|
||||
counts.set(&two, 5);
|
||||
t.expects(counts[&also] == 5 && counts.length == 1 && marks_hashed > 0);
|
||||
|
||||
var refs := vector::<&mark>::new();
|
||||
refs.append(&one);
|
||||
refs.append(&two);
|
||||
val wanted: &mark = &also;
|
||||
t.expects(refs.span.contains(&wanted));
|
||||
}
|
||||
|
||||
@test def references_to_what_a_call_gives_are_what_it_gives(t: &mut tester): void {
|
||||
# `&` of a call giving a reference is that reference, not one to a copy of it,
|
||||
# so it is the element's address and writes reach the element.
|
||||
var marks := vector::<mark>::new();
|
||||
marks.append(mark { n = 1 });
|
||||
val read := &marks.at(0);
|
||||
t.expects((read as *mark) == (&marks.at(0)) as *mark && read.n == 1);
|
||||
val written := &mut marks.at(0);
|
||||
written.n = 7;
|
||||
t.expects(marks.at(0).n == 7 && (written as *mark) == marks.span.data);
|
||||
}
|
||||
|
||||
@test def pointers_compare_their_addresses(t: &mut tester): void {
|
||||
var two := mark { n = 2 };
|
||||
var also := mark { n = 2 };
|
||||
val p := (&two) as *mark;
|
||||
val q := (&also) as *mark;
|
||||
t.expects(p != q && same(p, p) && !same(p, q));
|
||||
t.expects(p.equals(&p) && !p.equals(&q) && p.compare(&p) == 0);
|
||||
|
||||
# Hashed as addresses, two pointers at equal marks are two keys, and no mark is hashed.
|
||||
marks_hashed = 0;
|
||||
var seen := dict::<*mark, u64>::new();
|
||||
seen.set(p, 1);
|
||||
seen.set(q, 2);
|
||||
t.expects(seen.length == 2 && seen[p] == 1 && seen[q] == 2);
|
||||
t.expects(p.hash() == hash(&p) && marks_hashed == 0);
|
||||
|
||||
# What they point at is still compared through them.
|
||||
t.expects(p[0] == q[0] && (*p).n == (*q).n);
|
||||
val held: &*mark = &p;
|
||||
t.expects(held.equals(&p) && held.hash() == p.hash() && (*held).n == 2 && marks_hashed == 0);
|
||||
|
||||
# A type parameter bounded by `pointer` moves, subtracts, and starts at `null` as
|
||||
# pointers do, however deep.
|
||||
var xs := [1u, 2u, 3u, 4u];
|
||||
val first := (&mut xs) as *mut u64;
|
||||
t.expects(elements_between(first, first + 3) == 3 && no_pointer::<*mark>() == null);
|
||||
t.expects(addressed::<**mark>() == "pointer" && addressed::<&mark>() == "not" && addressed::<u64>() == "not");
|
||||
|
||||
# What a pointer points at is reached by dereferencing it, even a field named as one
|
||||
# of the pointer's own methods.
|
||||
var s := slot { hash = 9 };
|
||||
val at := (&mut s) as *mut slot;
|
||||
t.expects((*at).hash == 9 && through(at).hash == 9 && at.hash() == hash(&at));
|
||||
}
|
||||
|
||||
@test def containers_hold_references_and_pointers(t: &mut tester): void {
|
||||
# A container moves what it is given, which for a reference is the reference
|
||||
# itself, and closes none of what its references reach.
|
||||
tallies_closed = 0;
|
||||
var a := tally { n = 1 };
|
||||
var b := tally { n = 2 };
|
||||
{
|
||||
var refs := vector::<&mut tally>::new();
|
||||
refs.append(&mut a);
|
||||
refs.append(&mut b);
|
||||
refs[1].put(18);
|
||||
refs.remove_at(0);
|
||||
t.expects(refs.length == 1 && refs[0].n == 20);
|
||||
|
||||
var pointers := stack::<*mut tally>::new();
|
||||
pointers.push((&mut a) as *mut tally);
|
||||
(*pointers.peek()).put(9);
|
||||
|
||||
var named := dict::<u64, &tally>::new();
|
||||
named.set(1, &b);
|
||||
t.expects(named[1].size() == 20);
|
||||
}
|
||||
t.expects(a.n == 10);
|
||||
t.expects(b.n == 20);
|
||||
t.expects(tallies_closed == 0);
|
||||
}
|
||||
|
||||
@test def what_a_pointer_points_at_is_reached_by_dereferencing_it(t: &mut tester): void {
|
||||
var a := tally { n = 1 };
|
||||
var p := (&mut a) as *mut tally;
|
||||
(*p).put_twice(1);
|
||||
through(p).put(1);
|
||||
|
||||
# A reference to a pointer reads through to the pointer, which is dereferenced.
|
||||
val r: &mut *mut tally = &mut p;
|
||||
(*r).put(5);
|
||||
through(r).put_twice(1);
|
||||
p[0].put(1);
|
||||
t.expects(a.n == 12 && (*r).size() == 12 && r == (&mut a) as *mut tally);
|
||||
}
|
||||
|
||||
@test def generics_assign_references_as_their_templates_say(t: &mut tester): void {
|
||||
var a: u64 = 1;
|
||||
var b: u64 = 2;
|
||||
var r: &mut u64 = &mut a;
|
||||
|
||||
# References never stack, so `&mut r` is `r`, and the slot is `a`.
|
||||
put_in(&mut r, 5);
|
||||
t.expects(a == 5 && b == 2);
|
||||
|
||||
var n: u64 = 0;
|
||||
put_in(&mut n, 4);
|
||||
t.expects(n == 4);
|
||||
|
||||
# Where `T` is a reference, the template's assignment gives the slot the
|
||||
# reference, as it gives any other value.
|
||||
var slots := vector::<&mut u64>::new();
|
||||
slots.append(&mut a);
|
||||
put_in(&mut slots[0], &mut b);
|
||||
b = 9;
|
||||
t.expects(slots[0] == 9 && a == 5);
|
||||
|
||||
# A reference written as one points a variable elsewhere, and a value given to
|
||||
# a reference is written to what it refers to.
|
||||
r = &mut b;
|
||||
r = 7;
|
||||
t.expects(a == 5 && b == 7);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
# Tests of the properties and methods of `maybe` and `result`: reading what they
|
||||
# hold, by a copy where they are only read and by a move where they can be
|
||||
# written, making others of them, and comparing, hashing, and copying them. A
|
||||
# value that closes is closed once, whichever way it leaves.
|
||||
|
||||
import std::testing;
|
||||
|
||||
|
||||
# How many tokens holding a mark have been closed.
|
||||
var tokens_closed: u64 = 0;
|
||||
|
||||
struct token : owning, copyable {
|
||||
var mark: u64;
|
||||
}
|
||||
|
||||
def token::close(&mut this): void {
|
||||
if this.mark != 0 {
|
||||
tokens_closed++;
|
||||
this.mark = 0;
|
||||
}
|
||||
}
|
||||
|
||||
def token::copy_of(other: &token): token {
|
||||
return token { mark = other.mark };
|
||||
}
|
||||
|
||||
# Half a number, where it is even.
|
||||
def halved(n: i64): maybe<i64> {
|
||||
return n % 2 == 0 ? something(n / 2) : nothing {};
|
||||
}
|
||||
|
||||
# How long text is, or that it is empty.
|
||||
def measured(text: strview): result<u64, strview> {
|
||||
return text.length == 0 ? result::<u64, strview>::err("empty") : result::<u64, strview>::ok(text.length);
|
||||
}
|
||||
|
||||
@test def a_maybe_reads_what_it_holds(t: &mut tester): void {
|
||||
val held: maybe<i64> = 8;
|
||||
val empty: maybe<i64> = nothing {};
|
||||
t.expects(held.is_some && !held.is_none && empty.is_none && !empty.is_some);
|
||||
t.expects(held.unwrap() == 8 && held.expect("held") == 8 && empty.unwrap_or(3) == 3 && held.unwrap_or(3) == 8);
|
||||
t.expects(held.is_some_and(def(x: &i64) => x > 5) && !empty.is_some_and(def(x: &i64) => true));
|
||||
|
||||
# Plain data is copied out of what can be written, as `move` copies it.
|
||||
var kept: maybe<i64> = 6;
|
||||
t.expects(kept.unwrap() == 6 && kept.is_some && kept.unwrap_or(1) == 6);
|
||||
var unset: maybe<i64> = nothing {};
|
||||
t.expects(unset.unwrap_or_else(def(): i64 => 11) == 11);
|
||||
}
|
||||
|
||||
@test def a_maybe_makes_others(t: &mut tester): void {
|
||||
var six: maybe<i64> = 6;
|
||||
t.expects(six.map(def(x: i64) => x * 10) == 60 && six.and_then(halved) == 3);
|
||||
t.expects(six.and_then(halved).and_then(halved).is_none);
|
||||
t.expects(six.filter(def(x: &i64) => x > 10).is_none && six.filter(def(x: &i64) => x > 1) == 6);
|
||||
var empty: maybe<i64> = nothing {};
|
||||
t.expects(empty.or(5) == 5 && six.or(5) == 6 && empty.or_else(def(): maybe<i64> => 7) == 7);
|
||||
t.expects(six.ok_or::<strview>("none").unwrap() == 6 && empty.ok_or::<strview>("none").unwrap_err() == "none");
|
||||
t.expects(six.as_ref().map(def(x: &i64) => x + 1) == 7 && empty.as_ref().is_none);
|
||||
if six.as_mut() is some(&mut got) {
|
||||
got += 1;
|
||||
}
|
||||
t.expects(six == 7);
|
||||
|
||||
# `take` and `replace` leave it holding nothing, or the new value.
|
||||
t.expects(six.take() == 7 && six.is_none && six.replace(4).is_none && six == 4);
|
||||
}
|
||||
|
||||
@test def a_maybe_compares_hashes_and_copies(t: &mut tester): void {
|
||||
val a: maybe<i64> = 5;
|
||||
val b: maybe<i64> = 5;
|
||||
val c: maybe<i64> = 6;
|
||||
val none: maybe<i64> = nothing {};
|
||||
t.expects(a == b && a != c && a != none && none == maybe::<i64> { none = nothing {} } && a == 5);
|
||||
t.expects(hash(&a) == hash(&b) && hash(&a) != hash(&none));
|
||||
val text: maybe<string> = string::from("held", nothing {});
|
||||
val copied := copy(&text);
|
||||
t.expects(copied == text && copied.as_ref().map(def(s: &string) => s.length) == 4);
|
||||
}
|
||||
|
||||
@test def a_maybe_moves_out_what_closes(t: &mut tester): void {
|
||||
val before := tokens_closed;
|
||||
{
|
||||
# Moved out of what can be written, leaving it holding nothing.
|
||||
var held: maybe<token> = token { mark = 1 };
|
||||
var taken := held.unwrap();
|
||||
t.expects(taken.mark == 1 && held.is_none && tokens_closed == before);
|
||||
|
||||
# Moved into what a function makes, which closes it there.
|
||||
var given: maybe<token> = token { mark = 2 };
|
||||
t.expects(given.map(def(x: token) => x.mark) == 2 && given.is_none && tokens_closed == before + 1);
|
||||
|
||||
# Left behind by `filter`, `or`, and `replace`, each closed once.
|
||||
var failed: maybe<token> = token { mark = 3 };
|
||||
t.expects(failed.filter(def(x: &token) => false).is_none && tokens_closed == before + 2);
|
||||
var first: maybe<token> = token { mark = 4 };
|
||||
var other := first.or(token { mark = 5 });
|
||||
t.expects(other.as_ref().map(def(x: &token) => x.mark) == 4 && tokens_closed == before + 3);
|
||||
var swapped: maybe<token> = token { mark = 6 };
|
||||
var old := swapped.replace(token { mark = 7 });
|
||||
t.expects(old.is_some && swapped.as_ref().is_some_and(def(x) => x.mark == 7));
|
||||
|
||||
# A box held by a `maybe` in one word is taken whole.
|
||||
var boxed: maybe<box<token>> = box::<token>::new(token { mark = 8 });
|
||||
var out := boxed.take();
|
||||
t.expects(boxed.is_none && out.is_some && size_of::<maybe<box<token>>>() == 8);
|
||||
}
|
||||
# taken, other, old, swapped, and out's are closed at the end of the block.
|
||||
t.expects(tokens_closed == before + 8);
|
||||
}
|
||||
|
||||
@test def a_result_reads_what_it_holds(t: &mut tester): void {
|
||||
val good := measured("four");
|
||||
val bad := measured("");
|
||||
t.expects(good.is_ok && !good.is_err && bad.is_err && !bad.is_ok);
|
||||
t.expects(good.unwrap() == 4 && good.expect("good") == 4 && bad.unwrap_err() == "empty" && bad.expect_err("bad") == "empty");
|
||||
t.expects(bad.unwrap_or(9) == 9 && good.unwrap_or(9) == 4);
|
||||
t.expects(good.is_ok_and(def(x: &u64) => x == 4) && bad.is_err_and(def(e: &strview) => e.length == 5));
|
||||
var failed := measured("");
|
||||
t.expects(failed.unwrap_or_else(def(e: strview) => e.length) == 5);
|
||||
}
|
||||
|
||||
@test def a_result_makes_others(t: &mut tester): void {
|
||||
var two := measured("ab");
|
||||
var none := measured("");
|
||||
t.expects(two.map(def(x: u64) => x + 1).unwrap() == 3 && none.map(def(x: u64) => x + 1).unwrap_err() == "empty");
|
||||
t.expects(none.map_err(def(e: strview) => e.length).unwrap_err() == 5 && two.map_err(def(e: strview) => e.length).unwrap() == 2);
|
||||
t.expects(two.and_then(def(x: u64): result<u64, strview> => result::<u64, strview>::err("no")).unwrap_err() == "no");
|
||||
t.expects(none.or_else(def(e: strview): result<u64, i64> => result::<u64, i64>::ok(7)).unwrap() == 7);
|
||||
t.expects(two.to_maybe() == 2 && none.to_maybe().is_none && none.err_to_maybe() == "empty" && two.err_to_maybe().is_none);
|
||||
t.expects(two.as_ref().is_ok_and(def(x) => x == 2) && none.as_ref().is_err);
|
||||
|
||||
# A value and an error of one type are told apart.
|
||||
var same := result::<i64, i64>::err(5);
|
||||
t.expects(same.is_err && same.map(def(x: i64) => x + 100).unwrap_err() == 5);
|
||||
t.expects(result::<i64, i64>::ok(5) != result::<i64, i64>::err(5));
|
||||
|
||||
# A result of `void` says only whether it failed.
|
||||
val done := result::<void, i64>::ok(void {});
|
||||
done.unwrap();
|
||||
t.expects(done.is_ok);
|
||||
}
|
||||
|
||||
@test def a_result_compares_hashes_and_copies(t: &mut tester): void {
|
||||
val a := measured("abc");
|
||||
val b := measured("xyz");
|
||||
val c := measured("");
|
||||
t.expects(a == b && a != c && c == measured(""));
|
||||
t.expects(hash(&a) == hash(&b) && hash(&a) != hash(&c));
|
||||
val text := result::<string, u64>::ok(string::from("held", nothing {}));
|
||||
val copied := copy(&text);
|
||||
t.expects(copied == text && copied.as_ref().is_ok_and(def(s) => s.length == 4));
|
||||
}
|
||||
|
||||
@test def a_result_moves_out_what_closes(t: &mut tester): void {
|
||||
val before := tokens_closed;
|
||||
{
|
||||
var held := result::<token, u64>::ok(token { mark = 1 });
|
||||
var taken := held.unwrap();
|
||||
t.expects(taken.mark == 1 && tokens_closed == before);
|
||||
|
||||
var failed := result::<u64, token>::err(token { mark = 2 });
|
||||
t.expects(failed.map_err(def(x: token) => x.mark).unwrap_err() == 2 && tokens_closed == before + 1);
|
||||
var lost := result::<token, u64>::ok(token { mark = 3 });
|
||||
t.expects(lost.err_to_maybe().is_none && tokens_closed == before + 2);
|
||||
}
|
||||
t.expects(tokens_closed == before + 3);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
# Tests of std's scanning of text, which an executable does sixteen bytes at a
|
||||
# time: what it looks for at every place, so on either side of where each
|
||||
# sixteen ends, against the same work done a byte at a time.
|
||||
|
||||
import std::io;
|
||||
import std::testing;
|
||||
|
||||
# The text of a length whose bytes at the places a pattern sets are a byte, and
|
||||
# letters otherwise.
|
||||
def text_with(length: u64, pattern: u64, byte: u8): string {
|
||||
var made := string::new(nothing {});
|
||||
for i in 0..length {
|
||||
val set := ((pattern >> (i % 61)) & 1) != 0;
|
||||
made.push(set ? byte : ('a' as u64 + i % 26) as u8);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
@test def splitting_finds_every_delimiter_wherever_it_falls(t: &mut tester): void {
|
||||
for length in 0..80u {
|
||||
for pattern in [0 as u64, 1, 0x8000, 0x10001, 0x5555555555555555, 0xFFFFFFFFFFFFFFFF, 0x0123456789ABCDEF] {
|
||||
val text := text_with(length, pattern, ',');
|
||||
val parts := text.span.split(',').to_vector();
|
||||
# Each part, joined by the delimiter, is the text again, and none holds it.
|
||||
var joined := string::new(nothing {});
|
||||
var clean := true;
|
||||
for i in 0..parts.length {
|
||||
if i != 0 {
|
||||
joined.push(',');
|
||||
}
|
||||
joined.append(parts[i]);
|
||||
for k in 0..parts[i].length {
|
||||
clean = clean && parts[i][k] != ',';
|
||||
}
|
||||
}
|
||||
t.expects(joined.span == text.span && clean);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@test def text_compares_as_its_bytes_do(t: &mut tester): void {
|
||||
for length in 0..70u {
|
||||
val a := text_with(length, 0x0F0F0F0F0F0F0F0F, 'x');
|
||||
t.expects(a.span.compare(a.span) == 0);
|
||||
for place in 0..length {
|
||||
for byte in [0 as u8, 'a', 'x', 0x80, 0xFF] {
|
||||
var b := text_with(length, 0x0F0F0F0F0F0F0F0F, 'x');
|
||||
b[place] = byte;
|
||||
val was: u8 = a[place];
|
||||
val want: i64 = was == byte ? 0 : (was < byte ? -1 : 1);
|
||||
t.expects(a.span.compare(b.span) == want);
|
||||
}
|
||||
# A prefix orders first.
|
||||
t.expects(a.span.substr(0, place).compare(a.span) == -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@test def lines_are_read_wherever_their_breaks_fall(t: &mut tester): void {
|
||||
for length in 0..70u {
|
||||
val text := text_with(length, 0x2104210421042104, '\n');
|
||||
var input := io::reader_of(text.span);
|
||||
var seen := string::new(nothing {});
|
||||
for line in input.lines() {
|
||||
seen.append(line.span);
|
||||
seen.push('\n');
|
||||
}
|
||||
# The lines, each with its break, are the text, but for a last line without one.
|
||||
var want := string::new(nothing {});
|
||||
want.append(text.span);
|
||||
if want.length != 0 && want[want.length - 1] != '\n' {
|
||||
want.push('\n');
|
||||
}
|
||||
t.expects(seen.span == want.span);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
# Tests of signals: sending them, ignoring them, putting back what the system does
|
||||
# with them, handling them, at the program's safe points and where a wait is
|
||||
# interrupted, and watching for them. Each test runs in a copy of the program, so what one handles is its
|
||||
# own. Windows sends a program no signal from another, so there a thread, or a
|
||||
# copy of the program, sends what another program does on Linux.
|
||||
import std::io;
|
||||
import std::process;
|
||||
import system;
|
||||
import std::testing;
|
||||
import std::thread;
|
||||
|
||||
# A function of the program's own, which begins with a safe point.
|
||||
def safe_point(): void {}
|
||||
|
||||
when os == linux {
|
||||
# Runs a copy of the program that puts back what the system does with a signal,
|
||||
# then sends it to itself, giving the signal that stopped the copy, or zero where
|
||||
# the copy went on and exited.
|
||||
def raised_in_copy(sent: system::signal): i32 {
|
||||
val copy := system::fork();
|
||||
if copy == 0 {
|
||||
_ = system::restore(sent);
|
||||
_ = system::raise(sent);
|
||||
safe_point();
|
||||
system::exit(0);
|
||||
}
|
||||
|
||||
var status: system::process_status;
|
||||
_ = system::wait(copy, &mut status);
|
||||
return status.exited ? 0 : status.signal;
|
||||
}
|
||||
|
||||
# The signals the system says the program does something with, one bit each by
|
||||
# number less one: those it handles, where `named` is `SigCgt`, or ignores, where
|
||||
# it is `SigIgn`.
|
||||
def dispositions(named: strview): u64 {
|
||||
var at := path::parse("/proc/self/status") else (_) { return 0; };
|
||||
val text := io::read_file(&at) else (_) { return 0; };
|
||||
for line in text.span.split('\n') {
|
||||
if !line.starts_with(named) || line.length < 16 {
|
||||
continue;
|
||||
}
|
||||
|
||||
val hex := line.substr(line.length - 16, 16);
|
||||
var bits: u64 = 0;
|
||||
for i in 0..hex.length {
|
||||
val digit := hex[i] >= 'a' ? (hex[i] - 'a') as u64 + 10 : (hex[i] - '0') as u64;
|
||||
bits = bits * 16 + digit;
|
||||
}
|
||||
return bits;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
# Waits until a process is in a state, as `/proc` gives it: `S` where it sleeps,
|
||||
# as it does waiting in the system, so a signal sent to it then interrupts the
|
||||
# wait, and `T` where it is paused. Gives whether it was.
|
||||
def reaches(process: i64, state: u8): bool {
|
||||
var at := path::parse($"/proc/{process}/stat") else (_) { return false; };
|
||||
for tries in 0..1000000 {
|
||||
val text := io::read_file(&at) else (_) { return false; };
|
||||
val view := text.span;
|
||||
var end := view.length;
|
||||
while end > 0 && view[end - 1] != ')' {
|
||||
end--;
|
||||
}
|
||||
if end + 1 < view.length && view[end + 1] == state {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
# Starts a copy of the program that sends it a signal once it sleeps, then waits
|
||||
# to be stopped, giving the copy's number.
|
||||
def signalled_once_asleep(sent: system::signal): i64 {
|
||||
val program := system::getpid();
|
||||
val copy := system::fork();
|
||||
if copy == 0 {
|
||||
_ = system::restore(sent);
|
||||
if reaches(program, 'S') {
|
||||
_ = system::kill(program, sent);
|
||||
}
|
||||
system::pause();
|
||||
system::exit(0);
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
|
||||
# Whether a read failed because a signal ended its wait.
|
||||
def is_interrupted(error: maybe<io_error>): bool {
|
||||
if error is some(why) {
|
||||
return why == io_error::interrupted;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
# A stream that gives its text in two parts, failing between them as a read does
|
||||
# that a signal the program handles interrupts.
|
||||
struct halting : readable {
|
||||
var first: strview;
|
||||
var rest: strview;
|
||||
var halted: bool;
|
||||
}
|
||||
|
||||
def halting::read(&mut this, into: slice<u8>): result<u64, io_error> {
|
||||
if this.first.length > 0 {
|
||||
return this.first.read(into);
|
||||
}
|
||||
if !this.halted {
|
||||
this.halted = true;
|
||||
return io_error::interrupted;
|
||||
}
|
||||
return this.rest.read(into);
|
||||
}
|
||||
|
||||
when os == linux {
|
||||
@test def signals_have_the_numbers_of_the_system(t: &mut tester): void {
|
||||
# Those a program may handle are noted by the system under their numbers, and
|
||||
# each handler is given the signal that came. Each is restored after, so that
|
||||
# `child` interrupts no wait below.
|
||||
val members: system::signal[12] = [
|
||||
system::signal::hangup, system::signal::interrupt, system::signal::quit, system::signal::user1,
|
||||
system::signal::user2, system::signal::pipe, system::signal::alarm, system::signal::terminate,
|
||||
system::signal::child, system::signal::resume, system::signal::suspend, system::signal::resized
|
||||
];
|
||||
val numbers: u64[12] = [1, 2, 3, 10, 12, 13, 14, 15, 17, 18, 20, 28];
|
||||
var came := system::signal::kill;
|
||||
for i in 0..members.length {
|
||||
t.expects(system::handle(members[i], def(s: system::signal) { came = s; }) == 0);
|
||||
t.expects(((dispositions("SigCgt") >> (numbers[i] - 1)) & 1) == 1);
|
||||
t.expects(system::raise(members[i]) == 0);
|
||||
safe_point();
|
||||
t.expects(came == members[i]);
|
||||
t.expects(system::restore(members[i]) == 0);
|
||||
t.expects(((dispositions("SigCgt") >> (numbers[i] - 1)) & 1) == 0);
|
||||
}
|
||||
|
||||
# What stops a program by default stops a copy with its number.
|
||||
t.expects(raised_in_copy(system::signal::hangup) == 1);
|
||||
t.expects(raised_in_copy(system::signal::interrupt) == 2);
|
||||
t.expects(raised_in_copy(system::signal::kill) == 9);
|
||||
t.expects(raised_in_copy(system::signal::user1) == 10);
|
||||
t.expects(raised_in_copy(system::signal::user2) == 12);
|
||||
t.expects(raised_in_copy(system::signal::pipe) == 13);
|
||||
t.expects(raised_in_copy(system::signal::alarm) == 14);
|
||||
t.expects(raised_in_copy(system::signal::terminate) == 15);
|
||||
|
||||
# `stop` pauses a copy, and `resume` lets it go on.
|
||||
val copy := system::fork();
|
||||
if copy == 0 {
|
||||
_ = system::raise(system::signal::stop);
|
||||
system::exit(5);
|
||||
}
|
||||
t.expects(reaches(copy, 'T'));
|
||||
_ = system::kill(copy, system::signal::resume);
|
||||
var status: system::process_status;
|
||||
_ = system::wait(copy, &mut status);
|
||||
t.expects(status.exited && status.code == 5);
|
||||
}
|
||||
|
||||
@test def ignored_signals_do_nothing_until_restored(t: &mut tester): void {
|
||||
t.expects(system::ignore(system::signal::user1) == 0);
|
||||
t.expects(((dispositions("SigIgn") >> 9) & 1) == 1);
|
||||
t.expects(system::raise(system::signal::user1) == 0);
|
||||
safe_point();
|
||||
|
||||
t.expects(system::restore(system::signal::user1) == 0);
|
||||
t.expects(((dispositions("SigIgn") >> 9) & 1) == 0);
|
||||
t.expects(raised_in_copy(system::signal::user1) == 10);
|
||||
|
||||
# Restoring a handled signal stops its handler running.
|
||||
var count := 0;
|
||||
t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0);
|
||||
t.expects(system::ignore(system::signal::user2) == 0);
|
||||
t.expects(system::raise(system::signal::user2) == 0);
|
||||
safe_point();
|
||||
t.expects(count == 0 && ((dispositions("SigCgt") >> 11) & 1) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
@test def kill_and_stop_cannot_be_handled_nor_child_ignored(t: &mut tester): void {
|
||||
val nothing_done := def(s: system::signal) {};
|
||||
t.expects(system::error_of(system::handle(system::signal::kill, nothing_done)) == io_error::invalid);
|
||||
t.expects(system::error_of(system::handle(system::signal::stop, nothing_done)) == io_error::invalid);
|
||||
t.expects(system::error_of(system::ignore(system::signal::kill)) == io_error::invalid);
|
||||
t.expects(system::error_of(system::ignore(system::signal::stop)) == io_error::invalid);
|
||||
t.expects(system::error_of(system::ignore(system::signal::child)) == io_error::invalid);
|
||||
}
|
||||
|
||||
when os == linux {
|
||||
@test def signals_watched_for_wait_to_be_asked_for(t: &mut tester): void {
|
||||
t.expects(system::watch(system::signal::user1) == 0);
|
||||
t.expects(((dispositions("SigCgt") >> 9) & 1) == 1);
|
||||
t.expects(system::watched() == 0);
|
||||
_ = system::raise(system::signal::user1);
|
||||
safe_point();
|
||||
t.expects(system::watched() == 1u << 10);
|
||||
t.expects(system::watched() == 0);
|
||||
|
||||
# A handled signal is not given, and one watched for waits while the handlers
|
||||
# run.
|
||||
var count := 0;
|
||||
t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0);
|
||||
_ = system::raise(system::signal::user1);
|
||||
_ = system::raise(system::signal::user2);
|
||||
safe_point();
|
||||
t.expects(count == 1);
|
||||
t.expects(system::watched() == 1u << 10);
|
||||
|
||||
# Handling a signal watched for stops it being watched for.
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
|
||||
_ = system::raise(system::signal::user1);
|
||||
safe_point();
|
||||
t.expects(count == 2 && system::watched() == 0);
|
||||
t.expects(system::error_of(system::watch(system::signal::kill)) == io_error::invalid);
|
||||
t.expects(system::error_of(system::watch(system::signal::stop)) == io_error::invalid);
|
||||
}
|
||||
}
|
||||
|
||||
@test def handlers_run_at_the_next_safe_point(t: &mut tester): void {
|
||||
var count := 0;
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
|
||||
_ = system::raise(system::signal::user1);
|
||||
t.expects(count == 0);
|
||||
safe_point();
|
||||
t.expects(count == 1);
|
||||
|
||||
# Signals that come together are handled once each.
|
||||
_ = system::raise(system::signal::user1);
|
||||
_ = system::raise(system::signal::user1);
|
||||
safe_point();
|
||||
t.expects(count == 2);
|
||||
|
||||
# A loop of the program's own runs the handler as it goes round.
|
||||
var stopping := false;
|
||||
t.expects(system::handle(system::signal::user2, def(s: system::signal) { stopping = true; }) == 0);
|
||||
_ = system::raise(system::signal::user2);
|
||||
var passes := 0;
|
||||
while !stopping {
|
||||
passes++;
|
||||
}
|
||||
t.expects(passes == 1);
|
||||
}
|
||||
|
||||
when os == linux {
|
||||
@test def a_loop_calling_nothing_is_ended_by_its_safe_points(t: &mut tester): void {
|
||||
var flag := false;
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) { flag = true; }) == 0);
|
||||
val program := system::getpid();
|
||||
val copy := system::fork();
|
||||
if copy == 0 {
|
||||
_ = system::kill(program, system::signal::user1);
|
||||
system::exit(0);
|
||||
}
|
||||
|
||||
while !flag {}
|
||||
var status: system::process_status;
|
||||
_ = system::wait(copy, &mut status);
|
||||
t.expects(flag && status.exited);
|
||||
}
|
||||
}
|
||||
|
||||
@test def vectors_held_across_a_safe_point_keep_their_lanes(t: &mut tester): void {
|
||||
# The handler works vectors of its own, in the registers the loop holds its
|
||||
# sums in, which the safe point keeps whole for it: 16 bytes, and 32 where the
|
||||
# loop's code has AVX.
|
||||
var ran := 0;
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) {
|
||||
var noise := f32x8::splat(-1.0);
|
||||
var bytes := u32x4::splat(7);
|
||||
for _ in 0..4 {
|
||||
noise = noise * noise + f32x8::splat(3.0);
|
||||
bytes = bytes * bytes;
|
||||
}
|
||||
if noise.sum() > 0.0 && bytes.sum() != 0 {
|
||||
ran++;
|
||||
}
|
||||
}) == 0);
|
||||
# Raised before the loop, which calls nothing, so the handler runs at its
|
||||
# first pass's safe point, the sums in registers.
|
||||
_ = system::raise(system::signal::user1);
|
||||
var narrow := u32x4::splat(0);
|
||||
var wide := f32x8::splat(0.0);
|
||||
for i in 0..100u {
|
||||
narrow = narrow + u32x4::splat(i as u32);
|
||||
wide = wide + f32x8::splat(1.0);
|
||||
}
|
||||
t.expects(ran == 1 && narrow.sum() == 4 * 4950 && wide.sum() == 800.0);
|
||||
}
|
||||
|
||||
@test def handlers_do_not_nest(t: &mut tester): void {
|
||||
var depth := 0;
|
||||
var deepest := 0;
|
||||
var runs := 0;
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) {
|
||||
depth++;
|
||||
runs++;
|
||||
deepest = depth > deepest ? depth : deepest;
|
||||
if runs == 1 {
|
||||
_ = system::raise(system::signal::user1);
|
||||
safe_point();
|
||||
}
|
||||
depth--;
|
||||
}) == 0);
|
||||
|
||||
_ = system::raise(system::signal::user1);
|
||||
safe_point();
|
||||
t.expects(runs == 2 && deepest == 1);
|
||||
}
|
||||
|
||||
when os == linux {
|
||||
@test def a_wait_a_handler_interrupts_fails_with_interrupted(t: &mut tester): void {
|
||||
var count := 0;
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
|
||||
val copy := signalled_once_asleep(system::signal::user1);
|
||||
|
||||
# The handler has run by the time the wait ends.
|
||||
var status: system::process_status;
|
||||
val waited := system::wait(copy, &mut status);
|
||||
t.expects(system::error_of(waited) == io_error::interrupted && count == 1);
|
||||
|
||||
_ = system::kill(copy, system::signal::kill);
|
||||
t.expects(system::wait(copy, &mut status) == copy && !status.exited && status.signal == 9);
|
||||
}
|
||||
|
||||
@test def pause_returns_once_a_handler_has_run(t: &mut tester): void {
|
||||
var count := 0;
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
|
||||
|
||||
# A signal sent just before is not missed.
|
||||
_ = system::raise(system::signal::user1);
|
||||
system::pause();
|
||||
t.expects(count == 1);
|
||||
|
||||
# One sent while it waits ends the wait.
|
||||
val copy := signalled_once_asleep(system::signal::user1);
|
||||
system::pause();
|
||||
t.expects(count == 2);
|
||||
|
||||
var status: system::process_status;
|
||||
_ = system::kill(copy, system::signal::kill);
|
||||
_ = system::wait(copy, &mut status);
|
||||
}
|
||||
|
||||
@test def exit_in_a_handler_stops_the_program(t: &mut tester): void {
|
||||
val copy := system::fork();
|
||||
if copy == 0 {
|
||||
_ = system::handle(system::signal::user1, def(s: system::signal) { system::exit(7); });
|
||||
_ = system::raise(system::signal::user1);
|
||||
safe_point();
|
||||
system::exit(0);
|
||||
}
|
||||
|
||||
var status: system::process_status;
|
||||
_ = system::wait(copy, &mut status);
|
||||
t.expects(status.exited && status.code == 7);
|
||||
}
|
||||
}
|
||||
|
||||
@test def a_reader_keeps_what_a_signal_cut_short(t: &mut tester): void {
|
||||
# A line cut short is given whole by the next read.
|
||||
var lines := io::reader_of(halting { first = "hel", rest = "lo\nworld" });
|
||||
t.expects(lines.read_line() is none && is_interrupted(lines.error));
|
||||
val line := lines.read_line() else { t.expects(false); return; };
|
||||
t.expects(line.span == "hello" && lines.error is none);
|
||||
val last := lines.read_line() else { t.expects(false); return; };
|
||||
t.expects(last.span == "world");
|
||||
|
||||
# So are bytes asked for, and the rest of the input.
|
||||
var bytes := io::reader_of(halting { first = "0123", rest = "456789" });
|
||||
t.expects(bytes.read_exactly(6) is error);
|
||||
val six := bytes.read_exactly(6) else (_) { t.expects(false); return; };
|
||||
t.expects(six.span == "012345");
|
||||
|
||||
var rest := io::reader_of(halting { first = "ab", rest = "cd" });
|
||||
t.expects(rest.read_all() is error);
|
||||
val all := rest.read_all() else (_) { t.expects(false); return; };
|
||||
t.expects(all.span == "abcd");
|
||||
}
|
||||
|
||||
when os == windows {
|
||||
# Runs a copy of the program that puts back what the system does with a signal,
|
||||
# then sends it to itself, giving the signal that stopped the copy, or zero where
|
||||
# the copy went on and exited. Windows stops a program by a signal's default with
|
||||
# 128 more than its number, or by `interrupt` as the console's Ctrl-C does, which
|
||||
# is the signal itself.
|
||||
def raised_in_copy(sent: system::signal): i32 {
|
||||
val status := copied(def() {
|
||||
_ = system::restore(sent);
|
||||
_ = system::raise(sent);
|
||||
safe_point();
|
||||
});
|
||||
if !status.exited {
|
||||
return status.signal;
|
||||
}
|
||||
return status.code > 128 && status.code < 192 ? status.code - 128 : 0;
|
||||
}
|
||||
|
||||
# Starts a thread that sends the program a signal once a little time has passed.
|
||||
# The thread is given the signal, which it owns, since it outlives this call.
|
||||
def sent_soon(sent: system::signal): result<thread::handle<void>, io_error> {
|
||||
return thread::spawn_with(def(which: system::signal) {
|
||||
_ = system::sleep(50000000);
|
||||
_ = system::raise(which);
|
||||
}, sent);
|
||||
}
|
||||
|
||||
@test def signals_have_the_numbers_of_the_system(t: &mut tester): void {
|
||||
# Those a program may handle are noted under their numbers, and each handler
|
||||
# is given the signal that came.
|
||||
val members: system::signal[12] = [
|
||||
system::signal::hangup, system::signal::interrupt, system::signal::quit, system::signal::user1,
|
||||
system::signal::user2, system::signal::pipe, system::signal::alarm, system::signal::terminate,
|
||||
system::signal::child, system::signal::resume, system::signal::suspend, system::signal::resized
|
||||
];
|
||||
val numbers: u64[12] = [1, 2, 3, 10, 12, 13, 14, 15, 17, 18, 20, 28];
|
||||
var came := system::signal::kill;
|
||||
for i in 0..members.length {
|
||||
t.expects(system::handle(members[i], def(s: system::signal) { came = s; }) == 0);
|
||||
t.expects(system::raise(members[i]) == 0);
|
||||
safe_point();
|
||||
t.expects(came == members[i]);
|
||||
t.expects(system::watch(members[i]) == 0 && system::raise(members[i]) == 0);
|
||||
t.expects(system::watched() == 1u << numbers[i]);
|
||||
t.expects(system::restore(members[i]) == 0);
|
||||
}
|
||||
|
||||
# What stops a program by default stops a copy with its number.
|
||||
t.expects(raised_in_copy(system::signal::hangup) == 1);
|
||||
t.expects(raised_in_copy(system::signal::interrupt) == 2);
|
||||
t.expects(raised_in_copy(system::signal::kill) == 9);
|
||||
t.expects(raised_in_copy(system::signal::user1) == 10);
|
||||
t.expects(raised_in_copy(system::signal::user2) == 12);
|
||||
t.expects(raised_in_copy(system::signal::pipe) == 13);
|
||||
t.expects(raised_in_copy(system::signal::alarm) == 14);
|
||||
t.expects(raised_in_copy(system::signal::terminate) == 15);
|
||||
|
||||
# Windows cannot pause a program.
|
||||
t.expects(system::error_of(system::raise(system::signal::stop)) == io_error::unsupported);
|
||||
}
|
||||
|
||||
@test def ignored_signals_do_nothing_until_restored(t: &mut tester): void {
|
||||
t.expects(system::ignore(system::signal::user1) == 0);
|
||||
t.expects(system::raise(system::signal::user1) == 0);
|
||||
safe_point();
|
||||
|
||||
t.expects(system::restore(system::signal::user1) == 0);
|
||||
t.expects(raised_in_copy(system::signal::user1) == 10);
|
||||
|
||||
# Restoring a handled signal stops its handler running.
|
||||
var count := 0;
|
||||
t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0);
|
||||
t.expects(system::ignore(system::signal::user2) == 0);
|
||||
t.expects(system::raise(system::signal::user2) == 0);
|
||||
safe_point();
|
||||
t.expects(count == 0);
|
||||
}
|
||||
|
||||
@test def signals_watched_for_wait_to_be_asked_for(t: &mut tester): void {
|
||||
t.expects(system::watch(system::signal::user1) == 0);
|
||||
t.expects(system::watched() == 0);
|
||||
_ = system::raise(system::signal::user1);
|
||||
safe_point();
|
||||
t.expects(system::watched() == 1u << 10);
|
||||
t.expects(system::watched() == 0);
|
||||
|
||||
# A handled signal is not given, and one watched for waits while the handlers
|
||||
# run.
|
||||
var count := 0;
|
||||
t.expects(system::handle(system::signal::user2, def(s: system::signal) { count++; }) == 0);
|
||||
_ = system::raise(system::signal::user1);
|
||||
_ = system::raise(system::signal::user2);
|
||||
safe_point();
|
||||
t.expects(count == 1);
|
||||
t.expects(system::watched() == 1u << 10);
|
||||
|
||||
# Handling a signal watched for stops it being watched for.
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
|
||||
_ = system::raise(system::signal::user1);
|
||||
safe_point();
|
||||
t.expects(count == 2 && system::watched() == 0);
|
||||
t.expects(system::error_of(system::watch(system::signal::kill)) == io_error::invalid);
|
||||
t.expects(system::error_of(system::watch(system::signal::stop)) == io_error::invalid);
|
||||
}
|
||||
|
||||
@test def a_loop_calling_nothing_is_ended_by_its_safe_points(t: &mut tester): void {
|
||||
var flag := false;
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) { flag = true; }) == 0);
|
||||
var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; };
|
||||
while !flag {}
|
||||
sender.close();
|
||||
t.expects(flag);
|
||||
}
|
||||
|
||||
@test def a_wait_a_handler_interrupts_fails_with_interrupted(t: &mut tester): void {
|
||||
var count := 0;
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
|
||||
var pinger := process::command::new("ping");
|
||||
pinger.arguments(["-n", "30", "127.0.0.1"]);
|
||||
pinger.output(process::stdio::none);
|
||||
var running := pinger.spawn() else (_) { t.expects(false); return; };
|
||||
var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; };
|
||||
|
||||
# The handler has run by the time the wait ends.
|
||||
var status: system::process_status;
|
||||
val waited := system::wait(running.id as i64, &mut status);
|
||||
t.expects(system::error_of(waited) == io_error::interrupted && count == 1);
|
||||
sender.close();
|
||||
|
||||
t.expects(running.kill() is value);
|
||||
val stopped := running.wait() else (_) { t.expects(false); return; };
|
||||
t.expects(stopped == process::status { signaled = 9 });
|
||||
}
|
||||
|
||||
@test def pause_returns_once_a_handler_has_run(t: &mut tester): void {
|
||||
var count := 0;
|
||||
t.expects(system::handle(system::signal::user1, def(s: system::signal) { count++; }) == 0);
|
||||
|
||||
# A signal sent just before is not missed.
|
||||
_ = system::raise(system::signal::user1);
|
||||
system::pause();
|
||||
t.expects(count == 1);
|
||||
|
||||
# One sent while it waits ends the wait.
|
||||
var sender := sent_soon(system::signal::user1) else (_) { t.expects(false); return; };
|
||||
system::pause();
|
||||
t.expects(count == 2);
|
||||
sender.close();
|
||||
}
|
||||
|
||||
@test def exit_in_a_handler_stops_the_program(t: &mut tester): void {
|
||||
val status := copied(def() {
|
||||
_ = system::handle(system::signal::user1, def(s: system::signal) { system::exit(7); });
|
||||
_ = system::raise(system::signal::user1);
|
||||
safe_point();
|
||||
});
|
||||
t.expects(status.exited && status.code == 7);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
# Tests of std's vectors: each operation of each type of lane against what the
|
||||
# number's own operator or `std::math` gives lane by lane, to the bit, masks and
|
||||
# selecting, loading and storing at the ends of views, and what stops the
|
||||
# program. Built natively, the vectors are worked with the processor's vector
|
||||
# instructions where it has them, so the same tests check those against the
|
||||
# lanes; `SAKURA_CPU=x86-64` runs them as on a processor with SSE2 alone. The
|
||||
# corpus program `simd_lanes_agree_everywhere_1` compares their bits between the
|
||||
# compilers, the machine, executables, and constants.
|
||||
import system;
|
||||
import std::math;
|
||||
import std::testing;
|
||||
|
||||
|
||||
# Whether running the function stops the program, in a copy of the program that
|
||||
# writes nothing.
|
||||
def simd_stops(run: def(): void): bool {
|
||||
when os == windows {
|
||||
val stopped := copied(run);
|
||||
return !(stopped.exited && stopped.code == 0);
|
||||
}
|
||||
val child := fork();
|
||||
if child == 0 {
|
||||
val out: fd = fd::stdout;
|
||||
val err: fd = fd::stderr;
|
||||
out.close();
|
||||
err.close();
|
||||
run();
|
||||
exit(0);
|
||||
}
|
||||
var status: process_status;
|
||||
return wait(child, &mut status) >= 0 && !(status.exited && status.code == 0);
|
||||
}
|
||||
|
||||
# Whether two values have the same bytes, as NaNs of the same bits do.
|
||||
def same_lane_bits<T>(a: &T, b: &T): bool {
|
||||
val x := a as *u8;
|
||||
val y := b as *u8;
|
||||
for k in 0..size_of::<T>() {
|
||||
return false if x[k] != y[k];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# A lane worked alone as the vector works it: a whole number's wraps where it
|
||||
# overflows, as the processor's vector instructions do, which the operator
|
||||
# would stop at in a program built with `--checks`.
|
||||
def lane_add<L>(x: L, y: L): L where L: numeric {
|
||||
if const L is integer { return math::wrapping_add(x, y); }
|
||||
return x + y;
|
||||
}
|
||||
|
||||
def lane_sub<L>(x: L, y: L): L where L: numeric {
|
||||
if const L is integer { return math::wrapping_sub(x, y); }
|
||||
return x - y;
|
||||
}
|
||||
|
||||
def lane_mul<L>(x: L, y: L): L where L: numeric {
|
||||
if const L is integer { return math::wrapping_mul(x, y); }
|
||||
return x * y;
|
||||
}
|
||||
|
||||
def lane_neg<L>(x: L): L where L: numeric {
|
||||
if const L is integer { return math::wrapping_sub(0 as L, x); }
|
||||
return -x;
|
||||
}
|
||||
|
||||
var lane_seed: u64 = 0x2545F4914F6CDD1D;
|
||||
|
||||
def next_bits(): u64 {
|
||||
lane_seed = lane_seed ^ (lane_seed << 13);
|
||||
lane_seed = lane_seed ^ (lane_seed >> 7);
|
||||
lane_seed = lane_seed ^ (lane_seed << 17);
|
||||
return lane_seed;
|
||||
}
|
||||
|
||||
# A lane worth testing: one of the edges of its type, or something between.
|
||||
def random_lane<L>(): L where L: numeric, ordered, zeroable {
|
||||
val pick := next_bits() % 12;
|
||||
if const L is real {
|
||||
val edges: f64[9] = [0.0, -0.0, 1.0, -1.5, 2.5, -2.5, 1e-310, 0.75, -3.0];
|
||||
return edges[pick as u64] as L if pick < 9;
|
||||
return math::infinity::<L>() if pick == 9;
|
||||
return math::nan::<L>() if pick == 10;
|
||||
return ((next_bits() % 200000) as f64 / 100.0 - 1000.0) as L;
|
||||
}
|
||||
if const L is integer {
|
||||
return pick as L if pick < 2;
|
||||
return ~(0 as L) if pick == 2;
|
||||
return ~(0 as L) >> 1 if pick == 3;
|
||||
var made: L;
|
||||
val bits := next_bits();
|
||||
val p := (&mut made) as *mut u8;
|
||||
for k in 0..size_of::<L>() {
|
||||
p[k] = ((bits >> (8 * k)) & 0xFF) as u8;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
var none: L;
|
||||
return none;
|
||||
}
|
||||
|
||||
def random_vector<L, const N: u64>(): simd<L[N]> where L: numeric, ordered, zeroable {
|
||||
var made: simd<L[N]>;
|
||||
for i in 0..N {
|
||||
made[i] = random_lane::<L>();
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Whether a vector's lanes are those the scalar operation gives each pair of lanes.
|
||||
def lanes_agree<L, const N: u64>(made: &simd<L[N]>, a: &simd<L[N]>, b: &simd<L[N]>, op: def(L, L): L): bool
|
||||
where L: numeric, ordered, zeroable {
|
||||
for i in 0..N {
|
||||
val want := op(a[i], b[i]);
|
||||
val got: L = made[i];
|
||||
return false if !same_lane_bits(&got, &want);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Whether a vector's lanes are those the scalar operation gives each lane.
|
||||
def lanes_agree1<L, const N: u64>(made: &simd<L[N]>, a: &simd<L[N]>, op: def(L): L): bool
|
||||
where L: numeric, ordered, zeroable {
|
||||
for i in 0..N {
|
||||
val want := op(a[i]);
|
||||
val got: L = made[i];
|
||||
return false if !same_lane_bits(&got, &want);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Whether a mask has the lanes set the scalar comparison holds for.
|
||||
def mask_agrees<L, const N: u64>(made: &mask<L[N]>, a: &simd<L[N]>, b: &simd<L[N]>, op: def(L, L): bool): bool
|
||||
where L: numeric, ordered, zeroable {
|
||||
var bits: u32 = 0;
|
||||
for i in 0..N {
|
||||
val holds := op(a[i], b[i]);
|
||||
return false if made.has(i) != holds;
|
||||
if holds {
|
||||
bits = bits | ((1 as u32) << i);
|
||||
}
|
||||
}
|
||||
return made.bits() == bits && made.any() == (bits != 0) && made.count() == count_ones(bits);
|
||||
}
|
||||
|
||||
# Each operation of a type of lane, against the scalar one, over many vectors.
|
||||
def all_agree<L, const N: u64>(t: &mut tester): void where L: numeric, ordered, zeroable {
|
||||
for _ in 0..40 {
|
||||
val a := random_vector::<L, N>();
|
||||
val b := random_vector::<L, N>();
|
||||
val c := random_vector::<L, N>();
|
||||
t.expects(lanes_agree(&(a + b), &a, &b, def(x: L, y: L): L { return lane_add(x, y); }));
|
||||
t.expects(lanes_agree(&(a - b), &a, &b, def(x: L, y: L): L { return lane_sub(x, y); }));
|
||||
t.expects(lanes_agree(&(a * b), &a, &b, def(x: L, y: L): L { return lane_mul(x, y); }));
|
||||
t.expects(lanes_agree(&a.min(&b), &a, &b, def(x: L, y: L): L { return math::min(x, y); }));
|
||||
t.expects(lanes_agree(&a.max(&b), &a, &b, def(x: L, y: L): L { return math::max(x, y); }));
|
||||
t.expects(lanes_agree1(&(-a), &a, def(x: L): L { return lane_neg(x); }));
|
||||
t.expects(mask_agrees(&a.equal(&b), &a, &b, def(x: L, y: L): bool { return x == y; }));
|
||||
t.expects(mask_agrees(&a.equal(&a), &a, &a, def(x: L, y: L): bool { return x == y; }));
|
||||
t.expects(mask_agrees(&a.not_equal(&b), &a, &b, def(x: L, y: L): bool { return x != y; }));
|
||||
t.expects(mask_agrees(&a.less(&b), &a, &b, def(x: L, y: L): bool { return x < y; }));
|
||||
t.expects(mask_agrees(&a.less_equal(&b), &a, &b, def(x: L, y: L): bool { return x <= y; }));
|
||||
t.expects(mask_agrees(&a.greater(&b), &a, &b, def(x: L, y: L): bool { return x > y; }));
|
||||
t.expects(mask_agrees(&a.greater_equal(&b), &a, &b, def(x: L, y: L): bool { return x >= y; }));
|
||||
val m := a.less(&b);
|
||||
val chosen := select(m, a, b);
|
||||
for i in 0..N {
|
||||
val want: L = m.has(i) ? a[i] : b[i];
|
||||
val got: L = chosen[i];
|
||||
t.expects(same_lane_bits(&got, &want));
|
||||
}
|
||||
val fused := a.fma(&b, &c);
|
||||
for i in 0..N {
|
||||
val x: L = a[i];
|
||||
val y: L = b[i];
|
||||
val z: L = c[i];
|
||||
var want: L;
|
||||
if const L is real {
|
||||
want = math::fma(x, y, z);
|
||||
} else {
|
||||
want = lane_add(lane_mul(x, y), z);
|
||||
}
|
||||
val got: L = fused[i];
|
||||
t.expects(same_lane_bits(&got, &want));
|
||||
}
|
||||
if const L is real {
|
||||
t.expects(lanes_agree(&(a / b), &a, &b, def(x: L, y: L): L { return x / y; }));
|
||||
t.expects(lanes_agree1(&a.abs(), &a, def(x: L): L { return math::abs(x); }));
|
||||
t.expects(lanes_agree1(&a.sqrt(), &a, def(x: L): L { return math::sqrt(x); }));
|
||||
t.expects(lanes_agree1(&a.floor(), &a, def(x: L): L { return math::floor(x); }));
|
||||
t.expects(lanes_agree1(&a.ceil(), &a, def(x: L): L { return math::ceil(x); }));
|
||||
t.expects(lanes_agree1(&a.trunc(), &a, def(x: L): L { return math::trunc(x); }));
|
||||
t.expects(lanes_agree1(&a.round(), &a, def(x: L): L { return math::round(x); }));
|
||||
t.expects(lanes_agree1(&a.round_even(), &a, def(x: L): L { return math::round_even(x); }));
|
||||
}
|
||||
if const L is integer {
|
||||
t.expects(lanes_agree(&(a & b), &a, &b, def(x: L, y: L): L { return x & y; }));
|
||||
t.expects(lanes_agree(&(a | b), &a, &b, def(x: L, y: L): L { return x | y; }));
|
||||
t.expects(lanes_agree(&(a ^ b), &a, &b, def(x: L, y: L): L { return x ^ y; }));
|
||||
t.expects(lanes_agree1(&(~a), &a, def(x: L): L { return ~x; }));
|
||||
val counts: u32[8] = [0, 1, 3, 7, 15, 31, 63, 64];
|
||||
val count := counts[next_bits() % 8];
|
||||
val left := a << count;
|
||||
val right := a >> count;
|
||||
for i in 0..N {
|
||||
val want_left: L = a[i] << count;
|
||||
val want_right: L = a[i] >> count;
|
||||
val got_left: L = left[i];
|
||||
val got_right: L = right[i];
|
||||
t.expects(same_lane_bits(&got_left, &want_left));
|
||||
t.expects(same_lane_bits(&got_right, &want_right));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@test def every_operation_agrees_with_its_lanes(t: &mut tester): void {
|
||||
all_agree::<f32, 4>(t);
|
||||
all_agree::<f32, 8>(t);
|
||||
all_agree::<f64, 2>(t);
|
||||
all_agree::<f64, 4>(t);
|
||||
all_agree::<i8, 16>(t);
|
||||
all_agree::<u8, 32>(t);
|
||||
all_agree::<i16, 8>(t);
|
||||
all_agree::<u16, 16>(t);
|
||||
all_agree::<i32, 4>(t);
|
||||
all_agree::<u32, 8>(t);
|
||||
all_agree::<i64, 2>(t);
|
||||
all_agree::<u64, 4>(t);
|
||||
}
|
||||
|
||||
@test def lanes_wrap_and_round_as_their_numbers_do(t: &mut tester): void {
|
||||
val bytes := u8x16::splat(250) + u8x16::splat(10);
|
||||
t.expects(bytes[0] == 4 && bytes[15] == 4);
|
||||
val most := i32x4::splat(0x7FFFFFFF) + i32x4::splat(1);
|
||||
t.expects(most[2] == -2147483648);
|
||||
val least := i8x16::splat(-128);
|
||||
t.expects((-least)[3] == -128 && least.abs()[3] == -128);
|
||||
t.expects(u16x8::splat(40000).abs()[0] == 40000);
|
||||
val halves := f32x4::of([0.5, 1.5, 2.5, -2.5]);
|
||||
val away: f32[4] = [1.0, 2.0, 3.0, -3.0];
|
||||
val even: f32[4] = [0.0, 2.0, 2.0, -2.0];
|
||||
t.expects(halves.round().lanes() == away);
|
||||
t.expects(halves.round_even().lanes() == even);
|
||||
val roots := f64x2::of([2.0, -0.0]).sqrt();
|
||||
val root: f64 = roots[0];
|
||||
val zero: f64 = roots[1];
|
||||
t.expects(root == math::sqrt(2.0) && math::sign_bit(zero));
|
||||
val floor: f32 = f32x8::splat(-0.75).floor()[7];
|
||||
val ceil: f32 = f32x8::splat(-0.75).ceil()[7];
|
||||
t.expects(floor == -1.0 && ceil == 0.0 && math::sign_bit(ceil));
|
||||
}
|
||||
|
||||
@test def vector_fma_rounds_once(t: &mut tester): void {
|
||||
# (1 + 2^-52)(1 - 2^-52) - 1 is -2^-104 exactly, which multiplying then adding
|
||||
# rounds to 0.
|
||||
val epsilon := math::epsilon::<f64>();
|
||||
val fused := f64x2::splat(1.0 + epsilon).fma(&f64x2::splat(1.0 - epsilon), &f64x2::splat(-1.0));
|
||||
t.expects(fused[0] == -(epsilon * epsilon) && fused[1] == fused[0]);
|
||||
val plain := f64x2::splat(1.0 + epsilon) * f64x2::splat(1.0 - epsilon) - f64x2::splat(1.0);
|
||||
t.expects(plain[0] == 0.0);
|
||||
}
|
||||
|
||||
@test def least_and_greatest_of_reals_are_ieee_754s(t: &mut tester): void {
|
||||
val a := f32x4::of([-0.0, 0.0, math::nan::<f32>(), 1.0]);
|
||||
val b := f32x4::of([0.0, -0.0, 1.0, math::nan::<f32>()]);
|
||||
val least := a.min(&b);
|
||||
val most := a.max(&b);
|
||||
val small := least.lanes();
|
||||
val large := most.lanes();
|
||||
t.expects(math::sign_bit(small[0]) && math::sign_bit(small[1]));
|
||||
t.expects(!math::sign_bit(large[0]) && !math::sign_bit(large[1]));
|
||||
t.expects(math::is_nan(small[2]) && math::is_nan(small[3]) && math::is_nan(large[2]) && math::is_nan(large[3]));
|
||||
t.expects(a.equal(&a).bits() == 0b1011);
|
||||
t.expects(a.not_equal(&a).bits() == 0b0100);
|
||||
}
|
||||
|
||||
@test def masks_say_which_lanes_hold(t: &mut tester): void {
|
||||
val v := i16x8::of([1, -2, 3, -4, 5, -6, 7, -8]);
|
||||
val negative := v.less(&i16x8::splat(0));
|
||||
t.expects(negative.bits() == 0b10101010 && negative.count() == 4 && negative.any() && !negative.all());
|
||||
t.expects((negative.first() else 99) == 1);
|
||||
t.expects((~negative).bits() == 0b01010101);
|
||||
t.expects((negative | ~negative).all() && (negative & ~negative).none());
|
||||
val absolute: i16[8] = [1, 2, 3, 4, 5, 6, 7, 8];
|
||||
t.expects(select(negative, -v, v).lanes() == absolute);
|
||||
val wide := u8x32::splat(9).equal(&u8x32::splat(9));
|
||||
t.expects(wide.all() && wide.count() == 32 && wide.bits() == 0xFFFFFFFF);
|
||||
t.expects((u8x32::splat(1).equal(&u8x32::splat(2)).first() else 99) == 99);
|
||||
}
|
||||
|
||||
@test def vectors_load_and_store_within_views(t: &mut tester): void {
|
||||
val text: strview = "a vector of sixteen bytes and more";
|
||||
val first := u8x16::load(text.span, 0);
|
||||
t.expects(first[0] == 'a' as u8 && first[15] == 't' as u8);
|
||||
val last := u8x16::load(text.span, text.length - 16);
|
||||
t.expects(last[15] == 'e' as u8);
|
||||
if const contracts() {
|
||||
t.expects(simd_stops(def() { val past := u8x16::load("too short".span, 0); }));
|
||||
t.expects(simd_stops(def() { val at := u8x16::load("sixteen bytes, 1".span, 1); }));
|
||||
}
|
||||
|
||||
var room: f64[6] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
|
||||
f64x4::of([1.0, 2.0, 3.0, 4.0]).store(room[:], 2);
|
||||
val stored: f64[6] = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
|
||||
t.expects(room == stored);
|
||||
if const contracts() {
|
||||
t.expects(simd_stops(def() { var little: f64[3]; f64x2::splat(1.0).store(little[:], 2); }));
|
||||
}
|
||||
}
|
||||
|
||||
@test def lanes_are_reached_moved_and_converted(t: &mut tester): void {
|
||||
var v := i32x4::of([10, 20, 30, 40]);
|
||||
v[2] = 33;
|
||||
val written: i32[4] = [10, 20, 33, 40];
|
||||
val reversed: i32[4] = [40, 33, 20, 10];
|
||||
val big: f32 = 3e9;
|
||||
val converted: i32[4] = [1, -1, big as i32, 0];
|
||||
t.expects(v[2] == 33 && v.lanes() == written);
|
||||
t.expects(v.shuffle([3, 2, 1, 0]).lanes() == reversed);
|
||||
t.expects(v.sum() == 103 && v.product() == 10 * 20 * 33 * 40 && v.smallest() == 10 && v.largest() == 40);
|
||||
t.expects(f32x4::of([1.9, -1.9, 3e9, math::nan::<f32>()]).convert::<i32>().lanes() == converted);
|
||||
val ones := f32x4::splat(1.0).bits::<u32, 4>();
|
||||
t.expects(ones[0] == 0x3F800000);
|
||||
t.expects(v == i32x4::of([10, 20, 33, 40]) && v != i32x4::splat(0));
|
||||
if const contracts() {
|
||||
t.expects(simd_stops(def() { val w := i32x4::splat(1); val x := w[4]; }));
|
||||
}
|
||||
}
|
||||
|
||||
@test def integer_lanes_divided_by_zero_stop(t: &mut tester): void {
|
||||
val threes: i32[4] = [3, 3, 3, 3];
|
||||
val ones: i32[4] = [-1, -1, -1, -1];
|
||||
t.expects((i32x4::splat(7) / i32x4::splat(2)).lanes() == threes);
|
||||
t.expects((i32x4::splat(-7) % i32x4::splat(2)).lanes() == ones);
|
||||
t.expects(simd_stops(def() { val q := i32x4::splat(7) / i32x4::of([1, 1, 0, 1]); }));
|
||||
val infinite: f32 = (f32x4::splat(1.0) / f32x4::splat(0.0))[0];
|
||||
t.expects(math::is_infinite(infinite));
|
||||
}
|
||||
|
||||
# Whether converting each lane agrees with `as`, and with the lanes' own bits.
|
||||
def converts_as_lanes<L, M, const N: u64>(a: &simd<L[N]>): bool
|
||||
where L: numeric, ordered, zeroable where M: numeric, ordered, zeroable {
|
||||
val made := a.convert::<M>();
|
||||
for i in 0..N {
|
||||
val want: M = a[i] as M;
|
||||
val got: M = made[i];
|
||||
return false if !same_lane_bits(&got, &want);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Whether widening each half agrees with `as` of its lanes.
|
||||
def widens_as_lanes<L, M, const N: u64>(a: &simd<L[N]>): bool
|
||||
where L: numeric, ordered, zeroable where M: numeric, ordered, zeroable {
|
||||
val low := a.widened::<M>();
|
||||
val high := a.widened_high::<M>();
|
||||
for i in 0..N / 2 {
|
||||
val want_low: M = a[i] as M;
|
||||
val want_high: M = a[N / 2 + i] as M;
|
||||
val got_low: M = low[i];
|
||||
val got_high: M = high[i];
|
||||
return false if !same_lane_bits(&got_low, &want_low) || !same_lane_bits(&got_high, &want_high);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Whether reductions agree with the lanes worked one at a time, lane 0 first.
|
||||
def reduces_as_lanes<L, const N: u64>(a: &simd<L[N]>): bool where L: numeric, ordered, zeroable {
|
||||
var sum: L = a[0];
|
||||
var least: L = a[0];
|
||||
var most: L = a[0];
|
||||
for i in 1..N {
|
||||
val lane: L = a[i];
|
||||
sum = lane_add(sum, lane);
|
||||
least = least < lane ? least : lane;
|
||||
most = most > lane ? most : lane;
|
||||
}
|
||||
val got_sum: L = a.sum();
|
||||
if const L is integer {
|
||||
val got_least: L = a.smallest();
|
||||
val got_most: L = a.largest();
|
||||
return same_lane_bits(&got_sum, &sum) && got_least == least && got_most == most;
|
||||
}
|
||||
return same_lane_bits(&got_sum, &sum);
|
||||
}
|
||||
|
||||
@test def reshaping_agrees_with_its_lanes(t: &mut tester): void {
|
||||
for _ in 0..8 {
|
||||
t.expects(converts_as_lanes::<i32, f32, 4>(&random_vector::<i32, 4>()));
|
||||
t.expects(converts_as_lanes::<u32, f32, 8>(&random_vector::<u32, 8>()));
|
||||
t.expects(converts_as_lanes::<i16, f32, 8>(&random_vector::<i16, 8>()));
|
||||
t.expects(converts_as_lanes::<i32, f64, 4>(&random_vector::<i32, 4>()));
|
||||
t.expects(converts_as_lanes::<f32, i32, 8>(&random_vector::<f32, 8>()));
|
||||
t.expects(converts_as_lanes::<f32, u32, 4>(&random_vector::<f32, 4>()));
|
||||
t.expects(converts_as_lanes::<f64, i32, 4>(&random_vector::<f64, 4>()));
|
||||
t.expects(converts_as_lanes::<f32, f64, 4>(&random_vector::<f32, 4>()));
|
||||
t.expects(converts_as_lanes::<f64, f32, 4>(&random_vector::<f64, 4>()));
|
||||
t.expects(converts_as_lanes::<u8, u16, 16>(&random_vector::<u8, 16>()));
|
||||
t.expects(converts_as_lanes::<i8, i16, 16>(&random_vector::<i8, 16>()));
|
||||
t.expects(converts_as_lanes::<u16, u8, 16>(&random_vector::<u16, 16>()));
|
||||
t.expects(converts_as_lanes::<i64, i32, 4>(&random_vector::<i64, 4>()));
|
||||
t.expects(widens_as_lanes::<i8, i16, 16>(&random_vector::<i8, 16>()));
|
||||
t.expects(widens_as_lanes::<u16, u32, 16>(&random_vector::<u16, 16>()));
|
||||
t.expects(widens_as_lanes::<i32, i64, 4>(&random_vector::<i32, 4>()));
|
||||
t.expects(widens_as_lanes::<f32, f64, 8>(&random_vector::<f32, 8>()));
|
||||
t.expects(reduces_as_lanes::<u8, 32>(&random_vector::<u8, 32>()));
|
||||
t.expects(reduces_as_lanes::<i16, 8>(&random_vector::<i16, 8>()));
|
||||
t.expects(reduces_as_lanes::<u32, 8>(&random_vector::<u32, 8>()));
|
||||
t.expects(reduces_as_lanes::<i64, 2>(&random_vector::<i64, 2>()));
|
||||
t.expects(reduces_as_lanes::<u64, 4>(&random_vector::<u64, 4>()));
|
||||
t.expects(reduces_as_lanes::<f32, 8>(&random_vector::<f32, 8>()));
|
||||
t.expects(reduces_as_lanes::<f64, 4>(&random_vector::<f64, 4>()));
|
||||
}
|
||||
# Narrowing saturates, as packing does.
|
||||
val words := i16x8::of([-300, 300, 1, -1, 32767, -32768, 255, 0]);
|
||||
val signed: i8[16] = [-128, 127, 1, -1, 127, -128, 127, 0, 5, 5, 5, 5, 5, 5, 5, 5];
|
||||
val unsigned: u8[16] = [0, 255, 1, 0, 255, 0, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255];
|
||||
t.expects(words.narrowed::<i8>(&i16x8::splat(5)).lanes() == signed);
|
||||
t.expects(words.narrowed::<u8>(&i16x8::splat(1000)).lanes() == unsigned);
|
||||
val big: u16[4] = [65535, 7, 65535, 7];
|
||||
t.expects(u32x4::of([70000, 7, 70000, 7]).narrowed::<u16>(&u32x4::of([70000, 7, 70000, 7])).lanes()[0:4] == big[0:4]);
|
||||
# Halves taken apart and joined.
|
||||
val eight := u32x8::of([1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
val first: u32[4] = [1, 2, 3, 4];
|
||||
val second: u32[4] = [5, 6, 7, 8];
|
||||
t.expects(eight.low().lanes() == first && eight.high().lanes() == second);
|
||||
t.expects(simd::join(eight.low(), eight.high()) == eight);
|
||||
# Rounding halves away from zero keeps the sign of what it does not move.
|
||||
val halves := f64x4::of([-0.3, 0.49999999999999994, -2.5, 4503599627370495.5]).round();
|
||||
t.expects(math::sign_bit(halves[0]) && halves[1] == 0.0 && halves[2] == -3.0 && halves[3] == 4503599627370496.0);
|
||||
# Gathered and scattered by places, a later lane's write lasting.
|
||||
val table: f64[6] = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5];
|
||||
val gathered := f64x4::gather(table[0:6], i32x4::of([5, 0, 5, 2]));
|
||||
t.expects(gathered == f64x4::of([5.5, 0.5, 5.5, 2.5]));
|
||||
var into: i32[8];
|
||||
i32x8::of([1, 2, 3, 4, 5, 6, 7, 8]).scatter(into[0:8], i32x8::of([7, 6, 5, 4, 3, 2, 1, 7]));
|
||||
t.expects(into[7] == 8 && into[1] == 7 && into[0] == 0);
|
||||
# Shuffles of each size, against reading each lane.
|
||||
val order: u8[8] = [7, 0, 6, 1, 5, 2, 4, 3];
|
||||
val floats := random_vector::<f32, 8>();
|
||||
val moved := floats.shuffle(order);
|
||||
for i in 0..8u {
|
||||
val want: f32 = floats[order[i] as u64];
|
||||
val got: f32 = moved[i];
|
||||
t.expects(same_lane_bits(&got, &want));
|
||||
}
|
||||
val bytes := random_vector::<u8, 16>();
|
||||
t.expects(bytes.shuffle([15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])[0] == bytes[15]);
|
||||
if const contracts() {
|
||||
t.expects(simd_stops(def() { val wrong := i32x4::splat(1).shuffle([0, 1, 4, 2]); }));
|
||||
t.expects(simd_stops(def() { val far := f64x4::gather(table[0:6], i32x4::of([0, 6, 1, 2])); }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
# Tests of words of bytes, `core::swar`: every test against the same choice made a
|
||||
# byte at a time, for every value in every place, and the text functions that go
|
||||
# by words against their loops a byte at a time, for every length to past a few
|
||||
# words, wherever the bytes they look for fall.
|
||||
|
||||
import std::serial;
|
||||
import core::swar;
|
||||
import std::testing;
|
||||
|
||||
|
||||
var swar_seed: u64 = 0x2545F4914F6CDD1D;
|
||||
|
||||
def swar_random(): u64 {
|
||||
swar_seed = swar_seed ^ (swar_seed << 13);
|
||||
swar_seed = swar_seed ^ (swar_seed >> 7);
|
||||
swar_seed = swar_seed ^ (swar_seed << 17);
|
||||
return swar_seed;
|
||||
}
|
||||
|
||||
# What a search found, or a number where it found nothing.
|
||||
def swar_or(found: maybe<u64>, none: u64): u64 {
|
||||
if found is some(at) {
|
||||
return at;
|
||||
}
|
||||
return none;
|
||||
}
|
||||
|
||||
# The mask choosing the bytes of a word a test chooses, made a byte at a time.
|
||||
def swar_choice(word: u64, test: u64, a: u8, b: u8): u64 {
|
||||
var mask: u64 = 0;
|
||||
for k in 0..8u {
|
||||
val byte := ((word >> (k * 8)) & 0xFF) as u8;
|
||||
val chosen := match test {
|
||||
0 => byte == 0,
|
||||
1 => byte == a,
|
||||
2 => byte < a,
|
||||
3 => byte > a,
|
||||
4 => byte >= a && byte <= b,
|
||||
else => byte < 0x80,
|
||||
};
|
||||
if chosen {
|
||||
mask = mask | (0x80u << (k * 8));
|
||||
}
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
# The same choice by words.
|
||||
def swar_chosen(word: swar::bytes8, test: u64, a: u8, b: u8): u64 {
|
||||
return match test {
|
||||
0 => word.zero(),
|
||||
1 => word.equal(a),
|
||||
2 => word.below(a),
|
||||
3 => word.above(a),
|
||||
4 => word.within(a, b),
|
||||
else => word.ascii(),
|
||||
};
|
||||
}
|
||||
|
||||
@test def swar_tests_choose_exactly_the_bytes_they_say(t: &mut tester): void {
|
||||
# Bounds at their edges, and bytes the tests are given.
|
||||
val bounds: u8[12] = [0, 1, 9, 13, 32, 127, 128, 129, 200, 254, 255, '0'];
|
||||
var wrong: u64 = 0;
|
||||
for place in 0..8u {
|
||||
for value in 0..256u {
|
||||
# Each value in each place, with the other places random, and sometimes a
|
||||
# copy of the value, so a borrow from one byte would reach the next.
|
||||
var word := swar_random();
|
||||
if (value & 3) == 0 {
|
||||
word = word & 0x00FF00FF00FF00FF;
|
||||
}
|
||||
word = (word & ~(0xFFu << (place * 8))) | (value << (place * 8));
|
||||
if swar_chosen(word, 0, 0, 0) != swar_choice(word, 0, 0, 0) { wrong++; }
|
||||
if swar_chosen(word, 5, 0, 0) != swar_choice(word, 5, 0, 0) { wrong++; }
|
||||
for i in 0..12u {
|
||||
val a := bounds[i];
|
||||
val b := bounds[(i + 3) % 12];
|
||||
for test in 1..5u {
|
||||
if swar_chosen(word, test, a, b) != swar_choice(word, test, a, b) { wrong++; }
|
||||
}
|
||||
# The byte itself is equal, and within itself.
|
||||
if swar_chosen(word, 1, value as u8, 0) != swar_choice(word, 1, value as u8, 0) { wrong++; }
|
||||
if swar_chosen(word, 4, value as u8, value as u8) != swar_choice(word, 4, value as u8, value as u8) { wrong++; }
|
||||
}
|
||||
}
|
||||
}
|
||||
t.expects(wrong == 0);
|
||||
}
|
||||
|
||||
@test def swar_masks_say_where_and_how_many_they_choose(t: &mut tester): void {
|
||||
var wrong: u64 = 0;
|
||||
for bits in 0..256u {
|
||||
var mask: u64 = 0;
|
||||
var spread: u64 = 0;
|
||||
var first: u64 = 8;
|
||||
var last: u64 = 8;
|
||||
var count: u64 = 0;
|
||||
for k in 0..8u {
|
||||
if ((bits >> k) & 1) != 0 {
|
||||
mask = mask | (0x80u << (k * 8));
|
||||
spread = spread | (0xFFu << (k * 8));
|
||||
first = first == 8 ? k : first;
|
||||
last = k;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
val chosen: swar::mask8 = mask;
|
||||
val rest: u64 = first == 8 ? 0 : mask & ~(0x80u << (first * 8));
|
||||
if chosen.any() != (bits != 0) { wrong++; }
|
||||
if chosen.first() != first || chosen.last() != last || chosen.count() != count { wrong++; }
|
||||
if chosen.rest() != rest || chosen.spread() != spread { wrong++; }
|
||||
}
|
||||
t.expects(wrong == 0);
|
||||
for count in 0..10u {
|
||||
val want: u64 = count >= 8 ? 0x8080808080808080 : 0x8080808080808080 & ((1u << (count * 8)) - 1);
|
||||
t.expects(swar::mask8::leading(count) == want);
|
||||
}
|
||||
}
|
||||
|
||||
@test def swar_words_change_case_and_read_digits(t: &mut tester): void {
|
||||
var wrong: u64 = 0;
|
||||
for place in 0..8u {
|
||||
for value in 0..256u {
|
||||
val word: swar::bytes8 = (swar_random() & ~(0xFFu << (place * 8))) | (value << (place * 8));
|
||||
for k in 0..8u {
|
||||
val byte := word.byte(k);
|
||||
if word.upper().byte(k) != byte.to_upper || word.lower().byte(k) != byte.to_lower { wrong++; }
|
||||
}
|
||||
}
|
||||
}
|
||||
t.expects(wrong == 0);
|
||||
t.expects(swar::repeat(0xAB) == 0xABABABABABABABAB && swar::repeat(0) == 0);
|
||||
t.expects(swar::choose(0x0000800000000080, 0x1111111111111111, 0x2222222222222222) == 0x2222112222222211);
|
||||
|
||||
t.expects(swar_or(swar::load("20261016", 0).digits(), 1) == 20261016);
|
||||
t.expects(swar_or(swar::load("00000000", 0).digits(), 1) == 0);
|
||||
t.expects(swar_or(swar::load("99999999", 0).digits(), 1) == 99999999);
|
||||
t.expects(swar_or(swar::load("01234567", 0).digits(), 1) == 1234567);
|
||||
# Each place not a digit in turn, by a byte on either side of the digits.
|
||||
for place in 0..8u {
|
||||
for byte in ['/' as u8, ':', 'a', ' ', 0, 0xB0] {
|
||||
var text := string::from("12345678", nothing {});
|
||||
text[place] = byte;
|
||||
t.expects(swar::load(text.span, 0).digits() is none);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@test def swar_loads_read_only_the_bytes_of_the_view(t: &mut tester): void {
|
||||
val buffer: strview = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
for start in 0..8u {
|
||||
for length in 1..12u {
|
||||
# A view whose next byte is set, so a read past its end would show.
|
||||
val view := buffer.substr(start, length);
|
||||
for at in 0..length {
|
||||
var want: u64 = 0;
|
||||
val left := length - at;
|
||||
for k in 0..(left < 8 ? left : 8) {
|
||||
want = want | (('A' as u64 + start + at + k) << (k * 8));
|
||||
}
|
||||
t.expects(swar::load_last(view, at) == want);
|
||||
if left >= 8 {
|
||||
t.expects(swar::load(view, at) == want);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
t.expects(swar::load_last("".data, 0) == 0);
|
||||
}
|
||||
|
||||
# Text of a length over a few bytes, so each is found often, after `start` bytes
|
||||
# of a buffer, which then views it.
|
||||
def swar_text(buffer: &mut string, start: u64, length: u64, alphabet: strview): strview {
|
||||
buffer.clear();
|
||||
for _ in 0..start {
|
||||
buffer.push('#');
|
||||
}
|
||||
for _ in 0..length {
|
||||
buffer.push(alphabet[swar_random() % alphabet.length]);
|
||||
}
|
||||
buffer.push('#');
|
||||
return buffer.span.substr(start, length);
|
||||
}
|
||||
|
||||
@test def text_functions_find_what_a_byte_at_a_time_finds(t: &mut tester): void {
|
||||
var buffer := string::new(nothing {});
|
||||
var wrong: u64 = 0;
|
||||
for length in 0..41u {
|
||||
for start in 0..8u {
|
||||
val text := swar_text(&mut buffer, start, length, length % 3 == 0 ? "abcdefgh" : "ab");
|
||||
for byte in ['a' as u8, 'b', 'h', '#', 0] {
|
||||
var first: u64 = length;
|
||||
var last: u64 = length;
|
||||
var count: u64 = 0;
|
||||
for k in 0..length {
|
||||
if text[k] == byte {
|
||||
first = first == length ? k : first;
|
||||
last = k;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
val found := text.index_of(&byte);
|
||||
val found_last := text.last_index_of(&byte);
|
||||
if swar_or(found, length) != first { wrong++; }
|
||||
if swar_or(found_last, length) != last { wrong++; }
|
||||
if text.count_of(&byte) != count || text.contains(&byte) != (count != 0) { wrong++; }
|
||||
}
|
||||
|
||||
# Runs of the text and others, and any of a few bytes.
|
||||
for size in 0..6u {
|
||||
var sought := string::new(nothing {});
|
||||
val from := length > size ? swar_random() % (length - size + 1) : 0;
|
||||
for k in 0..size {
|
||||
sought.push(k + from < length && (swar_random() & 3) != 0 ? text[k + from] : 'a');
|
||||
}
|
||||
var want: u64 = length + 1;
|
||||
if sought.length <= length {
|
||||
for at in 0..(length - sought.length + 1) {
|
||||
if text.substr(at, sought.length) == sought.span {
|
||||
want = at;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
val got := text.find(sought.span);
|
||||
if swar_or(got, length + 1) != want { wrong++; }
|
||||
|
||||
var any: u64 = length;
|
||||
for at in 0..length {
|
||||
if sought.span.contains(&text[at]) {
|
||||
any = at;
|
||||
break;
|
||||
}
|
||||
}
|
||||
val got_any := text.find_any(sought.span);
|
||||
if swar_or(got_any, length) != any { wrong++; }
|
||||
}
|
||||
}
|
||||
}
|
||||
t.expects(wrong == 0);
|
||||
|
||||
# More than four bytes are looked for through a set.
|
||||
val text: strview = "the quick brown fox jumps over the lazy dog";
|
||||
t.expects(swar_or(text.find_any("xyzq!"), 99) == 4 && text.find_any("QWERTY") is none);
|
||||
t.expects(swar_or(text.find("the"), 99) == 0 && swar_or(text.find("lazy"), 99) == 35);
|
||||
t.expects(swar_or(text.find("dog"), 99) == 40 && text.find("dogs") is none);
|
||||
t.expects(swar_or(text.find(""), 99) == 0 && swar_or("".find(""), 99) == 0 && "".find("a") is none);
|
||||
}
|
||||
|
||||
@test def text_functions_change_and_check_as_a_byte_at_a_time_does(t: &mut tester): void {
|
||||
var buffer := string::new(nothing {});
|
||||
var wrong: u64 = 0;
|
||||
for length in 0..41u {
|
||||
for start in 0..8u {
|
||||
val text := swar_text(&mut buffer, start, length, "aZz@[`{ \t\n\r\x0B\x0C9");
|
||||
val upper := text.upper();
|
||||
val lower := text.lower();
|
||||
for k in 0..length {
|
||||
if upper[k] != text[k].to_upper || lower[k] != text[k].to_lower { wrong++; }
|
||||
}
|
||||
if upper.length != length || lower.length != length { wrong++; }
|
||||
|
||||
# Trimming, where the text is mostly whitespace.
|
||||
var left: u64 = 0;
|
||||
while left < length && text[left].is_space { left++; }
|
||||
var right := length;
|
||||
while right > 0 && text[right - 1].is_space { right--; }
|
||||
if text.ltrim() != text.substr(left, length - left) { wrong++; }
|
||||
if text.rtrim() != text.substr(0, right) { wrong++; }
|
||||
if text.trim() != (left < right ? text.substr(left, right - left) : text.substr(0, 0)) { wrong++; }
|
||||
|
||||
# ASCII, and a byte past it in each place.
|
||||
if !text.is_ascii() || !serial::is_utf8(text) { wrong++; }
|
||||
for place in 0..length {
|
||||
var wide := string::from(text, nothing {});
|
||||
wide[place] = 0x80 | (place as u8);
|
||||
if wide.span.is_ascii() || serial::is_utf8(wide.span) { wrong++; }
|
||||
wide[place] = 0xC3;
|
||||
if place + 1 < length {
|
||||
wide[place + 1] = 0xA9;
|
||||
if !serial::is_utf8(wide.span) { wrong++; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
t.expects(wrong == 0);
|
||||
|
||||
# Whitespace of every length on either side.
|
||||
for spaces in 0..20u {
|
||||
var text := string::new(nothing {});
|
||||
for k in 0..spaces { text.push(k % 3 == 0 ? '\t' : ' '); }
|
||||
text.append("word");
|
||||
for k in 0..spaces { text.push(k % 2 == 0 ? '\n' : ' '); }
|
||||
t.expects(text.span.trim() == "word" && text.span.ltrim().length == 4 + spaces && text.span.rtrim().length == 4 + spaces);
|
||||
}
|
||||
}
|
||||
|
||||
# Where a run of text is found, while compiling and while running.
|
||||
def swar_found(text: strview, sought: strview): u64 {
|
||||
return swar_or(text.find(sought), text.length);
|
||||
}
|
||||
|
||||
def swar_date(text: strview): u64 {
|
||||
return swar_or(swar::load(text, 0).digits(), 0);
|
||||
}
|
||||
|
||||
const swar_compiled_place: u64 = swar_found("a needle in a haystack of needles", "haystack");
|
||||
const swar_compiled_date: u64 = swar_date("20261016");
|
||||
const swar_compiled_count: u64 = "one\ntwo\nthree\nfour\n".count_of(&'\n');
|
||||
|
||||
@test def swar_words_work_alike_while_compiling(t: &mut tester): void {
|
||||
t.expects(swar_compiled_place == 14 && swar_compiled_place == swar_found("a needle in a haystack of needles", "haystack"));
|
||||
t.expects(swar_compiled_date == 20261016 && swar_compiled_date == swar_date("20261016"));
|
||||
t.expects(swar_compiled_count == 4);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
# Tests of text: what a literal is where nothing asks for a type, and what
|
||||
# trimming gives of a view and of a string.
|
||||
import std::testing;
|
||||
|
||||
|
||||
# Whether the type is `strview`, which a literal is where nothing asks otherwise.
|
||||
def is_view<T>(value: &T): bool {
|
||||
return name_of::<T>() == "strview";
|
||||
}
|
||||
|
||||
@test def text_literals_are_views(t: &mut tester): void {
|
||||
val plain := "abc";
|
||||
val built := $"abc{1}";
|
||||
t.expects(is_view(&plain) && !is_view(&built));
|
||||
t.expects(is_view(&"abc".trim()) && "abc".length == 3);
|
||||
|
||||
# Each trimmed literal views its own bytes, which last as long as the program.
|
||||
val first := " x ".trim();
|
||||
val second := " y ".trim();
|
||||
t.expects(first == "x" && second == "y");
|
||||
}
|
||||
|
||||
@test def text_trims_to_what_it_was_given(t: &mut tester): void {
|
||||
val view: strview = " \t both \n";
|
||||
t.expects(view.trim() == "both" && view.ltrim() == "both \n" && view.rtrim() == " \t both");
|
||||
t.expects(is_view(&view.trim()));
|
||||
|
||||
# A string's trims are strings of their own, which leave it as it was.
|
||||
val owned := string::from(" held ", nothing {});
|
||||
var trimmed := owned.trim();
|
||||
trimmed.append("!");
|
||||
t.expects(trimmed.span == "held!" && owned.span == " held ");
|
||||
t.expects(owned.ltrim().span == "held " && owned.rtrim().span == " held");
|
||||
t.expects(!is_view(&owned.trim()));
|
||||
}
|
||||
Reference in new issue
Block a user