Skip to content

Commit

Permalink
feat: Implement clock_res_get, fd_pwrite, and fd_tell (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
kateinoigakukun authored Dec 5, 2023
1 parent f3c5567 commit 66fded0
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
26 changes: 26 additions & 0 deletions src/fs_fd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ export class OpenFile extends Fd {
return { ret: 0, offset: this.file_pos };
}

fd_tell(): { ret: number; offset: bigint } {
return { ret: 0, offset: this.file_pos };
}

fd_write(
view8: Uint8Array,
iovs: Array<wasi.Ciovec>,
Expand All @@ -108,6 +112,28 @@ export class OpenFile extends Fd {
return { ret: 0, nwritten };
}

fd_pwrite(view8: Uint8Array, iovs: Array<wasi.Ciovec>, offset: bigint) {
let nwritten = 0;
if (this.file.readonly) return { ret: wasi.ERRNO_BADF, nwritten };
for (const iovec of iovs) {
const buffer = view8.slice(iovec.buf, iovec.buf + iovec.buf_len);
if (offset + BigInt(buffer.byteLength) > this.file.size) {
const old = this.file.data;
this.file.data = new Uint8Array(
Number(offset + BigInt(buffer.byteLength)),
);
this.file.data.set(old);
}
this.file.data.set(
buffer.slice(0, Number(this.file.size - offset)),
Number(offset),
);
offset += BigInt(buffer.byteLength);
nwritten += iovec.buf_len;
}
return { ret: 0, nwritten };
}

fd_filestat_get(): { ret: number; filestat: wasi.Filestat } {
return { ret: 0, filestat: this.file.stat() };
}
Expand Down
21 changes: 19 additions & 2 deletions src/wasi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,14 +134,31 @@ export default class WASI {

// eslint-disable-next-line @typescript-eslint/no-unused-vars
clock_res_get(id: number, res_ptr: number): number {
throw "unimplemented";
let resolutionValue: bigint;
switch (id) {
case wasi.CLOCKID_MONOTONIC: {
// https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
// > Resolution in isolated contexts: 5 microseconds
resolutionValue = 5_000n; // 5 microseconds
break;
}
case wasi.CLOCKID_REALTIME: {
resolutionValue = 1_000_000n; // 1 millisecond?
break;
}
default:
return wasi.ERRNO_NOSYS;
}
const view = new DataView(self.inst.exports.memory.buffer);
view.setBigUint64(res_ptr, resolutionValue, true);
return wasi.ERRNO_SUCCESS;
},
clock_time_get(id: number, precision: bigint, time: number): number {
const buffer = new DataView(self.inst.exports.memory.buffer);
if (id === wasi.CLOCKID_REALTIME) {
buffer.setBigUint64(
time,
BigInt(new Date().getTime()) * 1000000n,
BigInt(new Date().getTime()) * 1_000_000n,
true,
);
} else if (id == wasi.CLOCKID_MONOTONIC) {
Expand Down

0 comments on commit 66fded0

Please sign in to comment.