Debian Codegraph @

wasm/browser/polyfills/text-encoding.js

raw
1 // FROM https://gitlab.com/PseudoPsycho/text-encoding-shim/-/blob/master/index.js
2 const utf8Encodings = new Set(["utf8", "utf-8", "unicode-1-1-utf-8"]);
3
4 const TextEncoder = function (encoding) {
5 if (!utf8Encodings.has(encoding) && typeof encoding !== "undefined" && encoding !== null) {
6 throw new RangeError("Invalid encoding type. Only utf-8 is supported");
7 } else {
8 this.encoding = "utf-8";
9 this.encode = function (string) {
10 if (typeof string !== "string") {
11 throw new TypeError("passed argument must be of type string");
12 }
13 const binstr = unescape(encodeURIComponent(string));
14 const array = new Uint8Array(binstr.length);
15 binstr.split("").forEach(function (char, index) {
16 array[index] = char.charCodeAt(0);
17 });
18 return array;
19 };
20 }
21 };
22
23 const TextDecoder = function (encoding, options) {
24 if (!utf8Encodings.has(encoding) && typeof encoding !== "undefined" && encoding !== null) {
25 throw new RangeError("Invalid encoding type. Only utf-8 is supported");
26 }
27 this.encoding = "utf-8";
28 this.ignoreBOM = false;
29 this.fatal = typeof options !== "undefined" && "fatal" in options ? options.fatal : false;
30 if (typeof this.fatal !== "boolean") {
31 throw new TypeError("fatal flag must be boolean");
32 }
33 this.trimNull = (a) => {
34 const c = a.indexOf("\0");
35 if (c > -1) {
36 return a.slice(0, Math.max(0, c));
37 }
38 return a;
39 };
40
41 this.decode = function (view, options) {
42 if (typeof view === "undefined") {
43 return "";
44 }
45
46 const stream = typeof options !== "undefined" && "stream" in options ? options.stream : false;
47 if (typeof stream !== "boolean") {
48 throw new TypeError("stream option must be boolean");
49 }
50
51 if (!ArrayBuffer.isView(view)) {
52 throw new TypeError("passed argument must be an array buffer view");
53 } else {
54 const array = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
55 const charArray = new Array(array.length);
56 array.forEach(function (charcode, index) {
57 charArray[index] = String.fromCharCode(charcode);
58 });
59 return this.trimNull(charArray.join(""));
60 }
61 };
62 };