diff options
| author | nsfisis <nsfisis@gmail.com> | 2025-03-08 00:59:36 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2025-03-08 00:59:36 +0900 |
| commit | a10e8e64305e5002c682b45471b417ca4e33773d (patch) | |
| tree | 23bf4a707c1f168c252cc4d24d06c2d2ffb8c7a8 /worker/exec.mjs | |
| parent | efd34b970d0d1f88fa7d7e9d69e569f039867ca2 (diff) | |
| download | phperkaigi-2025-albatross-a10e8e64305e5002c682b45471b417ca4e33773d.tar.gz phperkaigi-2025-albatross-a10e8e64305e5002c682b45471b417ca4e33773d.tar.zst phperkaigi-2025-albatross-a10e8e64305e5002c682b45471b417ca4e33773d.zip | |
worker: swift to php
Diffstat (limited to 'worker/exec.mjs')
| -rw-r--r-- | worker/exec.mjs | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/worker/exec.mjs b/worker/exec.mjs new file mode 100644 index 0000000..7d64cc3 --- /dev/null +++ b/worker/exec.mjs @@ -0,0 +1,72 @@ +import PHPWasm from "./php-wasm.js"; + +process.once("message", async ({ code, input }) => { + const PRELUDE = ` + define('STDIN', fopen('php://stdin', 'r')); + define('STDOUT', fopen('php://stdout', 'r')); + define('STDERR', fopen('php://stderr', 'r')); + + `; + const BUFFER_MAX = 1024; + + let stdinPos = 0; // bytewise + const stdinBuf = Buffer.from(input); + let stdoutPos = 0; // bytewise + const stdoutBuf = Buffer.alloc(BUFFER_MAX); + let stderrPos = 0; // bytewise + const stderrBuf = Buffer.alloc(BUFFER_MAX); + + const { ccall } = await PHPWasm({ + stdin: () => { + if (stdinBuf.length <= stdinPos) { + return null; + } + return stdinBuf.readUInt8(stdinPos++); + }, + stdout: (asciiCode) => { + if (asciiCode === null) { + return; // flush + } + if (BUFFER_MAX <= stdoutPos) { + return; // ignore + } + stdoutBuf.writeUInt8( + asciiCode < 0 ? asciiCode + 256 : asciiCode, + stdoutPos++, + ); + }, + stderr: (asciiCode) => { + if (asciiCode === null) { + return; // flush + } + if (BUFFER_MAX <= stderrPos) { + return; // ignore + } + stderrBuf.writeUInt8( + asciiCode < 0 ? asciiCode + 256 : asciiCode, + stderrPos++, + ); + }, + }); + + let err; + let result; + try { + result = ccall("php_wasm_run", "number", ["string"], [PRELUDE + code]); + } catch (e) { + err = e; + } + if (err) { + process.send({ + status: "runtime_error", + stdout: stdoutBuf.subarray(0, stdoutPos).toString(), + stderr: `${stderrBuf.subarray(0, stderrPos).toString()}\n${err.toString()}`, + }); + } else { + process.send({ + status: result === 0 ? "success" : "runtime_error", + stdout: stdoutBuf.subarray(0, stdoutPos).toString(), + stderr: stderrBuf.subarray(0, stderrPos).toString(), + }); + } +}); |
