1 | // Licensed to the Apache Software Foundation (ASF) under one |
2 | // or more contributor license agreements. See the NOTICE file |
3 | // distributed with this work for additional information |
4 | // regarding copyright ownership. The ASF licenses this file |
5 | // to you under the Apache License, Version 2.0 (the |
6 | // "License"); you may not use this file except in compliance |
7 | // with the License. You may obtain a copy of the License at |
8 | // |
9 | // http://www.apache.org/licenses/LICENSE-2.0 |
10 | // |
11 | // Unless required by applicable law or agreed to in writing, |
12 | // software distributed under the License is distributed on an |
13 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
14 | // KIND, either express or implied. See the License for the |
15 | // specific language governing permissions and limitations |
16 | // under the License. |
17 | |
18 | |
19 | #ifndef BRPC_CLOSURE_GUARD_H |
20 | #define BRPC_CLOSURE_GUARD_H |
21 | |
22 | #include <google/protobuf/service.h> |
23 | #include "butil/macros.h" |
24 | |
25 | |
26 | namespace brpc { |
27 | |
28 | // RAII: Call Run() of the closure on destruction. |
29 | class ClosureGuard { |
30 | public: |
31 | ClosureGuard() : _done(NULL) {} |
32 | |
33 | // Constructed with a closure which will be Run() inside dtor. |
34 | explicit ClosureGuard(google::protobuf::Closure* done) : _done(done) {} |
35 | |
36 | // Run internal closure if it's not NULL. |
37 | ~ClosureGuard() { |
38 | if (_done) { |
39 | _done->Run(); |
40 | } |
41 | } |
42 | |
43 | // Run internal closure if it's not NULL and set it to `done'. |
44 | void reset(google::protobuf::Closure* done) { |
45 | if (_done) { |
46 | _done->Run(); |
47 | } |
48 | _done = done; |
49 | } |
50 | |
51 | // Return and set internal closure to NULL. |
52 | google::protobuf::Closure* release() { |
53 | google::protobuf::Closure* const prev_done = _done; |
54 | _done = NULL; |
55 | return prev_done; |
56 | } |
57 | |
58 | // True if no closure inside. |
59 | bool empty() const { return _done == NULL; } |
60 | |
61 | // Exchange closure with another guard. |
62 | void swap(ClosureGuard& other) { std::swap(_done, other._done); } |
63 | |
64 | private: |
65 | // Copying this object makes no sense. |
66 | DISALLOW_COPY_AND_ASSIGN(ClosureGuard); |
67 | |
68 | google::protobuf::Closure* _done; |
69 | }; |
70 | |
71 | } // namespace brpc |
72 | |
73 | |
74 | #endif // BRPC_CLOSURE_GUARD_H |
75 | |