From ec09d43f9a5299f09c79e7c7af550b927fe31bc1 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Thu, 11 Aug 2016 18:23:46 +0200 Subject: [PATCH] buffer: proof of concept that everything is possible --- lib/buffer.js | 47 ++++++++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index e40b81a693c9fd..890f9035b535be 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -8,20 +8,42 @@ const internalUtil = require('internal/util'); class FastBuffer extends Uint8Array {} -FastBuffer.prototype.constructor = Buffer; -Buffer.prototype = FastBuffer.prototype; +const kFromErrorMsg = 'First argument must be a string, Buffer, ' + + 'ArrayBuffer, Array, or array-like object.'; -exports.Buffer = Buffer; -exports.SlowBuffer = SlowBuffer; exports.INSPECT_MAX_BYTES = 50; exports.kMaxLength = binding.kMaxLength; -const kFromErrorMsg = 'First argument must be a string, Buffer, ' + - 'ArrayBuffer, Array, or array-like object.'; - Buffer.poolSize = 8 * 1024; var poolSize, poolOffset, allocPool; +const BufferClass = ((BufferFn) => class Buffer extends FastBuffer { + constructor(arg, encodingOrOffset, length) { + let realbuf; + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ); + } + realbuf = BufferFn.allocUnsafe(arg); + } else { + realbuf = BufferFn.from(arg, encodingOrOffset, length); + } + + super(realbuf.buffer, realbuf.byteOffset, realbuf.byteLength); + } +})(Buffer); + +FastBuffer.prototype.constructor = Buffer; +BufferClass.prototype.constructor = Buffer; +Buffer.prototype = FastBuffer.prototype; + +exports.Buffer = Buffer; +exports.SlowBuffer = SlowBuffer; +exports.BufferClass = BufferClass; binding.setupBufferJS(Buffer.prototype, bindingObj); @@ -65,16 +87,7 @@ function alignPool() { * would ever actually be removed. **/ function Buffer(arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ); - } - return Buffer.allocUnsafe(arg); - } - return Buffer.from(arg, encodingOrOffset, length); + return new BufferClass(arg, encodingOrOffset, length); } /**