1 // Copyright 2017 PDFium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "core/fxcrt/unowned_ptr.h" 6 7 #include <utility> 8 #include <vector> 9 10 #include "testing/gtest/include/gtest/gtest.h" 11 12 namespace fxcrt { 13 namespace { 14 15 class Clink { 16 public: 17 UnownedPtr<Clink> next_ = nullptr; 18 }; 19 20 void DeleteDangling() { 21 Clink* ptr1 = new Clink(); 22 Clink* ptr2 = new Clink(); 23 ptr2->next_ = ptr1; 24 delete ptr1; 25 delete ptr2; 26 } 27 28 void AssignDangling() { 29 Clink* ptr1 = new Clink(); 30 Clink* ptr2 = new Clink(); 31 ptr2->next_ = ptr1; 32 delete ptr1; 33 ptr2->next_ = nullptr; 34 delete ptr2; 35 } 36 37 void ReleaseDangling() { 38 Clink* ptr1 = new Clink(); 39 Clink* ptr2 = new Clink(); 40 ptr2->next_ = ptr1; 41 delete ptr1; 42 ptr2->next_.Release(); 43 delete ptr2; 44 } 45 46 } // namespace 47 48 TEST(UnownedPtr, PtrOk) { 49 Clink* ptr1 = new Clink(); 50 Clink* ptr2 = new Clink(); 51 ptr2->next_ = ptr1; 52 delete ptr2; 53 delete ptr1; 54 } 55 56 TEST(UnownedPtr, PtrNotOk) { 57 #if defined(ADDRESS_SANITIZER) 58 EXPECT_DEATH(DeleteDangling(), ""); 59 #else 60 DeleteDangling(); 61 #endif 62 } 63 64 TEST(UnownedPtr, AssignOk) { 65 Clink* ptr1 = new Clink(); 66 Clink* ptr2 = new Clink(); 67 ptr2->next_ = ptr1; 68 ptr2->next_ = nullptr; 69 delete ptr2; 70 delete ptr1; 71 } 72 73 TEST(UnownedPtr, AssignNotOk) { 74 #if defined(ADDRESS_SANITIZER) 75 EXPECT_DEATH(AssignDangling(), ""); 76 #else 77 AssignDangling(); 78 #endif 79 } 80 81 TEST(UnownedPtr, ReleaseOk) { 82 Clink* ptr1 = new Clink(); 83 Clink* ptr2 = new Clink(); 84 ptr2->next_ = ptr1; 85 ptr2->next_.Release(); 86 delete ptr1; 87 delete ptr2; 88 } 89 90 TEST(UnownedPtr, ReleaseNotOk) { 91 #if defined(ADDRESS_SANITIZER) 92 EXPECT_DEATH(ReleaseDangling(), ""); 93 #else 94 ReleaseDangling(); 95 #endif 96 } 97 98 TEST(UnownedPtr, OperatorEQ) { 99 int foo; 100 UnownedPtr<int> ptr1; 101 EXPECT_TRUE(ptr1 == ptr1); 102 103 UnownedPtr<int> ptr2; 104 EXPECT_TRUE(ptr1 == ptr2); 105 106 UnownedPtr<int> ptr3(&foo); 107 EXPECT_TRUE(&foo == ptr3); 108 EXPECT_TRUE(ptr3 == &foo); 109 EXPECT_FALSE(ptr1 == ptr3); 110 111 ptr1 = &foo; 112 EXPECT_TRUE(ptr1 == ptr3); 113 } 114 115 TEST(UnownedPtr, OperatorNE) { 116 int foo; 117 UnownedPtr<int> ptr1; 118 EXPECT_FALSE(ptr1 != ptr1); 119 120 UnownedPtr<int> ptr2; 121 EXPECT_FALSE(ptr1 != ptr2); 122 123 UnownedPtr<int> ptr3(&foo); 124 EXPECT_FALSE(&foo != ptr3); 125 EXPECT_FALSE(ptr3 != &foo); 126 EXPECT_TRUE(ptr1 != ptr3); 127 128 ptr1 = &foo; 129 EXPECT_FALSE(ptr1 != ptr3); 130 } 131 132 TEST(UnownedPtr, OperatorLT) { 133 int foos[2]; 134 UnownedPtr<int> ptr1(&foos[0]); 135 UnownedPtr<int> ptr2(&foos[1]); 136 137 EXPECT_FALSE(ptr1 < ptr1); 138 EXPECT_TRUE(ptr1 < ptr2); 139 EXPECT_FALSE(ptr2 < ptr1); 140 } 141 142 } // namespace fxcrt 143