blob: fa0bcfb6e5948f54b47405b283aadbaff2ff6290 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright (c) 2016 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/third_party/quiche/src/quic/test_tools/simulator/traffic_policer.h"
6
7#include <algorithm>
8
9namespace quic {
10namespace simulator {
11
12TrafficPolicer::TrafficPolicer(Simulator* simulator,
vasilvvc48c8712019-03-11 13:38:16 -070013 std::string name,
QUICHE teama6ef0a62019-03-07 20:34:33 -050014 QuicByteCount initial_bucket_size,
15 QuicByteCount max_bucket_size,
16 QuicBandwidth target_bandwidth,
17 Endpoint* input)
18 : PacketFilter(simulator, name, input),
19 initial_bucket_size_(initial_bucket_size),
20 max_bucket_size_(max_bucket_size),
21 target_bandwidth_(target_bandwidth),
22 last_refill_time_(clock_->Now()) {}
23
24TrafficPolicer::~TrafficPolicer() {}
25
26void TrafficPolicer::Refill() {
27 QuicTime::Delta time_passed = clock_->Now() - last_refill_time_;
28 QuicByteCount refill_size = time_passed * target_bandwidth_;
29
30 for (auto& bucket : token_buckets_) {
31 bucket.second = std::min(bucket.second + refill_size, max_bucket_size_);
32 }
33
34 last_refill_time_ = clock_->Now();
35}
36
37bool TrafficPolicer::FilterPacket(const Packet& packet) {
38 // Refill existing buckets.
39 Refill();
40
41 // Create a new bucket if one does not exist.
42 if (token_buckets_.count(packet.destination) == 0) {
43 token_buckets_.insert(
44 std::make_pair(packet.destination, initial_bucket_size_));
45 }
46
47 auto bucket = token_buckets_.find(packet.destination);
48 DCHECK(bucket != token_buckets_.end());
49
50 // Silently drop the packet on the floor if out of tokens
51 if (bucket->second < packet.size) {
52 return false;
53 }
54
55 bucket->second -= packet.size;
56 return true;
57}
58
59} // namespace simulator
60} // namespace quic