From 01d523fb483e2f2cb5d86a18c6fb03a8d1c4961c Mon Sep 17 00:00:00 2001 From: Miroslav Lichvar Date: Thu, 10 Sep 2015 11:49:26 +0200 Subject: [PATCH] util: add function for simple rate limiting. Signed-off-by: Miroslav Lichvar --- util.c | 14 ++++++++++++++ util.h | 9 +++++++++ 2 files changed, 23 insertions(+) diff --git a/util.c b/util.c index 6bbbe91..e10cedc 100644 --- a/util.c +++ b/util.c @@ -512,3 +512,17 @@ void parray_extend(void ***a, ...) va_end(ap); (*a)[len - 1] = NULL; } + +int rate_limited(int interval, time_t *last) +{ + struct timespec ts; + + if (clock_gettime(CLOCK_MONOTONIC, &ts)) + return 1; + if (*last + interval > ts.tv_sec) + return 1; + + *last = ts.tv_sec; + + return 0; +} diff --git a/util.h b/util.h index cc521b6..e912f19 100644 --- a/util.h +++ b/util.h @@ -354,4 +354,13 @@ void parray_append(void ***a, void *p); */ void parray_extend(void ***a, ...); +/** + * Check if enough time has passed to implement a simple rate limiting. + * + * @param interval Minimum interval between two calls returning 0 (in seconds). + * @param last Time of the last call that returned 0, input/output. + * @return 1 when rate limited, 0 otherwise. + */ +int rate_limited(int interval, time_t *last); + #endif