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