Skip to content

Use resizable ArrayBuffer for encoding #5166

@pepone

Description

@pepone

The current approach is to create a new buffer and copy the data over

reserve(n) {
if (n > this.capacity) {
const capacity = Math.max(1024, Math.max(n, 2 * this.capacity));
if (!this.b) {
this.b = new ArrayBuffer(capacity);
} else {
const b = new Uint8Array(capacity);
b.set(new Uint8Array(this.b, 0, this._limit));
this.b = b.buffer;
}
this.v = new DataView(this.b);
} else if (n < this.capacity) {
this.b = this.b.slice(0, n);
this.v = new DataView(this.b);
}
}

There is a newer API (2024) that allow to resize the buffers directly, this has the advantage of keeping views alive

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/resize

It is already available in all major browsers and JavaScript runtimes, I think makes sense to update the code to use this.

Metadata

Metadata

Assignees

Labels

javascriptPull requests that update javascript code

Type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions