1 // Copyright 2018 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_SYSTEM_SCOPE_TO_MESSAGE_PIPE_H_ 6 #define MOJO_PUBLIC_CPP_SYSTEM_SCOPE_TO_MESSAGE_PIPE_H_ 7 8 #include <memory> 9 10 #include "base/bind.h" 11 #include "base/callback.h" 12 #include "base/macros.h" 13 #include "mojo/public/cpp/system/message_pipe.h" 14 #include "mojo/public/cpp/system/simple_watcher.h" 15 #include "mojo/public/cpp/system/system_export.h" 16 17 namespace mojo { 18 19 namespace internal { 20 21 // Owns the state and details to implement ScopeToMessagePipe (see below). 22 class MOJO_CPP_SYSTEM_EXPORT MessagePipeScoperBase { 23 public: 24 explicit MessagePipeScoperBase(ScopedMessagePipeHandle pipe); 25 virtual ~MessagePipeScoperBase(); 26 27 static void StartWatchingPipe(std::unique_ptr<MessagePipeScoperBase> scoper); 28 29 private: 30 ScopedMessagePipeHandle pipe_; 31 SimpleWatcher pipe_watcher_; 32 33 DISALLOW_COPY_AND_ASSIGN(MessagePipeScoperBase); 34 }; 35 36 template <typename T> 37 class MessagePipeScoper : public MessagePipeScoperBase { 38 public: MessagePipeScoper(T scoped_object,ScopedMessagePipeHandle pipe)39 explicit MessagePipeScoper(T scoped_object, ScopedMessagePipeHandle pipe) 40 : MessagePipeScoperBase(std::move(pipe)), 41 scoped_object_(std::move(scoped_object)) {} 42 ~MessagePipeScoper() override = default; 43 44 private: 45 T scoped_object_; 46 47 DISALLOW_COPY_AND_ASSIGN(MessagePipeScoper); 48 }; 49 50 } // namespace internal 51 52 // Binds the lifetime of |object| to that of |pipe|'s connection. When |pipe|'s 53 // peer is closed, |pipe| will be closed and |object| will be destroyed. This 54 // can be useful as a simple mechanism to track object lifetime across process 55 // boundaries. 56 template <typename T> ScopeToMessagePipe(T object,ScopedMessagePipeHandle pipe)57void ScopeToMessagePipe(T object, ScopedMessagePipeHandle pipe) { 58 internal::MessagePipeScoperBase::StartWatchingPipe( 59 std::make_unique<internal::MessagePipeScoper<T>>(std::move(object), 60 std::move(pipe))); 61 } 62 63 } // namespace mojo 64 65 #endif // MOJO_PUBLIC_CPP_SYSTEM_SCOPE_TO_MESSAGE_PIPE_H_ 66