/// import { BLOCK_MAXSIZE } from "./rt/common"; import { COMPARATOR, SORT } from "./util/sort"; import { ArrayBuffer, ArrayBufferView } from "./arraybuffer"; import { itoa, dtoa, itoa_stream, dtoa_stream, MAX_DOUBLE_LENGTH } from "./util/number"; import { idof, isArray as builtin_isArray } from "./builtins"; import { E_INDEXOUTOFRANGE, E_INVALIDLENGTH, E_EMPTYARRAY, E_HOLEYARRAY } from "./util/error"; /** Ensures that the given array has _at least_ the specified backing size. */ function ensureSize(array: usize, minSize: usize, alignLog2: u32): void { var oldCapacity = changetype(array).dataLength; if (minSize > oldCapacity >>> alignLog2) { if (minSize > BLOCK_MAXSIZE >>> alignLog2) throw new RangeError(E_INVALIDLENGTH); let oldData = changetype(changetype(array).data); let newCapacity = minSize << alignLog2; let newData = __realloc(oldData, newCapacity); memory.fill(newData + oldCapacity, 0, newCapacity - oldCapacity); if (newData !== oldData) { // oldData has been free'd store(changetype(array), __retain(newData), offsetof("data")); changetype(array).dataStart = newData; } changetype(array).dataLength = newCapacity; } } export class Array extends ArrayBufferView { [key: number]: T; // Implementing ArrayBufferView isn't strictly necessary here but is done to allow glue code // to work with typed and normal arrays interchangeably. Technically, normal arrays do not need // `dataStart` (equals `data`) and `dataLength` (equals computed `data.byteLength`). // Also note that Array with non-nullable T must guard against implicit null values whenever // length is modified in a way that a null value would exist. Otherwise, the compiler wouldn't be // able to guarantee type-safety anymore. For lack of a better word, such an array is "holey". private length_: i32; static isArray(value: U): bool { return builtin_isArray(value) && value !== null; } static create(capacity: i32 = 0): Array { if (capacity > BLOCK_MAXSIZE >>> alignof()) throw new RangeError(E_INVALIDLENGTH); var array = changetype>(__allocArray(capacity, alignof(), idof())); // retains changetype>(array).length_ = 0; // safe even if T is a non-nullable reference memory.fill(array.dataStart, 0, array.dataLength); return array; } constructor(length: i32 = 0) { super(length, alignof()); if (isReference()) { if (!isNullable()) { if (length) throw new Error(E_HOLEYARRAY); } } this.length_ = length; } @unsafe get buffer(): ArrayBuffer { return this.data; } get length(): i32 { return this.length_; } set length(length: i32) { if (isReference()) { if (!isNullable()) { if (length > this.length_) throw new Error(E_HOLEYARRAY); } } ensureSize(changetype(this), length, alignof()); this.length_ = length; } every(callbackfn: (element: T, index: i32, array: Array) => bool): bool { for (let index = 0, length = this.length_; index < min(length, this.length_); ++index) { if (!callbackfn(load(this.dataStart + (index << alignof())), index, this)) return false; } return true; } findIndex(predicate: (element: T, index: i32, array: Array) => bool): i32 { for (let index = 0, length = this.length_; index < min(length, this.length_); ++index) { if (predicate(load(this.dataStart + (index << alignof())), index, this)) return index; } return -1; } @operator("[]") private __get(index: i32): T { if (isReference()) { if (!isNullable()) { if (index >= this.length_) throw new Error(E_HOLEYARRAY); } } if (index >= this.dataLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); return this.__unchecked_get(index); } @operator("{}") private __unchecked_get(index: i32): T { return load(this.dataStart + (index << alignof())); } @operator("[]=") private __set(index: i32, value: T): void { var length = this.length_; if (isReference()) { if (!isNullable()) { if (index > length) throw new Error(E_HOLEYARRAY); } } ensureSize(changetype(this), index + 1, alignof()); this.__unchecked_set(index, value); if (index >= length) this.length_ = index + 1; } @operator("{}=") private __unchecked_set(index: i32, value: T): void { if (isManaged()) { let offset = this.dataStart + (index << alignof()); let oldRef: usize = load(offset); if (changetype(value) != oldRef) { store(offset, __retain(changetype(value))); __release(oldRef); } } else { store(this.dataStart + (index << alignof()), value); } } fill(value: T, start: i32 = 0, end: i32 = i32.MAX_VALUE): this { var dataStart = this.dataStart; var length = this.length_; start = start < 0 ? max(length + start, 0) : min(start, length); end = end < 0 ? max(length + end, 0) : min(end, length); if (sizeof() == 1) { if (start < end) { memory.fill( dataStart + start, u8(value), (end - start) ); } } else { for (; start < end; ++start) { store(dataStart + (start << alignof()), value); } } return this; } includes(searchElement: T, fromIndex: i32 = 0): bool { return this.indexOf(searchElement, fromIndex) >= 0; } indexOf(searchElement: T, fromIndex: i32 = 0): i32 { var length = this.length_; if (length == 0 || fromIndex >= length) return -1; if (fromIndex < 0) fromIndex = max(length + fromIndex, 0); var dataStart = this.dataStart; while (fromIndex < length) { if (load(dataStart + (fromIndex << alignof())) == searchElement) return fromIndex; ++fromIndex; } return -1; } lastIndexOf(searchElement: T, fromIndex: i32 = this.length_): i32 { var length = this.length_; if (length == 0) return -1; if (fromIndex < 0) fromIndex = length + fromIndex; else if (fromIndex >= length) fromIndex = length - 1; var dataStart = this.dataStart; while (fromIndex >= 0) { if (load(dataStart + (fromIndex << alignof())) == searchElement) return fromIndex; --fromIndex; } return -1; } push(value: T): i32 { var length = this.length_; var newLength = length + 1; ensureSize(changetype(this), newLength, alignof()); if (isManaged()) { let offset = this.dataStart + (length << alignof()); let oldRef: usize = load(offset); if (changetype(value) != oldRef) { store(offset, __retain(changetype(value))); __release(oldRef); } } else { store(this.dataStart + (length << alignof()), value); } this.length_ = newLength; return newLength; } concat(other: Array): Array { var thisLen = this.length_; var otherLen = select(0, other.length_, other === null); var outLen = thisLen + otherLen; if (outLen > BLOCK_MAXSIZE >>> alignof()) throw new Error(E_INVALIDLENGTH); var out = changetype>(__allocArray(outLen, alignof(), idof>())); // retains var outStart = out.dataStart; var thisSize = thisLen << alignof(); if (isManaged()) { let thisStart = this.dataStart; for (let offset: usize = 0; offset < thisSize; offset += sizeof()) { let ref = load(thisStart + offset); store(outStart + offset, __retain(ref)); } outStart += thisSize; let otherStart = other.dataStart; let otherSize = otherLen << alignof(); for (let offset: usize = 0; offset < otherSize; offset += sizeof()) { let ref = load(otherStart + offset); store(outStart + offset, __retain(ref)); } } else { memory.copy(outStart, this.dataStart, thisSize); memory.copy(outStart + thisSize, other.dataStart, otherLen << alignof()); } return out; } copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): this { var dataStart = this.dataStart; var len = this.length_; end = min(end, len); var to = target < 0 ? max(len + target, 0) : min(target, len); var from = start < 0 ? max(len + start, 0) : min(start, len); var last = end < 0 ? max(len + end, 0) : min(end, len); var count = min(last - from, len - to); if (from < to && to < (from + count)) { from += count - 1; to += count - 1; while (count) { store(dataStart + (to << alignof()), load(dataStart + (from << alignof()))); --from, --to, --count; } } else { memory.copy( dataStart + (to << alignof()), dataStart + (from << alignof()), count << alignof() ); } return this; } pop(): T { var length = this.length_; if (length < 1) throw new RangeError(E_EMPTYARRAY); var element = load(this.dataStart + ((--length) << alignof())); this.length_ = length; return element; } forEach(callbackfn: (value: T, index: i32, array: Array) => void): void { for (let index = 0, length = this.length_; index < min(length, this.length_); ++index) { callbackfn(load(this.dataStart + (index << alignof())), index, this); } } map(callbackfn: (value: T, index: i32, array: Array) => U): Array { var length = this.length_; var out = changetype>(__allocArray(length, alignof(), idof>())); // retains var outStart = out.dataStart; for (let index = 0; index < min(length, this.length_); ++index) { let result = callbackfn(load(this.dataStart + (index << alignof())), index, this); // retains if (isManaged()) { store(outStart + (index << alignof()), __retain(changetype(result))); } else { store(outStart + (index << alignof()), result); } // releases result } return out; } filter(callbackfn: (value: T, index: i32, array: Array) => bool): Array { var result = changetype>(__allocArray(0, alignof(), idof>())); // retains for (let index = 0, length = this.length_; index < min(length, this.length_); ++index) { let value = load(this.dataStart + (index << alignof())); if (callbackfn(value, index, this)) result.push(value); } return result; } reduce( callbackfn: (previousValue: U, currentValue: T, currentIndex: i32, array: Array) => U, initialValue: U ): U { var accum = initialValue; for (let index = 0, length = this.length_; index < min(length, this.length_); ++index) { accum = callbackfn(accum, load(this.dataStart + (index << alignof())), index, this); } return accum; } reduceRight( callbackfn: (previousValue: U, currentValue: T, currentIndex: i32, array: Array) => U, initialValue: U ): U { var accum = initialValue; for (let index = this.length_ - 1; index >= 0; --index) { accum = callbackfn(accum, load(this.dataStart + (index << alignof())), index, this); } return accum; } shift(): T { var length = this.length_; if (length < 1) throw new RangeError(E_EMPTYARRAY); var base = this.dataStart; var element = load(base); var lastIndex = length - 1; memory.copy( base, base + sizeof(), lastIndex << alignof() ); store(base + (lastIndex << alignof()), // @ts-ignore: cast null ); this.length_ = lastIndex; return element; } some(callbackfn: (element: T, index: i32, array: Array) => bool): bool { for (let index = 0, length = this.length_; index < min(length, this.length_); ++index) { if (callbackfn(load(this.dataStart + (index << alignof())), index, this)) return true; } return false; } unshift(element: T): i32 { var newLength = this.length_ + 1; ensureSize(changetype(this), newLength, alignof()); var dataStart = this.dataStart; memory.copy( dataStart + sizeof(), dataStart, (newLength - 1) << alignof() ); if (isManaged()) { store(dataStart, __retain(changetype(element))); } else { store(dataStart, element); } this.length_ = newLength; return newLength; } slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Array { var length = this.length_; begin = begin < 0 ? max(begin + length, 0) : min(begin, length); end = end < 0 ? max(end + length, 0) : min(end , length); length = max(end - begin, 0); var slice = changetype>(__allocArray(length, alignof(), idof>())); // retains var sliceBase = slice.dataStart; var thisBase = this.dataStart + (begin << alignof()); if (isManaged()) { let off = 0; let end = length << alignof(); while (off < end) { let ref = load(thisBase + off); store(sliceBase + off, __retain(ref)); off += sizeof(); } } else { memory.copy(sliceBase, thisBase, length << alignof()); } return slice; } splice(start: i32, deleteCount: i32 = i32.MAX_VALUE): Array { var length = this.length_; start = start < 0 ? max(length + start, 0) : min(start, length); deleteCount = max(min(deleteCount, length - start), 0); var result = changetype>(__allocArray(deleteCount, alignof(), idof>())); // retains var resultStart = result.dataStart; var thisStart = this.dataStart; var thisBase = thisStart + (start << alignof()); if (isManaged()) { for (let i = 0; i < deleteCount; ++i) { store(resultStart + (i << alignof()), load(thisBase + (i << alignof())) ); // element is moved, so refcount doesn't change } } else { memory.copy( resultStart, thisBase, deleteCount << alignof() ); } var offset = start + deleteCount; if (length != offset) { memory.copy( thisBase, thisStart + (offset << alignof()), (length - offset) << alignof() ); } this.length_ = length - deleteCount; return result; } reverse(): Array { var length = this.length_; if (length) { let front = this.dataStart; let back = this.dataStart + ((length - 1) << alignof()); while (front < back) { let temp = load(front); store(front, load(back)); store(back, temp); front += sizeof(); back -= sizeof(); } } return this; } sort(comparator: (a: T, b: T) => i32 = COMPARATOR()): this { var length = this.length_; if (length <= 1) return this; var base = this.dataStart; if (length == 2) { let a: T = load(base, sizeof()); // a = arr[1] let b: T = load(base); // b = arr[0] if (comparator(a, b) < 0) { store(base, b, sizeof()); // arr[1] = b; store(base, a); // arr[0] = a; } return this; } SORT(base, length, comparator); return this; } join(separator: string = ","): string { if (isBoolean()) return this.join_bool(separator); if (isInteger()) return this.join_int(separator); if (isFloat()) return this.join_flt(separator); if (isString()) return this.join_str(separator); if (isArray()) return this.join_arr(separator); if (isReference()) return this.join_ref(separator); ERROR("unspported element type"); return unreachable(); } private join_bool(separator: string = ","): string { var lastIndex = this.length_ - 1; if (lastIndex < 0) return ""; var dataStart = this.dataStart; if (!lastIndex) return select("true", "false", load(dataStart)); var sepLen = separator.length; var valueLen = 5; // max possible length of element len("false") var estLen = (valueLen + sepLen) * lastIndex + valueLen; var result = changetype(__alloc(estLen << 1, idof())); // retains var offset = 0; var value: bool; for (let i = 0; i < lastIndex; ++i) { value = load(dataStart + i); valueLen = 4 + i32(!value); memory.copy( changetype(result) + (offset << 1), changetype(select("true", "false", value)), valueLen << 1 ); offset += valueLen; if (sepLen) { memory.copy( changetype(result) + (offset << 1), changetype(separator), sepLen << 1 ); offset += sepLen; } } value = load(dataStart + lastIndex); valueLen = 4 + i32(!value); memory.copy( changetype(result) + (offset << 1), changetype(select("true", "false", value)), valueLen << 1 ); offset += valueLen; if (estLen > offset) return result.substring(0, offset); return result; } private join_int(separator: string = ","): string { var lastIndex = this.length_ - 1; if (lastIndex < 0) return ""; var dataStart = this.dataStart; // @ts-ignore: type if (!lastIndex) return changetype(itoa(load(dataStart))); // retains var sepLen = separator.length; const valueLen = (sizeof() <= 4 ? 10 : 20) + i32(isSigned()); var estLen = (valueLen + sepLen) * lastIndex + valueLen; var result = changetype(__alloc(estLen << 1, idof())); // retains var offset = 0; var value: T; for (let i = 0; i < lastIndex; ++i) { value = load(dataStart + (i << alignof())); // @ts-ignore: type offset += itoa_stream(changetype(result), offset, value); if (sepLen) { memory.copy( changetype(result) + (offset << 1), changetype(separator), sepLen << 1 ); offset += sepLen; } } value = load(dataStart + (lastIndex << alignof())); // @ts-ignore: type offset += itoa_stream(changetype(result), offset, value); if (estLen > offset) return result.substring(0, offset); return result; } private join_flt(separator: string = ","): string { var lastIndex = this.length_ - 1; if (lastIndex < 0) return ""; var dataStart = this.dataStart; if (!lastIndex) { return changetype(dtoa( // @ts-ignore: type load(dataStart)) ); // retains } const valueLen = MAX_DOUBLE_LENGTH; var sepLen = separator.length; var estLen = (valueLen + sepLen) * lastIndex + valueLen; var result = changetype(__alloc(estLen << 1, idof())); // retains var offset = 0; var value: T; for (let i = 0; i < lastIndex; ++i) { value = load(dataStart + (i << alignof())); offset += dtoa_stream(changetype(result), offset, // @ts-ignore: type value ); if (sepLen) { memory.copy( changetype(result) + (offset << 1), changetype(separator), sepLen << 1 ); offset += sepLen; } } value = load(dataStart + (lastIndex << alignof())); offset += dtoa_stream(changetype(result), offset, // @ts-ignore: type value ); if (estLen > offset) return result.substring(0, offset); return result; } private join_str(separator: string = ","): string { var lastIndex = this.length_ - 1; if (lastIndex < 0) return ""; var dataStart = this.dataStart; if (!lastIndex) return load(dataStart); var sepLen = separator.length; var estLen = 0; var value: string | null; for (let i = 0, len = lastIndex + 1; i < len; ++i) { value = load(dataStart + (i << alignof())); if (value !== null) estLen += value.length; } var offset = 0; var result = changetype(__alloc((estLen + sepLen * lastIndex) << 1, idof())); // retains for (let i = 0; i < lastIndex; ++i) { value = load(dataStart + (i << alignof())); if (value !== null) { let valueLen = changetype(value).length; memory.copy( changetype(result) + (offset << 1), changetype(value), valueLen << 1 ); offset += valueLen; } if (sepLen) { memory.copy( changetype(result) + (offset << 1), changetype(separator), sepLen << 1 ); offset += sepLen; } } value = load(dataStart + (lastIndex << alignof())); if (value !== null) { memory.copy( changetype(result) + (offset << 1), changetype(value), changetype(value).length << 1 ); } return result; } private join_arr(separator: string = ","): string { var lastIndex = this.length_ - 1; if (lastIndex < 0) return ""; var result = ""; var sepLen = separator.length; var base = this.dataStart; var value: T; if (!lastIndex) { value = load(base); // @ts-ignore: type return value ? value.join(separator) : ""; } for (let i = 0; i < lastIndex; ++i) { value = load(base + (i << alignof())); // @ts-ignore: type if (value) result += value.join(separator); if (sepLen) result += separator; } value = load(base + (lastIndex << alignof())); // @ts-ignore: type if (value) result += value.join(separator); return result; // registered by concatenation (FIXME: lots of garbage) } private join_ref(separator: string = ","): string { var lastIndex = this.length_ - 1; if (lastIndex < 0) return ""; var base = this.dataStart; if (!lastIndex) return "[object Object]"; const valueLen = 15; // max possible length of element len("[object Object]") var sepLen = separator.length; var estLen = (valueLen + sepLen) * lastIndex + valueLen; var result = changetype(__alloc(estLen << 1, idof())); var offset = 0; var value: T; for (let i = 0; i < lastIndex; ++i) { value = load(base + (i << alignof())); if (value) { memory.copy( changetype(result) + (offset << 1), changetype("[object Object]"), valueLen << 1 ); offset += valueLen; } if (sepLen) { memory.copy( changetype(result) + (offset << 1), changetype(separator), sepLen << 1 ); offset += sepLen; } } if (load(base + (lastIndex << alignof()))) { memory.copy( changetype(result) + (offset << 1), changetype("[object Object]"), valueLen << 1 ); offset += valueLen; } if (estLen > offset) return result.substring(0, offset); return result; } toString(): string { return this.join(); } // RT integration @unsafe private __visit_impl(cookie: u32): void { if (isManaged()) { let cur = this.dataStart; let end = cur + this.dataLength; while (cur < end) { let val = load(cur); if (val) __visit(val, cookie); cur += sizeof(); } } // automatically visits ArrayBufferView (.data) next } }