1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "perfetto/protozero/message_handle.h"
18 
19 #include <utility>
20 
21 #include "perfetto/protozero/message.h"
22 
23 namespace protozero {
24 
~FinalizationListener()25 MessageHandleBase::FinalizationListener::~FinalizationListener() {}
26 
MessageHandleBase(Message * message)27 MessageHandleBase::MessageHandleBase(Message* message) : message_(message) {
28 #if PERFETTO_DCHECK_IS_ON()
29   generation_ = message_ ? message->generation_ : 0;
30   if (message_)
31     message_->set_handle(this);
32 #endif
33 }
34 
~MessageHandleBase()35 MessageHandleBase::~MessageHandleBase() {
36   if (message_) {
37 #if PERFETTO_DCHECK_IS_ON()
38     PERFETTO_DCHECK(generation_ == message_->generation_);
39 #endif
40     FinalizeMessage();
41   }
42 }
43 
MessageHandleBase(MessageHandleBase && other)44 MessageHandleBase::MessageHandleBase(MessageHandleBase&& other) noexcept {
45   Move(std::move(other));
46 }
47 
operator =(MessageHandleBase && other)48 MessageHandleBase& MessageHandleBase::operator=(MessageHandleBase&& other) {
49   // If the current handle was pointing to a message and is being reset to a new
50   // one, finalize the old message. However, if the other message is the same as
51   // the one we point to, don't finalize.
52   if (message_ && message_ != other.message_)
53     FinalizeMessage();
54   Move(std::move(other));
55   return *this;
56 }
57 
Move(MessageHandleBase && other)58 void MessageHandleBase::Move(MessageHandleBase&& other) {
59   message_ = other.message_;
60   other.message_ = nullptr;
61   listener_ = other.listener_;
62   other.listener_ = nullptr;
63 #if PERFETTO_DCHECK_IS_ON()
64   if (message_) {
65     generation_ = message_->generation_;
66     message_->set_handle(this);
67   }
68 #endif
69 }
70 
71 }  // namespace protozero
72