Created
June 18, 2020 13:04
-
-
Save realmayus/afa9923705ed473cb582d947f4eba7d2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
writeUTF8(str) { | |
let utf8 = [] | |
let utflen = str.length; // optimized for ASCII | |
for (let i = 0; i < str.length; i++) { | |
let c = str.charAt(i); | |
if (c >= 0x80 || c === 0) | |
utflen += (c >= 0x800) ? 2 : 1; | |
} | |
utf8.push(rshift(utflen, 8) & 0xFF) | |
utf8.push(rshift(utflen, 0) & 0xFF) | |
for (let i = 0; i < str.length; i++) { | |
let charcode = str.charCodeAt(i) | |
if (charcode < 0x80) utf8.push(charcode) | |
else if (charcode < 0x800) { | |
utf8.push(0xC0 | (charcode >> 6), 0x80 | (charcode & 0x3f)) | |
} | |
else if (charcode < 0xd800 || charcode >= 0xe000) { | |
utf8.push(0xE0 | (charcode >> 12), | |
0x80 | ((charcode>>6) & 0x3f), | |
0x80 | (charcode & 0x3f)) | |
} | |
// surrogate pair | |
else { | |
i++ | |
charcode = ((charcode&0x3ff)<<10)|(str.charCodeAt(i)&0x3ff) | |
utf8.push(0xf0 | (charcode >>18), | |
0x80 | ((charcode>>12) & 0x3f), | |
0x80 | ((charcode>>6) & 0x3f), | |
0x80 | (charcode & 0x3f)) | |
} | |
} | |
this.writeByteArray(utf8) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment