From f553dbf7db9f78667eeb6e84fe17e0977e501e92 Mon Sep 17 00:00:00 2001 From: Aaron Cook Date: Sat, 13 May 2023 14:09:16 -0500 Subject: [PATCH] #11 Add helpers for doing math with timespec structs --- src/timer_math.c | 71 ++++++++++++++++++++++++++++++++++++++++++++++++ src/timer_math.h | 27 ++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 src/timer_math.c create mode 100644 src/timer_math.h diff --git a/src/timer_math.c b/src/timer_math.c new file mode 100644 index 0000000..bce2efd --- /dev/null +++ b/src/timer_math.c @@ -0,0 +1,71 @@ +#include "timer_math.h" + +int +timer_cmp(const struct timespec *a, const struct timespec *b) +{ + if (a->tv_sec < b->tv_sec) { + return -1; + } + else if (a->tv_sec > b->tv_sec) { + return 1; + } + else if (a->tv_nsec < b->tv_nsec) { + return -1; + } + else if (a->tv_nsec > b->tv_nsec) { + return 1; + } + else { + return 0; + } +} + +void +timer_add(struct timespec *a, const struct timespec *b) +{ + a->tv_sec += b->tv_sec; + a->tv_nsec += b->tv_nsec; + + if (a->tv_nsec > 1000000000) { + a->tv_sec += 1; + a->tv_nsec -= 1000000000; + } +} + +void +timer_add_ms(struct timespec *ts, uint32_t ms) +{ + struct timespec tmp = { + .tv_sec = ms / 1000, + .tv_nsec = (ms % 1000) * 1000000 + }; + timer_add(ts, &tmp); +} + +void +timer_sub(struct timespec *a, const struct timespec *b) +{ + if (timer_cmp(a, b) <= 0) { + a->tv_sec = 0; + a->tv_nsec = 0; + return; + } + + a->tv_sec -= b->tv_sec; + a->tv_nsec -= b->tv_nsec; + + if (a->tv_nsec < 0) { + a->tv_nsec += 1000000000; + a->tv_sec -= 1; + } +} + +void +timer_sub_ms(struct timespec *ts, uint32_t ms) +{ + struct timespec tmp = { + .tv_sec = ms / 1000, + .tv_nsec = (ms % 1000) * 1000000 + }; + timer_sub(ts, &tmp); +} diff --git a/src/timer_math.h b/src/timer_math.h new file mode 100644 index 0000000..99cdcd9 --- /dev/null +++ b/src/timer_math.h @@ -0,0 +1,27 @@ +#ifndef _TIMER_MATH_H_ +#define _TIMER_MATH_H_ + +#include +#include + +/* NOTE + * All math here is assuming that the second and nanosecond values of the + * timespecs are all non-negative, and nanoseconds is in the range [0, 999999999] */ + +/* Compare the two timespecs + * Return -1 if a < b, 0 if a = b, and 1 if a > b */ +int timer_cmp(const struct timespec *a, const struct timespec *b); + +/* Add the timespec value of b to a */ +void timer_add(struct timespec *a, const struct timespec *b); + +/* Add ms milliseconds to the timespec*/ +void timer_add_ms(struct timespec *ts, uint32_t ms); + +/* Subtract time b from a. If b > a, then a is set to 0 */ +void timer_sub(struct timespec *a, const struct timespec *b); + +/* Subtract ms milliseconds from ts. If ts would become negative, it is set to 0 */ +void timer_sub_ms(struct timespec *ts, uint32_t ms); + +#endif /* _TIMER_MATH_H_ */