-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutf8.js
39 lines (36 loc) · 829 Bytes
/
utf8.js
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
function stringToBytes(str) {
try {
return unescape(encodeURIComponent(str));
} catch (e) {
throw new Error("Invalid string " +
bytes.split('').map(c => c.charCodeAt(0)));
}
}
function bytesToString(bytes) {
try {
return decodeURIComponent(escape(bytes));
} catch (e) {
throw new Error("Invalid bytes " +
bytes.split('').map(c => c.charCodeAt(0)));
}
}
function getSequenceLength(firstByte) {
var x = firstByte.charCodeAt(0);
if (x < 128) {
return 1;
}
if (x >> 5 == 0b110) {
return 2;
}
if (x >> 4 == 0b1110) {
return 3;
}
if (x >> 3 == 0b11110) {
return 4;
}
// Invalid first byte
return 0;
}
exports.stringToBytes = stringToBytes;
exports.bytesToString = bytesToString;
exports.getSequenceLength = getSequenceLength;