mirror of
https://github.com/fluencelabs/assemblyscript
synced 2025-06-13 23:11:41 +00:00
Improve arena allocator a bit
This commit is contained in:
@ -1,23 +1,25 @@
|
||||
// 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.
|
||||
// A simple arena allocator that provides a `clear_memory` function to reset
|
||||
// the heap to its initial state. A user has to make sure that there are no
|
||||
// more references to cleared memory afterwards. Always aligns to 8 bytes.
|
||||
|
||||
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
|
||||
var HEAP_OFFSET: usize = HEAP_BASE;
|
||||
|
||||
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);
|
||||
var ptr = HEAP_OFFSET;
|
||||
var off = (ptr + size + ALIGN_MASK) & ~ALIGN_MASK;
|
||||
var avail = <usize>current_memory() << 16;
|
||||
if (off > avail && grow_memory(
|
||||
max(
|
||||
(((off + 0xffff) & ~0xffff) - avail) >> 16, // minimum required pages
|
||||
avail >> 16 // at least double memory
|
||||
)
|
||||
) < 0) unreachable(); // out of memory
|
||||
HEAP_OFFSET = off;
|
||||
return ptr;
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user