-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist.zig
More file actions
40 lines (35 loc) · 1.14 KB
/
list.zig
File metadata and controls
40 lines (35 loc) · 1.14 KB
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
const std = @import("std");
const Allocator = std.mem.Allocator;
pub fn List(comptime T: type) type {
return struct {
const Self = @This();
count: usize,
capacity: usize,
items: []T,
allocator: *Allocator,
pub fn init(allocator: *Allocator) Self {
return Self{
.count = 0,
.capacity = 0,
.items = &[_]T{},
.allocator = allocator,
};
}
pub fn deinit(self: *Self) void {
if (self.capacity == 0) return;
self.allocator.free(self.items);
self.* = Self.init(self.allocator);
}
pub fn appendItem(self: *Self, item: T) void {
if (self.capacity < self.count + 1) {
self.capacity = growCapacity(self.capacity);
self.items = self.allocator.realloc(self.items, self.capacity) catch @panic("Error reallocating memory");
}
self.items[self.count] = item;
self.count += 1;
}
};
}
pub fn growCapacity(capacity: usize) usize {
return if (capacity < 8) 8 else capacity * 2;
}