Skip to content

Instantly share code, notes, and snippets.

@andrewrk
Created April 23, 2017 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewrk/dd5b0f79adb902a0369f54d05ed1c014 to your computer and use it in GitHub Desktop.
Save andrewrk/dd5b0f79adb902a0369f54d05ed1c014 to your computer and use it in GitHub Desktop.
attempting to call a function that allocates memory at compile time
const mem = @import("std").mem;
const assert = @import("std").debug.assert;
const AllocState = struct {
some_mem: [100 * 1024]u8,
index: usize,
fn alloc(a: &mem.Allocator, n: usize) -> %[]u8 {
const self = @ptrCast(&AllocState, a.context);
const result = self.some_mem[self.index ... self.index + n];
self.index += n;
return result;
}
fn realloc(a: &mem.Allocator, old_mem: []u8, new_size: usize) -> %[]u8 {
const result = %return alloc(a, new_size);
@memcpy(result.ptr, old_mem.ptr, old_mem.len);
return result;
}
fn free(a: &mem.Allocator, old_mem: []u8) { }
};
fn foo() {
comptime {
var state = AllocState {
.some_mem = undefined,
.index = 0,
};
var some_mem: [100 * 1024]u8 = undefined;
var allocator = mem.Allocator {
.allocFn = AllocState.alloc,
.reallocFn = AllocState.realloc,
.freeFn = AllocState.free,
.context = @ptrCast(&mem.Allocator.Context, &state),
};
const ptr = bar(&allocator);
assert(*ptr == 1234);
}
}
fn bar(a: &mem.Allocator) -> %i32 {
const ptr = a.create(i32);
*ptr = 1234;
return ptr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment