OLD | NEW |
| (Empty) |
1 // Copyright 2014 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 MOJO_COMMON_WEAK_INTERFACE_PTR_SET_H_ | |
6 #define MOJO_COMMON_WEAK_INTERFACE_PTR_SET_H_ | |
7 | |
8 #include <vector> | |
9 | |
10 #include "base/logging.h" | |
11 #include "base/memory/weak_ptr.h" | |
12 #include "mojo/public/cpp/bindings/interface_ptr.h" | |
13 | |
14 namespace mojo { | |
15 | |
16 // A WeakInterfacePtrSet contains a collection of InterfacePtrs | |
17 // that are automatically removed from the collection and destroyed | |
18 // when their associated MessagePipe experiences a connection error. | |
19 // When the set is destroyed all of the MessagePipes will be closed. | |
20 // TODO(rudominer) Rename this class since the ownership of the elements | |
21 // is not "weak" from the point of view of the client. | |
22 template <typename Interface> | |
23 class WeakInterfacePtrSet { | |
24 public: | |
25 WeakInterfacePtrSet() {} | |
26 ~WeakInterfacePtrSet() { CloseAll(); } | |
27 | |
28 // |ptr| must be bound to a message pipe. | |
29 void AddInterfacePtr(InterfacePtr<Interface> ptr) { | |
30 DCHECK(ptr.is_bound()); | |
31 ptrs_.emplace_back(ptr.Pass()); | |
32 InterfacePtr<Interface>& intrfc_ptr = ptrs_.back(); | |
33 Interface* pointer = intrfc_ptr.get(); | |
34 // Set the connection error handler for the newly added InterfacePtr to be a | |
35 // function that will erase it from the vector. | |
36 intrfc_ptr.set_connection_error_handler([pointer, this]() { | |
37 // Since InterfacePtr itself is a movable type, the thing that uniquely | |
38 // identifies the InterfacePtr we wish to erase is its Interface*. | |
39 auto it = std::find_if(ptrs_.begin(), ptrs_.end(), | |
40 [pointer](const InterfacePtr<Interface>& p) { | |
41 return (p.get() == pointer); | |
42 }); | |
43 DCHECK(it != ptrs_.end()); | |
44 ptrs_.erase(it); | |
45 }); | |
46 } | |
47 | |
48 // Applies |function| to each of the InterfacePtrs in the set. | |
49 template <typename FunctionType> | |
50 void ForAllPtrs(FunctionType function) { | |
51 for (const auto& it : ptrs_) { | |
52 if (it) | |
53 function(it.get()); | |
54 } | |
55 } | |
56 | |
57 // Closes the MessagePipe associated with each of the InterfacePtrs in | |
58 // this set and clears the set. | |
59 void CloseAll() { | |
60 for (auto& it : ptrs_) { | |
61 if (it) | |
62 it.reset(); | |
63 } | |
64 ptrs_.clear(); | |
65 } | |
66 | |
67 size_t size() const { return ptrs_.size(); } | |
68 | |
69 private: | |
70 std::vector<InterfacePtr<Interface>> ptrs_; | |
71 }; | |
72 | |
73 } // namespace mojo | |
74 | |
75 #endif // MOJO_COMMON_WEAK_INTERFACE_PTR_SET_H_ | |
OLD | NEW |