Repository navigation
Expand file tree
/
Copy pathtime.wave
More file actions
81 lines (73 loc) · 2.5 KB
/
Copy pathtime.wave
File metadata and controls
81 lines (73 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// This file is part of the Wave language project.
// Copyright (c) 2024-2026 Wave Foundation
// Copyright (c) 2024-2026 LunaStev and contributors
// SPDX-License-Identifier: Apache-2.0
// Windows clock and sleep provider.
extern(system, "Sleep") fun win_sleep(milliseconds: u32);
extern(system, "GetSystemTimeAsFileTime") fun win_get_system_time_as_file_time(value: ptr<FileTime>);
extern(system, "QueryPerformanceCounter") fun win_query_performance_counter(value: ptr<i64>) -> i32;
extern(system, "QueryPerformanceFrequency") fun win_query_performance_frequency(value: ptr<i64>) -> i32;
struct FileTime {
low: u32;
high: u32;
}
pub struct TimeSpec {
sec: i64;
nsec: i64;
}
pub fun nanosleep(req: ptr<TimeSpec>, rem: ptr<TimeSpec>) -> i64 {
if (req == null || deref req.sec < 0
|| deref req.nsec < 0 || deref req.nsec >= 1000000000) {
return -22;
}
// Sleep uses milliseconds and reserves u32::MAX for an infinite wait.
// Break long durations into finite chunks and round a fractional
// millisecond up so a positive request is never shortened to zero.
var seconds: i64 = deref req.sec;
while (seconds >= 4294967) {
win_sleep(4294967000 as u32);
seconds -= 4294967;
}
var millis: i64 = seconds * 1000;
if (deref req.nsec > 0) {
millis += (deref req.nsec + 999999) / 1000000;
}
if (millis > 0) {
win_sleep(millis as u32);
}
if (rem != null) {
deref rem.sec = 0;
deref rem.nsec = 0;
}
return 0;
}
pub fun clock_gettime(clock_id: i32, tp: ptr<TimeSpec>) -> i64 {
if (tp == null) {
return -22;
}
if (clock_id == 1) {
var counter: i64 = 0;
var frequency: i64 = 0;
if (
win_query_performance_counter(&counter) == 0 ||
win_query_performance_frequency(&frequency) == 0 ||
frequency <= 0
) {
return -1;
}
deref tp.sec = counter / frequency;
deref tp.nsec = ((counter % frequency) * 1000000000) / frequency;
return 0;
}
if (clock_id != 0) {
return -22;
}
var raw: FileTime;
win_get_system_time_as_file_time(&raw);
var ticks: u64 = (raw.high as u64 << 32) | raw.low as u64;
// Divide before subtracting: the quotient fits in i64 even for u64::MAX
// ticks. The unsigned remainder keeps pre-1970 nanoseconds normalized.
deref tp.sec = (ticks / 10000000) as i64 - 11644473600;
deref tp.nsec = ((ticks % 10000000) * 100) as i64;
return 0;
}