Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/kernel/src/wasm/posix/time.ts
1068 views
1
const dateFormat = require("date-format");
2
import { notImplemented } from "./util";
3
4
export default function time({ child_process, memory, os }) {
5
return {
6
// int adjtime (const struct timeval *, struct timeval *);
7
adjtime() {
8
// TODO: similar to clock_settime below... but really maybe not necessary since
9
// cowasm should be pretty sandboxed!
10
notImplemented("TODO: implement adjtime");
11
},
12
settimeofday() {
13
notImplemented("TODO: settimeofday");
14
},
15
// int clock_settime(clockid_t clk_id, const struct timespec *tp);
16
clock_settime(_clk_id: number, timespec: number): number {
17
if (child_process.spawnSync == null) {
18
throw Error("clock_settime is not supported on this platform");
19
}
20
// NOTE: We assume the clk_id is CLOCK_REALTIME without a check.
21
22
const view = new DataView(memory.buffer);
23
const tv_sec = view.getUint32(timespec, true);
24
// we ignore nanoseconds here; the date commands aren't that precise anyways.
25
26
let cmd,
27
cmd2 = "",
28
args,
29
args2 = [];
30
31
switch (os.platform?.()) {
32
case "darwin":
33
// date -f "%s" "1660173350" # <-- number of seconds.
34
cmd = "date";
35
args = ["-f", "%s", `${tv_sec}`];
36
break;
37
case "linux":
38
// date --date='@2147483647' # <-- number of seconds
39
cmd = "date";
40
args = [`--set=@${tv_sec}`];
41
break;
42
case "win32":
43
const dateTime = new Date(1000 * tv_sec);
44
cmd = "date";
45
args = [dateFormat("m/d/yyyy", dateTime)];
46
cmd2 = "time";
47
args = [dateFormat("HH:MM:ss", dateTime)];
48
break;
49
default:
50
throw Error(
51
`clock_settime not supported on platform = ${os.platform?.()}`
52
);
53
}
54
const { status, stderr } = child_process.spawnSync(cmd, args);
55
if (status) {
56
throw Error(`clock_settime failed - ${stderr}`);
57
}
58
if (cmd2) {
59
const { status, stderr } = child_process.spawnSync(cmd2, args2);
60
if (status) {
61
throw Error(`clock_settime failed - ${stderr}`);
62
}
63
}
64
return 0;
65
},
66
};
67
}
68
69