1 // Copyright (c) 2012 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/switch.h"
6
7 #include <cinttypes>
8 #include <utility>
9
10 #include "absl/strings/str_cat.h"
11
12 namespace quic {
13 namespace simulator {
14
Switch(Simulator * simulator,std::string name,SwitchPortNumber port_count,QuicByteCount queue_capacity)15 Switch::Switch(Simulator* simulator, std::string name,
16 SwitchPortNumber port_count, QuicByteCount queue_capacity) {
17 for (size_t port_number = 1; port_number <= port_count; port_number++) {
18 ports_.emplace_back(simulator,
19 absl::StrCat(name, " (port ", port_number, ")"), this,
20 port_number, queue_capacity);
21 }
22 }
23
~Switch()24 Switch::~Switch() {}
25
Port(Simulator * simulator,std::string name,Switch * parent,SwitchPortNumber port_number,QuicByteCount queue_capacity)26 Switch::Port::Port(Simulator* simulator, std::string name, Switch* parent,
27 SwitchPortNumber port_number, QuicByteCount queue_capacity)
28 : Endpoint(simulator, name),
29 parent_(parent),
30 port_number_(port_number),
31 connected_(false),
32 queue_(simulator, absl::StrCat(name, " (queue)"), queue_capacity) {}
33
AcceptPacket(std::unique_ptr<Packet> packet)34 void Switch::Port::AcceptPacket(std::unique_ptr<Packet> packet) {
35 parent_->DispatchPacket(port_number_, std::move(packet));
36 }
37
EnqueuePacket(std::unique_ptr<Packet> packet)38 void Switch::Port::EnqueuePacket(std::unique_ptr<Packet> packet) {
39 queue_.AcceptPacket(std::move(packet));
40 }
41
GetRxPort()42 UnconstrainedPortInterface* Switch::Port::GetRxPort() { return this; }
43
SetTxPort(ConstrainedPortInterface * port)44 void Switch::Port::SetTxPort(ConstrainedPortInterface* port) {
45 queue_.set_tx_port(port);
46 connected_ = true;
47 }
48
Act()49 void Switch::Port::Act() {}
50
DispatchPacket(SwitchPortNumber port_number,std::unique_ptr<Packet> packet)51 void Switch::DispatchPacket(SwitchPortNumber port_number,
52 std::unique_ptr<Packet> packet) {
53 Port* source_port = &ports_[port_number - 1];
54 const auto source_mapping_it = switching_table_.find(packet->source);
55 if (source_mapping_it == switching_table_.end()) {
56 switching_table_.insert(std::make_pair(packet->source, source_port));
57 }
58
59 const auto destination_mapping_it =
60 switching_table_.find(packet->destination);
61 if (destination_mapping_it != switching_table_.end()) {
62 destination_mapping_it->second->EnqueuePacket(std::move(packet));
63 return;
64 }
65
66 // If no mapping is available yet, broadcast the packet to all ports
67 // different from the source.
68 for (Port& egress_port : ports_) {
69 if (!egress_port.connected()) {
70 continue;
71 }
72 egress_port.EnqueuePacket(std::make_unique<Packet>(*packet));
73 }
74 }
75
76 } // namespace simulator
77 } // namespace quic
78