data_rate_limiter.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright 2012 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef RTC_BASE_DATA_RATE_LIMITER_H_
  11. #define RTC_BASE_DATA_RATE_LIMITER_H_
  12. #include <stddef.h>
  13. #include "rtc_base/system/rtc_export.h"
  14. namespace rtc {
  15. // Limits the rate of use to a certain maximum quantity per period of
  16. // time. Use, for example, for simple bandwidth throttling.
  17. //
  18. // It's implemented like a diet plan: You have so many calories per
  19. // day. If you hit the limit, you can't eat any more until the next
  20. // day.
  21. class RTC_EXPORT DataRateLimiter {
  22. public:
  23. // For example, 100kb per second.
  24. DataRateLimiter(size_t max, double period)
  25. : max_per_period_(max),
  26. period_length_(period),
  27. used_in_period_(0),
  28. period_start_(0.0),
  29. period_end_(period) {}
  30. virtual ~DataRateLimiter() {}
  31. // Returns true if if the desired quantity is available in the
  32. // current period (< (max - used)). Once the given time passes the
  33. // end of the period, used is set to zero and more use is available.
  34. bool CanUse(size_t desired, double time);
  35. // Increment the quantity used this period. If past the end of a
  36. // period, a new period is started.
  37. void Use(size_t used, double time);
  38. size_t used_in_period() const { return used_in_period_; }
  39. size_t max_per_period() const { return max_per_period_; }
  40. private:
  41. size_t max_per_period_;
  42. double period_length_;
  43. size_t used_in_period_;
  44. double period_start_;
  45. double period_end_;
  46. };
  47. } // namespace rtc
  48. #endif // RTC_BASE_DATA_RATE_LIMITER_H_