main
Last change
on this file since 79a0317 was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 3 days ago |
F4 Finalna Verzija
|
-
Property mode
set to
100644
|
File size:
1.3 KB
|
Line | |
---|
1 | function con(b) {
|
---|
2 | if ((b & 0xc0) === 0x80) {
|
---|
3 | return b & 0x3f;
|
---|
4 | } else {
|
---|
5 | throw new Error("invalid UTF-8 encoding");
|
---|
6 | }
|
---|
7 | }
|
---|
8 |
|
---|
9 | function code(min, n) {
|
---|
10 | if (n < min || 0xd800 <= n && n < 0xe000 || n >= 0x10000) {
|
---|
11 | throw new Error("invalid UTF-8 encoding");
|
---|
12 | } else {
|
---|
13 | return n;
|
---|
14 | }
|
---|
15 | }
|
---|
16 |
|
---|
17 | export function decode(bytes) {
|
---|
18 | return _decode(bytes).map(function (x) {
|
---|
19 | return String.fromCharCode(x);
|
---|
20 | }).join("");
|
---|
21 | }
|
---|
22 |
|
---|
23 | function _decode(bytes) {
|
---|
24 | var result = [];
|
---|
25 |
|
---|
26 | while (bytes.length > 0) {
|
---|
27 | var b1 = bytes[0];
|
---|
28 |
|
---|
29 | if (b1 < 0x80) {
|
---|
30 | result.push(code(0x0, b1));
|
---|
31 | bytes = bytes.slice(1);
|
---|
32 | continue;
|
---|
33 | }
|
---|
34 |
|
---|
35 | if (b1 < 0xc0) {
|
---|
36 | throw new Error("invalid UTF-8 encoding");
|
---|
37 | }
|
---|
38 |
|
---|
39 | var b2 = bytes[1];
|
---|
40 |
|
---|
41 | if (b1 < 0xe0) {
|
---|
42 | result.push(code(0x80, ((b1 & 0x1f) << 6) + con(b2)));
|
---|
43 | bytes = bytes.slice(2);
|
---|
44 | continue;
|
---|
45 | }
|
---|
46 |
|
---|
47 | var b3 = bytes[2];
|
---|
48 |
|
---|
49 | if (b1 < 0xf0) {
|
---|
50 | result.push(code(0x800, ((b1 & 0x0f) << 12) + (con(b2) << 6) + con(b3)));
|
---|
51 | bytes = bytes.slice(3);
|
---|
52 | continue;
|
---|
53 | }
|
---|
54 |
|
---|
55 | var b4 = bytes[3];
|
---|
56 |
|
---|
57 | if (b1 < 0xf8) {
|
---|
58 | result.push(code(0x10000, (((b1 & 0x07) << 18) + con(b2) << 12) + (con(b3) << 6) + con(b4)));
|
---|
59 | bytes = bytes.slice(4);
|
---|
60 | continue;
|
---|
61 | }
|
---|
62 |
|
---|
63 | throw new Error("invalid UTF-8 encoding");
|
---|
64 | }
|
---|
65 |
|
---|
66 | return result;
|
---|
67 | } |
---|
Note:
See
TracBrowser
for help on using the repository browser.