-
Notifications
You must be signed in to change notification settings - Fork 21
/
TokenBucket.h
46 lines (38 loc) · 1.25 KB
/
TokenBucket.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// © 2023 Erik Rigtorp <[email protected]>
// SPDX-License-Identifier: MIT
#pragma once
#include <atomic>
#include <chrono>
template <typename Clock = std::chrono::steady_clock> class TokenBucket {
public:
TokenBucket() = default;
TokenBucket(const uint64_t rate, const uint64_t burstSize)
: timePerToken_(std::chrono::nanoseconds(std::chrono::seconds(1)) / rate),
timePerBurst_(burstSize * timePerToken_) {}
bool consume(const uint64_t tokens) {
const auto now = Clock::now();
const auto timeNeeded = tokens * timePerToken_;
const auto minTime = now - timePerBurst_;
auto oldTime = time_.load(std::memory_order_relaxed);
for (;;) {
auto newTime = oldTime;
if (minTime > newTime) {
newTime = minTime;
}
newTime += timeNeeded;
if (newTime > now) {
return false;
}
if (time_.compare_exchange_weak(oldTime, newTime,
std::memory_order_relaxed,
std::memory_order_relaxed)) {
return true;
}
}
return false;
}
private:
std::atomic<typename Clock::time_point> time_ = {Clock::time_point::min()};
std::chrono::nanoseconds timePerToken_;
std::chrono::nanoseconds timePerBurst_;
};