1 /*
2 * Copyright (C) 2019 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/copyable_ptr.h"
18
19 #include "test/gtest_and_gmock.h"
20
21 namespace protozero {
22 namespace {
23
24 struct X {
25 X() = default;
26 X(const X&) = default;
27 X& operator=(const X&) = default;
~Xprotozero::__anonb78a4bc50111::X28 ~X() { val = -1; }
29
operator ==(const X & lhs,const X & rhs)30 friend bool operator==(const X& lhs, const X& rhs) {
31 return lhs.val == rhs.val;
32 }
33
34 // Deliberately unusual implementation.
operator !=(const X & lhs,const X & rhs)35 friend bool operator!=(const X& lhs, const X& rhs) {
36 return lhs.val == rhs.val * -1;
37 }
38
39 int val = 0;
40 };
41
TEST(CopyablePtrTest,CopyOperators)42 TEST(CopyablePtrTest, CopyOperators) {
43 CopyablePtr<X> p1;
44 p1->val = 1;
45 ASSERT_NE(p1.get(), nullptr);
46 ASSERT_EQ(&*p1, p1.get());
47
48 CopyablePtr<X> p2(p1);
49 EXPECT_NE(p1.get(), nullptr);
50 EXPECT_NE(p2.get(), nullptr);
51 EXPECT_NE(p1.get(), p2.get());
52
53 p2->val = 2;
54 EXPECT_EQ(p1->val, 1);
55 EXPECT_EQ(p2->val, 2);
56
57 {
58 CopyablePtr<X> p3;
59 p3 = p1;
60 EXPECT_EQ(p3->val, 1);
61
62 p3 = p2;
63 EXPECT_EQ(p3->val, 2);
64
65 p3->val = 3;
66 EXPECT_EQ(p3->val, 3);
67 }
68
69 EXPECT_EQ(p1->val, 1);
70 EXPECT_EQ(p2->val, 2);
71 }
72
TEST(CopyablePtrTest,MoveOperators)73 TEST(CopyablePtrTest, MoveOperators) {
74 CopyablePtr<X> p1;
75 p1->val = 1;
76
77 CopyablePtr<X> p2(std::move(p1));
78 EXPECT_EQ(p2->val, 1);
79
80 // The moved-from object needs to stay valid and non-null.
81 EXPECT_EQ(p1->val, 0);
82 {
83 CopyablePtr<X> p3;
84 p3->val = 3;
85 p1 = std::move(p3);
86 EXPECT_EQ(p1->val, 3);
87 EXPECT_EQ(p3->val, 0);
88 }
89 EXPECT_EQ(p1->val, 3);
90 }
91
TEST(CopyablePtrTest,DeepCompare)92 TEST(CopyablePtrTest, DeepCompare) {
93 CopyablePtr<X> p1;
94 p1->val = 1;
95
96 CopyablePtr<X> p2;
97 p2->val = 2;
98
99 CopyablePtr<X> p3;
100 p3->val = -2;
101
102 EXPECT_NE(p1.get(), p2.get());
103 EXPECT_NE(p1.get(), p3.get());
104
105 EXPECT_FALSE(p1 == p2);
106 EXPECT_FALSE(p1 == p3);
107 EXPECT_FALSE(p2 == p3);
108
109 EXPECT_FALSE(p1 != p2); // The operator!= is special, see above.
110 EXPECT_TRUE(p2 != p3);
111
112 p1->val = -2;
113 EXPECT_TRUE(p1 != p2);
114 EXPECT_FALSE(p1 == p2);
115 }
116
117 } // namespace
118 } // namespace protozero
119