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_PUBLIC_CPP_SYSTEM_HANDLE_H_
6 #define MOJO_PUBLIC_CPP_SYSTEM_HANDLE_H_
11 #include "mojo/public/c/system/functions.h"
12 #include "mojo/public/c/system/types.h"
13 #include "mojo/public/cpp/system/macros.h"
19 // |Handle| and |...Handle|:
21 // |Handle| is a simple, copyable wrapper for the C type |MojoHandle| (which is
22 // just an integer). Its purpose is to increase type-safety, not provide
23 // lifetime management. For the same purpose, we have trivial *subclasses* of
24 // |Handle|, e.g., |MessagePipeHandle| and |DataPipeProducerHandle|. |Handle|
25 // and its subclasses impose *no* extra overhead over using |MojoHandle|s
28 // Note that though we provide constructors for |Handle|/|...Handle| from a
29 // |MojoHandle|, we do not provide, e.g., a constructor for |MessagePipeHandle|
30 // from a |Handle|. This is for type safety: If we did, you'd then be able to
31 // construct a |MessagePipeHandle| from, e.g., a |DataPipeProducerHandle| (since
34 // |ScopedHandleBase| and |Scoped...Handle|:
36 // |ScopedHandleBase<HandleType>| is a templated scoped wrapper, for the handle
37 // types above (in the same sense that a C++11 |unique_ptr<T>| is a scoped
38 // wrapper for a |T*|). It provides lifetime management, closing its owned
39 // handle on destruction. It also provides (emulated) move semantics, again
40 // along the lines of C++11's |unique_ptr| (and exactly like Chromium's
43 // |ScopedHandle| is just (a typedef of) a |ScopedHandleBase<Handle>|.
44 // Similarly, |ScopedMessagePipeHandle| is just a
45 // |ScopedHandleBase<MessagePipeHandle>|. Etc. Note that a
46 // |ScopedMessagePipeHandle| is *not* a (subclass of) |ScopedHandle|.
50 // We provide simple wrappers for the |Mojo...()| functions (in
51 // mojo/public/c/system/core.h -- see that file for details on individual
54 // The general guideline is functions that imply ownership transfer of a handle
55 // should take (or produce) an appropriate |Scoped...Handle|, while those that
56 // don't take a |...Handle|. For example, |CreateMessagePipe()| has two
57 // |ScopedMessagePipe| "out" parameters, whereas |Wait()| and |WaitMany()| take
58 // |Handle| parameters. Some, have both: e.g., |DuplicatedBuffer()| takes a
59 // suitable (unscoped) handle (e.g., |SharedBufferHandle|) "in" parameter and
60 // produces a suitable scoped handle (e.g., |ScopedSharedBufferHandle| a.k.a.
61 // |ScopedHandleBase<SharedBufferHandle>|) as an "out" parameter.
63 // An exception are some of the |...Raw()| functions. E.g., |CloseRaw()| takes a
64 // |Handle|, leaving the user to discard the handle.
66 // More significantly, |WriteMessageRaw()| exposes the full API complexity of
67 // |MojoWriteMessage()| (but doesn't require any extra overhead). It takes a raw
68 // array of |Handle|s as input, and takes ownership of them (i.e., invalidates
69 // them) on *success* (but not on failure). There are a number of reasons for
70 // this. First, C++03 |std::vector|s cannot contain the move-only
71 // |Scoped...Handle|s. Second, |std::vector|s impose extra overhead
72 // (necessitating heap-allocation of the buffer). Third, |std::vector|s wouldn't
73 // provide the desired level of flexibility/safety: a vector of handles would
74 // have to be all of the same type (probably |Handle|/|ScopedHandle|). Fourth,
75 // it's expected to not be used directly, but instead be used by generated
78 // Other |...Raw()| functions expose similar rough edges, e.g., dealing with raw
79 // pointers (and lengths) instead of taking |std::vector|s or similar.
81 // ScopedHandleBase ------------------------------------------------------------
83 // Scoper for the actual handle types defined further below. It's move-only,
84 // like the C++11 |unique_ptr|.
85 template <class HandleType
>
86 class ScopedHandleBase
{
87 MOJO_MOVE_ONLY_TYPE_FOR_CPP_03(ScopedHandleBase
, RValue
)
91 explicit ScopedHandleBase(HandleType handle
) : handle_(handle
) {}
92 ~ScopedHandleBase() { CloseIfNecessary(); }
94 template <class CompatibleHandleType
>
95 explicit ScopedHandleBase(ScopedHandleBase
<CompatibleHandleType
> other
)
96 : handle_(other
.release()) {}
98 // Move-only constructor and operator=.
99 ScopedHandleBase(RValue other
) : handle_(other
.object
->release()) {}
100 ScopedHandleBase
& operator=(RValue other
) {
101 if (other
.object
!= this) {
103 handle_
= other
.object
->release();
108 const HandleType
& get() const { return handle_
; }
110 template <typename PassedHandleType
>
111 static ScopedHandleBase
<HandleType
> From(
112 ScopedHandleBase
<PassedHandleType
> other
) {
114 sizeof(static_cast<PassedHandleType
*>(static_cast<HandleType
*>(0))),
115 "HandleType is not a subtype of PassedHandleType");
116 return ScopedHandleBase
<HandleType
>(
117 static_cast<HandleType
>(other
.release().value()));
120 void swap(ScopedHandleBase
& other
) { handle_
.swap(other
.handle_
); }
122 HandleType
release() MOJO_WARN_UNUSED_RESULT
{
128 void reset(HandleType handle
= HandleType()) {
133 bool is_valid() const { return handle_
.is_valid(); }
136 void CloseIfNecessary() {
137 if (!handle_
.is_valid())
139 MojoResult result MOJO_ALLOW_UNUSED
= MojoClose(handle_
.value());
140 assert(result
== MOJO_RESULT_OK
);
146 template <typename HandleType
>
147 inline ScopedHandleBase
<HandleType
> MakeScopedHandle(HandleType handle
) {
148 return ScopedHandleBase
<HandleType
>(handle
);
151 // Handle ----------------------------------------------------------------------
153 const MojoHandle kInvalidHandleValue
= MOJO_HANDLE_INVALID
;
155 // Wrapper base class for |MojoHandle|.
158 Handle() : value_(kInvalidHandleValue
) {}
159 explicit Handle(MojoHandle value
) : value_(value
) {}
162 void swap(Handle
& other
) {
163 MojoHandle temp
= value_
;
164 value_
= other
.value_
;
168 bool is_valid() const { return value_
!= kInvalidHandleValue
; }
170 const MojoHandle
& value() const { return value_
; }
171 MojoHandle
* mutable_value() { return &value_
; }
172 void set_value(MojoHandle value
) { value_
= value
; }
177 // Copying and assignment allowed.
180 // Should have zero overhead.
181 static_assert(sizeof(Handle
) == sizeof(MojoHandle
), "Bad size for C++ Handle");
183 // The scoper should also impose no more overhead.
184 typedef ScopedHandleBase
<Handle
> ScopedHandle
;
185 static_assert(sizeof(ScopedHandle
) == sizeof(Handle
),
186 "Bad size for C++ ScopedHandle");
188 inline MojoResult
Wait(Handle handle
,
189 MojoHandleSignals signals
,
190 MojoDeadline deadline
) {
191 return MojoWait(handle
.value(), signals
, deadline
);
194 // |HandleVectorType| and |FlagsVectorType| should be similar enough to
195 // |std::vector<Handle>| and |std::vector<MojoHandleSignals>|, respectively:
196 // - They should have a (const) |size()| method that returns an unsigned type.
197 // - They must provide contiguous storage, with access via (const) reference to
198 // that storage provided by a (const) |operator[]()| (by reference).
199 template <class HandleVectorType
, class FlagsVectorType
>
200 inline MojoResult
WaitMany(const HandleVectorType
& handles
,
201 const FlagsVectorType
& signals
,
202 MojoDeadline deadline
) {
203 if (signals
.size() != handles
.size())
204 return MOJO_RESULT_INVALID_ARGUMENT
;
205 if (handles
.size() > std::numeric_limits
<uint32_t>::max())
206 return MOJO_RESULT_OUT_OF_RANGE
;
208 if (handles
.size() == 0)
209 return MojoWaitMany(nullptr, nullptr, 0, deadline
);
211 const Handle
& first_handle
= handles
[0];
212 const MojoHandleSignals
& first_signals
= signals
[0];
214 reinterpret_cast<const MojoHandle
*>(&first_handle
),
215 reinterpret_cast<const MojoHandleSignals
*>(&first_signals
),
216 static_cast<uint32_t>(handles
.size()),
220 // |Close()| takes ownership of the handle, since it'll invalidate it.
221 // Note: There's nothing to do, since the argument will be destroyed when it
222 // goes out of scope.
223 template <class HandleType
>
224 inline void Close(ScopedHandleBase
<HandleType
> /*handle*/) {
227 // Most users should typically use |Close()| (above) instead.
228 inline MojoResult
CloseRaw(Handle handle
) {
229 return MojoClose(handle
.value());
232 // Strict weak ordering, so that |Handle|s can be used as keys in |std::map|s,
233 inline bool operator<(const Handle a
, const Handle b
) {
234 return a
.value() < b
.value();
239 #endif // MOJO_PUBLIC_CPP_SYSTEM_HANDLE_H_