librfn
An ad-hoc utility library
utiltest.c
Go to the documentation of this file.
1 /*
2  * utiltest.c
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 #undef NDEBUG
15 
16 #include <assert.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 
20 #include <librfn.h>
21 
22 struct alpha {
23  int a;
24 } a;
25 
26 struct bravo {
27  struct alpha a;
28  int b;
29 } b;
30 
31 struct charlie {
32  struct alpha a;
33  struct bravo b;
34  int c;
35 } c;
36 
37 int main()
38 {
39  struct alpha *ap = &b.a;
40  verify(&b == containerof(ap, struct bravo, a));
41 
42  struct bravo *bp = &c.b;
43  verify(&c == containerof(bp, struct charlie, b));
44 
45  /* test ratelimit_check() (including resumption after limiting */
46  static ratelimit_state_t rs;
47  verify(ratelimit_check(&rs, 3, 10));
48  verify(ratelimit_check(&rs, 3, 10));
49  verify(ratelimit_check(&rs, 3, 10));
50  verify(!ratelimit_check(&rs, 3, 10));
51  verify(!ratelimit_check(&rs, 3, 10));
52  rs.time -= 11*10000000; /* move time 11s forwards... */
53  verify(ratelimit_check(&rs, 3, 10));
54  verify(ratelimit_check(&rs, 3, 10));
55  verify(ratelimit_check(&rs, 3, 10));
56  verify(!ratelimit_check(&rs, 3, 10));
57 
58  /* check RATELIMIT() (no wait for resumption since that's too time consuming */
59  int counter = 0;
60  for (int i=0; i<10; i++) {
61  RATELIMIT(counter++);
62  if (i < 3)
63  verify(counter == i+1);
64  }
65  verify(counter == 3);
66 
67  return 0;
68 }
#define containerof(ptr, type, member)
Definition: util.h:35
struct charlie c
struct alpha a
uint32_t time
Definition: util.h:77
struct alpha a
Definition: utiltest.c:27
int c
Definition: utiltest.c:34
struct alpha a
Definition: utiltest.c:32
int main()
Definition: utiltest.c:37
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
#define verify(x)
Definition: util.h:55
Control structure used for rate limiting.
Definition: util.h:76
#define RATELIMIT(fn)
Ratelimit a single expression using default ratelimiter values.
Definition: util.h:106
Definition: utiltest.c:26
int b
Definition: utiltest.c:28
Definition: utiltest.c:22
struct bravo b
Definition: utiltest.c:33
int a
Definition: utiltest.c:23