Skip to content

Commit e336166

Browse files
committed
[Fix] provide a fallback for engines without ArrayBuffer.isView
1 parent 286c96a commit e336166

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

index.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,20 @@
22

33
var Buffer = require('safe-buffer').Buffer;
44
var isArray = require('isarray');
5+
var typedArrayBuffer = require('typed-array-buffer');
6+
7+
var isView = ArrayBuffer.isView || function isView(obj) {
8+
try {
9+
typedArrayBuffer(obj);
10+
return true;
11+
} catch (e) {
12+
return false;
13+
}
14+
};
515

616
var useUint8Array = typeof Uint8Array !== 'undefined';
717
var useArrayBuffer = typeof ArrayBuffer !== 'undefined'
8-
&& typeof Uint8Array !== 'undefined'
9-
&& ArrayBuffer.isView;
18+
&& typeof Uint8Array !== 'undefined';
1019
var useFromArrayBuffer = useArrayBuffer && (Buffer.prototype instanceof Uint8Array || Buffer.TYPED_ARRAY_SUPPORT);
1120

1221
module.exports = function toBuffer(data, encoding) {
@@ -26,7 +35,7 @@ module.exports = function toBuffer(data, encoding) {
2635
* Wrap any TypedArray instances and DataViews
2736
* Makes sense only on engines with full TypedArray support -- let Buffer detect that
2837
*/
29-
if (useArrayBuffer && ArrayBuffer.isView(data)) {
38+
if (useArrayBuffer && isView(data)) {
3039
// Bug in Node.js <6.3.1, which treats this as out-of-bounds
3140
if (data.byteLength === 0) {
3241
return Buffer.alloc(0);

package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@
2626
"homepage": "https://github.com/browserify/to-buffer",
2727
"dependencies": {
2828
"isarray": "^2.0.5",
29-
"safe-buffer": "^5.2.1"
29+
"safe-buffer": "^5.2.1",
30+
"typed-array-buffer": "^1.0.3"
3031
},
3132
"devDependencies": {
3233
"@ljharb/eslint-config": "^21.1.1",
@@ -37,8 +38,7 @@
3738
"for-each": "^0.3.5",
3839
"npmignore": "^0.3.1",
3940
"nyc": "^10.3.2",
40-
"tape": "^5.9.0",
41-
"typed-array-buffer": "^1.0.3"
41+
"tape": "^5.9.0"
4242
},
4343
"engines": {
4444
"node": ">= 0.4"

0 commit comments

Comments
 (0)