Debian Codegraph @

regressions/ck_ec/validate/prop_test_timeutil_add_ns.c

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