Browse Source

Merge pull request #120 from Majora320/master

Implement clock() and add CLOCK_* constants
Jeremy Soller 6 years ago
parent
commit
8eec109cc0
3 changed files with 23 additions and 2 deletions
  1. 7 0
      src/time/src/constants.rs
  2. 14 2
      src/time/src/lib.rs
  3. 2 0
      tests/time.c

+ 7 - 0
src/time/src/constants.rs

@@ -42,3 +42,10 @@ 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;
+
+pub(crate) const CLOCKS_PER_SEC: time_t = 1_000_000;

+ 14 - 2
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,20 @@ 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 { core::mem::uninitialized() };
+
+    if clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &mut ts) != 0 {
+        return -1;
+    }
+
+    if ts.tv_sec > time_t::max_value() / CLOCKS_PER_SEC
+        || ts.tv_nsec / (1_000_000_000 / CLOCKS_PER_SEC)
+            > time_t::max_value() - CLOCKS_PER_SEC * ts.tv_sec
+    {
+        return -1;
+    }
+
+    return ts.tv_sec * CLOCKS_PER_SEC + ts.tv_nsec / (1_000_000_000 / CLOCKS_PER_SEC);
 }
 
 #[no_mangle]

+ 2 - 0
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;
 }