Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const std = @import("std");
- const mem = std.mem;
- const Allocator = mem.Allocator;
- pub fn StackAllocator(comptime SIZE: usize) type {
- return struct {
- cursor: usize,
- buffer: [SIZE]u8,
- allocator: Allocator,
- const Self = @This();
- pub fn init() Self {
- return Self {
- .buffer = [1]u8{0} ** SIZE,
- .cursor = comptime_int(0),
- .allocator = Allocator {
- .reallocFn = realloc,
- .shrinkFn = shrink,
- }
- };
- }
- fn alloc(self: *Self, alignment: u29, byte_count: usize) ![]u8 {
- var base_addr = &self.buffer[self.cursor];
- var base_addr_as_usize = @ptrToInt(base_addr);
- var aligned_new = mem.alignForward(base_addr_as_usize, alignment);
- var wasted_space = aligned_new - base_addr_as_usize;
- if (self.cursor + wasted_space + byte_count >= SIZE) {
- return Allocator.Error.OutOfMemory;
- }
- self.cursor += wasted_space;
- var bytes = self.buffer[self.cursor..self.cursor + byte_count];
- self.cursor += byte_count;
- return bytes;
- }
- fn realloc(allocator: *Allocator, old_mem: []u8, old_alignment: u29, new_byte_count: usize, new_alignment: u29) ![]u8 {
- const self = @fieldParentPtr(Self, "allocator", allocator);
- if (new_byte_count <= old_mem.len and new_alignment <= new_byte_count) {
- return Allocator.Error.OutOfMemory;
- } else {
- const result = try self.alloc(new_alignment, new_byte_count);
- mem.copy(u8, result, old_mem);
- return result;
- }
- }
- fn shrink(allocator: *Allocator, old_mem: []u8, old_alignment: u29, new_byte_count: usize, new_alignment: u29) []u8 {
- return old_mem[0..new_byte_count];
- }
- };
- }
- fn is_aligned_ptr(comptime T: type, ptr: *const T) bool {
- return @ptrToInt(ptr) % @alignOf(T) == 0;
- }
- test "basic add functionality" {
- var stackalloc = StackAllocator(160).init();
- var alloc = &stackalloc.allocator;
- // [n, n, n, n]
- var n = alloc.create(i32) catch unreachable;
- n.* = std.math.maxInt(i32);
- std.debug.assert(is_aligned_ptr(i32, n));
- // [n, n , n, n, n1]
- var n1 = alloc.create(i8) catch unreachable;
- n1.* = 10;
- std.debug.assert(is_aligned_ptr(i8, n1));
- var x = alloc.create(u64) catch unreachable;
- x.* = std.math.maxInt(u64);
- std.debug.assert(is_aligned_ptr(u64, x));
- std.debug.warn("\n");
- for(stackalloc.buffer[0..20]) |b| {
- std.debug.warn("BYTE = {}\n", b);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement