///
import { ALLOCATE, REALLOCATE, DISCARD, REGISTER, MAX_BYTELENGTH, MAKEARRAY, ArrayBufferView } from "./runtime";
import { ArrayBuffer } from "./arraybuffer";
import { COMPARATOR, SORT } from "./util/sort";
import { itoa, dtoa, itoa_stream, dtoa_stream, MAX_DOUBLE_LENGTH } from "./util/number";
import { 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 capacity. */
function ensureCapacity(array: ArrayBufferView, minCapacity: i32, alignLog2: u32): void {
if (minCapacity > array.dataLength >>> alignLog2) {
if (minCapacity > (MAX_BYTELENGTH >>> alignLog2)) throw new RangeError(E_INVALIDLENGTH);
let oldData = array.data;
let newByteLength = minCapacity << alignLog2;
let newData = REALLOCATE(changetype(oldData), newByteLength); // registers on move
if (newData !== changetype(oldData)) {
array.data = changetype(newData); // links
array.dataStart = newData;
}
array.dataLength = newByteLength;
}
}
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 > MAX_BYTELENGTH >>> alignof()) throw new RangeError(E_INVALIDLENGTH);
var array = MAKEARRAY(capacity);
memory.fill(array.dataStart, 0, array.dataLength);
array.length_ = 0; // !
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);
}
}
ensureCapacity(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);
}
}
ensureCapacity(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 oldValue = load(offset);
if (value !== oldValue) {
store(offset, value);
if (isNullable()) {
if (isDefined(__ref_link)) {
if (isDefined(__ref_unlink)) if (oldValue !== null) __ref_unlink(changetype(oldValue), changetype(this));
if (value !== null) __ref_link(changetype(value), changetype(this));
} else if (__ref_retain) {
if (oldValue !== null) __ref_release(changetype(oldValue));
if (value !== null) __ref_retain(changetype(value));
} else assert(false);
} else {
if (isDefined(__ref_link)) {
if (isDefined(__ref_unlink)) if (oldValue !== null) __ref_unlink(changetype(oldValue), changetype(this));
__ref_link(changetype(value), changetype(this));
} else if (__ref_retain) {
if (oldValue !== null) __ref_release(changetype(oldValue));
__ref_retain(changetype(value));
} else assert(false);
}
}
} 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;
ensureCapacity(this, newLength, alignof());
if (isManaged()) {
let offset = this.dataStart + (length << alignof());
let oldValue = load(offset);
if (oldValue !== value) {
store(offset, value);
if (isNullable()) {
if (isDefined(__ref_link)) {
if (value !== null) __ref_link(changetype(value), changetype(this));
if (isDefined(__ref_unlink)) if (oldValue !== null) __ref_unlink(changetype(oldValue), changetype(this));
} else if (__ref_retain) {
if (oldValue !== null) __ref_retain(changetype(value));
if (value !== null) __ref_release(changetype(oldValue));
} else assert(false);
} else {
if (isDefined(__ref_link)) {
__ref_link(changetype(value), changetype(this));
if (isDefined(__ref_unlink)) if (oldValue !== null) __ref_unlink(changetype(oldValue), changetype(this));
} else if (__ref_retain) {
__ref_retain(changetype(value));
if (oldValue !== null) __ref_release(changetype(oldValue));
} else assert(false);
}
}
} 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 out = MAKEARRAY(thisLen + otherLen);
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, ref);
if (isNullable()) {
if (ref) {
if (isDefined(__ref_link)) __ref_link(ref, changetype(this));
else if (isDefined(__ref_retain)) __ref_retain(ref);
else assert(false);
}
} else {
if (isDefined(__ref_link)) __ref_link(ref, changetype(this));
else if (isDefined(__ref_retain)) __ref_retain(ref);
else assert(false);
}
}
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, ref);
if (isNullable()) {
if (ref) {
if (isDefined(__ref_link)) __ref_link(ref, changetype(this));
else if (isDefined(__ref_retain)) __ref_retain(ref);
else assert(false);
}
} else {
if (isDefined(__ref_link)) __ref_link(ref, changetype(this));
else if (isDefined(__ref_retain)) __ref_retain(ref);
else assert(false);
}
}
} 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 = MAKEARRAY(length);
var outStart = out.dataStart;
for (let index = 0; index < min(length, this.length_); ++index) {
let value = load(this.dataStart + (index << alignof()));
if (isManaged()) {
let ref = changetype(callbackfn(value, index, this));
store(outStart + (index << alignof()), ref);
if (isNullable()) {
if (ref) {
if (isDefined(__ref_link)) __ref_link(ref, changetype(out));
else if (isDefined(__ref_retain)) __ref_retain(ref);
else assert(false);
}
} else {
if (isDefined(__ref_link)) __ref_link(ref, changetype(out));
else if (isDefined(__ref_retain)) __ref_retain(ref);
else assert(false);
}
} else {
store(outStart + (index << alignof()), callbackfn(value, index, this));
}
}
return out;
}
filter(callbackfn: (value: T, index: i32, array: Array) => bool): Array {
var result = MAKEARRAY(0);
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;
ensureCapacity(this, newLength, alignof());
var dataStart = this.dataStart;
memory.copy(
dataStart + sizeof(),
dataStart,
(newLength - 1) << alignof()
);
store(dataStart, element);
if (isManaged()) {
if (isNullable()) {
if (element !== null) {
if (isDefined(__ref_link)) __ref_link(changetype(element), changetype(this));
else if (isDefined(__ref_retain)) __ref_retain(changetype(element));
else assert(false);
}
} else {
if (isDefined(__ref_link)) __ref_link(changetype(element), changetype(this));
else if (isDefined(__ref_retain)) __ref_retain(changetype(element));
else assert(false);
}
}
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 = MAKEARRAY(length);
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, ref);
if (isNullable()) {
if (ref) {
if (isDefined(__ref_link)) __ref_link(ref, changetype(slice));
else if (isDefined(__ref_retain)) __ref_retain(ref);
else assert(false);
}
} else {
if (isDefined(__ref_link)) __ref_link(ref, changetype(slice));
else if (isDefined(__ref_retain)) __ref_retain(ref);
else assert(false);
}
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 = MAKEARRAY(deleteCount);
var resultStart = result.dataStart;
var thisStart = this.dataStart;
var thisBase = thisStart + (start << alignof());
if (isManaged()) {
for (let i = 0; i < deleteCount; ++i) {
let ref = load(thisBase + (i << alignof()));
store(resultStart + (i << alignof()), ref);
if (isDefined(__ref_link)) {
if (isNullable()) {
if (ref) {
if (isDefined(__ref_unlink)) __ref_unlink(ref, changetype(this));
__ref_link(ref, changetype(result));
}
} else {
if (isDefined(__ref_unlink)) __ref_unlink(ref, changetype(this));
__ref_link(ref, changetype(result));
}
}
}
} else {
memory.copy(
result.dataStart,
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