Skip to content

Commit b5a068f

Browse files
committed
Other: Just polyfill Buffer.from / .allocUnsafe for good
1 parent c3023a2 commit b5a068f

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

src/util/runtime.js

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,29 @@ util.isIE8 = false; try { util.isIE8 = eval("!-[1,]"); } catch (e) {} // eslint-
2626
* Node's Buffer class if available.
2727
* @type {?function(new: Buffer)}
2828
*/
29-
util.Buffer = (util.Buffer = util.inquire("buffer")) && util.Buffer.Buffer || null;
30-
31-
if (util.Buffer) {
32-
// Don't use browser-buffer for performance
33-
if (!util.Buffer.prototype.utf8Write)
34-
util.Buffer = null;
35-
// Polyfill Buffer.from
36-
else if (!util.Buffer.from)
37-
util.Buffer.from = function from(value, encoding) { return new util.Buffer(value, encoding); };
38-
}
29+
util.Buffer = (function() {
30+
try {
31+
var Buffer = util.inquire("buffer").Buffer;
32+
33+
/* istanbul ignore next */
34+
if (!Buffer.prototype.utf8Write) // refuse to use non-node buffers (performance)
35+
return null;
36+
37+
/* istanbul ignore next */
38+
if (!Buffer.from)
39+
Buffer.from = function from(value, encoding) { return new Buffer(value, encoding); };
40+
41+
/* istanbul ignore next */
42+
if (!Buffer.allocUnsafe)
43+
Buffer.allocUnsafe = function allocUnsafe(size) { return new Buffer(size); };
44+
45+
return Buffer;
46+
47+
/* istanbul ignore next */
48+
} catch (e) {
49+
return null;
50+
}
51+
})();
3952

4053
/**
4154
* Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.

0 commit comments

Comments
 (0)