aboutsummaryrefslogtreecommitdiffstats
path: root/test/js/encode_decode.html
blob: 069ddc72c647837bc8b59ef92640dc481e3af57f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!doctype html>
<title>TextEncoder/TextDecoder test</title>
<div id="success">Fail</div>
<script>
(function() {
	/* Adapted from: https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem */
	function base64ToBytes(base64) {
		const binString = atob(base64);
		const result = [];
		for (const c of binString)
			result.push(Uint8Array.from(c, (m) => m.codePointAt(0)));
		return result;
	}

	function bytesToBase64(bytes) {
		const binString = String.fromCodePoint(...bytes);
		return btoa(binString);
	}

	const utf8 = new TextEncoder().encode("a Ā 𐀀 文 🦄")
	const b64utf8 = bytesToBase64(utf8);
	if (b64utf8 !== "YSDEgCDwkICAIOaWhyDwn6aE") {
		console.log(b64utf8);
		return;
	}
	const dec = new TextDecoder();
	const bytes = base64ToBytes(b64utf8);
	const a = [];
	let res = "";
	for (const c of bytes)
		res += dec.decode(c, {stream: true});
	res += dec.decode();
	if (res !== "a Ā 𐀀 文 🦄") {
		console.log(res);
		return;
	}
	document.getElementById("success").textContent = "Success";
})();
</script>