xref: /aosp_15_r20/external/cronet/net/third_party/quiche/src/quiche/quic/test_tools/simulator/traffic_policer.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 "quiche/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, std::string name,
13                                QuicByteCount initial_bucket_size,
14                                QuicByteCount max_bucket_size,
15                                QuicBandwidth target_bandwidth, Endpoint* input)
16     : PacketFilter(simulator, name, input),
17       initial_bucket_size_(initial_bucket_size),
18       max_bucket_size_(max_bucket_size),
19       target_bandwidth_(target_bandwidth),
20       last_refill_time_(clock_->Now()) {}
21 
~TrafficPolicer()22 TrafficPolicer::~TrafficPolicer() {}
23 
Refill()24 void TrafficPolicer::Refill() {
25   QuicTime::Delta time_passed = clock_->Now() - last_refill_time_;
26   QuicByteCount refill_size = time_passed * target_bandwidth_;
27 
28   for (auto& bucket : token_buckets_) {
29     bucket.second = std::min(bucket.second + refill_size, max_bucket_size_);
30   }
31 
32   last_refill_time_ = clock_->Now();
33 }
34 
FilterPacket(const Packet & packet)35 bool TrafficPolicer::FilterPacket(const Packet& packet) {
36   // Refill existing buckets.
37   Refill();
38 
39   // Create a new bucket if one does not exist.
40   if (token_buckets_.count(packet.destination) == 0) {
41     token_buckets_.insert(
42         std::make_pair(packet.destination, initial_bucket_size_));
43   }
44 
45   auto bucket = token_buckets_.find(packet.destination);
46   QUICHE_DCHECK(bucket != token_buckets_.end());
47 
48   // Silently drop the packet on the floor if out of tokens
49   if (bucket->second < packet.size) {
50     return false;
51   }
52 
53   bucket->second -= packet.size;
54   return true;
55 }
56 
57 }  // namespace simulator
58 }  // namespace quic
59