Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / mojo / common / weak_interface_ptr_set.h
blob4e64534463fd29c52f9e6410a0f0fd6f2da6b468
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.
5 #ifndef MOJO_COMMON_WEAK_INTERFACE_PTR_SET_H_
6 #define MOJO_COMMON_WEAK_INTERFACE_PTR_SET_H_
8 #include <vector>
10 #include "base/memory/weak_ptr.h"
11 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_ptr.h"
13 namespace mojo {
15 template <typename Interface>
16 class WeakInterfacePtr;
18 template <typename Interface>
19 class WeakInterfacePtrSet {
20 public:
21 WeakInterfacePtrSet() {}
22 ~WeakInterfacePtrSet() { CloseAll(); }
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();
30 template <typename FunctionType>
31 void ForAllPtrs(FunctionType function) {
32 for (const auto& it : ptrs_) {
33 if (it)
34 function(it->get());
36 ClearNullInterfacePtrs();
39 void CloseAll() {
40 for (const auto& it : ptrs_) {
41 if (it)
42 it->Close();
44 ptrs_.clear();
47 private:
48 using WPWIPI = base::WeakPtr<WeakInterfacePtr<Interface>>;
50 void ClearNullInterfacePtrs() {
51 ptrs_.erase(std::remove_if(ptrs_.begin(), ptrs_.end(), [](const WPWIPI& p) {
52 return p.get() == nullptr;
53 }), ptrs_.end());
56 std::vector<WPWIPI> ptrs_;
59 template <typename Interface>
60 class WeakInterfacePtr {
61 public:
62 explicit WeakInterfacePtr(InterfacePtr<Interface> ptr)
63 : ptr_(ptr.Pass()), weak_ptr_factory_(this) {
64 ptr_.set_connection_error_handler([this]() { delete this; });
66 ~WeakInterfacePtr() {}
68 void Close() { ptr_.reset(); }
70 Interface* get() { return ptr_.get(); }
72 base::WeakPtr<WeakInterfacePtr> GetWeakPtr() {
73 return weak_ptr_factory_.GetWeakPtr();
76 private:
77 InterfacePtr<Interface> ptr_;
78 base::WeakPtrFactory<WeakInterfacePtr> weak_ptr_factory_;
80 DISALLOW_COPY_AND_ASSIGN(WeakInterfacePtr);
83 } // namespace mojo
85 #endif // MOJO_COMMON_WEAK_INTERFACE_PTR_SET_H_