Created
October 19, 2018 21:50
-
-
Save bendmorris/ec09628a0575ed9a506908178d632c95 to your computer and use it in GitHub Desktop.
Kit allocator example
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
import kit.mem; | |
struct MyStruct { | |
public var x: Int; | |
public var y: Int; | |
public static function new(allocator: Box[Allocator]): Ptr[MyStruct] { | |
var newValue: Ptr[MyStruct] = allocator.alloc(sizeof MyStruct); | |
newValue.x = 1; | |
newValue.y = 2; | |
return newValue; | |
} | |
} | |
function main() { | |
// this will allocate a new struct via malloc | |
var a = MyStruct.new(); | |
printf("%i %i\n", a.x, a.y); | |
free(a); | |
// this will allocate a new struct from a custom stack allocator | |
var myStack = StackAllocator.new(sizeof MyStruct * 4); | |
using implicit myStack as Box[Allocator] { | |
var b = MyStruct.new(); | |
printf("%i %i\n", b.x, b.y); | |
myStack.free(b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment