Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
Loading...
Searching...
No Matches
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
16#include "roc_core/ticker.h"
17
18namespace roc {
19namespace core {
20
21//! Rate limiter.
22class RateLimiter : public NonCopyable<> {
23public:
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
47private:
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_
Base class for non-copyable objects.
Definition: noncopyable.h:23
RateLimiter(nanoseconds_t period)
Initialize rate limiter.
Definition: rate_limiter.h:27
bool allow()
Check whether an event is allowed to occur now.
Definition: rate_limiter.h:37
Ticker.
Definition: ticker.h:23
Ticks elapsed()
Returns number of ticks elapsed since start. If ticker is not started yet, it is started automaticall...
Definition: ticker.h:48
uint64_t Ticks
Number of ticks.
Definition: ticker.h:26
const nanoseconds_t Nanosecond
One nanosecond represented in nanoseconds.
Definition: time.h:24
const nanoseconds_t Second
One second represented in nanoseconds.
Definition: time.h:33
int64_t nanoseconds_t
Nanoseconds.
Definition: time.h:21
Root namespace.
Non-copyable object.
#define roc_panic(...)
Print error message and terminate program gracefully.
Definition: panic.h:42
Ticker.