forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilder.zig
33 lines (29 loc) · 1016 Bytes
/
builder.zig
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
const Allocator = @import("std").mem.Allocator;
const assert = @import("std").debug.assert;
const copy = @import("std").mem.copy;
const io = @import("io");
pub fn Builder(comptime Type: type) type {
return struct {
const This = @This();
len: usize = 0,
cap: usize = 0,
ptr: ?[*]Type = null,
pub fn count(this: *This, slice: Type) void {
this.cap += slice.len;
}
pub fn allocate(this: *This, allocator: Allocator) !void {
var slice = try allocator.alloc(Type, this.cap);
this.ptr = slice.ptr;
this.len = 0;
}
pub fn append(this: *This, item: Type) *const Type {
assert(this.len <= this.cap); // didn't count everything
assert(this.ptr != null); // must call allocate first
var result = &this.ptr.?[this.len];
result.* = item;
this.len += 1;
assert(this.len <= this.cap);
return result;
}
};
}