-
Notifications
You must be signed in to change notification settings - Fork 0
/
base-lol.mjs
60 lines (52 loc) · 1.79 KB
/
base-lol.mjs
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
/**
* Encodes binary data as emojis in utf8.
*/
// use the most recognisable emojis for ascii/utf8 text
const asciiTextStart = "😀".codePointAt(0);
const asciiTextEnd = asciiTextStart + 128;
// 256 char run after rat
const lowStart = "🐀".codePointAt(0);
const lowEnd = lowStart + 64;
const highStart = lowEnd + 1;
const highEnd = highStart + 127;
// emojis are all non-BMP, and share same first element when encoded
// as utf8
const emojiLowElement = 55357;
export function encode(byte) {
if(byte < 65) {
return String.fromCodePoint(byte + lowStart);
} if (byte >= 128) {
return String.fromCodePoint(byte + highStart - 128);
} else {
// ascii printable
return String.fromCodePoint(asciiTextStart + byte - 65);
}
}
export function decode(codePoint) {
if(codePoint >= asciiTextStart && codePoint <= asciiTextEnd) {
return codePoint - asciiTextStart + 65;
} else if(codePoint >= lowStart && codePoint <= lowEnd) {
return codePoint - lowStart;
} else if(codePoint >= highStart && codePoint <= highEnd) {
return codePoint - highStart + 128;
} else {
throw Error(`character out of range '${codePoint}'`);
}
}
export function decodeString(emojiString) {
const bytes = new Array(emojiString.length/2);
for(let i = 0; i < emojiString.length; i+=2) {
if(emojiString.charCodeAt(i) !== emojiLowElement) {
throw Error(`failed to decode string at index ${i}: '${emojiString.slice(i, i+2)}'`);
}
const codePoint = emojiString.codePointAt(i);
bytes[i/2] = decode(codePoint);
}
return bytes;
}
export function encodeUInt8Array(ints) {
return ints.map(encode).join('');
}
export function encodeString(s) {
return s.split("").map(s => encode(s.charCodeAt(0))).join('');
}