jacobson_karels: New module
[ccan] / ccan / jacobson_karels / jacobson_karels.h
1 /* Licensed under LGPLv2.1+ - see LICENSE file for details */
2 #ifndef CCAN_JACOBSON_KARELS_H
3 #define CCAN_JACOBSON_KARELS_H
4
5 #include "config.h"
6
7 #include <ccan/minmax/minmax.h>
8
9 #define JACOBSON_KARELS(_name, _type, _a1, _a2, _b1, _b2, _g, _k) \
10         struct _name##_state { \
11                 _type rtt, variance; \
12         }; \
13         static void _name##_init(struct _name##_state *s, \
14                                  _type rtt0, _type var0)  \
15         { \
16                 s->rtt = rtt0; \
17                 s->variance = var0; \
18         } \
19         static void _name##_update(struct _name##_state *s, _type sample) \
20         { \
21                 _type diff = sample - s->rtt; \
22                 s->rtt += (_a2) * diff / ((_a1) + (_a2)); \
23                 diff = (diff < 0) ? -diff : diff; \
24                 s->variance = ((_b1)*s->variance + (_b2) * diff) \
25                         / ((_b1) + (_b2));                       \
26         } \
27         static _type _name##_timeout(struct _name##_state *s, \
28                                      _type tmin, _type tmax)  \
29         { \
30                 return clamp((_g) * s->rtt + (_k)*s->variance, tmin, tmax); \
31         }
32
33 JACOBSON_KARELS(jacobson_karels, unsigned long, 7, 1, 3, 1, 1, 4)
34
35 #endif /* CCAN_JACOBSON_KARELS_H */