Wrote my first data structure using comptime to replace an ArrayList where the maximum size is known at compile time. As I use it as a stack, it only implements append and pop as that is all I need.
pub fn ConstStack(comptime T: type, size: comptime_int) type {
return struct {
items: [size]T = undefined,
len: usize = 0,
const Self = @This();
pub fn append(self: *Self, item: T) !void {
if (self.len == size) {
return error.OutOfMemory;
}
self.items[self.len] = item;
self.len += 1;
}
pub fn pop(self: *Self) ?T {
if (self.len == 0) return null;
self.len -= 1;
return self.items[self.len];
}
};
}