Merge branch 'std.os.time' of https://github.com/tgschultz/zig into tgschultz-std.os.time

This commit is contained in:
Andrew Kelley 2018-04-22 13:24:25 -04:00
commit 0dcadc61b4
12 changed files with 403 additions and 54 deletions

View File

@ -510,6 +510,8 @@ set(ZIG_STD_FILES
"os/linux/index.zig"
"os/linux/x86_64.zig"
"os/path.zig"
"os/time.zig"
"os/epoch.zig"
"os/windows/error.zig"
"os/windows/index.zig"
"os/windows/util.zig"

View File

@ -3,10 +3,28 @@ pub extern "c" fn _NSGetExecutablePath(buf: &u8, bufsize: &u32) c_int;
pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: &u8, buf_len: usize, basep: &i64) usize;
pub extern "c" fn mach_absolute_time() u64;
pub extern "c" fn mach_timebase_info(tinfo: ?&mach_timebase_info_data) void;
pub use @import("../os/darwin_errno.zig");
pub const _errno = __error;
pub const timeval = extern struct {
tv_sec: isize,
tv_usec: isize,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
pub const mach_timebase_info_data = struct {
numer: u32,
denom: u32,
};
/// Renamed to Stat to not conflict with the stat function.
pub const Stat = extern struct {
dev: i32,

View File

@ -41,6 +41,7 @@ pub extern "c" fn dup2(old_fd: c_int, new_fd: c_int) c_int;
pub extern "c" fn readlink(noalias path: &const u8, noalias buf: &u8, bufsize: usize) isize;
pub extern "c" fn realpath(noalias file_name: &const u8, noalias resolved_name: &u8) ?&u8;
pub extern "c" fn sigprocmask(how: c_int, noalias set: &const sigset_t, noalias oset: ?&sigset_t) c_int;
pub extern "c" fn gettimeofday(tv: ?&timeval, tz: ?&timezone) c_int;
pub extern "c" fn sigaction(sig: c_int, noalias act: &const Sigaction, noalias oact: ?&Sigaction) c_int;
pub extern "c" fn nanosleep(rqtp: &const timespec, rmtp: ?&timespec) c_int;
pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int;

View File

@ -86,7 +86,8 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
},
's' => {
state = State.Buf;
},'.' => {
},
'.' => {
state = State.Float;
},
else => @compileError("Unknown format character: " ++ []u8{c}),

View File

@ -260,6 +260,10 @@ pub fn readlink(noalias path: &const u8, noalias buf_ptr: &u8, buf_len: usize) u
return errnoWrap(c.readlink(path, buf_ptr, buf_len));
}
pub fn gettimeofday(tv: ?&timeval, tz: ?&timezone) usize {
return errnoWrap(c.gettimeofday(tv, tz));
}
pub fn nanosleep(req: &const timespec, rem: ?&timespec) usize {
return errnoWrap(c.nanosleep(req, rem));
}
@ -330,3 +334,11 @@ pub fn sigaddset(set: &sigset_t, signo: u5) void {
fn errnoWrap(value: isize) usize {
return @bitCast(usize, if (value == -1) -isize(*c._errno()) else value);
}
pub const timezone = c.timezone;
pub const timeval = c.timeval;
pub const mach_timebase_info_data = c.mach_timebase_info_data;
pub const mach_absolute_time = c.mach_absolute_time;
pub const mach_timebase_info = c.mach_timebase_info;

26
std/os/epoch.zig Normal file
View File

@ -0,0 +1,26 @@
/// Epoch reference times in terms of their difference from
/// posix epoch in seconds.
pub const posix = 0; //Jan 01, 1970 AD
pub const dos = 315532800; //Jan 01, 1980 AD
pub const ios = 978307200; //Jan 01, 2001 AD
pub const openvms = -3506716800; //Nov 17, 1858 AD
pub const zos = -2208988800; //Jan 01, 1900 AD
pub const windows = -11644473600; //Jan 01, 1601 AD
pub const amiga = 252460800; //Jan 01, 1978 AD
pub const pickos = -63244800; //Dec 31, 1967 AD
pub const gps = 315964800; //Jan 06, 1980 AD
pub const clr = -62135769600; //Jan 01, 0001 AD
pub const unix = posix;
pub const android = posix;
pub const os2 = dos;
pub const bios = dos;
pub const vfat = dos;
pub const ntfs = windows;
pub const ntp = zos;
pub const jbase = pickos;
pub const aros = amiga;
pub const morphos = amiga;
pub const brew = gps;
pub const atsc = gps;
pub const go = clr;

View File

@ -4,16 +4,16 @@ const Os = builtin.Os;
const is_windows = builtin.os == Os.windows;
const os = this;
test "std.os" {
comptime {
if (!builtin.is_test) return;
_ = @import("child_process.zig");
_ = @import("darwin.zig");
_ = @import("darwin_errno.zig");
_ = @import("get_user_id.zig");
_ = @import("linux/errno.zig");
_ = @import("linux/index.zig");
_ = @import("linux/x86_64.zig");
_ = @import("path.zig");
_ = @import("test.zig");
_ = @import("time.zig");
_ = @import("windows/index.zig");
}
@ -32,6 +32,7 @@ pub const net = @import("net.zig");
pub const ChildProcess = @import("child_process.zig").ChildProcess;
pub const path = @import("path.zig");
pub const File = @import("file.zig").File;
pub const time = @import("time.zig");
pub const FileMode = switch (builtin.os) {
Os.windows => void,
@ -1379,50 +1380,6 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) ![]u8 {
}
}
pub fn sleep(seconds: usize, nanoseconds: usize) void {
switch(builtin.os) {
Os.linux, Os.macosx, Os.ios => {
posixSleep(u63(seconds), u63(nanoseconds));
},
Os.windows => {
const milliseconds = seconds * 1000 + nanoseconds / 1000000;
windows.Sleep(windows.DWORD(milliseconds));
},
else => @compileError("Unsupported OS"),
}
}
const u63 = @IntType(false, 63);
pub fn posixSleep(seconds: u63, nanoseconds: u63) void {
var req = posix.timespec {
.tv_sec = seconds,
.tv_nsec = nanoseconds,
};
var rem: posix.timespec = undefined;
while (true) {
const ret_val = posix.nanosleep(&req, &rem);
const err = posix.getErrno(ret_val);
if (err == 0) return;
switch (err) {
posix.EFAULT => unreachable,
posix.EINVAL => {
// Sometimes Darwin returns EINVAL for no reason.
// We treat it as a spurious wakeup.
return;
},
posix.EINTR => {
req = rem;
continue;
},
else => return,
}
}
}
test "os.sleep" {
sleep(0, 1);
}
pub fn posix_setuid(uid: u32) !void {
const err = posix.getErrno(posix.setuid(uid));
if (err == 0) return;

View File

@ -805,6 +805,26 @@ pub fn waitpid(pid: i32, status: &i32, options: i32) usize {
return syscall4(SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), @bitCast(usize, isize(options)), 0);
}
pub fn clock_gettime(clk_id: i32, tp: &timespec) usize {
return syscall2(SYS_clock_gettime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
}
pub fn clock_getres(clk_id: i32, tp: &timespec) usize {
return syscall2(SYS_clock_getres, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
}
pub fn clock_settime(clk_id: i32, tp: &const timespec) usize {
return syscall2(SYS_clock_settime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
}
pub fn gettimeofday(tv: &timeval, tz: &timezone) usize {
return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz));
}
pub fn settimeofday(tv: &const timeval, tz: &const timezone) usize {
return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz));
}
pub fn nanosleep(req: &const timespec, rem: ?&timespec) usize {
return syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem));
}
@ -1289,10 +1309,7 @@ pub fn capset(hdrp: &cap_user_header_t, datap: &const cap_user_data_t) usize {
return syscall2(SYS_capset, @ptrToInt(hdrp), @ptrToInt(datap));
}
test "import linux test" {
// TODO lazy analysis should prevent this test from being compiled on windows, but
// it is still compiled on windows
if (builtin.os == builtin.Os.linux) {
_ = @import("test.zig");
}
comptime {
if (!builtin.is_test) return;
_ = @import("test.zig");
}

View File

@ -1,8 +1,11 @@
const std = @import("../../index.zig");
const builtin = @import("builtin");
const linux = std.os.linux;
const assert = std.debug.assert;
test "timer" {
if (builtin.os != builtin.Os.linux) return;
const epoll_fd = linux.epoll_create();
var err = linux.getErrno(epoll_fd);
assert(err == 0);

View File

@ -492,6 +492,16 @@ pub const timespec = extern struct {
tv_nsec: isize,
};
pub const timeval = extern struct {
tv_sec: isize,
tv_usec: isize,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
pub const dirent = extern struct {
d_ino: usize,
d_off: usize,

288
std/os/time.zig Normal file
View File

@ -0,0 +1,288 @@
const std = @import("../index.zig");
const builtin = @import("builtin");
const Os = builtin.Os;
const debug = std.debug;
const windows = std.os.windows;
const linux = std.os.linux;
const darwin = std.os.darwin;
const posix = std.os.posix;
pub const epoch = @import("epoch.zig");
/// Sleep for the specified duration
pub fn sleep(seconds: usize, nanoseconds: usize) void {
switch (builtin.os) {
Os.linux, Os.macosx, Os.ios => {
posixSleep(u63(seconds), u63(nanoseconds));
},
Os.windows => {
const ns_per_ms = ns_per_s / ms_per_s;
const milliseconds = seconds * ms_per_s + nanoseconds / ns_per_ms;
windows.Sleep(windows.DWORD(milliseconds));
},
else => @compileError("Unsupported OS"),
}
}
const u63 = @IntType(false, 63);
pub fn posixSleep(seconds: u63, nanoseconds: u63) void {
var req = posix.timespec {
.tv_sec = seconds,
.tv_nsec = nanoseconds,
};
var rem: posix.timespec = undefined;
while (true) {
const ret_val = posix.nanosleep(&req, &rem);
const err = posix.getErrno(ret_val);
if (err == 0) return;
switch (err) {
posix.EFAULT => unreachable,
posix.EINVAL => {
// Sometimes Darwin returns EINVAL for no reason.
// We treat it as a spurious wakeup.
return;
},
posix.EINTR => {
req = rem;
continue;
},
else => return,
}
}
}
/// Get the posix timestamp, UTC, in seconds
pub fn timestamp() u64 {
return @divFloor(milliTimestamp(), ms_per_s);
}
/// Get the posix timestamp, UTC, in milliseconds
pub const milliTimestamp = switch (builtin.os) {
Os.windows => milliTimestampWindows,
Os.linux => milliTimestampPosix,
Os.macosx, Os.ios => milliTimestampDarwin,
else => @compileError("Unsupported OS"),
};
fn milliTimestampWindows() u64 {
//FileTime has a granularity of 100 nanoseconds
// and uses the NTFS/Windows epoch
var ft: i64 = undefined;
windows.GetSystemTimeAsFileTime(&ft);
const hns_per_ms = (ns_per_s / 100) / ms_per_s;
const epoch_adj = epoch.windows * ms_per_s;
return u64(@divFloor(ft, hns_per_ms) + epoch_adj);
}
fn milliTimestampDarwin() u64 {
//Sources suggest MacOS 10.12 has support for
// posix clock_gettime.
var tv: darwin.timeval = undefined;
var err = darwin.gettimeofday(&tv, null);
debug.assert(err == 0);
const sec_ms = u64(tv.tv_sec) * ms_per_s;
const usec_ms = @divFloor(u64(tv.tv_usec), us_per_s / ms_per_s);
return u64(sec_ms) + u64(usec_ms);
}
fn milliTimestampPosix() u64 {
//From what I can tell there's no reason clock_gettime
// should ever fail for us with CLOCK_REALTIME,
// seccomp aside.
var ts: posix.timespec = undefined;
const err = posix.clock_gettime(posix.CLOCK_REALTIME, &ts);
debug.assert(err == 0);
const sec_ms = u64(ts.tv_sec) * ms_per_s;
const nsec_ms = @divFloor(u64(ts.tv_nsec), ns_per_s / ms_per_s);
return sec_ms + nsec_ms;
}
/// Divisions of a second
pub const ns_per_s = 1000000000;
pub const us_per_s = 1000000;
pub const ms_per_s = 1000;
pub const cs_per_s = 100;
/// Common time divisions
pub const s_per_min = 60;
pub const s_per_hour = s_per_min * 60;
pub const s_per_day = s_per_hour * 24;
pub const s_per_week = s_per_day * 7;
/// A monotonic high-performance timer.
/// Timer.start() must be called to initialize the struct, which captures
/// the counter frequency on windows and darwin, records the resolution,
/// and gives the user an oportunity to check for the existnece of
/// monotonic clocks without forcing them to check for error on each read.
/// .resolution is in nanoseconds on all platforms but .start_time's meaning
/// depends on the OS. On Windows and Darwin it is a hardware counter
/// value that requires calculation to convert to a meaninful unit.
pub const Timer = struct {
//if we used resolution's value when performing the
// performance counter calc on windows/darwin, it would
// be less precise
frequency: switch (builtin.os) {
Os.windows => u64,
Os.macosx, Os.ios => darwin.mach_timebase_info_data,
else => void,
},
resolution: u64,
start_time: u64,
//At some point we may change our minds on RAW, but for now we're
// sticking with posix standard MONOTONIC. For more information, see:
// https://github.com/zig-lang/zig/pull/933
//
//const monotonic_clock_id = switch(builtin.os) {
// Os.linux => linux.CLOCK_MONOTONIC_RAW,
// else => posix.CLOCK_MONOTONIC,
//};
const monotonic_clock_id = posix.CLOCK_MONOTONIC;
/// Initialize the timer structure.
//This gives us an oportunity to grab the counter frequency in windows.
//On Windows: QueryPerformanceCounter will succeed on anything >= XP/2000.
//On Posix: CLOCK_MONOTONIC will only fail if the monotonic counter is not
// supported, or if the timespec pointer is out of bounds, which should be
// impossible here barring cosmic rays or other such occurances of
// incredibly bad luck.
//On Darwin: This cannot fail, as far as I am able to tell.
const TimerError = error{TimerUnsupported, Unexpected};
pub fn start() TimerError!Timer {
var self: Timer = undefined;
switch (builtin.os) {
Os.windows => {
var freq: i64 = undefined;
var err = windows.QueryPerformanceFrequency(&freq);
if (err == 0) return error.TimerUnsupported;
self.frequency = u64(freq);
self.resolution = @divFloor(ns_per_s, self.frequency);
var start_time: i64 = undefined;
err = windows.QueryPerformanceCounter(&start_time);
debug.assert(err != 0);
self.start_time = u64(start_time);
},
Os.linux => {
//On Linux, seccomp can do arbitrary things to our ability to call
// syscalls, including return any errno value it wants and
// inconsistently throwing errors. Since we can't account for
// abuses of seccomp in a reasonable way, we'll assume that if
// seccomp is going to block us it will at least do so consistently
var ts: posix.timespec = undefined;
var result = posix.clock_getres(monotonic_clock_id, &ts);
var errno = posix.getErrno(result);
switch (errno) {
0 => {},
posix.EINVAL => return error.TimerUnsupported,
else => return std.os.unexpectedErrorPosix(errno),
}
self.resolution = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec);
result = posix.clock_gettime(monotonic_clock_id, &ts);
errno = posix.getErrno(result);
if (errno != 0) return std.os.unexpectedErrorPosix(errno);
self.start_time = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec);
},
Os.macosx, Os.ios => {
darwin.mach_timebase_info(&self.frequency);
self.resolution = @divFloor(self.frequency.numer, self.frequency.denom);
self.start_time = darwin.mach_absolute_time();
},
else => @compileError("Unsupported OS"),
}
return self;
}
/// Reads the timer value since start or the last reset in nanoseconds
pub fn read(self: &Timer) u64 {
var clock = clockNative() - self.start_time;
return switch (builtin.os) {
Os.windows => @divFloor(clock * ns_per_s, self.frequency),
Os.linux => clock,
Os.macosx, Os.ios => @divFloor(clock * self.frequency.numer, self.frequency.denom),
else => @compileError("Unsupported OS"),
};
}
/// Resets the timer value to 0/now.
pub fn reset(self: &Timer) void
{
self.start_time = clockNative();
}
/// Returns the current value of the timer in nanoseconds, then resets it
pub fn lap(self: &Timer) u64 {
var now = clockNative();
var lap_time = self.read();
self.start_time = now;
return lap_time;
}
const clockNative = switch (builtin.os) {
Os.windows => clockWindows,
Os.linux => clockLinux,
Os.macosx, Os.ios => clockDarwin,
else => @compileError("Unsupported OS"),
};
fn clockWindows() u64 {
var result: i64 = undefined;
var err = windows.QueryPerformanceCounter(&result);
debug.assert(err != 0);
return u64(result);
}
fn clockDarwin() u64 {
return darwin.mach_absolute_time();
}
fn clockLinux() u64 {
var ts: posix.timespec = undefined;
var result = posix.clock_gettime(monotonic_clock_id, &ts);
debug.assert(posix.getErrno(result) == 0);
return u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec);
}
};
test "os.time.sleep" {
sleep(0, 1);
}
test "os.time.timestamp" {
const ns_per_ms = (ns_per_s / ms_per_s);
const margin = 50;
const time_0 = milliTimestamp();
sleep(0, ns_per_ms);
const time_1 = milliTimestamp();
const interval = time_1 - time_0;
debug.assert(interval > 0 and interval < margin);
}
test "os.time.Timer" {
const ns_per_ms = (ns_per_s / ms_per_s);
const margin = ns_per_ms * 50;
var timer = try Timer.start();
sleep(0, 10 * ns_per_ms);
const time_0 = timer.read();
debug.assert(time_0 > 0 and time_0 < margin);
const time_1 = timer.lap();
debug.assert(time_1 > time_0);
timer.reset();
debug.assert(timer.read() < time_1);
}

View File

@ -1,3 +1,10 @@
const builtin = @import("builtin");
comptime {
if (!builtin.is_test) return;
_ = @import("util.zig");
}
pub const ERROR = @import("error.zig");
pub extern "advapi32" stdcallcc fn CryptAcquireContextA(phProv: &HCRYPTPROV, pszContainer: ?LPCSTR,
@ -61,6 +68,8 @@ pub extern "kernel32" stdcallcc fn GetFinalPathNameByHandleA(hFile: HANDLE, lpsz
pub extern "kernel32" stdcallcc fn GetProcessHeap() ?HANDLE;
pub extern "kernel32" stdcallcc fn GetSystemTimeAsFileTime(?&FILETIME) void;
pub extern "kernel32" stdcallcc fn HeapCreate(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T) ?HANDLE;
pub extern "kernel32" stdcallcc fn HeapDestroy(hHeap: HANDLE) BOOL;
pub extern "kernel32" stdcallcc fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: &c_void, dwBytes: SIZE_T) ?&c_void;
@ -77,6 +86,10 @@ pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem
pub extern "kernel32" stdcallcc fn MoveFileExA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR,
dwFlags: DWORD) BOOL;
pub extern "kernel32" stdcallcc fn QueryPerformanceCounter(lpPerformanceCount: &LARGE_INTEGER) BOOL;
pub extern "kernel32" stdcallcc fn QueryPerformanceFrequency(lpFrequency: &LARGE_INTEGER) BOOL;
pub extern "kernel32" stdcallcc fn PathFileExists(pszPath: ?LPCTSTR) BOOL;
@ -139,6 +152,7 @@ pub const UNICODE = false;
pub const WCHAR = u16;
pub const WORD = u16;
pub const LARGE_INTEGER = i64;
pub const FILETIME = i64;
pub const TRUE = 1;
pub const FALSE = 0;