Files
kraken/stdlib/mem.krak
2016-05-31 21:29:05 -07:00

127 lines
2.9 KiB
Plaintext

ext fun malloc(size: ulong): *void
ext fun free(size: *void)
ext fun memmove(dest: *void, src: *void, size: ulong): *void
fun calloc(size: ulong): *void {
var to_ret = malloc(size)
for (var i = 0; i < size; i++;)
*((to_ret) cast *char + i) = 0
return to_ret
}
fun null<T>(): *T
return (0) cast *T
fun new<T>(count: int): *T
return (malloc( (#sizeof<T> * count ) cast ulong )) cast *T
fun new<T>(): *T
return new<T>(1)
/* We specilize on the trait Object to decide on whether or not the destructor should be called */
fun delete<T>(toDelete: *T, itemCount: int)
delete<T>(toDelete)
/* Calling this with itemCount = 0 allows you to delete destructable objects without calling their destructors. */
fun delete<T(Object)>(toDelete: *T, itemCount: int): void {
// start at one because the actual delete will call the destructor of the first one as it
// finishes the pointer
for (var i: int = 0; i < itemCount; i++;)
toDelete[i].destruct();
free((toDelete) cast *void);
}
/* We specilize on the trait Object to decide on whether or not the destructor should be called */
fun delete<T>(toDelete: *T)
free((toDelete) cast *void)
fun delete<T(Object)>(toDelete: *T): void {
toDelete->destruct();
free((toDelete) cast *void);
}
// a wrapper for construct if it has the Object trait
fun maybe_construct<T>(it:*T):*T
return it
fun maybe_construct<T(Object)>(it:*T):*T
return it->construct()
// a wrapper for copy constructing if it has the Object trait
fun maybe_copy_construct<T>(to:*T, from:*T)
*to = *from
fun maybe_copy_construct<T(Object)>(to:*T, from:*T)
to->copy_construct(from)
// a wrapper for destruct if it has the Object trait
fun maybe_destruct<T>(it:*T) {}
fun maybe_destruct<T(Object)>(it:*T)
it->destruct()
obj shared_ptr<T> (Object){
var data: *T;
var refCount: int;
fun construct(): *shared_ptr<T> {
data = 0;
refCount = 1;
return this;
}
fun construct(newPtr: *T): *shared_ptr<T> {
data = newPtr;
refCount = 1;
return this;
}
fun construct(newPtr: ref shared_ptr<T>): *shared_ptr<T> {
data = newPtr.data;
refCount = newPtr.refCount;
refCount++;
return this;
}
fun destruct(): void {
if(refCount == 1){
delete(data,1);
refCount--;
}
}
fun operator*(): ref T {
return *data;
}
fun operator->(): *T {
return data;
}
fun operator=(newPtr: ref shared_ptr<T>): ref shared_ptr<T> {
if(this != &newPtr){
if(refCount == 1){
delete(data,1);
refCount--;
}
//use copy constructor here???
data = newPtr.data;
refCount = newPtr.refCount;
refCount++;
}//end self-assignment check
return *this;
}
fun operator=(newPtr: ref *T): ref shared_ptr<T> {
data = newPtr;
refCount = 1;
delete(newPtr,1);
return *this;
}
}; //end shared_ptr class