From: Feross Aboukhadijeh Date: Tue, 30 Jun 2015 22:52:55 +0000 (-0700) Subject: update byteLength impl to pass new node tests X-Git-Url: https://zoso.dev/?a=commitdiff_plain;h=ed3da63eb22abb30691c123f5fef1f3f1d8a8690;p=buffer.git update byteLength impl to pass new node tests --- diff --git a/index.js b/index.js index 28ac51e..5f66a3f 100644 --- a/index.js +++ b/index.js @@ -296,29 +296,38 @@ Buffer.concat = function concat (list, length) { } function byteLength (string, encoding) { - if (typeof string !== 'string') string = String(string) + if (typeof string !== 'string') string = '' + string - if (string.length === 0) return 0 + var len = string.length + if (len === 0) return 0 - switch (encoding || 'utf8') { - case 'ascii': - case 'binary': - case 'raw': - return string.length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return string.length * 2 - case 'hex': - return string.length >>> 1 - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'base64': - return base64ToBytes(string).length - default: - return string.length + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'binary': + // Deprecated + case 'raw': + case 'raws': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } } } Buffer.byteLength = byteLength