1 // Copyright 2012 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef NET_BASE_HOST_PORT_PAIR_H_ 6 #define NET_BASE_HOST_PORT_PAIR_H_ 7 8 #include <stdint.h> 9 10 #include <optional> 11 #include <string> 12 #include <string_view> 13 #include <tuple> 14 15 #include "base/values.h" 16 #include "net/base/net_export.h" 17 18 class GURL; 19 20 namespace url { 21 class SchemeHostPort; 22 } // namespace url 23 24 namespace net { 25 26 class IPEndPoint; 27 28 class NET_EXPORT HostPortPair { 29 public: 30 HostPortPair(); 31 // If |in_host| represents an IPv6 address, it should not bracket the address. 32 HostPortPair(std::string_view in_host, uint16_t in_port); 33 34 // Creates a HostPortPair for the origin of |url|. 35 static HostPortPair FromURL(const GURL& url); 36 37 static HostPortPair FromSchemeHostPort( 38 const url::SchemeHostPort& scheme_host_port); 39 40 // Creates a HostPortPair from an IPEndPoint. 41 static HostPortPair FromIPEndPoint(const IPEndPoint& ipe); 42 43 // Creates a HostPortPair from a string formatted in same manner as 44 // ToString(). 45 static HostPortPair FromString(std::string_view str); 46 47 // Nullopt if `value` is malformed to be deserialized to HostPortPair. 48 static std::optional<HostPortPair> FromValue(const base::Value& value); 49 50 // TODO(willchan): Define a functor instead. 51 // Comparator function so this can be placed in a std::map. 52 bool operator<(const HostPortPair& other) const { 53 return std::tie(port_, host_) < std::tie(other.port_, other.host_); 54 } 55 56 bool operator==(const HostPortPair& other) const { return Equals(other); } 57 58 // Equality test of contents. (Probably another violation of style guide). Equals(const HostPortPair & other)59 bool Equals(const HostPortPair& other) const { 60 return host_ == other.host_ && port_ == other.port_; 61 } 62 IsEmpty()63 bool IsEmpty() const { 64 return host_.empty() && port_ == 0; 65 } 66 host()67 const std::string& host() const { 68 return host_; 69 } 70 port()71 uint16_t port() const { return port_; } 72 set_host(const std::string & in_host)73 void set_host(const std::string& in_host) { 74 host_ = in_host; 75 } 76 set_port(uint16_t in_port)77 void set_port(uint16_t in_port) { port_ = in_port; } 78 79 // ToString() will convert the HostPortPair to "host:port". If |host_| is an 80 // IPv6 literal, it will add brackets around |host_|. 81 std::string ToString() const; 82 83 // Returns |host_|, adding IPv6 brackets if needed. 84 std::string HostForURL() const; 85 86 base::Value ToValue() const; 87 88 private: 89 // If |host_| represents an IPv6 address, this string will not contain 90 // brackets around the address. 91 std::string host_; 92 uint16_t port_; 93 }; 94 95 } // namespace net 96 97 #endif // NET_BASE_HOST_PORT_PAIR_H_ 98