-
Notifications
You must be signed in to change notification settings - Fork 0
/
timespec.c
86 lines (69 loc) · 1.94 KB
/
timespec.c
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
82
83
84
85
86
// SPDX-License-Identifier: MIT
#include "timespec.h"
#include "macros.h"
#include <assert.h>
#include <time.h>
static const long nsec_per_sec = 1000000000;
struct timespec
reify_timespec(const struct timespec delta) {
struct timespec now;
TRY(clock_gettime, CLOCK_BOOTTIME, &now);
return normalize_timespec((struct timespec){
now.tv_sec + delta.tv_sec,
now.tv_nsec + delta.tv_nsec,
});
}
struct timespec
normalize_timespec(const struct timespec ts) {
struct timespec normal = ts;
if (normal.tv_nsec <= -nsec_per_sec || normal.tv_nsec >= nsec_per_sec) {
normal.tv_sec += normal.tv_nsec / nsec_per_sec;
normal.tv_nsec %= nsec_per_sec;
}
if (normal.tv_nsec < 0) {
normal.tv_sec -= 1;
normal.tv_nsec += nsec_per_sec;
}
return normal;
}
struct timespec
timespec_from_double(double d) {
return normalize_timespec((struct timespec){
.tv_sec = (time_t)d,
.tv_nsec = nsec_per_sec * (d - (time_t)d),
});
}
double
double_from_timespec(const struct timespec ts) {
assert(timespec_normalized(ts));
return ts.tv_sec + ts.tv_nsec / (double)nsec_per_sec;
}
int
timespec_when(const struct timespec ts) {
assert(timespec_normalized(ts));
return timespec_past(ts) ? -1
: timespec_present(ts) ? 0
: timespec_future(ts) ? 1
: (abort(),0);
}
bool
timespec_past(const struct timespec ts) {
assert(timespec_normalized(ts));
return ts.tv_sec < 0;
}
bool
timespec_present(const struct timespec ts) {
assert(timespec_normalized(ts));
return ts.tv_sec == 0 && ts.tv_nsec == 0;
}
bool
timespec_future(const struct timespec ts) {
assert(timespec_normalized(ts));
return ts.tv_sec > 0 || (ts.tv_sec == 0 && ts.tv_nsec > 0);
}
bool
timespec_normalized(struct timespec ts) {
struct timespec normal = normalize_timespec(ts);
return ts.tv_sec == normal.tv_sec && ts.tv_nsec == normal.tv_nsec && ts.tv_nsec >= 0;
}
//