summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/encoding/legacy-mb-korean/euc-kr/euckr-decoder.js
blob: a248b5c6cf97e37b44aa32b4f4f6b0994d51d1d5 (plain)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
function dec2char(n) {
	// converts a decimal number to a Unicode character
	// n: the dec codepoint value to be converted
	if (n <= 0xffff) {
		out = String.fromCharCode(n);
	} else if (n <= 0x10ffff) {
		n -= 0x10000;
		out =
			String.fromCharCode(0xd800 | (n >> 10)) +
			String.fromCharCode(0xdc00 | (n & 0x3ff));
	} else out = "dec2char error: Code point out of range: " + n;
	return out;
}

function euckrDecoder(stream) {
	stream = stream.replace(/%/g, " ");
	stream = stream.replace(/[\s]+/g, " ").trim();
	var bytes = stream.split(" ");
	for (var i = 0; i < bytes.length; i++) bytes[i] = parseInt(bytes[i], 16);
	var out = "";
	var lead, byte, offset, ptr, cp;
	var euckrLead = 0x00;
	var endofstream = 2000000;
	var finished = false;

	while (!finished) {
		if (bytes.length == 0) byte = endofstream;
		else byte = bytes.shift();

		if (byte == endofstream && euckrLead != 0x00) {
			euckrLead = 0x00;
			out += "�";
			continue;
		}
		if (byte == endofstream && euckrLead == 0x00) {
			finished = true;
			continue;
		}

		if (euckrLead != 0x00) {
			lead = euckrLead;
			ptr = null;
			euckrLead = 0x00;
			if (byte >= 0x41 && byte <= 0xfe)
				ptr = (lead - 0x81) * 190 + (byte - 0x41);
			if (ptr == null) cp = null;
			else cp = euckr[ptr];
			if (cp == null && byte >= 0x00 && byte <= 0x7f) bytes.unshift(byte);
			if (cp == null) {
				out += "�";
				continue;
			}
			out += dec2char(cp);
			continue;
		}
		if (byte >= 0x00 && byte <= 0x7f) {
			out += dec2char(byte);
			continue;
		}
		if (byte >= 0x81 && byte <= 0xfe) {
			euckrLead = byte;
			continue;
		}
		out += "�";
	}
	return out;
}