import { ALLOCATE, REGISTER, MAX_BYTELENGTH, HEADER, HEADER_SIZE, RETAIN, RELEASE } from "./runtime"; // NOTE: DO NOT USE YET! // TODO: FixedArray with S being the static size, i.e. `new FixedArray`. // Then hard-wire this special type to the compiler and do static length checks instead :) export class FixedArray { [key: number]: T; constructor(length: i32) { if (length > MAX_BYTELENGTH >>> alignof()) throw new RangeError("Invalid length"); var outSize = length << alignof(); var out = ALLOCATE(outSize); memory.fill(out, 0, outSize); return REGISTER>(out); } get length(): i32 { return changetype
(changetype(this) - HEADER_SIZE).payloadSize >>> alignof(); } @operator("[]") private __get(index: i32): T { if (index >= this.length) throw new RangeError("Offset out of bounds"); return this.__unchecked_get(index); } @operator("[]=") private __set(index: i32, value: T): void { if (index >= this.length) throw new RangeError("Offset out of bounds"); return this.__unchecked_set(index, value); } @operator("{}") private __unchecked_get(index: i32): T { return load(changetype(this) + (index << alignof())); } @operator("{}=") private __unchecked_set(index: i32, value: T): void { if (isManaged()) { let offset = changetype(this) + (index << alignof()); let oldValue = load(offset); if (value !== oldValue) { RELEASE(oldValue, this); store(offset, RETAIN(value, this)); } } else { store(changetype(this) + (index << alignof()), value); } } // GC integration @unsafe private __iter(fn: (ref: usize) => void): void { if (isManaged()) { let cur = changetype(this); let end = cur + changetype
(changetype(this) - HEADER_SIZE).payloadSize; while (cur < end) { fn(load(cur)); cur += sizeof(); } } } }