simpletokenbucket.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  4. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. /* Original author: bcampen@mozilla.com */
  6. /*
  7. * This file defines a dirt-simple token bucket class.
  8. */
  9. #ifndef simpletokenbucket_h__
  10. #define simpletokenbucket_h__
  11. #include <stdint.h>
  12. #include "prinrval.h"
  13. #include "m_cpp_utils.h"
  14. namespace mozilla {
  15. class SimpleTokenBucket {
  16. public:
  17. /*
  18. * Create a SimpleTokenBucket with a given maximum size and
  19. * token replenishment rate.
  20. * (eg; if you want a maximum rate of 5 per second over a 7 second
  21. * period, call SimpleTokenBucket b(5*7, 5);)
  22. */
  23. SimpleTokenBucket(size_t bucket_size, size_t tokens_per_second);
  24. /*
  25. * Attempt to acquire a number of tokens. If successful, returns
  26. * |num_tokens|, otherwise returns the number of tokens currently
  27. * in the bucket.
  28. * Note: To get the number of tokens in the bucket, pass something
  29. * like UINT32_MAX.
  30. */
  31. size_t getTokens(size_t num_tokens);
  32. protected: // Allow testing to touch these.
  33. uint64_t max_tokens_;
  34. uint64_t num_tokens_;
  35. size_t tokens_per_second_;
  36. PRIntervalTime last_time_tokens_added_;
  37. DISALLOW_COPY_ASSIGN(SimpleTokenBucket);
  38. };
  39. } // namespace mozilla
  40. #endif // simpletokenbucket_h__