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