lib/std/mem/heap/tests.rad 2.6 KiB raw
1
//! Tests for static heaps.
2
3
use std::testing;
4
use std::lang::alloc;
5
6
/// Region that the tests grow slices in.
7
static POOL: super::Heap = super::new(256);
8
9
/// Storage for the constant heap check.
10
constant CONSTANT_POOL: super::Heap = super::new(128);
11
12
/// A slice grows in a static heap and keeps its elements.
13
@test fn testHeapAppend() throws (testing::TestError) {
14
    let mut xs: *mut [u32] = &mut [];
15
    let mut i: u32 = 0;
16
    while i < 8 {
17
        try! xs.append(i * 3, &POOL);
18
        set i += 1;
19
    }
20
    try testing::expect(xs.len == 8);
21
    try testing::expect(xs[7] == 21);
22
}
23
24
/// Growth beyond the region throws the allocation error.
25
@test fn testHeapExhausted() throws (testing::TestError) {
26
    let mut xs: *mut [u64] = &mut [];
27
    try xs.resize(1024, 0, &POOL) catch e {
28
        try testing::expect(e == alloc::AllocError::OutOfMemory);
29
        return;
30
    };
31
    try testing::expect(false);
32
}
33
34
/// Storage for a heap made over bytes.
35
static STORAGE: [u8; 256] = [0; 256];
36
37
/// A heap over bytes grows slices, reports its use, and rewinds to a mark.
38
@test unsafe fn testOverMarkRewind() throws (testing::TestError) {
39
    let heap = super::over(&mut STORAGE[..]);
40
    try testing::expect(super::used(heap) == 0);
41
    try testing::expect(super::remaining(heap) > 160);
42
    let before = super::remaining(heap);
43
    let state = super::mark(heap);
44
    let mut xs: *mut [u32] = &mut [];
45
    try! xs.resize(4, 7, heap);
46
    try testing::expect(super::used(heap) >= 16);
47
    try testing::expect(super::remaining(heap) < before);
48
    try testing::expect(xs[3] == 7);
49
    super::rewind(heap, state);
50
    try testing::expect(super::used(heap) == 0 and super::remaining(heap) == before);
51
    // The memory is handed out again.
52
    let mut ys: *mut [u32] = &mut [];
53
    try! ys.resize(4, 9, heap);
54
    try testing::expect(ys[0] == 9);
55
}
56
57
/// A heap over bytes throws when the storage is used up.
58
@test unsafe fn testOverExhausted() throws (testing::TestError) {
59
    static SMALL: [u8; 64] = [0; 64];
60
    let heap = super::over(&mut SMALL[..]);
61
    let mut xs: *mut [u64] = &mut [];
62
    try xs.resize(64, 0, heap) catch e {
63
        try testing::expect(e == alloc::AllocError::OutOfMemory);
64
        return;
65
    };
66
    try testing::expect(false);
67
}
68
69
/// Constant heap storage retains its capacity and allocation state.
70
@test fn testConstantHeap() throws (testing::TestError) {
71
    assert super::remaining(&CONSTANT_POOL) == 128;
72
    let mut items: *mut [u32] = &mut [];
73
    try! items.resize(4, 7, &CONSTANT_POOL);
74
    assert items.len == 4 and items[3] == 7;
75
    assert super::used(&CONSTANT_POOL) == 16;
76
    assert super::remaining(&CONSTANT_POOL) == 112;
77
}