diff options
Diffstat (limited to 'lib/internal/util.js')
-rw-r--r-- | lib/internal/util.js | 77 |
1 files changed, 50 insertions, 27 deletions
diff --git a/lib/internal/util.js b/lib/internal/util.js index 2516b84f34..b144063ee5 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -96,36 +96,59 @@ function assertCrypto() { throw new errors.Error('ERR_NO_CRYPTO'); } -// The loop should only run at most twice, retrying with lowercased enc -// if there is no match in the first pass. -// We use a loop instead of branching to retry with a helper -// function in order to avoid the performance hit. // Return undefined if there is no match. +// Move the "slow cases" to a separate function to make sure this function gets +// inlined properly. That prioritizes the common case. function normalizeEncoding(enc) { - if (enc == null || enc === '') return 'utf8'; - let retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': + if (enc == null || enc === 'utf8' || enc === 'utf-8') return 'utf8'; + return slowCases(enc); +} + +function slowCases(enc) { + switch (enc.length) { + case 4: + if (enc === 'UTF8') return 'utf8'; + if (enc === 'ucs2' || enc === 'UCS2') return 'utf16le'; + enc = `${enc}`.toLowerCase(); + if (enc === 'utf8') return 'utf8'; + if (enc === 'ucs2' || enc === 'UCS2') return 'utf16le'; + break; + case 3: + if (enc === 'hex' || enc === 'HEX' || `${enc}`.toLowerCase() === 'hex') + return 'hex'; + break; + case 5: + if (enc === 'ascii') return 'ascii'; + if (enc === 'ucs-2') return 'utf16le'; + if (enc === 'UTF-8') return 'utf8'; + if (enc === 'ASCII') return 'ascii'; + if (enc === 'UCS-2') return 'utf16le'; + enc = `${enc}`.toLowerCase(); + if (enc === 'utf-8') return 'utf8'; + if (enc === 'ascii') return 'ascii'; + if (enc === 'usc-2') return 'utf16le'; + break; + case 6: + if (enc === 'base64') return 'base64'; + if (enc === 'latin1' || enc === 'binary') return 'latin1'; + if (enc === 'BASE64') return 'base64'; + if (enc === 'LATIN1' || enc === 'BINARY') return 'latin1'; + enc = `${enc}`.toLowerCase(); + if (enc === 'base64') return 'base64'; + if (enc === 'latin1' || enc === 'binary') return 'latin1'; + break; + case 7: + if (enc === 'utf16le' || enc === 'UTF16LE' || + `${enc}`.toLowerCase() === 'utf16le') return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } + break; + case 8: + if (enc === 'utf-16le' || enc === 'UTF-16LE' || + `${enc}`.toLowerCase() === 'utf-16le') + return 'utf16le'; + break; + default: + if (enc === '') return 'utf8'; } } |