xref: /aosp_15_r20/external/webrtc/rtc_base/fake_mdns_responder.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2018 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef RTC_BASE_FAKE_MDNS_RESPONDER_H_
12 #define RTC_BASE_FAKE_MDNS_RESPONDER_H_
13 
14 #include <map>
15 #include <memory>
16 #include <string>
17 
18 #include "absl/strings/string_view.h"
19 #include "rtc_base/ip_address.h"
20 #include "rtc_base/mdns_responder_interface.h"
21 #include "rtc_base/thread.h"
22 
23 namespace webrtc {
24 
25 // This class posts tasks on the given `thread` to invoke callbacks. It's the
26 // callback's responsibility to be aware of potential destruction of state it
27 // depends on, e.g., using WeakPtrFactory or PendingTaskSafetyFlag.
28 class FakeMdnsResponder : public MdnsResponderInterface {
29  public:
FakeMdnsResponder(rtc::Thread * thread)30   explicit FakeMdnsResponder(rtc::Thread* thread) : thread_(thread) {}
31   ~FakeMdnsResponder() = default;
32 
CreateNameForAddress(const rtc::IPAddress & addr,NameCreatedCallback callback)33   void CreateNameForAddress(const rtc::IPAddress& addr,
34                             NameCreatedCallback callback) override {
35     std::string name;
36     if (addr_name_map_.find(addr) != addr_name_map_.end()) {
37       name = addr_name_map_[addr];
38     } else {
39       name = std::to_string(next_available_id_++) + ".local";
40       addr_name_map_[addr] = name;
41     }
42     thread_->PostTask([callback, addr, name]() { callback(addr, name); });
43   }
RemoveNameForAddress(const rtc::IPAddress & addr,NameRemovedCallback callback)44   void RemoveNameForAddress(const rtc::IPAddress& addr,
45                             NameRemovedCallback callback) override {
46     auto it = addr_name_map_.find(addr);
47     if (it != addr_name_map_.end()) {
48       addr_name_map_.erase(it);
49     }
50     bool result = it != addr_name_map_.end();
51     thread_->PostTask([callback, result]() { callback(result); });
52   }
53 
GetMappedAddressForName(absl::string_view name)54   rtc::IPAddress GetMappedAddressForName(absl::string_view name) const {
55     for (const auto& addr_name_pair : addr_name_map_) {
56       if (addr_name_pair.second == name) {
57         return addr_name_pair.first;
58       }
59     }
60     return rtc::IPAddress();
61   }
62 
63  private:
64   uint32_t next_available_id_ = 0;
65   std::map<rtc::IPAddress, std::string> addr_name_map_;
66   rtc::Thread* const thread_;
67 };
68 
69 }  // namespace webrtc
70 
71 #endif  // RTC_BASE_FAKE_MDNS_RESPONDER_H_
72