token_bucket.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* Copyright (c) 2018, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file token_bucket.h
  5. * \brief Headers for token_bucket.c
  6. **/
  7. #ifndef TOR_TOKEN_BUCKET_H
  8. #define TOR_TOKEN_BUCKET_H
  9. #include "torint.h"
  10. typedef struct token_bucket_t {
  11. uint32_t rate;
  12. int32_t burst;
  13. int32_t read_bucket;
  14. int32_t write_bucket;
  15. uint32_t last_refilled_at_ts;
  16. } token_bucket_t;
  17. #define TOKEN_BUCKET_MAX_BURST INT32_MAX
  18. void token_bucket_init(token_bucket_t *bucket,
  19. uint32_t rate,
  20. uint32_t burst,
  21. uint32_t now_ts);
  22. void token_bucket_adjust(token_bucket_t *bucket,
  23. uint32_t rate, uint32_t burst);
  24. void token_bucket_reset(token_bucket_t *bucket,
  25. uint32_t now_ts);
  26. #define TB_READ 1
  27. #define TB_WRITE 2
  28. int token_bucket_refill(token_bucket_t *bucket,
  29. uint32_t now_ts);
  30. int token_bucket_dec_read(token_bucket_t *bucket,
  31. ssize_t n);
  32. int token_bucket_dec_write(token_bucket_t *bucket,
  33. ssize_t n);
  34. static inline size_t token_bucket_get_read(const token_bucket_t *bucket);
  35. static inline size_t
  36. token_bucket_get_read(const token_bucket_t *bucket)
  37. {
  38. const ssize_t b = bucket->read_bucket;
  39. return b >= 0 ? b : 0;
  40. }
  41. static inline size_t token_bucket_get_write(const token_bucket_t *bucket);
  42. static inline size_t
  43. token_bucket_get_write(const token_bucket_t *bucket)
  44. {
  45. const ssize_t b = bucket->write_bucket;
  46. return b >= 0 ? b : 0;
  47. }
  48. #ifdef TOKEN_BUCKET_PRIVATE
  49. /* To avoid making the rates too small, we consider units of "steps",
  50. * where a "step" is defined as this many timestamp ticks. Keep this
  51. * a power of two if you can. */
  52. #define TICKS_PER_STEP 16
  53. #endif
  54. #endif /* TOR_TOKEN_BUCKET_H */