Libove Blog

Personal Blog about anything - mostly programming, cooking and random thoughts

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.

#zig #dev

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];
        }
    };
}




Interactions

Reply from Chaz Haws:

@h4kor If you don’t know of it, BoundedArray in the standard library may suit your needs. If you do know of it and just want this simpler API, then carry on.


(Original Post)