list or whatever

This commit is contained in:
nora 2023-12-16 14:13:45 +01:00
parent 179c4b3505
commit b2b80fe2ee
5 changed files with 59 additions and 33 deletions

View file

@ -1,21 +1,48 @@
type List[T] = struct {
ptr: Int,
len: Int,
cap: Int,
ptr: I32,
len: I32,
cap: I32,
};
function new(): List[Int] = (
List { ptr: 0, len: 0, cap: 0 }
List { ptr: 0_I32, len: 0_I32, cap: 0_I32 }
);
function push(list: List[Int], elem: Int) = (
growIfNeeded(list, 1);
growIfNeeded(list, 1_I32);
let addr = list.ptr + (SIZEOF * list.len);
__i64_store(addr, elem);
list.len = list.len + 1_I32;
);
function debugPrint(list: List[Int]) = (
let i = 0_I32;
print("[");
loop (
if i >= list.len then (
break;
);
let elem = __i64_load(list.ptr + (i * SIZEOF));
std.printInt(elem);
if (i + 1_I32) < list.len then print(", ");
i = i + 1_I32;
);
std.println("]");
);
// PRIVATE:
function growIfNeeded(list: List[Int], elems: Int) = (
global SIZEOF: I32 = 8_I32;
global ALIGNOF: I32 = 8_I32;
function growIfNeeded(list: List[Int], elems: I32) = (
if (list.len + elems) < list.cap then (
let newMemory = std.rt.alloc.allocateItem(0_I32, 0_I32);
let newMemory = std.rt.alloc.allocate(SIZEOF * list.cap * 2_I32, ALIGNOF);
let oldMemory = list.ptr;
let amount = SIZEOF * list.len;
std.rt.memcpy(newMemory, oldMemory, amount);
if list.cap > 0_I32 then std.rt.alloc.deallocate(list.ptr, list.cap * SIZEOF);
);
);

View file

@ -7,23 +7,13 @@ global HEAD_PTR: I32 = 1024_I32;
// Allocate a new item. We do not deallocate anything yet.
// lol.
function allocateItem(objSize: I32, align: I32): I32 = (
function allocate(size: I32, align: I32): I32 = (
if align < 4_I32 then std.abort("invalid alignment");
// Include the refcount header.
let actualSize = 4_I32 + objSize;
// Let's see whether we can fit the refcount into the align bits.
// I happen to know that everything will always be at least 4 bytes aligned.
let alignedPtr = std.alignUp(HEAD_PTR, align);
let actualObjPtr = if (alignedPtr - HEAD_PTR) > align then (
alignedPtr - 4_I32
) else (
// Take up the next spot.
alignedPtr + align - 4_I32
);
let newHeadPtr = actualObjPtr + actualSize;
let newHeadPtr = alignedPtr + size;
if newHeadPtr > __memory_size() then (
// 16 pages, very arbitrary.
@ -36,10 +26,10 @@ function allocateItem(objSize: I32, align: I32): I32 = (
HEAD_PTR = newHeadPtr;
actualObjPtr
alignedPtr
);
function deallocateItem(ptr: I32, objSize: I32) = (
function deallocate(ptr: I32, size: I32) = (
std.println("uwu deawwocate :3");
);