Skip to content

buffer: add Buffer.createView() to create a new buffer that shares ArrayBuffer with another ArrayBufferView

This is a proposal for a new method Buffer.createView(), although its name could be changed.

This is not ready to merge because of missing docs and tests, but rather I've made this PR for discussion.

Rationale

When users convert ArrayBufferView (e.g. typed arrays and buffer itself) to Buffer, there are typical mistakes about handling underlying ArrayBuffer.:

  • A mistake on Buffer.from(arrayBufferView) that copies the underlying ArrayBuffer of arrayBufferView which might be unexpectedly slow
  • A mistake on Buffer.from(arrayBufferView.buffer) that creates a view of the underlying ArrayBuffer without offset and length parameters

So this PR creates a new method Buffer.createView(arrayBufferView):

const bytes = someMethodToCreateUint8Array();
// The same as `Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)`
const buffer = Buffer.createView(bytes);

// It requires no temporary variable:
const buffer = Buffer.createView(someMethodToCreateUint8Array());

And also Buffer.createView(arrayBuffer) is provided as the same semantics of the current Buffer.from(arrayBuffer) to clarify that it is just a view of arrayBuffer.

I think Buffer.from(arrayBuffer) should be deprecated because it is extremely confusing, and ECMA-262's typed arrays have no such overload, anyway. However, it is not directly related to this PR.

refs: https://github.com/nodejs/node/issues/28725

Checklist

  • make -j4 test (UNIX), or vcbuild test (Windows) passes
  • tests and/or benchmarks are included
  • documentation is changed or added NOT YET
  • commit message follows commit guidelines

Merge request reports

Loading