• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2024 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {assertTrue} from './logging';
16
17/**
18 * A dynamically resizable array buffer implementation for efficient
19 * storage and manipulation of binary data. It starts with a specified
20 * initial size and grows as needed to accommodate appended data.
21 * Efficiently grows the buffer using an exponential strategy up to 32MB,
22 * and then linearly in 32MB increments to minimize reallocation overhead.
23 * Provides methods to append data, shrink the size, clear the buffer,
24 * and retrieve the stored data as a `Uint8Array`.
25 */
26export class ResizableArrayBuffer {
27  private buf: Uint8Array;
28  private _size = 0;
29
30  constructor(private readonly initialSize = 128) {
31    this.buf = new Uint8Array(initialSize);
32  }
33
34  append(data: ArrayLike<number>) {
35    const capacityNeeded = this._size + data.length;
36    if (this.capacity < capacityNeeded) {
37      this.grow(capacityNeeded);
38    }
39    this.buf.set(data, this._size);
40    this._size = capacityNeeded;
41  }
42
43  shrink(newSize: number) {
44    assertTrue(newSize <= this._size);
45    this._size = newSize;
46  }
47
48  clear() {
49    this.buf = new Uint8Array(this.initialSize);
50    this._size = 0;
51  }
52
53  get(): Uint8Array {
54    return this.buf.subarray(0, this._size);
55  }
56
57  get size(): number {
58    return this._size;
59  }
60
61  get capacity(): number {
62    return this.buf.length;
63  }
64
65  private grow(capacityNeeded: number) {
66    let newSize = this.buf.length;
67    const MB32 = 32 * 1024 * 1024;
68    do {
69      newSize = newSize < MB32 ? newSize * 2 : newSize + MB32;
70    } while (newSize < capacityNeeded);
71    const newBuf = new Uint8Array(newSize);
72    assertTrue(newBuf.length >= capacityNeeded);
73    newBuf.set(this.buf);
74    this.buf = newBuf;
75  }
76}
77