Skip to content

Commit

Permalink
Accept string for pluto_give_file
Browse files Browse the repository at this point in the history
  • Loading branch information
Sainan committed Sep 29, 2024
1 parent c1d619e commit bc47239
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Barring the script tags needed for PlutoScript's usage, this is the entire sourc
- `pluto_require(src)`
- `pluto_load(code)`
- `pluto_invoke(name, ...args)` can be used to invoke a global Pluto function
- `pluto_give_file(name, data)` writes a Uint8Array for Pluto code to read from the file with the given name
- `pluto_give_file(name, data)` writes a string or Uint8Array for Pluto code to read from the file with the given name
## Pluto API
Expand Down
54 changes: 53 additions & 1 deletion plutoscript.js
Original file line number Diff line number Diff line change
Expand Up @@ -412,8 +412,60 @@ function pluto_invoke(name, ...args)
return pluto_invoke_impl(...args);
}

function pluto_give_file(name, data/*: Uint8Array */)
function utf32_to_utf8(utf8/*: array */, utf32/*: number */)/*: void */
{
// 1
if (utf32 < 0b10000000)
{
utf8.push(utf32);
return;
}
// 2
const UTF8_CONTINUATION_FLAG = 0b10000000;
utf8.push((utf32 & 0b111111) | UTF8_CONTINUATION_FLAG);
utf32 >>= 6;
if (utf32 <= 0b11111)
{
utf8.splice(utf8.length - 1, 0, utf32 | 0b11000000); // 110xxxxx
return;
}
// 3
utf8.splice(utf8.length - 1, 0, (utf32 & 0b111111) | UTF8_CONTINUATION_FLAG);
utf32 >>= 6;
if (utf32 <= 0b1111)
{
utf8.splice(utf8.length - 2, 0, utf32 | 0b11100000); // 1110xxxx
return;
}
// 4
utf8.splice(utf8.length - 2, 0, (utf32 & 0b111111) | UTF8_CONTINUATION_FLAG);
utf32 >>= 6;
utf8.splice(utf8.length - 3, 0, utf32 | 0b11110000); // 11110xxx
}

function utf16_to_utf8(str)
{
let arr = [];
for(let i = 0; i != str.length; ++i)
{
let c = str.charCodeAt(i);
if ((c >> 10) == 0x36) // Surrogate pair?
{
let hi = c & 0x3ff;
let lo = str.charCodeAt(++i) & 0x3ff;
c = (((hi * 0x400) + lo) + 0x10000);
}
utf32_to_utf8(arr, c);
}
return arr;
}

function pluto_give_file(name, data)
{
if (typeof data == "string")
{
data = new Uint8Array(utf16_to_utf8(data));
}
let stream = lib.mod.FS.open(name, "w+");
lib.mod.FS.write(stream, data, 0, data.length, 0);
lib.mod.FS.close(stream);
Expand Down

0 comments on commit bc47239

Please sign in to comment.