1// Copyright 2019 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5namespace growable_fixed_array {
6// TODO(pwong): Support FixedTypedArrays.
7struct GrowableFixedArray {
8  macro Push(obj: Object): void {
9    this.EnsureCapacity();
10    this.array.objects[this.length++] = obj;
11  }
12  macro ResizeFixedArray(newCapacity: intptr): FixedArray {
13    dcheck(this.length >= 0);
14    dcheck(newCapacity >= 0);
15    dcheck(newCapacity >= this.length);
16    const first: intptr = 0;
17    return ExtractFixedArray(this.array, first, this.length, newCapacity);
18  }
19  macro EnsureCapacity(): void {
20    dcheck(this.length <= this.capacity);
21    if (this.capacity == this.length) {
22      // Growth rate is analog to JSObject::NewElementsCapacity:
23      // new_capacity = (current_capacity + (current_capacity >> 1)) + 16.
24      this.capacity = this.capacity + (this.capacity >> 1) + 16;
25      this.array = this.ResizeFixedArray(this.capacity);
26    }
27  }
28
29  macro ToJSArray(implicit context: Context)(): JSArray {
30    const nativeContext: NativeContext = LoadNativeContext(context);
31    const map: Map =
32        LoadJSArrayElementsMap(ElementsKind::PACKED_ELEMENTS, nativeContext);
33    const fixedArray: FixedArray = this.ResizeFixedArray(this.length);
34    const lengthSmi = Convert<Smi>(this.length);
35    return AllocateJSArray(map, fixedArray, lengthSmi);
36  }
37
38  array: FixedArray;
39  // TODO(v8:4153): make capacity and length uintptr
40  capacity: intptr;
41  length: intptr;
42}
43
44macro NewGrowableFixedArray(): GrowableFixedArray {
45  return GrowableFixedArray{array: kEmptyFixedArray, capacity: 0, length: 0};
46}
47}
48