Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix UT8 handling in fs_writefile #83

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions tools/make.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,40 @@ function fs_readfile(p) {
return std.loadFile(p);
}

// Modification of https://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array
function toUInt8Array(str) {
let utf8 = [];
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++;
// UTF-16 encodes 0x10000-0x10FFFF by
// subtracting 0x10000 and splitting the
// 20 bits of 0x0-0xFFFFF into two halves
charcode = 0x10000 + (((charcode & 0x3ff)<<10)
| (str.charCodeAt(i) & 0x3ff));
utf8.push(0xf0 | (charcode >>18),
0x80 | ((charcode>>12) & 0x3f),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
}
return new Uint8Array(utf8);
}

function fs_writefile(p, data) {
let u8 = new Uint8Array(data.length);
for (let i = 0; i < data.length; ++i) {
u8[i] = data.charCodeAt(i);
}
let u8 = toUInt8Array(data);
let f = std.open(p, "w");
f.write(u8.buffer, 0, u8.length);
f.close();
Expand Down
Loading