Skip to content

Commit

Permalink
src: refactor ucs2, utf8 & utf16le in encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
tony-go committed Aug 28, 2022
1 parent bb4dff7 commit 217f482
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 26 deletions.
32 changes: 7 additions & 25 deletions src/api/encoding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,14 @@ enum encoding ParseEncoding(const char* encoding,
switch (encoding[0]) {
case 'u':
case 'U':
// utf8, utf16le
if (encoding[1] == 't' && encoding[2] == 'f') {
// Skip `-`
const size_t skip = encoding[3] == '-' ? 4 : 3;
if (encoding[skip] == '8' && encoding[skip + 1] == '\0')
return UTF8;
if (strncmp(encoding + skip, "16le", 5) == 0)
return UCS2;
// ucs2
} else if (encoding[1] == 'c' && encoding[2] == 's') {
const size_t skip = encoding[3] == '-' ? 4 : 3;
if (encoding[skip] == '2' && encoding[skip + 1] == '\0')
return UCS2;
}
if (StringEqualNoCase(encoding, "utf8"))
return UTF8;
if (StringEqualNoCase(encoding, "utf-8"))
return UTF8;
if (StringEqualNoCase(encoding, "ucs2"))
return UCS2;
if (StringEqualNoCase(encoding, "ucs-2"))
return UCS2;
if (StringEqualNoCase(encoding, "utf16le"))
return UCS2;
if (StringEqualNoCase(encoding, "utf-16le"))
if (StringEqualNoCase(encoding, "ucs2") ||
StringEqualNoCase(encoding, "ucs-2") ||
StringEqualNoCase(encoding, "utf16le") ||
StringEqualNoCase(encoding, "utf-16le"))
return UCS2;
if (StringEqualNoCase(encoding, "utf8") ||
StringEqualNoCase(encoding, "utf-8"))
return UTF8;
break;

case 'l':
Expand Down
6 changes: 5 additions & 1 deletion test/addons/parse-encoding/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@ assert.strictEqual(parseEncoding('buffer'), 'BUFFER');
assert.strictEqual(parseEncoding('hex'), 'HEX');
assert.strictEqual(parseEncoding('latin1'), 'LATIN1');
assert.strictEqual(parseEncoding('ucs2'), 'UCS2');
assert.strictEqual(parseEncoding('ucs-2'), 'UCS2');
assert.strictEqual(parseEncoding('utf8'), 'UTF8');
assert.strictEqual(parseEncoding('utf-8'), 'UTF8');
assert.strictEqual(parseEncoding('utf16le'), 'UCS2');
assert.strictEqual(parseEncoding('utf-16LE'), 'UCS2');

assert.strictEqual(parseEncoding('utf-buffer'), 'UNKNOWN');
assert.strictEqual(parseEncoding('utf-16leNOT'), 'UNKNOWN');

assert.strictEqual(parseEncoding('linary'), 'UNKNOWN');
assert.strictEqual(parseEncoding('luffer'), 'UNKNOWN');

0 comments on commit 217f482

Please sign in to comment.