summaryrefslogtreecommitdiff
path: root/src/zisp/util/seg_stack.zig
blob: 4abb6ef473a10d308daa35e123f74a6053e2737d (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//! Segmented linked list backed stack

const std = @import("std");

const Alloc = std.mem.Allocator;

/// Segmented linked list backed stack
pub fn SegStack(T: type, seg_max_bytes: comptime_int) type {

    // Each Segment has a pointer (= usize) and the element array; calculate
    // correct segment size (in element count) based on that.
    const seg_size = (seg_max_bytes - @sizeOf(usize)) / @sizeOf(T);

    const IdxType = std.math.IntFittingRange(seg_size);

    comptime {
        if (seg_size < 4) {
            @panic("Surely you didn't want to have segments this small?");
        }
    }

    const Segment = struct {
        const Self = @This();

        prev: ?*Self = null,
        elts: [seg_size]T = undefined,

        pub fn new(alloc: Alloc) !*Self {
            const self = try alloc.create(Self);
            self.* = .{};
            return self;
        }
    };

    return struct {
        const Self = @This();

        cur: *Segment,
        idx: IdxType = 0,

        // To prevent "thrashing" we don't immediately deallocate the current
        // segment when it's emptied but rather save it aside.
        aside: ?*Segment = null,

        pub fn init(alloc: Alloc) !Self {
            return .{ .cur = try .new(alloc) };
        }

        pub fn deinit(self: *Self, alloc: Alloc) void {
            if (self.aside) |aside| alloc.destroy(aside);
            var seg: ?Segment = self.cur;
            while (seg) |n| {
                alloc.destroy(n);
                seg = n.prev;
            }
        }

        pub fn push(self: *Self, alloc: Alloc, elt: T) !void {
            if (self.idx == seg_size) {
                if (self.aside) |aside| {
                    self.cur = aside;
                    self.aside = null;
                } else {
                    const prev = self.cur;
                    self.cur = try .new(alloc);
                    self.cur.prev = prev;
                }
                self.idx = 0;
            }
            self.cur.elts[self.idx] = elt;
            self.idx += 1;
        }

        pub fn pop(self: *Self, alloc: Alloc) ?T {
            if (self.idx == 0) {
                if (self.cur.prev) |prev| {
                    if (self.aside) |aside| alloc.destroy(aside);
                    self.aside = self.cur;
                    self.cur = prev;
                    self.idx = seg_size;
                } else {
                    return null;
                }
            }
            self.idx -= 1;
            return self.cur.elts[self.idx];
        }
    };
}