mirror of
https://github.com/nodejs/node.git
synced 2026-11-26 21:58:26 -05:00
buffer,string_decoder: consolidate encoding validation logic
Buffer.isEncoding and string_decoder.normalizeEncoding shared quite a bit of logic. This moves the primary logic into internal/util. The userland modules that monkey patch Buffer.isEncoding should still work. PR-URL: https://github.com/nodejs/node/pull/7207 Reviewed-By: Brian White <mscdex@mscdex.net> Reviewed-By: Trevor Norris <trev.norris@gmail.com> Refs: https://github.com/nodejs/node/pull/8463 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Jeremiah Senkpiel <fishrock123@rocketmail.com>
This commit is contained in:
1 parent
49f996f4f6
commit
dd51b1f428
5 files changed
+107
-52
No files matched your search
+7
-28
@@ -1,38 +1,17 @@
|
||||
'use strict';
|
||||
|
||||
const Buffer = require('buffer').Buffer;
|
||||
const internalUtil = require('internal/util');
|
||||
const isEncoding = Buffer[internalUtil.kIsEncodingSymbol];
|
||||
|
||||
// Do not cache `Buffer.isEncoding` when checking encoding names as some
|
||||
// modules monkey-patch it to support additional encodings
|
||||
function normalizeEncoding(enc) {
|
||||
if (!enc) return 'utf8';
|
||||
var low;
|
||||
for (;;) {
|
||||
switch (enc) {
|
||||
case 'utf8':
|
||||
case 'utf-8':
|
||||
return 'utf8';
|
||||
case 'ucs2':
|
||||
case 'utf16le':
|
||||
case 'ucs-2':
|
||||
case 'utf-16le':
|
||||
return 'utf16le';
|
||||
case 'base64':
|
||||
case 'ascii':
|
||||
case 'latin1':
|
||||
case 'binary':
|
||||
case 'hex':
|
||||
return enc;
|
||||
default:
|
||||
if (low) {
|
||||
if (!Buffer.isEncoding(enc))
|
||||
throw new Error('Unknown encoding: ' + enc);
|
||||
return enc;
|
||||
}
|
||||
low = true;
|
||||
enc = ('' + enc).toLowerCase();
|
||||
}
|
||||
}
|
||||
const nenc = internalUtil.normalizeEncoding(enc);
|
||||
if (typeof nenc !== 'string' &&
|
||||
(Buffer.isEncoding === isEncoding || !Buffer.isEncoding(enc)))
|
||||
throw new Error(`Unknown encoding: ${enc}`);
|
||||
return nenc || enc;
|
||||
}
|
||||
|
||||
// StringDecoder provides an interface for efficiently splitting a series of
|
||||
|
||||
Reference in new issue
Block a user