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_BINDING_SET_H_
6 #define MOJO_COMMON_WEAK_BINDING_SET_H_
11 #include "base/memory/weak_ptr.h"
12 #include "third_party/mojo/src/mojo/public/cpp/bindings/binding.h"
16 template <typename Interface
>
19 // Use this class to manage a set of weak pointers to bindings each of which is
20 // owned by the pipe they are bound to.
21 template <typename Interface
>
22 class WeakBindingSet
{
25 ~WeakBindingSet() { CloseAllBindings(); }
27 void set_connection_error_handler(const Closure
& error_handler
) {
28 error_handler_
= error_handler
;
31 void AddBinding(Interface
* impl
, InterfaceRequest
<Interface
> request
) {
32 auto binding
= new WeakBinding
<Interface
>(impl
, request
.Pass());
33 binding
->set_connection_error_handler([this]() { OnConnectionError(); });
34 bindings_
.push_back(binding
->GetWeakPtr());
37 void CloseAllBindings() {
38 for (const auto& it
: bindings_
) {
45 bool empty() const { return bindings_
.empty(); }
48 void OnConnectionError() {
49 // Clear any deleted bindings.
51 std::remove_if(bindings_
.begin(), bindings_
.end(),
52 [](const base::WeakPtr
<WeakBinding
<Interface
>>& p
) {
53 return p
.get() == nullptr;
60 Closure error_handler_
;
61 std::vector
<base::WeakPtr
<WeakBinding
<Interface
>>> bindings_
;
63 DISALLOW_COPY_AND_ASSIGN(WeakBindingSet
);
66 template <typename Interface
>
69 WeakBinding(Interface
* impl
, InterfaceRequest
<Interface
> request
)
70 : binding_(impl
, request
.Pass()),
71 weak_ptr_factory_(this) {
72 binding_
.set_connection_error_handler([this]() { OnConnectionError(); });
77 void set_connection_error_handler(const Closure
& error_handler
) {
78 error_handler_
= error_handler
;
81 base::WeakPtr
<WeakBinding
> GetWeakPtr() {
82 return weak_ptr_factory_
.GetWeakPtr();
85 void Close() { binding_
.Close(); }
87 void OnConnectionError() {
88 Closure error_handler
= error_handler_
;
94 Binding
<Interface
> binding_
;
95 Closure error_handler_
;
96 base::WeakPtrFactory
<WeakBinding
> weak_ptr_factory_
;
98 DISALLOW_COPY_AND_ASSIGN(WeakBinding
);
103 #endif // MOJO_COMMON_WEAK_BINDING_SET_H_