C23: add timespec_getres() and the new TIME_* constants.
Nothing to see here --- you'll want to keep using POSIX clock_gettime()
and clock_getres() instead. But portable code might use this eventually,
and it's trivial, so let's add it anyway.
(The whole "zero as an error return" precluding the direct use of
Linux's CLOCK_ constants is what really makes this a terrible API ---
we're going to have to add explicit translation any time they add a
new base.)
Test: treehugger
Change-Id: Iddb6cbe67b67b2b10fdd8b5ee654896d23deee47
diff --git a/libc/bionic/timespec_get.cpp b/libc/bionic/time.cpp
similarity index 70%
rename from libc/bionic/timespec_get.cpp
rename to libc/bionic/time.cpp
index 7fc2182..3a41027 100644
--- a/libc/bionic/timespec_get.cpp
+++ b/libc/bionic/time.cpp
@@ -28,6 +28,27 @@
#include <time.h>
+static clockid_t __base_to_clock(int base) {
+ switch (base) {
+ case TIME_UTC:
+ return CLOCK_REALTIME;
+ case TIME_MONOTONIC:
+ return CLOCK_MONOTONIC;
+ case TIME_ACTIVE:
+ return CLOCK_PROCESS_CPUTIME_ID;
+ case TIME_THREAD_ACTIVE:
+ return CLOCK_THREAD_CPUTIME_ID;
+ default:
+ return -1;
+ }
+}
+
int timespec_get(timespec* ts, int base) {
- return (base == TIME_UTC && clock_gettime(CLOCK_REALTIME, ts) != -1) ? base : 0;
+ clockid_t clock = __base_to_clock(base);
+ return (clock != -1 && clock_gettime(clock, ts) != -1) ? base : 0;
+}
+
+int timespec_getres(timespec* ts, int base) {
+ clockid_t clock = __base_to_clock(base);
+ return (clock != -1 && clock_getres(clock, ts) != -1) ? base : 0;
}