node icon indicating copy to clipboard operation
node copied to clipboard

buffer: make `Buffer.from` throw on `DataView`

Open LiviaMedeiros opened this issue 1 year ago • 7 comments

Passing DataView instance or arbitrary object with any ArrayBuffer in its buffer property and without numeric length property results in a new empty Buffer.

This behaviour isn't documented, and is confusing since buffer property is checked but not used.

LiviaMedeiros avatar Jun 10 '23 17:06 LiviaMedeiros

CI: https://ci.nodejs.org/job/node-test-pull-request/52194/

nodejs-github-bot avatar Jun 10 '23 19:06 nodejs-github-bot

This is a breaking change right? I think we should add semver-major label.

anonrig avatar Jun 10 '23 19:06 anonrig

CI: https://ci.nodejs.org/job/node-test-pull-request/52207/

nodejs-github-bot avatar Jun 11 '23 07:06 nodejs-github-bot

CI: https://ci.nodejs.org/job/node-test-pull-request/52211/

nodejs-github-bot avatar Jun 11 '23 18:06 nodejs-github-bot

CI: https://ci.nodejs.org/job/node-test-pull-request/52252/

nodejs-github-bot avatar Jun 14 '23 11:06 nodejs-github-bot

As far as I can tell, the existing behavior of Buffer.from() is compatible with Uint8Array.from() in this regard, and since Buffer extends Uint8Array, it seems wrong to intentionally deviate from spec'd behavior.

The specs of both 23.2.2.1 %TypedArray%.from() and 23.2.5.1 TypedArray constructor don't mention buffer property nor DataView.

Uint8Array.from() returns empty buffer for arbitrary argument (as long as it's not null):

assert.deepStrictEqual(new Uint8Array(), Uint8Array.from({ buffer: new ArrayBuffer(8) }));
assert.deepStrictEqual(new Uint8Array(), Uint8Array.from(new DataView(new ArrayBuffer(8))));
assert.deepStrictEqual(new Uint8Array(), Uint8Array.from({ buffer: null }));
assert.deepStrictEqual(new Uint8Array(), Uint8Array.from({}));
assert.deepStrictEqual(new Uint8Array(), Uint8Array.from(123));
assert.deepStrictEqual(new Uint8Array(), Uint8Array.from(123n));
assert.deepStrictEqual(new Uint8Array(), Uint8Array.from(true));

Does that mean that Buffer.from() should do the same?

LiviaMedeiros avatar Jun 14 '23 18:06 LiviaMedeiros

Does that mean that Buffer.from() should do the same?

I don't know. I am not generally in favor of adopting more web APIs where they don't make sense, but intentionally reducing compatibility with web APIs (as in this PR) does not seem helpful to me either.

tniessen avatar Jun 16 '23 12:06 tniessen