Spicy
port.h
1 // Copyright (c) 2020-2021 by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <arpa/inet.h>
6 
7 #include <string>
8 #include <variant>
9 
10 #include <hilti/rt/extension-points.h>
11 #include <hilti/rt/types/address.h>
12 #include <hilti/rt/util.h>
13 
14 namespace hilti::rt {
15 
17 HILTI_RT_ENUM(Protocol, Undef = 0, TCP, UDP, ICMP);
18 
22 class Port {
23 public:
27  Port(uint16_t port, Protocol protocol) : _port(port), _protocol(protocol) {}
28 
39  explicit Port(const std::string& port) { _parse(port); }
40 
41  Port() = default;
42  Port(const Port&) = default;
43  Port(Port&&) noexcept = default;
44  ~Port() = default;
45 
46  Port& operator=(const Port&) = default;
47  Port& operator=(Port&&) noexcept = default;
48 
50  auto port() const { return _port; }
51 
53  auto protocol() const { return _protocol; }
54 
55  bool operator==(const Port& other) const { return _port == other._port && _protocol == other._protocol; }
56  bool operator!=(const Port& other) const { return ! (*this == other); }
57  bool operator<(const Port& other) const {
58  return std::tie(_port, _protocol) < std::tie(other._port, other._protocol);
59  };
60 
65  operator std::string() const;
66 
67 private:
68  // Throws RuntimeError if it cannot parse the address.
69  void _parse(const std::string& port);
70 
71  uint16_t _port = 0;
72  Protocol _protocol = Protocol::Undef;
73 };
74 
75 namespace detail::adl {
76 extern std::string to_string(const Protocol& x, adl::tag /*unused*/);
77 inline std::string to_string(const Port& x, adl::tag /*unused*/) { return x; };
78 } // namespace detail::adl
79 
80 inline std::ostream& operator<<(std::ostream& out, const Protocol& x) {
81  out << to_string(x);
82  return out;
83 }
84 
85 inline std::ostream& operator<<(std::ostream& out, const Port& x) {
86  out << to_string(x);
87  return out;
88 }
89 
90 } // namespace hilti::rt
std::string to_string(T &&x)
Definition: extension-points.h:26
auto protocol() const
Definition: port.h:53
Definition: port.h:22
Definition: any.h:7
Port(uint16_t port, Protocol protocol)
Definition: port.h:27
Port(const std::string &port)
Definition: port.h:39
auto port() const
Definition: port.h:50