zig/std/list.zig

68 lines
1.7 KiB
Zig
Raw Normal View History

const debug = @import("debug.zig");
const assert = debug.assert;
const mem = @import("mem.zig");
const Allocator = mem.Allocator;
pub fn List(comptime T: type) -> type{
2016-12-19 08:40:26 +08:00
struct {
const Self = this;
2016-12-19 08:40:26 +08:00
items: []T,
len: usize,
allocator: &Allocator,
2016-12-19 08:40:26 +08:00
pub fn init(allocator: &Allocator) -> Self {
Self {
2016-12-31 14:31:23 +08:00
.items = []T{},
2016-12-19 08:40:26 +08:00
.len = 0,
.allocator = allocator,
}
}
2016-12-19 08:40:26 +08:00
pub fn deinit(l: &Self) {
l.allocator.free(l.items);
2016-12-19 08:40:26 +08:00
}
2017-01-06 07:50:36 +08:00
pub fn toSlice(l: &const Self) -> []const T {
2016-12-19 08:40:26 +08:00
return l.items[0...l.len];
}
2016-12-19 08:40:26 +08:00
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;
}
2016-12-19 08:40:26 +08:00
pub fn resize(l: &Self, new_len: usize) -> %void {
%return l.ensureCapacity(new_len);
l.len = new_len;
}
2016-12-19 08:40:26 +08:00
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);
}
}
}
2016-08-17 13:42:50 +08:00
fn basicListTest() {
@setFnTest(this);
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));
}}
}