Skip to content

Instantly share code, notes, and snippets.

@bananu7

bananu7/Vector.t Secret

Last active July 24, 2016 11:54
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save bananu7/6218512414e5de1f6e8480f4c792ba47 to your computer and use it in GitHub Desktop.
--[[
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