summaryrefslogtreecommitdiff
path: root/chromium/net/third_party/quiche/src/quic/test_tools/simulator/traffic_policer.cc
blob: be62669d383b1eda7bcd3c5788369d331eae83bf (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "quic/test_tools/simulator/traffic_policer.h"

#include <algorithm>

namespace quic {
namespace simulator {

TrafficPolicer::TrafficPolicer(Simulator* simulator,
                               std::string name,
                               QuicByteCount initial_bucket_size,
                               QuicByteCount max_bucket_size,
                               QuicBandwidth target_bandwidth,
                               Endpoint* input)
    : PacketFilter(simulator, name, input),
      initial_bucket_size_(initial_bucket_size),
      max_bucket_size_(max_bucket_size),
      target_bandwidth_(target_bandwidth),
      last_refill_time_(clock_->Now()) {}

TrafficPolicer::~TrafficPolicer() {}

void TrafficPolicer::Refill() {
  QuicTime::Delta time_passed = clock_->Now() - last_refill_time_;
  QuicByteCount refill_size = time_passed * target_bandwidth_;

  for (auto& bucket : token_buckets_) {
    bucket.second = std::min(bucket.second + refill_size, max_bucket_size_);
  }

  last_refill_time_ = clock_->Now();
}

bool TrafficPolicer::FilterPacket(const Packet& packet) {
  // Refill existing buckets.
  Refill();

  // Create a new bucket if one does not exist.
  if (token_buckets_.count(packet.destination) == 0) {
    token_buckets_.insert(
        std::make_pair(packet.destination, initial_bucket_size_));
  }

  auto bucket = token_buckets_.find(packet.destination);
  QUICHE_DCHECK(bucket != token_buckets_.end());

  // Silently drop the packet on the floor if out of tokens
  if (bucket->second < packet.size) {
    return false;
  }

  bucket->second -= packet.size;
  return true;
}

}  // namespace simulator
}  // namespace quic