Skip to content

Commit db98ca5

Browse files
committed
misc/wasm: add polyfill for TextEncoder/TextDecoder for Edge support
Fixes golang#27295
1 parent 1d15354 commit db98ca5

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

misc/wasm/wasm_exec.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,82 @@
2727
global.TextEncoder = util.TextEncoder;
2828
global.TextDecoder = util.TextDecoder;
2929
} else {
30+
// Add polyfill for TextEncoder and TextDecoder for Microsoft Edge 17/18 support
31+
// https://caniuse.com/#feat=textencoder
32+
if (!window.TextEncoder) {
33+
TextEncoder = function(){}
34+
TextEncoder.prototype.encode = function (string) {
35+
var octets = [];
36+
var length = string.length;
37+
var i = 0;
38+
while (i < length) {
39+
var codePoint = string.codePointAt(i);
40+
var c = 0;
41+
var bits = 0;
42+
if (codePoint <= 0x0000007F) {
43+
c = 0;
44+
bits = 0x00;
45+
} else if (codePoint <= 0x000007FF) {
46+
c = 6;
47+
bits = 0xC0;
48+
} else if (codePoint <= 0x0000FFFF) {
49+
c = 12;
50+
bits = 0xE0;
51+
} else if (codePoint <= 0x001FFFFF) {
52+
c = 18;
53+
bits = 0xF0;
54+
}
55+
octets.push(bits | (codePoint >> c));
56+
c -= 6;
57+
while (c >= 0) {
58+
octets.push(0x80 | ((codePoint >> c) & 0x3F));
59+
c -= 6;
60+
}
61+
i += codePoint >= 0x10000 ? 2 : 1;
62+
}
63+
return octets;
64+
};
65+
}
66+
if (!window.TextDecoder) {
67+
TextDecoder = function(){}
68+
TextDecoder.prototype.decode = function (octets) {
69+
var string = "";
70+
var i = 0;
71+
while (i < octets.length) {
72+
var octet = octets[i];
73+
var bytesNeeded = 0;
74+
var codePoint = 0;
75+
if (octet <= 0x7F) {
76+
bytesNeeded = 0;
77+
codePoint = octet & 0xFF;
78+
} else if (octet <= 0xDF) {
79+
bytesNeeded = 1;
80+
codePoint = octet & 0x1F;
81+
} else if (octet <= 0xEF) {
82+
bytesNeeded = 2;
83+
codePoint = octet & 0x0F;
84+
} else if (octet <= 0xF4) {
85+
bytesNeeded = 3;
86+
codePoint = octet & 0x07;
87+
}
88+
if (octets.length - i - bytesNeeded > 0) {
89+
var k = 0;
90+
while (k < bytesNeeded) {
91+
octet = octets[i + k + 1];
92+
codePoint = (codePoint << 6) | (octet & 0x3F);
93+
k += 1;
94+
}
95+
} else {
96+
codePoint = 0xFFFD;
97+
bytesNeeded = octets.length - i;
98+
}
99+
string += String.fromCodePoint(codePoint);
100+
i += bytesNeeded + 1;
101+
}
102+
return string
103+
};
104+
}
105+
30106
if (typeof window !== "undefined") {
31107
window.global = window;
32108
} else if (typeof self !== "undefined") {

0 commit comments

Comments
 (0)