1 // Copyright 2019 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 #ifndef DISCOVERY_DNSSD_IMPL_INSTANCE_KEY_H_
6 #define DISCOVERY_DNSSD_IMPL_INSTANCE_KEY_H_
7
8 #include <string>
9 #include <utility>
10
11 #include "absl/strings/string_view.h"
12 #include "discovery/dnssd/impl/service_key.h"
13
14 namespace openscreen {
15 namespace discovery {
16
17 class DnsSdInstance;
18 class DomainName;
19 class MdnsRecord;
20 class ServiceKey;
21
22 // This class is intended to be used as the key of a std::unordered_map or
23 // std::map when referencing data related to a specific service instance.
24 class InstanceKey : public ServiceKey {
25 public:
26 // NOTE: The record provided must have valid instance, service, and domain
27 // labels.
28 explicit InstanceKey(const MdnsRecord& record);
29 explicit InstanceKey(const DomainName& domain);
30 explicit InstanceKey(const DnsSdInstance& instance);
31
32 // NOTE: The provided parameters must be valid instance, service and domain
33 // ids.
34 InstanceKey(absl::string_view instance,
35 absl::string_view service,
36 absl::string_view domain);
37
38 InstanceKey(const InstanceKey& other);
39 InstanceKey(InstanceKey&& other);
40
41 InstanceKey& operator=(const InstanceKey& rhs);
42 InstanceKey& operator=(InstanceKey&& rhs);
43
44 DomainName GetName() const override;
45
instance_id()46 const std::string& instance_id() const { return instance_id_; }
47
48 private:
49 std::string instance_id_;
50
51 template <typename H>
52 friend H AbslHashValue(H h, const InstanceKey& key);
53
54 friend bool operator<(const InstanceKey& lhs, const InstanceKey& rhs);
55 };
56
57 template <typename H>
AbslHashValue(H h,const InstanceKey & key)58 H AbslHashValue(H h, const InstanceKey& key) {
59 return H::combine(std::move(h), key.service_id(), key.domain_id(),
60 key.instance_id_);
61 }
62
63 inline bool operator<(const InstanceKey& lhs, const InstanceKey& rhs) {
64 int comp = lhs.domain_id().compare(rhs.domain_id());
65 if (comp != 0) {
66 return comp < 0;
67 }
68
69 comp = lhs.service_id().compare(rhs.service_id());
70 if (comp != 0) {
71 return comp < 0;
72 }
73
74 return lhs.instance_id_ < rhs.instance_id_;
75 }
76
77 inline bool operator>(const InstanceKey& lhs, const InstanceKey& rhs) {
78 return rhs < lhs;
79 }
80
81 inline bool operator<=(const InstanceKey& lhs, const InstanceKey& rhs) {
82 return !(rhs > lhs);
83 }
84
85 inline bool operator>=(const InstanceKey& lhs, const InstanceKey& rhs) {
86 return !(rhs < lhs);
87 }
88
89 inline bool operator==(const InstanceKey& lhs, const InstanceKey& rhs) {
90 return lhs <= rhs && lhs >= rhs;
91 }
92
93 inline bool operator!=(const InstanceKey& lhs, const InstanceKey& rhs) {
94 return !(lhs == rhs);
95 }
96
97 } // namespace discovery
98 } // namespace openscreen
99
100 #endif // DISCOVERY_DNSSD_IMPL_INSTANCE_KEY_H_
101