Files
sakurac/tests/core/owners.sakura
T
2026-12-06 13:52:57 -06:00

75 lines
2.0 KiB
Plaintext

# 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);
}