//! 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: usize) type { const seg_size: usize = (seg_max_bytes - @sizeOf(usize)) / @sizeOf(T); comptime { if (seg_size < 4) { @panic("Surely you didn't want to have segments this small?"); } } const Node = 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(); head: *Node, idx: usize = 0, // To prevent "thrashing" we don't immediately deallocate the current // node when it's emptied but rather save it aside. aside: ?*Node = null, pub fn init(alloc: Alloc) !Self { return .{ .head = try .new(alloc) }; } pub fn deinit(self: *Self, alloc: Alloc) void { if (self.aside) |aside| alloc.destroy(aside); var node: ?Node = self.head; while (node) |n| { alloc.destroy(n); node = n.prev; } } pub fn push(self: *Self, alloc: Alloc, elt: T) !void { if (self.idx == seg_size) { if (self.aside) |aside| { self.head = aside; self.aside = null; } else { const prev = self.head; self.head = try .new(alloc); self.head.prev = prev; } self.idx = 0; } self.head.elts[self.idx] = elt; self.idx += 1; } pub fn pop(self: *Self, alloc: Alloc) ?T { if (self.idx == 0) { if (self.head.prev) |prev| { if (self.aside) |aside| alloc.destroy(aside); self.aside = self.head; self.head = prev; self.idx = seg_size; } else { return null; } } self.idx -= 1; return self.head.elts[self.idx]; } }; }