import { HEADER, HEADER_SIZE, MAX_BYTELENGTH } from "./util/runtime"; import { runtime, __runtime_id, __gc_mark_members } from "./runtime"; import { E_INDEXOUTOFRANGE, E_INVALIDLENGTH, E_HOLEYARRAY } from "./util/error"; // 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(E_INVALIDLENGTH); if (isReference()) { if (!isNullable()) { if (length) throw new Error(E_HOLEYARRAY); } } var outSize = length << alignof(); var out = runtime.allocate(outSize); memory.fill(out, 0, outSize); return changetype>(runtime.register(out, __runtime_id>())); } get length(): i32 { return changetype
(changetype(this) - HEADER_SIZE).payloadSize >>> alignof(); } @operator("[]") private __get(index: i32): T { if (index >= this.length) throw new RangeError(E_INDEXOUTOFRANGE); return this.__unchecked_get(index); } @operator("[]=") private __set(index: i32, value: T): void { if (index >= this.length) throw new RangeError(E_INDEXOUTOFRANGE); 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) { store(offset, value); if (oldValue !== null) { if (isDefined(__ref_link)) { if (isDefined(__ref_unlink)) __ref_unlink(changetype(oldValue), changetype(this)); } else if (isDefined(__ref_retain)) __ref_release(changetype(oldValue)); else assert(false); } if (isNullable()) { if (value !== null) { if (isDefined(__ref_link)) __ref_link(changetype(value), changetype(this)); else if (isDefined(__ref_retain)) __ref_retain(changetype(value)); else assert(false); } } else { if (isDefined(__ref_link)) __ref_link(changetype(value), changetype(this)); else if (isDefined(__ref_retain)) __ref_retain(changetype(value)); else assert(false); } } } else { store(changetype(this) + (index << alignof()), value); } } // GC integration @unsafe private __traverse(): void { if (isManaged()) { let cur = changetype(this); let end = cur + changetype
(changetype(this) - HEADER_SIZE).payloadSize; while (cur < end) { let val = load(cur); if (isNullable()) { if (val) { __ref_mark(val); __gc_mark_members(__runtime_id(), val); } } else { __ref_mark(val); __gc_mark_members(__runtime_id(), val); } cur += sizeof(); } } } }