librfn
An ad-hoc utility library
util.h
Go to the documentation of this file.
1 /*
2  * util.h
3  *
4  * Part of librfn (a general utility library from redfelineninja.org.uk)
5  *
6  * Copyright (C) 2012-2014 Daniel Thompson <daniel@redfelineninja.org.uk>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as published
10  * by the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  */
13 
14 #ifndef RF_UTIL_H_
15 #define RF_UTIL_H_
16 
17 #include <assert.h>
18 #include <stdbool.h>
19 #include <stddef.h>
20 #include <stdlib.h>
21 #include <stdint.h>
22 
35 #define containerof(ptr, type, member) \
36  ((type *) (((char *) ptr) - offsetof(type, member)))
37 
44 #define lengthof(x) ((sizeof(x) / sizeof(*(x))))
45 
46 #ifdef VERBOSE
47 #define verify(s) \
48  do { \
49  printf("Checking %s ... ", #s); \
50  assert(s); \
51  printf("OK\n"); \
52  } while (0)
53 
54 #else
55 #define verify(x) assert(x)
56 #endif
57 
69 int32_t cyclecmp32(uint32_t a, uint32_t b);
70 
76 typedef struct {
77  uint32_t time;
78  uint32_t count;
80 
89 bool ratelimit_check(ratelimit_state_t *rs, uint32_t n, uint32_t window);
90 
96 #define RATELIMIT_TO(n, window, fn) \
97  { \
98  static ratelimit_state_t rs_; \
99  if (ratelimit_check(&rs_, n, window)) \
100  (fn); \
101  }
102 
106 #define RATELIMIT(fn) RATELIMIT_TO(3, 10, fn)
107 
108 void rf_internal_out_of_memory(void);
109 void *xmalloc(size_t sz);
110 
112 #endif // RF_UTIL_H_
struct alpha a
uint32_t time
Definition: util.h:77
void * xmalloc(size_t sz)
Definition: util.c:45
struct bravo b
bool ratelimit_check(ratelimit_state_t *rs, uint32_t n, uint32_t window)
Check that the rate limiter has not triggered.
Definition: util.c:24
int32_t cyclecmp32(uint32_t a, uint32_t b)
Compares values that may be subject to overflow.
Definition: util.c:19
Control structure used for rate limiting.
Definition: util.h:76
void rf_internal_out_of_memory(void)
Definition: util.c:40
uint32_t count
Definition: util.h:78