dte test coverage


Directory: ./
File: src/util/time-util.h
Date: 2024-12-21 16:03:22
Exec Total Coverage
Lines: 23 23 100.0%
Functions: 4 4 100.0%
Branches: 12 14 85.7%

Line Branch Exec Source
1 #ifndef UTIL_TIME_UTIL_H
2 #define UTIL_TIME_UTIL_H
3
4 #include <stdbool.h>
5 #include <stddef.h>
6 #include <sys/stat.h>
7 #include <time.h>
8 #include "debug.h"
9 #include "macros.h"
10
11 #define TIME_STR_BUFSIZE (64) // sizeof("292271025015-12-01 23:59:00.999999999 +0400")
12 #define NS_PER_SECOND (1000000000L)
13 #define MS_PER_SECOND (1000L)
14 #define NS_PER_MS (1000000L)
15 #define US_PER_MS (1000L)
16
17 42 static inline const struct timespec *get_stat_mtime(const struct stat *st)
18 {
19 #if defined(__APPLE__)
20 return &st->st_mtimespec;
21 #else
22 // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html#tag_13_61_03
23 42 return &st->st_mtim;
24 #endif
25 }
26
27 197 static inline struct timespec timespec_subtract (
28 const struct timespec *lhs,
29 const struct timespec *rhs
30 ) {
31 197 BUG_ON(lhs->tv_nsec >= NS_PER_SECOND);
32 197 BUG_ON(rhs->tv_nsec >= NS_PER_SECOND);
33 197 time_t sec = lhs->tv_sec - rhs->tv_sec;
34 197 long nsec = lhs->tv_nsec - rhs->tv_nsec;
35 394 return (struct timespec) {
36 197 .tv_sec = sec - (nsec < 0),
37
2/2
✓ Branch 0 taken 196 times.
✓ Branch 1 taken 1 times.
197 .tv_nsec = nsec + (nsec < 0 ? NS_PER_SECOND : 0),
38 };
39 }
40
41 7 static inline int timespec_cmp(const struct timespec *a, const struct timespec *b)
42 {
43 7 time_t sa = a->tv_sec;
44 7 time_t sb = b->tv_sec;
45 7 long na = a->tv_nsec;
46 7 long nb = b->tv_nsec;
47 7 BUG_ON(na >= NS_PER_SECOND);
48 7 BUG_ON(nb >= NS_PER_SECOND);
49
50 // Example #1: (sa == sb) && (na == nb): 0 + 0 = 0
51 // Example #2: (sa < sb) && (na > nb): -2 + 1 = -1
52 7 int r = 0;
53
4/4
✓ Branch 0 taken 6 times.
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 3 times.
✓ Branch 3 taken 3 times.
7 r += (sa == sb) ? 0 : (sa < sb ? -2 : 2);
54
4/4
✓ Branch 0 taken 4 times.
✓ Branch 1 taken 3 times.
✓ Branch 2 taken 2 times.
✓ Branch 3 taken 2 times.
7 r += (na == nb) ? 0 : (na < nb ? -1 : 1);
55 7 return r;
56 }
57
58 1 static inline bool timespecs_equal(const struct timespec *a, const struct timespec *b)
59 {
60
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1 times.
1 return a->tv_sec == b->tv_sec && a->tv_nsec == b->tv_nsec;
61 }
62
63 char *timespec_to_str(const struct timespec *ts, char *buf, size_t bufsize) NONNULL_ARGS WARN_UNUSED_RESULT;
64
65 #endif
66