From 1ecd5f8f21bbf35cb3f840944823d9d8f6de1eb6 Mon Sep 17 00:00:00 2001 From: Moses Miller <Majora320@gmail.com> Date: Thu, 10 May 2018 20:31:35 -0700 Subject: [PATCH] Implement clock() and add CLOCK_* constants --- src/time/src/constants.rs | 5 +++++ src/time/src/lib.rs | 19 +++++++++++++++++-- tests/time.c | 2 ++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/time/src/constants.rs b/src/time/src/constants.rs index a7c1aa0d..1836c7ce 100644 --- a/src/time/src/constants.rs +++ b/src/time/src/constants.rs @@ -42,3 +42,8 @@ pub(crate) const DAY_NAMES: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri pub(crate) const MON_NAMES: [&str; 12] = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; + +pub(crate) const CLOCK_REALTIME: clockid_t = 0; +pub(crate) const CLOCK_MONOTONIC: clockid_t = 1; +pub(crate) const CLOCK_PROCESS_CPUTIME_ID: clockid_t = 2; +pub(crate) const CLOCK_THREAD_CPUTIME_ID: clockid_t = 3; diff --git a/src/time/src/lib.rs b/src/time/src/lib.rs index cd338df1..2ae68ffd 100644 --- a/src/time/src/lib.rs +++ b/src/time/src/lib.rs @@ -12,7 +12,6 @@ mod helpers; use platform::types::*; use constants::*; use helpers::*; -use core::fmt::write; use core::mem::transmute; use errno::EIO; @@ -99,7 +98,23 @@ pub extern "C" fn asctime_r(tm: *const tm, buf: *mut c_char) -> *mut c_char { #[no_mangle] pub extern "C" fn clock() -> clock_t { - unimplemented!(); + let mut ts: timespec; + + unsafe { + ts = core::mem::uninitialized(); + } + + if clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut ts) != 0 { + return -1; + } + + if ts.tv_sec > time_t::max_value() / 1000000 + || ts.tv_nsec / 1000 > time_t::max_value() - 1000000 * ts.tv_sec + { + return -1; + } + + return ts.tv_sec * 1_000_000 + ts.tv_nsec / 1000; } #[no_mangle] diff --git a/tests/time.c b/tests/time.c index e6ce164c..5c60f4a4 100644 --- a/tests/time.c +++ b/tests/time.c @@ -7,5 +7,7 @@ int main(int argc, char** argv) { perror("clock_gettime"); time(NULL); perror("time"); + clock_t c = clock(); + perror("clock"); return 0; } -- GitLab