QUICHE team | a6ef0a6 | 2019-03-07 20:34:33 -0500 | [diff] [blame] | 1 | // 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 | |
| 9 | namespace quic { |
| 10 | namespace simulator { |
| 11 | |
| 12 | TrafficPolicer::TrafficPolicer(Simulator* simulator, |
vasilvv | c48c871 | 2019-03-11 13:38:16 -0700 | [diff] [blame^] | 13 | std::string name, |
QUICHE team | a6ef0a6 | 2019-03-07 20:34:33 -0500 | [diff] [blame] | 14 | 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 | |
| 24 | TrafficPolicer::~TrafficPolicer() {} |
| 25 | |
| 26 | void 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 | |
| 37 | bool 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 |