Rename heap to memory; Allocator strategies

This commit is contained in:
dcodeIO
2018-01-28 15:30:49 +01:00
parent 1b0ed61072
commit 219ee81bc9
15 changed files with 2694 additions and 1235 deletions

View File

@ -1,24 +1,4 @@
const ALIGN_LOG2: usize = 3;
const ALIGN_SIZE: usize = 1 << ALIGN_LOG2;
const ALIGN_MASK: usize = ALIGN_SIZE - 1;
var HEAP_OFFSET: usize = HEAP_BASE; // HEAP_BASE is a constant generated by the compiler
export function allocate_memory(size: usize): usize {
if (!size) return 0;
var len: i32 = current_memory();
if (HEAP_OFFSET + size > <usize>len << 16)
if(grow_memory(max<i32>(<i32>ceil<f64>(<f64>size / 65536), len * 2 - len)) < 0)
unreachable();
var ptr: usize = HEAP_OFFSET;
if ((HEAP_OFFSET += size) & ALIGN_MASK) // align next offset
HEAP_OFFSET = (HEAP_OFFSET | ALIGN_MASK) + 1;
return ptr;
}
export function free_memory(ptr: usize): void {
// just a big chunk of non-disposable memory for now
}
import "std:memory/arena";
function copy_memory(dest: usize, src: usize, n: usize): void {
// based on musl's implementation of memcpy

View File

@ -0,0 +1,30 @@
// An simple arena allocator that provides a `clear_memory` function to reset
// everything to the initial state. A user must have to make sure that there
// a no more references to cleared memory.
const ALIGN_LOG2: usize = 3;
const ALIGN_SIZE: usize = 1 << ALIGN_LOG2;
const ALIGN_MASK: usize = ALIGN_SIZE - 1;
var HEAP_OFFSET: usize = HEAP_BASE; // generated by the compiler
export function allocate_memory(size: usize): usize {
if (!size) return 0;
var len: i32 = current_memory();
if (HEAP_OFFSET + size > <usize>len << 16)
if(grow_memory(max<i32>(<i32>ceil<f64>(<f64>size / 65536), len * 2 - len)) < 0)
unreachable();
var ptr: usize = HEAP_OFFSET;
if ((HEAP_OFFSET += size) & ALIGN_MASK) // align next offset
HEAP_OFFSET = (HEAP_OFFSET | ALIGN_MASK) + 1;
set_memory(ptr, 0, size);
return ptr;
}
export function free_memory(ptr: usize): void {
// nop
}
export function clear_memory(): void {
HEAP_OFFSET = HEAP_BASE;
}