From 04e243c85cab89fe16a07667122d5288e8ae9b59 Mon Sep 17 00:00:00 2001 From: Gleb Smirnoff Date: Wed, 27 Dec 2017 14:24:27 -0800 Subject: [PATCH] Add handy functions for timeval manipulations. Obtained from FreeBSD. --- utils.c | 40 ++++++++++++++++++++++++++++++++++++++++ utils.h | 8 ++++++++ 2 files changed, 48 insertions(+) diff --git a/utils.c b/utils.c index fc21b7f..294c1cd 100644 --- a/utils.c +++ b/utils.c @@ -531,3 +531,43 @@ valid_media_types(const char *path) return ALL_MEDIA; } + +/* + * Add and subtract routines for timevals. + * N.B.: subtract routine doesn't deal with + * results which are before the beginning, + * it just gets very confused in this case. + * Caveat emptor. + */ +static void timevalfix(struct timeval *); +void +timevaladd(struct timeval *t1, const struct timeval *t2) +{ + + t1->tv_sec += t2->tv_sec; + t1->tv_usec += t2->tv_usec; + timevalfix(t1); +} + +void +timevalsub(struct timeval *t1, const struct timeval *t2) +{ + + t1->tv_sec -= t2->tv_sec; + t1->tv_usec -= t2->tv_usec; + timevalfix(t1); +} + +static void +timevalfix(struct timeval *t1) +{ + + if (t1->tv_usec < 0) { + t1->tv_sec--; + t1->tv_usec += 1000000; + } + if (t1->tv_usec >= 1000000) { + t1->tv_sec++; + t1->tv_usec -= 1000000; + } +} diff --git a/utils.h b/utils.h index a200756..1cd7546 100644 --- a/utils.h +++ b/utils.h @@ -101,4 +101,12 @@ const char *mime_to_ext(const char * mime); int make_dir(char * path, mode_t mode); unsigned int DJBHash(uint8_t *data, int len); +/* Timeval manipulations */ +void timevaladd(struct timeval *t1, const struct timeval *t2); +void timevalsub(struct timeval *t1, const struct timeval *t2); +#define timevalcmp(tvp, uvp, cmp) \ + (((tvp)->tv_sec == (uvp)->tv_sec) ? \ + ((tvp)->tv_usec cmp (uvp)->tv_usec) : \ + ((tvp)->tv_sec cmp (uvp)->tv_sec)) + #endif