Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: improve ArrayBuffer brand check in ensureBuffer #429

Merged
merged 1 commit into from
Apr 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/ensure_buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ export function ensureBuffer(potentialBuffer: Buffer | ArrayBufferView | ArrayBu
return Buffer.from(potentialBuffer.buffer);
}

if (potentialBuffer instanceof ArrayBuffer) {
if (
['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(
Object.prototype.toString.call(potentialBuffer)
)
) {
return Buffer.from(potentialBuffer);
}

Expand Down
31 changes: 30 additions & 1 deletion test/node/ensure_buffer_test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* global SharedArrayBuffer */
'use strict';

const { Buffer } = require('buffer');
Expand All @@ -19,7 +20,7 @@ describe('ensureBuffer tests', function () {
expect(bufferOut).to.equal(bufferIn);
});

it('should wrap a UInt8Array with a buffer', function () {
it('should wrap a Uint8Array with a buffer', function () {
const arrayIn = Uint8Array.from([1, 2, 3]);
let bufferOut;

Expand All @@ -31,6 +32,34 @@ describe('ensureBuffer tests', function () {
expect(bufferOut.buffer).to.equal(arrayIn.buffer);
});

it('should wrap a ArrayBuffer with a buffer', function () {
const arrayBufferIn = Uint8Array.from([1, 2, 3]).buffer;
let bufferOut;

expect(function () {
bufferOut = ensureBuffer(arrayBufferIn);
}).to.not.throw(Error);

expect(bufferOut).to.be.an.instanceOf(Buffer);
expect(bufferOut.buffer).to.equal(arrayBufferIn);
});

it('should wrap a SharedArrayBuffer with a buffer', function () {
if (typeof SharedArrayBuffer === 'undefined') {
this.skip();
return;
}
const arrayBufferIn = new SharedArrayBuffer(3);
let bufferOut;

expect(function () {
bufferOut = ensureBuffer(arrayBufferIn);
}).to.not.throw(Error);

expect(bufferOut).to.be.an.instanceOf(Buffer);
expect(bufferOut.buffer).to.equal(arrayBufferIn);
});

[0, 12, -1, '', 'foo', null, undefined, ['list'], {}, /x/].forEach(function (item) {
it(`should throw if input is ${typeof item}: ${item}`, function () {
expect(function () {
Expand Down