15094f816b607018eaadd482294e2c333518e0e0
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / rpc / pending_call_cache.cpp
1 /*
2  * Copyright © 2012 Canonical Ltd.
3  *
4  * This program is free software: you can redistribute it and/or modify it
5  * under the terms of the GNU Lesser General Public License version 3,
6  * as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public License
14  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  * Authored by: Alan Griffiths <alan@octopull.co.uk>
17  */
18
19 #include "anbox/rpc/pending_call_cache.h"
20
21 #include "anbox_rpc.pb.h"
22
23 #ifdef USE_PROTOBUF_CALLBACK_HEADER
24 #include <google/protobuf/stubs/callback.h>
25 #endif
26
27 namespace anbox {
28 namespace rpc {
29 PendingCallCache::PendingCallCache() {}
30
31 void PendingCallCache::save_completion_details(
32     anbox::protobuf::rpc::Invocation const& invocation,
33     google::protobuf::MessageLite* response,
34     google::protobuf::Closure* complete) {
35   std::unique_lock<std::mutex> lock(mutex_);
36   pending_calls_[invocation.id()] = PendingCall(response, complete);
37 }
38
39 void PendingCallCache::populate_message_for_result(
40     anbox::protobuf::rpc::Result& result,
41     std::function<void(google::protobuf::MessageLite*)> const& populator) {
42   std::unique_lock<std::mutex> lock(mutex_);
43   populator(pending_calls_.at(result.id()).response);
44 }
45
46 void PendingCallCache::complete_response(anbox::protobuf::rpc::Result& result) {
47   PendingCall completion;
48
49   {
50     std::unique_lock<std::mutex> lock(mutex_);
51     auto call = pending_calls_.find(result.id());
52     if (call != pending_calls_.end()) {
53       completion = call->second;
54       pending_calls_.erase(call);
55     }
56   }
57
58   if (completion.complete) completion.complete->Run();
59 }
60
61 void PendingCallCache::force_completion() {
62   std::unique_lock<std::mutex> lock(mutex_);
63   for (auto& call : pending_calls_) {
64     auto& completion = call.second;
65     completion.complete->Run();
66   }
67
68   pending_calls_.erase(pending_calls_.begin(), pending_calls_.end());
69 }
70
71 bool PendingCallCache::empty() const {
72   std::unique_lock<std::mutex> lock(mutex_);
73   return pending_calls_.empty();
74 }
75 }  // namespace rpc
76 }  // namespace anbox