Line data Source code
1 : #ifndef HEADER_fd_src_waltz_fd_token_bucket_h 2 : #define HEADER_fd_src_waltz_fd_token_bucket_h 3 : 4 : #include "../util/fd_util_base.h" 5 : #include <math.h> 6 : 7 : struct fd_token_bucket { 8 : long ts; 9 : float rate; 10 : float burst; 11 : float balance; 12 : }; 13 : 14 : typedef struct fd_token_bucket fd_token_bucket_t; 15 : 16 : FD_PROTOTYPES_BEGIN 17 : 18 : static inline int 19 : fd_token_bucket_consume( fd_token_bucket_t * bucket, 20 : float delta, 21 0 : long ts ) { 22 : /* Refill bucket */ 23 0 : long elapsed = ts - bucket->ts; 24 0 : float balance = bucket->balance + ((float)elapsed * bucket->rate); 25 0 : balance = fminf( balance, bucket->burst ); 26 : 27 : /* Consume tokens */ 28 0 : int ok = delta <= balance; 29 0 : balance -= (float)ok * delta; 30 : 31 : /* Store bucket */ 32 0 : bucket->balance = balance; 33 0 : bucket->ts = ts; 34 0 : return ok; 35 0 : } 36 : 37 : FD_PROTOTYPES_END 38 : 39 : #endif /* HEADER_fd_src_waltz_fd_token_bucket_h */