From 231d5e4437163a2b99e87793d2766bf1ae283f38 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Tue, 15 Oct 2024 10:22:15 -0700 Subject: [PATCH] buffer: make Buffer work with resizable ArrayBuffer Fixes: https://github.com/nodejs/node/issues/52195 PR-URL: https://github.com/nodejs/node/pull/55377 Reviewed-By: Robert Nagy Reviewed-By: Yagiz Nizipli Reviewed-By: Benjamin Gruenbaum Reviewed-By: Ruben Bridgewater Reviewed-By: Matteo Collina --- lib/buffer.js | 4 +--- test/parallel/test-buffer-resizable.js | 29 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 test/parallel/test-buffer-resizable.js diff --git a/lib/buffer.js b/lib/buffer.js index 2c56b6c504d..756657e9108 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -504,9 +504,7 @@ function fromArrayBuffer(obj, byteOffset, length) { if (maxLength < 0) throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); - if (length === undefined) { - length = maxLength; - } else { + if (length !== undefined) { // Convert length to non-negative integer. length = +length; if (length > 0) { diff --git a/test/parallel/test-buffer-resizable.js b/test/parallel/test-buffer-resizable.js new file mode 100644 index 00000000000..dcfe6385b68 --- /dev/null +++ b/test/parallel/test-buffer-resizable.js @@ -0,0 +1,29 @@ +// Flags: --no-warnings +'use strict'; + +require('../common'); +const { Buffer } = require('node:buffer'); +const { strictEqual } = require('node:assert'); +const { describe, it } = require('node:test'); + +describe('Using resizable ArrayBuffer with Buffer...', () => { + it('works as expected', () => { + const ab = new ArrayBuffer(10, { maxByteLength: 20 }); + const buffer = Buffer.from(ab, 1); + strictEqual(buffer.byteLength, 9); + ab.resize(15); + strictEqual(buffer.byteLength, 14); + ab.resize(5); + strictEqual(buffer.byteLength, 4); + }); + + it('works with the deprecated constructor also', () => { + const ab = new ArrayBuffer(10, { maxByteLength: 20 }); + const buffer = new Buffer(ab, 1); + strictEqual(buffer.byteLength, 9); + ab.resize(15); + strictEqual(buffer.byteLength, 14); + ab.resize(5); + strictEqual(buffer.byteLength, 4); + }); +});