1 #include "gtest/gtest.h"
2
3 #include "chre/util/unique_ptr.h"
4
5 using chre::UniquePtr;
6 using chre::MakeUnique;
7
8 struct Value {
ValueValue9 Value(int value) : value(value) {
10 constructionCounter++;
11 }
12
~ValueValue13 ~Value() {
14 constructionCounter--;
15 }
16
operator =Value17 Value& operator=(Value&& other) {
18 value = other.value;
19 return *this;
20 }
21
22 int value;
23 static int constructionCounter;
24 };
25
26 int Value::constructionCounter = 0;
27
TEST(UniquePtr,Construct)28 TEST(UniquePtr, Construct) {
29 UniquePtr<Value> myInt = MakeUnique<Value>(0xcafe);
30 ASSERT_FALSE(myInt.isNull());
31 EXPECT_EQ(myInt.get()->value, 0xcafe);
32 EXPECT_EQ(myInt->value, 0xcafe);
33 EXPECT_EQ((*myInt).value, 0xcafe);
34 EXPECT_EQ(myInt[0].value, 0xcafe);
35 }
36
TEST(UniquePtr,MoveConstruct)37 TEST(UniquePtr, MoveConstruct) {
38 UniquePtr<Value> myInt = MakeUnique<Value>(0xcafe);
39 ASSERT_FALSE(myInt.isNull());
40 Value *value = myInt.get();
41
42 UniquePtr<Value> moved(std::move(myInt));
43 EXPECT_EQ(moved.get(), value);
44 EXPECT_EQ(myInt.get(), nullptr);
45 }
46
TEST(UniquePtr,Move)47 TEST(UniquePtr, Move) {
48 Value::constructionCounter = 0;
49
50 {
51 UniquePtr<Value> myInt = MakeUnique<Value>(0xcafe);
52 ASSERT_FALSE(myInt.isNull());
53 EXPECT_EQ(Value::constructionCounter, 1);
54
55 UniquePtr<Value> myMovedInt = MakeUnique<Value>(0);
56 ASSERT_FALSE(myMovedInt.isNull());
57 EXPECT_EQ(Value::constructionCounter, 2);
58 myMovedInt = std::move(myInt);
59 ASSERT_FALSE(myMovedInt.isNull());
60 ASSERT_TRUE(myInt.isNull());
61 EXPECT_EQ(myMovedInt.get()->value, 0xcafe);
62 }
63
64 EXPECT_EQ(Value::constructionCounter, 0);
65 }
66
TEST(UniquePtr,Release)67 TEST(UniquePtr, Release) {
68 Value::constructionCounter = 0;
69
70 Value *value1, *value2;
71 {
72 UniquePtr<Value> myInt = MakeUnique<Value>(0xcafe);
73 ASSERT_FALSE(myInt.isNull());
74 EXPECT_EQ(Value::constructionCounter, 1);
75 value1 = myInt.get();
76 EXPECT_NE(value1, nullptr);
77 value2 = myInt.release();
78 EXPECT_EQ(value1, value2);
79 EXPECT_EQ(myInt.get(), nullptr);
80 EXPECT_TRUE(myInt.isNull());
81 }
82
83 EXPECT_EQ(Value::constructionCounter, 1);
84 EXPECT_EQ(value2->value, 0xcafe);
85 value2->~Value();
86 chre::memoryFree(value2);
87 }
88