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 
MessageHandleBase(Message * message)25 MessageHandleBase::MessageHandleBase(Message* message) : message_(message) {
26 #if PERFETTO_DCHECK_IS_ON()
27   generation_ = message_ ? message->generation_ : 0;
28   if (message_)
29     message_->set_handle(this);
30 #endif
31 }
32 
~MessageHandleBase()33 MessageHandleBase::~MessageHandleBase() {
34   if (message_) {
35 #if PERFETTO_DCHECK_IS_ON()
36     PERFETTO_DCHECK(generation_ == message_->generation_);
37 #endif
38     FinalizeMessage();
39   }
40 }
41 
MessageHandleBase(MessageHandleBase && other)42 MessageHandleBase::MessageHandleBase(MessageHandleBase&& other) noexcept {
43   Move(std::move(other));
44 }
45 
operator =(MessageHandleBase && other)46 MessageHandleBase& MessageHandleBase::operator=(MessageHandleBase&& other) {
47   // If the current handle was pointing to a message and is being reset to a new
48   // one, finalize the old message. However, if the other message is the same as
49   // the one we point to, don't finalize.
50   if (message_ && message_ != other.message_)
51     FinalizeMessage();
52   Move(std::move(other));
53   return *this;
54 }
55 
Move(MessageHandleBase && other)56 void MessageHandleBase::Move(MessageHandleBase&& other) {
57   message_ = other.message_;
58   other.message_ = nullptr;
59 #if PERFETTO_DCHECK_IS_ON()
60   if (message_) {
61     generation_ = message_->generation_;
62     message_->set_handle(this);
63   }
64 #endif
65 }
66 
67 }  // namespace protozero
68