| 1 |
#include <assert.h> |
| 2 |
#include <ck_limits.h> |
| 3 |
#include <ck_stdint.h> |
| 4 |
|
| 5 |
#include "../../../src/ck_ec_timeutil.h" |
| 6 |
#include "fuzz_harness.h" |
| 7 |
|
| 8 |
#if ULONG_MAX > 4294967295 |
| 9 |
typedef unsigned __int128 dword_t; |
| 10 |
#else |
| 11 |
typedef uint64_t dword_t; |
| 12 |
#endif |
| 13 |
|
| 14 |
struct example { |
| 15 |
struct timespec ts; |
| 16 |
struct timespec inc; |
| 17 |
}; |
| 18 |
|
| 19 |
static const struct example examples[] = { |
| 20 |
{ |
| 21 |
{ |
| 22 |
42, |
| 23 |
100 |
| 24 |
}, |
| 25 |
{ |
| 26 |
1, |
| 27 |
2 |
| 28 |
} |
| 29 |
}, |
| 30 |
{ |
| 31 |
{ |
| 32 |
42, |
| 33 |
100 |
| 34 |
}, |
| 35 |
{ |
| 36 |
1, |
| 37 |
NSEC_MAX |
| 38 |
} |
| 39 |
}, |
| 40 |
{ |
| 41 |
{ |
| 42 |
42, |
| 43 |
NSEC_MAX |
| 44 |
}, |
| 45 |
{ |
| 46 |
0, |
| 47 |
NSEC_MAX |
| 48 |
} |
| 49 |
}, |
| 50 |
{ |
| 51 |
{ |
| 52 |
TIME_MAX - 1, |
| 53 |
1000 |
| 54 |
}, |
| 55 |
{ |
| 56 |
2, |
| 57 |
NSEC_MAX |
| 58 |
} |
| 59 |
} |
| 60 |
}; |
| 61 |
|
| 62 |
static struct timespec normalize_ts(const struct timespec ts) |
| 63 |
{ |
| 64 |
struct timespec ret = ts; |
| 65 |
|
| 66 |
if (ret.tv_sec < 0) { |
| 67 |
ret.tv_sec = ~ret.tv_sec; |
| 68 |
} |
| 69 |
|
| 70 |
if (ret.tv_nsec < 0) { |
| 71 |
ret.tv_nsec = ~ret.tv_nsec; |
| 72 |
} |
| 73 |
|
| 74 |
ret.tv_nsec %= NSEC_MAX + 1; |
| 75 |
return ret; |
| 76 |
} |
| 77 |
|
| 78 |
static dword_t ts_to_nanos(const struct timespec ts) |
| 79 |
{ |
| 80 |
return (dword_t)ts.tv_sec * (NSEC_MAX + 1) + ts.tv_nsec; |
| 81 |
} |
| 82 |
|
| 83 |
static inline int test_timespec_add(const struct example *example) |
| 84 |
{ |
| 85 |
const struct timespec ts = normalize_ts(example->ts); |
| 86 |
const struct timespec inc = normalize_ts(example->inc); |
| 87 |
const struct timespec actual = timespec_add(ts, inc); |
| 88 |
const dword_t nanos = ts_to_nanos(ts) + ts_to_nanos(inc); |
| 89 |
|
| 90 |
if (nanos / (NSEC_MAX + 1) > TIME_MAX) { |
| 91 |
assert(actual.tv_sec == TIME_MAX); |
| 92 |
assert(actual.tv_nsec == NSEC_MAX); |
| 93 |
} else { |
| 94 |
assert(actual.tv_sec == (time_t)(nanos / (NSEC_MAX + 1))); |
| 95 |
assert(actual.tv_nsec == (long)(nanos % (NSEC_MAX + 1))); |
| 96 |
} |
| 97 |
|
| 98 |
return 0; |
| 99 |
} |
| 100 |
|
| 101 |
TEST(test_timespec_add, examples) |