Sponge
CS144's user-space TCP library
lossy_fd_adapter.hh
Go to the documentation of this file.
1 #ifndef SPONGE_LIBSPONGE_LOSSY_FD_ADAPTER_HH
2 #define SPONGE_LIBSPONGE_LOSSY_FD_ADAPTER_HH
3 
4 #include "file_descriptor.hh"
5 #include "tcp_config.hh"
6 #include "tcp_segment.hh"
7 #include "util.hh"
8 
9 #include <optional>
10 #include <random>
11 #include <utility>
12 
14 template <typename AdapterT>
16  private:
19 
21  AdapterT _adapter;
22 
26  bool _should_drop(bool uplink) {
27  const auto &cfg = _adapter.config();
28  const uint16_t loss = uplink ? cfg.loss_rate_up : cfg.loss_rate_dn;
29  return loss != 0 && uint16_t(_rand()) < loss;
30  }
31 
32  public:
34  operator const FileDescriptor &() const { return _adapter; }
35 
37  explicit LossyFdAdapter(AdapterT &&adapter) : _adapter(std::move(adapter)) {}
38 
42  std::optional<TCPSegment> read() {
43  auto ret = _adapter.read();
44  if (_should_drop(false)) {
45  return {};
46  }
47  return ret;
48  }
49 
52  void write(TCPSegment &seg) {
53  if (_should_drop(true)) {
54  return;
55  }
56  return _adapter.write(seg);
57  }
58 
61 
63  void set_listening(const bool l) { _adapter.set_listening(l); }
64  const FdAdapterConfig &config() const { return _adapter.config(); }
65  FdAdapterConfig &config_mut() { return _adapter.config_mut(); }
66  void tick(const size_t ms_since_last_tick) {
67  _adapter.tick(ms_since_last_tick);
68  }
69 };
71 
72 #endif // SPONGE_LIBSPONGE_LOSSY_FD_ADAPTER_HH
util.hh
LossyFdAdapter::read
std::optional< TCPSegment > read()
Read from the underlying AdapterT instance, potentially dropping the read datagram.
Definition: lossy_fd_adapter.hh:42
tcp_segment.hh
file_descriptor.hh
get_random_generator
mt19937 get_random_generator()
Seed a fast random generator.
Definition: util.cc:64
FileDescriptor
A reference-counted handle to a file descriptor.
Definition: file_descriptor.hh:12
std::mt19937
LossyFdAdapter::write
void write(TCPSegment &seg)
Write to the underlying AdapterT instance, potentially dropping the datagram to be written.
Definition: lossy_fd_adapter.hh:52
FdAdapterConfig
Config for classes derived from FdAdapter.
Definition: tcp_config.hh:26
tcp_config.hh
LossyFdAdapter
An adapter class that adds random dropping behavior to an FD adapter.
Definition: lossy_fd_adapter.hh:15
LossyFdAdapter::LossyFdAdapter
LossyFdAdapter(AdapterT &&adapter)
Construct from a FileDescriptor appropriate to the AdapterT constructor.
Definition: lossy_fd_adapter.hh:37
LossyFdAdapter::_adapter
AdapterT _adapter
The underlying FD adapter.
Definition: lossy_fd_adapter.hh:21
LossyFdAdapter::_should_drop
bool _should_drop(bool uplink)
Determine whether or not to drop a given read or write.
Definition: lossy_fd_adapter.hh:26
std
LossyFdAdapter::_rand
std::mt19937 _rand
Fast RNG used by _should_drop()
Definition: lossy_fd_adapter.hh:18
TCPSegment
TCP segment
Definition: tcp_segment.hh:10