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_
10 #include "base/memory/weak_ptr.h"
11 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_ptr.h"
15 template <typename Interface
>
16 class WeakInterfacePtr
;
18 template <typename Interface
>
19 class WeakInterfacePtrSet
{
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_
) {
36 ClearNullInterfacePtrs();
40 for (const auto& it
: ptrs_
) {
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;
56 std::vector
<WPWIPI
> ptrs_
;
59 template <typename Interface
>
60 class WeakInterfacePtr
{
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();
77 InterfacePtr
<Interface
> ptr_
;
78 base::WeakPtrFactory
<WeakInterfacePtr
> weak_ptr_factory_
;
80 DISALLOW_COPY_AND_ASSIGN(WeakInterfacePtr
);
85 #endif // MOJO_COMMON_WEAK_INTERFACE_PTR_SET_H_