/src/casync/src/time-util.h
Line | Count | Source |
1 | | /* SPDX-License-Identifier: LGPL-2.1+ */ |
2 | | |
3 | | #ifndef footimeutilfoo |
4 | | #define footimeutilfoo |
5 | | |
6 | | #include <stdint.h> |
7 | | #include <time.h> |
8 | | |
9 | | #define NSEC_INFINITY ((uint64_t) -1) |
10 | | |
11 | | #define NSEC_PER_SEC ((uint64_t) UINT64_C(1000000000)) |
12 | | #define NSEC_PER_MSEC ((uint64_t) UINT64_C(1000000)) |
13 | | #define NSEC_PER_USEC ((uint64_t) UINT64_C(1000)) |
14 | | |
15 | | #define NSEC_PER_MINUTE ((uint64_t) (UINT64_C(60)*NSEC_PER_SEC)) |
16 | | #define NSEC_PER_HOUR ((uint64_t) (UINT64_C(60)*NSEC_PER_MINUTE)) |
17 | | #define NSEC_PER_DAY ((uint64_t) (UINT64_C(24)*NSEC_PER_HOUR)) |
18 | | #define NSEC_PER_WEEK ((uint64_t) (UINT64_C(7)*NSEC_PER_DAY)) |
19 | | #define NSEC_PER_MONTH ((uint64_t) (UINT64_C(2629800)*NSEC_PER_SEC)) |
20 | | #define NSEC_PER_YEAR ((uint64_t) (UINT64_C(31557600)*NSEC_PER_SEC)) |
21 | | |
22 | 0 | static inline uint64_t timespec_to_nsec(struct timespec t) { |
23 | |
|
24 | 0 | if (t.tv_sec == (time_t) -1 && |
25 | 0 | t.tv_nsec == (long) -1) |
26 | 0 | return UINT64_MAX; |
27 | | |
28 | 0 | return (uint64_t) t.tv_sec * UINT64_C(1000000000) + (uint64_t) t.tv_nsec; |
29 | 0 | } |
30 | | |
31 | 0 | static inline struct timespec nsec_to_timespec(uint64_t u) { |
32 | 0 |
|
33 | 0 | if (u == UINT64_MAX) |
34 | 0 | return (struct timespec) { |
35 | 0 | .tv_sec = (time_t) -1, |
36 | 0 | .tv_nsec = (long) -1, |
37 | 0 | }; |
38 | 0 |
|
39 | 0 | return (struct timespec) { |
40 | 0 | .tv_sec = u / UINT64_C(1000000000), |
41 | 0 | .tv_nsec = u % UINT64_C(1000000000) |
42 | 0 | }; |
43 | 0 | } |
44 | | |
45 | | #define NSEC_TO_TIMESPEC_INIT(u) \ |
46 | | { .tv_sec = u == UINT64_MAX ? (time_t) -1 : (time_t) (u / UINT64_C(1000000000)), \ |
47 | | .tv_nsec = u == UINT64_MAX ? (long) -1 : (long) (u % UINT64_C(1000000000)) } |
48 | | |
49 | 0 | static inline uint64_t now(clockid_t id) { |
50 | 0 | struct timespec ts; |
51 | 0 |
|
52 | 0 | if (clock_gettime(id, &ts) < 0) |
53 | 0 | return UINT64_MAX; |
54 | 0 |
|
55 | 0 | return timespec_to_nsec(ts); |
56 | 0 | } |
57 | | |
58 | | char *format_timespan(char *buf, size_t l, uint64_t t, uint64_t accuracy); |
59 | | |
60 | | #endif |