diff --git a/lib/buffer.js b/lib/buffer.js index ba832de975db4d..5427a5a5a66e29 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -480,47 +480,45 @@ Buffer.prototype.write = function(string, offset, length, encoding) { if (length === undefined || length > remaining) length = remaining; - encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8'; - if (string.length > 0 && (length < 0 || offset < 0)) throw new RangeError('attempt to write outside buffer bounds'); - var ret; - switch (encoding) { - case 'hex': - ret = this.hexWrite(string, offset, length); - break; + if (!encoding) + encoding = 'utf8'; - case 'utf8': - case 'utf-8': - ret = this.utf8Write(string, offset, length); - break; + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return this.hexWrite(string, offset, length); - case 'ascii': - ret = this.asciiWrite(string, offset, length); - break; + case 'utf8': + case 'utf-8': + return this.utf8Write(string, offset, length); - case 'binary': - ret = this.binaryWrite(string, offset, length); - break; + case 'ascii': + return this.asciiWrite(string, offset, length); - case 'base64': - // Warning: maxLength not taken into account in base64Write - ret = this.base64Write(string, offset, length); - break; + case 'binary': + return this.binaryWrite(string, offset, length); - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - ret = this.ucs2Write(string, offset, length); - break; + case 'base64': + // Warning: maxLength not taken into account in base64Write + return this.base64Write(string, offset, length); - default: - throw new TypeError('Unknown encoding: ' + encoding); - } + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return this.ucs2Write(string, offset, length); - return ret; + default: + if (loweredCase) + throw new TypeError('Unknown encoding: ' + encoding); + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } };