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 Streaming 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_t(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 allow() would succeed.
37 bool would_allow() {
38 return ticker_.elapsed() >= pos_;
39 }
40
41 //! Check whether an event is allowed to occur now, and if yes, mark it as occurred.
42 bool allow() {
43 const Ticker::ticks_t elapsed = ticker_.elapsed();
44 if (elapsed >= pos_) {
45 pos_ = (elapsed / period_ + 1) * period_;
46 return true;
47 } else {
48 return false;
49 }
50 }
51
52private:
53 const Ticker::ticks_t period_;
54 Ticker::ticks_t pos_;
55 Ticker ticker_;
56};
57
58} // namespace core
59} // namespace roc
60
61#endif // ROC_CORE_RATE_LIMITER_H_
Base class for non-copyable objects.
Definition noncopyable.h:23
RateLimiter(nanoseconds_t period)
Initialize rate limiter.
bool allow()
Check whether an event is allowed to occur now, and if yes, mark it as occurred.
bool would_allow()
Check whether allow() would succeed.
ticks_t 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_t
Number of ticks.
Definition ticker.h:26
const nanoseconds_t Nanosecond
One nanosecond represented in nanoseconds.
Definition time.h:61
const nanoseconds_t Second
One second represented in nanoseconds.
Definition time.h:70
int64_t nanoseconds_t
Nanoseconds.
Definition time.h:58
Root namespace.
Non-copyable object.
#define roc_panic(...)
Print error message and terminate program gracefully.
Definition panic.h:50
Ticker.