# 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; 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>; } @test def boxes_and_maybe_boxes_are_one_word(t: &mut tester): void { t.expects(size_of::>() == 8 && size_of::>>() == 8); val none_held: maybe> = 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::::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::::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> = nothing {}; for i in 0..100u { front = box::::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); }