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
--[[ | |
terralib.includepath = | |
"C:/Program Files (x86)/Windows Kits/10/Include/10.0.10150.0/ucrt" .. ";" .. | |
"C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include" | |
]] | |
terralib.includepath = | |
"/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include" | |
--C = terralib.includec("stdlib.h") | |
C = terralib.includecstring [[ | |
#include <stdlib.h> | |
#include <string.h> | |
#include <stdio.h> | |
]] | |
function VectorGeneric(typ) | |
local Vector = struct { | |
data: &typ; | |
size: uint64; | |
capacity: uint64; | |
} | |
Vector.methods.new = terra() | |
var v: Vector | |
v.data = nil | |
v.size = 0 | |
v.capacity = 0 | |
return v | |
end | |
terra Vector:_realloc(newCapacity: uint64) | |
C.printf('malloc of %d\n', sizeof(typ) * newCapacity) | |
var newBuf = [&typ](C.malloc(sizeof(typ) * newCapacity)) | |
if newBuf == nil then | |
C.puts('ERROR MALLOC') | |
end | |
C.puts('memcpy') | |
C.memcpy(newBuf, self.data, sizeof(typ) * self.size) | |
C.puts('free') | |
C.free(self.data) | |
self.data = newBuf | |
self.capacity = newCapacity | |
end | |
terra Vector:push(x: typ) | |
C.puts('pushing') | |
if (self.size >= self.capacity) then | |
C.puts('reallocating') | |
self:_realloc(self.capacity * 2 + 5); | |
end | |
self.data[self.size] = x | |
self.size = self.size + 1 | |
end | |
terra Vector:getSize() | |
return self.size | |
end | |
return Vector | |
end | |
VectorInt = VectorGeneric(int8) | |
--v = VectorInt.new() | |
terra main() | |
var v = VectorInt.new() | |
v:push(5); | |
end | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment