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 
TrafficPolicer(Simulator * simulator,std::string name,QuicByteCount initial_bucket_size,QuicByteCount max_bucket_size,QuicBandwidth target_bandwidth,Endpoint * input)12 TrafficPolicer::TrafficPolicer(Simulator* simulator,
13                                std::string name,
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 
~TrafficPolicer()24 TrafficPolicer::~TrafficPolicer() {}
25 
Refill()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 
FilterPacket(const Packet & packet)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
61