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 enum class 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 
62  operator std::string() const;
63 
64 private:
65  // Throws RuntimeError if it cannot parse the address.
66  void _parse(const std::string& port);
67 
68  uint16_t _port = 0;
69  Protocol _protocol = Protocol::Undef;
70 };
71 
72 namespace detail::adl {
73 extern std::string to_string(const Protocol& x, adl::tag /*unused*/);
74 inline std::string to_string(const Port& x, adl::tag /*unused*/) { return x; };
75 } // namespace detail::adl
76 
77 inline std::ostream& operator<<(std::ostream& out, const Protocol& x) {
78  out << to_string(x);
79  return out;
80 }
81 
82 inline std::ostream& operator<<(std::ostream& out, const Port& x) {
83  out << to_string(x);
84  return out;
85 }
86 
87 } // namespace hilti::rt
std::string to_string(T &&x)
Definition: extension-points.h:26
auto protocol() const
Definition: port.h:53
Protocol
Definition: port.h:17
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