MCPcopy Index your code
hub / github.com/hoothin/UserScripts / decodeArrayBufferByCharset

Function decodeArrayBufferByCharset

Pagetual/pagetual.user.js:4193–4235  ·  view source on GitHub ↗
(buffer, preferredCharset)

Source from the content-addressed store, hash-verified

4191 return match && match[1] ? match[1].trim() : "";
4192 }
4193 function decodeArrayBufferByCharset(buffer, preferredCharset) {
4194 let bytes = new Uint8Array(buffer);
4195 let decoderList = [];
4196 let normalize = label => String(label || "").trim().toLowerCase();
4197 let addAlias = (name, aliases) => {
4198 if (aliases.indexOf(normalizedPreferred) !== -1) {
4199 pushDecoder(name);
4200 for (let i = 0; i < aliases.length; i++) {
4201 pushDecoder(aliases[i]);
4202 }
4203 }
4204 };
4205 let pushDecoder = label => {
4206 let raw = String(label || "").trim();
4207 if (raw && decoderList.indexOf(raw) === -1) {
4208 decoderList.push(raw);
4209 }
4210 };
4211 let normalizedPreferred = normalize(preferredCharset).replace(/["']/g, "");
4212 pushDecoder(preferredCharset);
4213 pushDecoder(normalizedPreferred);
4214 pushDecoder(normalizedPreferred.replace(/_/g, "-"));
4215 pushDecoder(normalizedPreferred.replace(/-/g, "_"));
4216 addAlias("shift_jis", ["shiftjis", "shift-jis", "sjis", "ms_kanji", "windows-31j", "cp932", "ms932"]);
4217 addAlias("euc-jp", ["eucjp"]);
4218 addAlias("iso-2022-jp", ["iso2022jp", "jis"]);
4219 addAlias("gb18030", ["gbk", "gb2312", "x-gbk", "cp936", "ms936", "windows-936"]);
4220 addAlias("big5", ["big-5", "cn-big5", "x-x-big5"]);
4221 addAlias("euc-kr", ["euckr", "ks_c_5601-1987", "ksc5601", "windows-949", "cp949"]);
4222 addAlias("windows-1251", ["cp1251"]);
4223 addAlias("windows-1252", ["cp1252", "iso-8859-1", "latin1", "latin-1"]);
4224 pushDecoder("utf-8");
4225 for (let i = 0; i < decoderList.length; i++) {
4226 try {
4227 return new TextDecoder(decoderList[i]).decode(bytes);
4228 } catch (e) {}
4229 }
4230 try {
4231 return new TextDecoder().decode(bytes);
4232 } catch (e) {
4233 return "";
4234 }
4235 }
4236 function detectCharsetFromHtmlHead(buffer) {
4237 if (!buffer || !buffer.byteLength) return "";
4238 let scanLen = Math.min(buffer.byteLength, 16384);

Callers 1

requestWithFetchFunction · 0.85

Calls 3

normalizeFunction · 0.85
pushDecoderFunction · 0.85
addAliasFunction · 0.85

Tested by

no test coverage detected