Created
November 26, 2018 02:30
-
-
Save ibebrett/563530d2124e3af5c3e3ca7e11a189bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const Allocator = std.mem.Allocator; | |
/// A "IdioticAllocator." An idiotic allocator that does not free, ignores | |
/// alignment and simply returns an offset into a static buffer. Not useful | |
/// for anything but a learning tool. | |
pub fn IdioticAllocator(comptime bufferSize: usize) type { | |
return struct { | |
const Self = @This(); | |
buffer: [bufferSize]u8, | |
index: usize, | |
pub allocator: Allocator, | |
fn allocFn(allocator: *Allocator, n: usize, alignment: u29) ![]u8 { | |
const self = @fieldParentPtr(Self, "allocator", allocator); | |
std.debug.warn("BUFF LEN {} INDEX {} N {}", self.buffer.len, self.index, n); | |
if (n + self.index > self.buffer.len) { | |
return Allocator.Error.OutOfMemory; | |
} | |
var ret = self.buffer[self.index..n+self.index]; | |
self.index += n; | |
return ret; | |
} | |
fn reallocFn(self: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { | |
return self.allocFn(self, new_size, alignment); | |
} | |
fn freeFn(self: *Allocator, old_mem: []u8) void {} | |
pub fn init() Self { | |
std.debug.warn("BUFF SIZE AT INIT {}\n", bufferSize); | |
return Self { | |
.allocator = Allocator { | |
.allocFn = allocFn, | |
.reallocFn = reallocFn, | |
.freeFn = freeFn | |
}, | |
.buffer = []u8{0} ** bufferSize, | |
.index = 0 | |
}; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment