Skip to content

Documentation for creating a Buffer which shares a TypedArray's memory is misleading #31348

Closed
@qntm

Description

  • Version: v12.13.0
  • Platform: Windows 10 64-bit
  • Subsystem: docs

The documentation for Buffer reads, in part (abbreviated for clarity):

It is possible to create a new Buffer that shares the same allocated memory as a TypedArray instance by using the TypedArray object's .buffer property.

const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
const buf2 = Buffer.from(arr.buffer);
console.log(buf2);
// Prints: <Buffer 88 13 a0 0f>

This works in this case, but I think it's hazardous advice for arbitrary TypedArrays because the backing ArrayBuffer could extend beyond the bounds of the TypedArray which is providing a view of it. For example:

const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]) // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2) // 2 elements
console.log(arrA.buffer === arrB.buffer) // true

const buf = Buffer.from(arrB.buffer)
console.log(buf)
// expected, based on documented advice: <Buffer 64 65>
// actual: <Buffer 63 64 65 66>

It might be better to have the docs suggest Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength) as the general solution to this problem.

Metadata

Assignees

No one assigned

    Labels

    bufferIssues and PRs related to the buffer subsystem.docIssues and PRs related to the documentations.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions