blob: d2c6aaadf12ad3b39effc1818f3b0dda43f636f4 (
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 Node has a pointer (= usize) and the element array; calculate the
// correct segment size (as 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 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: IdxType = 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];
}
};
}
|