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/memory/weak_ptr.h" |
| 11 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_ptr.h" |
| 12 |
| 13 namespace mojo { |
| 14 |
| 15 template <typename Interface> |
| 16 class WeakInterfacePtr; |
| 17 |
| 18 template <typename Interface> |
| 19 class WeakInterfacePtrSet { |
| 20 public: |
| 21 WeakInterfacePtrSet() {} |
| 22 ~WeakInterfacePtrSet() { CloseAll(); } |
| 23 |
| 24 void AddInterfacePtr(InterfacePtr<Interface> ptr) { |
| 25 auto weak_interface_ptr = new WeakInterfacePtr<Interface>(ptr.Pass()); |
| 26 ptrs_.push_back(weak_interface_ptr->GetWeakPtr()); |
| 27 ClearNullInterfacePtrs(); |
| 28 } |
| 29 |
| 30 template <typename FunctionType> |
| 31 void ForAllPtrs(FunctionType function) { |
| 32 for (const auto& it : ptrs_) { |
| 33 if (it) |
| 34 function(it->get()); |
| 35 } |
| 36 ClearNullInterfacePtrs(); |
| 37 } |
| 38 |
| 39 void CloseAll() { |
| 40 for (const auto& it : ptrs_) { |
| 41 if (it) |
| 42 it->Close(); |
| 43 } |
| 44 ptrs_.clear(); |
| 45 } |
| 46 |
| 47 private: |
| 48 using WPWIPI = base::WeakPtr<WeakInterfacePtr<Interface>>; |
| 49 |
| 50 void ClearNullInterfacePtrs() { |
| 51 ptrs_.erase(std::remove_if(ptrs_.begin(), ptrs_.end(), [](const WPWIPI& p) { |
| 52 return p.get() == nullptr; |
| 53 }), ptrs_.end()); |
| 54 } |
| 55 |
| 56 std::vector<WPWIPI> ptrs_; |
| 57 }; |
| 58 |
| 59 template <typename Interface> |
| 60 class WeakInterfacePtr : public ErrorHandler { |
| 61 public: |
| 62 explicit WeakInterfacePtr(InterfacePtr<Interface> ptr) |
| 63 : ptr_(ptr.Pass()), weak_ptr_factory_(this) { |
| 64 ptr_.set_error_handler(this); |
| 65 } |
| 66 ~WeakInterfacePtr() override {} |
| 67 |
| 68 void Close() { ptr_.reset(); } |
| 69 |
| 70 Interface* get() { return ptr_.get(); } |
| 71 |
| 72 base::WeakPtr<WeakInterfacePtr> GetWeakPtr() { |
| 73 return weak_ptr_factory_.GetWeakPtr(); |
| 74 } |
| 75 |
| 76 private: |
| 77 // ErrorHandler implementation |
| 78 void OnConnectionError() override { delete this; } |
| 79 |
| 80 InterfacePtr<Interface> ptr_; |
| 81 base::WeakPtrFactory<WeakInterfacePtr> weak_ptr_factory_; |
| 82 |
| 83 DISALLOW_COPY_AND_ASSIGN(WeakInterfacePtr); |
| 84 }; |
| 85 |
| 86 } // namespace mojo |
| 87 |
| 88 #endif // MOJO_COMMON_WEAK_INTERFACE_PTR_SET_H_ |
OLD | NEW |