aboutsummaryrefslogtreecommitdiff
path: root/std/list.zig
blob: 0c5bf92da6486eb42f0c26212246ad751f2cd00d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const debug = @import("debug.zig");
const assert = debug.assert;
const mem = @import("mem.zig");
const Allocator = mem.Allocator;

pub struct List(T: type) {
    const Self = this;

    items: []T,
    len: usize,
    allocator: &Allocator,

    pub fn init(allocator: &Allocator) -> Self {
        Self {
            .items = zeroes,
            .len = 0,
            .allocator = allocator,
        }
    }

    pub fn deinit(l: &Self) {
        l.allocator.free(T, l.items);
    }

    pub fn toSlice(l: &Self) -> []T {
        return l.items[0...l.len];
    }

    pub fn append(l: &Self, item: T) -> %void {
        const new_length = l.len + 1;
        %return l.ensureCapacity(new_length);
        l.items[l.len] = item;
        l.len = new_length;
    }

    pub fn resize(l: &Self, new_len: usize) -> %void {
        %return l.ensureCapacity(new_len);
        l.len = new_len;
    }

    pub fn ensureCapacity(l: &Self, new_capacity: usize) -> %void {
        var better_capacity = l.items.len;
        if (better_capacity >= new_capacity) return;
        while (true) {
            better_capacity += better_capacity / 2 + 8;
            if (better_capacity >= new_capacity) break;
        }
        l.items = %return l.allocator.realloc(T, l.items, better_capacity);
    }
}

fn basicListTest() {
    @setFnTest(this, true);

    var list = List(i32).init(&debug.global_allocator);
    defer list.deinit();

    {var i: usize = 0; while (i < 10; i += 1) {
        %%list.append(i32(i + 1));
    }}

    {var i: usize = 0; while (i < 10; i += 1) {
        assert(list.items[i] == i32(i + 1));
    }}
}