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 #include "mojo/public/cpp/environment/lib/default_async_waiter.h"
9 #include "mojo/public/c/environment/async_waiter.h"
10 #include "mojo/public/cpp/utility/run_loop.h"
11 #include "mojo/public/cpp/utility/run_loop_handler.h"
17 // RunLoopHandler implementation used for a request to AsyncWait(). There are
18 // two ways RunLoopHandlerImpl is deleted:
19 // . when the handle is ready (or errored).
20 // . when CancelWait() is invoked.
21 class RunLoopHandlerImpl
: public RunLoopHandler
{
23 RunLoopHandlerImpl(const Handle
& handle
,
24 MojoAsyncWaitCallback callback
,
26 : handle_(handle
), callback_(callback
), closure_(closure
) {}
28 ~RunLoopHandlerImpl() override
{ RunLoop::current()->RemoveHandler(handle_
); }
31 void OnHandleReady(const Handle
& handle
) override
{
32 NotifyCallback(MOJO_RESULT_OK
);
35 void OnHandleError(const Handle
& handle
, MojoResult result
) override
{
36 NotifyCallback(result
);
40 void NotifyCallback(MojoResult result
) {
41 // Delete this to unregister the handle. That way if the callback
42 // reregisters everything is ok.
43 MojoAsyncWaitCallback callback
= callback_
;
44 void* closure
= closure_
;
47 callback(closure
, result
);
51 MojoAsyncWaitCallback callback_
;
54 MOJO_DISALLOW_COPY_AND_ASSIGN(RunLoopHandlerImpl
);
57 MojoAsyncWaitID
AsyncWait(MojoHandle handle
,
58 MojoHandleSignals signals
,
59 MojoDeadline deadline
,
60 MojoAsyncWaitCallback callback
,
62 RunLoop
* run_loop
= RunLoop::current();
65 // |run_loop_handler| is destroyed either when the handle is ready or if
66 // CancelWait is invoked.
67 RunLoopHandlerImpl
* run_loop_handler
=
68 new RunLoopHandlerImpl(Handle(handle
), callback
, closure
);
69 run_loop
->AddHandler(run_loop_handler
, Handle(handle
), signals
, deadline
);
70 return reinterpret_cast<MojoAsyncWaitID
>(run_loop_handler
);
73 void CancelWait(MojoAsyncWaitID wait_id
) {
74 delete reinterpret_cast<RunLoopHandlerImpl
*>(wait_id
);
81 const MojoAsyncWaiter kDefaultAsyncWaiter
= {AsyncWait
, CancelWait
};
83 } // namespace internal