Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
rate_limiter.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017 Roc authors
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7  */
8 
9 //! @file roc_core/rate_limiter.h
10 //! @brief Rate limiter.
11 
12 #ifndef ROC_CORE_RATE_LIMITER_H_
13 #define ROC_CORE_RATE_LIMITER_H_
14 
15 #include "roc_core/noncopyable.h"
16 #include "roc_core/ticker.h"
17 
18 namespace roc {
19 namespace core {
20 
21 //! Rate limiter.
22 class RateLimiter : public NonCopyable<> {
23 public:
24  //! Initialize rate limiter.
25  //! @remarks
26  //! @p period is tick duration in nanoseconds.
27  explicit RateLimiter(nanoseconds_t period)
28  : period_(Ticker::Ticks(period))
29  , pos_(0)
30  , ticker_(Second / Nanosecond) {
31  if (period <= 0) {
32  roc_panic("rate limiter: expected positive period, got %ld", (long)period);
33  }
34  }
35 
36  //! Check whether an event is allowed to occur now.
37  bool allow() {
38  const Ticker::Ticks elapsed = ticker_.elapsed();
39  if (elapsed >= pos_) {
40  pos_ = (elapsed / period_ + 1) * period_;
41  return true;
42  } else {
43  return false;
44  }
45  }
46 
47 private:
48  const Ticker::Ticks period_;
49  Ticker::Ticks pos_;
50  Ticker ticker_;
51 };
52 
53 } // namespace core
54 } // namespace roc
55 
56 #endif // ROC_CORE_RATE_LIMITER_H_
uint64_t Ticks
Number of ticks.
Definition: ticker.h:26
Rate limiter.
Definition: rate_limiter.h:22
Root namespace.
int64_t nanoseconds_t
Nanoseconds.
Definition: time.h:21
Ticker.
#define roc_panic(...)
Print error message and terminate program gracefully.
Definition: panic.h:42
Base class for non-copyable objects.
Definition: noncopyable.h:23
const nanoseconds_t Nanosecond
One nanosecond represented in nanoseconds.
Definition: time.h:24
Ticks elapsed()
Returns number of ticks elapsed since start. If ticker is not started yet, it is started automaticall...
Definition: ticker.h:48
bool allow()
Check whether an event is allowed to occur now.
Definition: rate_limiter.h:37
const nanoseconds_t Second
One second represented in nanoseconds.
Definition: time.h:33
Non-copyable object.
RateLimiter(nanoseconds_t period)
Initialize rate limiter.
Definition: rate_limiter.h:27
Ticker.
Definition: ticker.h:23