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