forked from booniepepper/zig-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_allocator.zig
More file actions
257 lines (203 loc) · 8.23 KB
/
Copy pathstack_allocator.zig
File metadata and controls
257 lines (203 loc) · 8.23 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
///////////////////////////////////////////////////////////////
//// Motivation and Explanation for StackAllocator ////////////
// The StackAllocator has a congtiguous memory buffer (size in bytes)
// that it attempts to utilize before deferring to it's backing_allocator.
//
// It can only roll-back the used capacity if what is being freed was the
// last thing to be allocated (like a typical stack, first-in-last-out).
//
// To free all of the memory from the stack, deallocate the items in
// reverse order to what they were allocated in.
//
// Resize will only work if you are attempting to resize the last
// allocated item (item on top of the stack).
//
// If you overflow the stack, the StackAllocator will defer to using
// its backing_allocator.
//
const std = @import("std");
pub fn StackBuffer(comptime size: usize) type {
return struct {
const Self = @This();
const Size = size;
items: [Size]u8 = undefined,
used: usize = 0,
pub fn withdraw(self: *Self, n: usize) ?[]u8 {
if ((n + self.used) <= self.items.len) {
var data = self.items[self.used..self.used + n];
self.used += n;
return data;
}
return null;
}
pub inline fn owns(self: *const Self, data: []u8) bool {
const lhs = @intFromPtr(&self.items[0]);
const rhs = @intFromPtr(&self.items[self.items.len - 1]);
const ptr = @intFromPtr(data.ptr);
return (lhs <= ptr) and (ptr <= rhs);
}
pub inline fn isTop(self: *const Self, data: []u8) bool {
// can only pop values off the top of the stack
if(self.used < data.len) {
return false;
}
// check to see if we can back up the values
return (@intFromPtr(&self.items[self.used - data.len]) == @intFromPtr(data.ptr));
}
pub fn canResize(self: *const Self, data: []u8, n: usize) bool {
// can only resize values at the top of the stack
if(!self.isTop(data)) {
return false;
}
const old_used = self.used - data.len;
const new_used = old_used + n;
return new_used <= Size;
}
pub fn deposit(self: *Self, data: []u8) bool {
if (!self.owns(data)){
return false;
}
// check to see if we can back up the values
if(self.isTop(data)) {
self.used -= data.len;
}
return true;
}
};
}
////////////////////////////////////////////////////////
//////// StackAllocator Implementation /////////////////
pub fn StackAllocator(comptime size: usize) type {
return struct {
const Self = @This();
const Size = size;
stack_buffer: StackBuffer(Size),
backing_allocator: std.mem.Allocator,
// TODO: Create a dummy mutex that can be swapped via policy
mutex: std.Thread.Mutex = std.Thread.Mutex{ },
pub fn init(backing_allocator: std.mem.Allocator) Self {
return Self {
.backing_allocator = backing_allocator,
.stack_buffer = .{ },
};
}
pub fn allocator(self: *Self) std.mem.Allocator {
return .{
.ptr = self,
.vtable = &.{
.alloc = alloc,
.resize = resize,
.free = free,
},
};
}
pub fn alloc(
ctx: *anyopaque,
len: usize,
log2_ptr_align: u8,
ret_addr: usize
) ?[*]u8 {
const self: *Self = @ptrCast(@alignCast(ctx));
self.mutex.lock();
defer self.mutex.unlock();
if(self.stack_buffer.withdraw(len)) |data| {
return data.ptr;
}
return self.backing_allocator.rawAlloc(len, log2_ptr_align, ret_addr);
}
pub fn resize(
ctx: *anyopaque,
old_mem: []u8,
log2_align: u8,
new_len: usize,
ret_addr: usize,
) bool {
const self: *Self = @ptrCast(@alignCast(ctx));
self.mutex.lock();
defer self.mutex.unlock();
if (!self.stack_buffer.owns(old_mem)) {
return self.backing_allocator.rawResize(old_mem, log2_align, new_len, ret_addr);
}
return self.stack_buffer.canResize(old_mem, new_len);
}
pub fn free(
ctx: *anyopaque,
old_mem: []u8,
log2_align: u8,
ret_addr: usize,
) void {
const self: *Self = @ptrCast(@alignCast(ctx));
self.mutex.lock();
defer self.mutex.unlock();
// if we do not own the memory, we'll try
// to free it using the backing allocator
if (!self.stack_buffer.deposit(old_mem)) {
self.backing_allocator.rawFree(old_mem, log2_align, ret_addr);
}
}
};
}
/////////////////////////////////////////////////////////
/////// StackAllocator Testing Section //////////////////
test "basic stack properties" {
var GPA = std.heap.GeneralPurposeAllocator(.{ }){ };
var stack_allocator = StackAllocator(100).init(GPA.allocator());
var allocator = stack_allocator.allocator();
{ // reverse-order stack popping
var a = try allocator.alloc(u8, 10);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 10);
var b = try allocator.alloc(u8, 10);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 20);
allocator.free(b);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 10);
allocator.free(a);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 0);
}
{ // unordered stack popping
var a = try allocator.alloc(u8, 10);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 10);
var b = try allocator.alloc(u8, 10);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 20);
allocator.free(a);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 20);
allocator.free(b);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 10);
}
if (GPA.deinit() == .leak) @panic("MEMORY LEAK DETECTED!!");
}
test "basic stack resize" {
var GPA = std.heap.GeneralPurposeAllocator(.{ }){ };
var stack_allocator = StackAllocator(100).init(GPA.allocator());
var allocator = stack_allocator.allocator();
{ // resize checking
var a = try allocator.alloc(u8, 10);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 10);
var b = try allocator.alloc(u8, 10);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 20);
// a cannot resize because it is not on the top of the stack
try std.testing.expect(!allocator.resize(a, 20));
// b can resize because it is on the top of the stack
try std.testing.expect(allocator.resize(b, 20));
// b should be able to take the remaining memory
try std.testing.expect(allocator.resize(b, 90));
// b should not be able to take more than remainder
try std.testing.expect(!allocator.resize(b, 91));
}
if (GPA.deinit() == .leak) @panic("MEMORY LEAK DETECTED!!");
}
test "stack-overflow allocation" {
var GPA = std.heap.GeneralPurposeAllocator(.{ }){ };
var stack_allocator = StackAllocator(100).init(GPA.allocator());
var allocator = stack_allocator.allocator();
{ // overflow the full memory stack
var a = try allocator.alloc(u8, 100);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 100);
var b = try allocator.alloc(u8, 100);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 100);
allocator.free(a);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 0);
allocator.free(b);
try std.testing.expectEqual(stack_allocator.stack_buffer.used, 0);
}
if (GPA.deinit() == .leak) @panic("MEMORY LEAK DETECTED!!");
}