about summary refs log tree commit diff
path: root/aoc/2021/10/stack.zig
blob: 1002d616c4adfa6da983447cbd2efce29154323c (plain) (blame)
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
const Allocator = @import("std").mem.Allocator;

pub fn Stack(comptime T: type) type {
    return struct {
        allocator: *Allocator,
        memory: []T,
        len: usize,

        const Self = @This();

        pub fn alloc(allocator: *Allocator, size: usize) !Self {
            return Self{
                .allocator = allocator,
                .memory = try allocator.alloc(T, size),
                .len = 0,
            };
        }

        pub fn free(self: *Self) void {
            self.allocator.free(self.memory);
            self.* = undefined;
        }

        pub fn push(self: *Self, node: T) void {
            self.memory[self.len] = node;
            self.len += 1;
        }

        pub fn pop(self: *Self) T {
            self.len -= 1;
            return self.memory[self.len];
        }

        pub fn reset(self: *Self) void {
            self.len = 0;
        }
    };
}