summaryrefslogtreecommitdiff
path: root/std/node/_utils.ts
diff options
context:
space:
mode:
Diffstat (limited to 'std/node/_utils.ts')
-rw-r--r--std/node/_utils.ts64
1 files changed, 64 insertions, 0 deletions
diff --git a/std/node/_utils.ts b/std/node/_utils.ts
index 463d4e67c..66b7b10d9 100644
--- a/std/node/_utils.ts
+++ b/std/node/_utils.ts
@@ -44,3 +44,67 @@ export function spliceOne(list: string[], index: number): void {
for (; index + 1 < list.length; index++) list[index] = list[index + 1];
list.pop();
}
+
+// Taken from: https://github.com/nodejs/node/blob/ba684805b6c0eded76e5cd89ee00328ac7a59365/lib/internal/util.js#L125
+// 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.
+export function normalizeEncoding(enc: string | null): string | undefined {
+ if (enc == null || enc === "utf8" || enc === "utf-8") return "utf8";
+ return slowCases(enc);
+}
+
+// https://github.com/nodejs/node/blob/ba684805b6c0eded76e5cd89ee00328ac7a59365/lib/internal/util.js#L130
+function slowCases(enc: string): string | undefined {
+ 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") 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 === "ucs-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";
+ break;
+ case 8:
+ if (
+ enc === "utf-16le" ||
+ enc === "UTF-16LE" ||
+ `${enc}`.toLowerCase() === "utf-16le"
+ )
+ return "utf16le";
+ break;
+ default:
+ if (enc === "") return "utf8";
+ }
+}