From b5a068f5b79b6f00c4b05d9ac458878650ffa09a Mon Sep 17 00:00:00 2001 From: dcodeIO Date: Mon, 26 Dec 2016 18:23:22 +0100 Subject: [PATCH] Other: Just polyfill Buffer.from / .allocUnsafe for good --- src/util/runtime.js | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/util/runtime.js b/src/util/runtime.js index 5cf8474ab..f21461f96 100644 --- a/src/util/runtime.js +++ b/src/util/runtime.js @@ -26,16 +26,29 @@ util.isIE8 = false; try { util.isIE8 = eval("!-[1,]"); } catch (e) {} // eslint- * Node's Buffer class if available. * @type {?function(new: Buffer)} */ -util.Buffer = (util.Buffer = util.inquire("buffer")) && util.Buffer.Buffer || null; - -if (util.Buffer) { - // Don't use browser-buffer for performance - if (!util.Buffer.prototype.utf8Write) - util.Buffer = null; - // Polyfill Buffer.from - else if (!util.Buffer.from) - util.Buffer.from = function from(value, encoding) { return new util.Buffer(value, encoding); }; -} +util.Buffer = (function() { + try { + var Buffer = util.inquire("buffer").Buffer; + + /* istanbul ignore next */ + if (!Buffer.prototype.utf8Write) // refuse to use non-node buffers (performance) + return null; + + /* istanbul ignore next */ + if (!Buffer.from) + Buffer.from = function from(value, encoding) { return new Buffer(value, encoding); }; + + /* istanbul ignore next */ + if (!Buffer.allocUnsafe) + Buffer.allocUnsafe = function allocUnsafe(size) { return new Buffer(size); }; + + return Buffer; + + /* istanbul ignore next */ + } catch (e) { + return null; + } +})(); /** * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.