import { AL_MASK, MAX_SIZE_32 } from "./allocator"; /** Size of an ArrayBuffer header. */ export const HEADER_SIZE: usize = (offsetof() + AL_MASK) & ~AL_MASK; /** Maximum byte length of an ArrayBuffer. */ export const MAX_BLENGTH: i32 = MAX_SIZE_32 - HEADER_SIZE; function computeSize(byteLength: i32): usize { // round up to power of 2, with HEADER_SIZE=8: // 0 -> 2^3 = 8 // 1..8 -> 2^4 = 16 // 9..24 -> 2^5 = 32 // ... // MAX_LENGTH -> 2^30 = 0x40000000 (MAX_SIZE_32) return 1 << (32 - clz(byteLength + HEADER_SIZE - 1)); } // Low-level utility function __gc(ref: usize): void {} export function allocateUnsafe(byteLength: i32): ArrayBuffer { assert(byteLength <= MAX_BLENGTH); var buffer: usize; if (isManaged()) { buffer = __gc_allocate(computeSize(byteLength), __gc); // tslint:disable-line } else { buffer = memory.allocate(computeSize(byteLength)); } store(buffer, byteLength, offsetof("byteLength")); return changetype(buffer); } export function reallocateUnsafe(buffer: ArrayBuffer, newByteLength: i32): ArrayBuffer { var oldByteLength = buffer.byteLength; if (newByteLength > oldByteLength) { assert(newByteLength <= MAX_BLENGTH); if (newByteLength <= (computeSize(oldByteLength) - HEADER_SIZE)) { // fast path: zero out additional space store(changetype(buffer), newByteLength, offsetof("byteLength")); memory.fill( changetype(buffer) + HEADER_SIZE + oldByteLength, 0, (newByteLength - oldByteLength) ); } else { // slow path: copy to new buffer let newBuffer = allocateUnsafe(newByteLength); memory.copy( changetype(newBuffer) + HEADER_SIZE, changetype(buffer) + HEADER_SIZE, oldByteLength ); memory.fill( changetype(newBuffer) + HEADER_SIZE + oldByteLength, 0, (newByteLength - oldByteLength) ); return newBuffer; } } else if (newByteLength < oldByteLength) { // fast path: override size // TBD: worth to copy and release if size is significantly less than before? assert(newByteLength >= 0); store(changetype(buffer), newByteLength, offsetof("byteLength")); } return buffer; } // The helpers below use two different types in order to emit loads and stores that load respectively // store one type to/from memory while returning/taking the desired output/input type. This allows to // emit instructions like // // * `i32.load8` ^= `load(...)` that reads an i8 but returns an i32, or // * `i64.load32_s` ^= `load(...)`) that reads a 32-bit as a 64-bit integer // // without having to emit an additional instruction for conversion purposes. The second parameter // can be omitted for references and other loads and stores that simply return the exact type. @inline export function LOAD(buffer: ArrayBuffer, index: i32, byteOffset: i32 = 0): TOut { return load(changetype(buffer) + (index << alignof()) + byteOffset, HEADER_SIZE); } @inline export function STORE(buffer: ArrayBuffer, index: i32, value: TIn, byteOffset: i32 = 0): void { store(changetype(buffer) + (index << alignof()) + byteOffset, value, HEADER_SIZE); }