-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
53 lines (44 loc) · 1.32 KB
/
index.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
export default function encodeUtf8 (input) {
const result = []
const size = input.length
for (let index = 0; index < size; index++) {
let point = input.charCodeAt(index)
if (point >= 0xD800 && point <= 0xDBFF && size > index + 1) {
const second = input.charCodeAt(index + 1)
if (second >= 0xDC00 && second <= 0xDFFF) {
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
point = (point - 0xD800) * 0x400 + second - 0xDC00 + 0x10000
index += 1
}
}
// US-ASCII
if (point < 0x80) {
result.push(point)
continue
}
// 2-byte UTF-8
if (point < 0x800) {
result.push((point >> 6) | 192)
result.push((point & 63) | 128)
continue
}
// 3-byte UTF-8
if (point < 0xD800 || (point >= 0xE000 && point < 0x10000)) {
result.push((point >> 12) | 224)
result.push(((point >> 6) & 63) | 128)
result.push((point & 63) | 128)
continue
}
// 4-byte UTF-8
if (point >= 0x10000 && point <= 0x10FFFF) {
result.push((point >> 18) | 240)
result.push(((point >> 12) & 63) | 128)
result.push(((point >> 6) & 63) | 128)
result.push((point & 63) | 128)
continue
}
// Invalid character
result.push(0xEF, 0xBF, 0xBD)
}
return new Uint8Array(result).buffer
}