1 //
2 // Tests for
3 //  void swap(safe_allocation& a, safe_allocation& b);
4 //
5 
6 #include <libkern/c++/safe_allocation.h>
7 #include <darwintest.h>
8 #include "test_utils.h"
9 
10 struct T {
11 	int i;
12 };
13 
14 template <typename T>
15 static void
16 tests()
17 {
18 	// Swap non-null with non-null
19 	{
20 		tracked_safe_allocation<T> a(10, libkern::allocate_memory);
21 		tracked_safe_allocation<T> b(20, libkern::allocate_memory);
22 		T* a_mem = a.data();
23 		T* b_mem = b.data();
24 		tracking_allocator::reset();
25 
26 		swap(a, b); // ADL call
27 
28 		CHECK(!tracking_allocator::did_allocate);
29 		CHECK(!tracking_allocator::did_deallocate);
30 		CHECK(a.data() == b_mem);
31 		CHECK(b.data() == a_mem);
32 		CHECK(a.size() == 20);
33 		CHECK(b.size() == 10);
34 	}
35 
36 	// Swap non-null with null
37 	{
38 		tracked_safe_allocation<T> a(10, libkern::allocate_memory);
39 		tracked_safe_allocation<T> b = nullptr;
40 		T* a_mem = a.data();
41 		tracking_allocator::reset();
42 
43 		swap(a, b); // ADL call
44 
45 		CHECK(!tracking_allocator::did_allocate);
46 		CHECK(!tracking_allocator::did_deallocate);
47 		CHECK(a.data() == nullptr);
48 		CHECK(b.data() == a_mem);
49 		CHECK(a.size() == 0);
50 		CHECK(b.size() == 10);
51 	}
52 
53 	// Swap null with non-null
54 	{
55 		tracked_safe_allocation<T> a = nullptr;
56 		tracked_safe_allocation<T> b(20, libkern::allocate_memory);
57 		T* b_mem = b.data();
58 		tracking_allocator::reset();
59 
60 		swap(a, b); // ADL call
61 
62 		CHECK(!tracking_allocator::did_allocate);
63 		CHECK(!tracking_allocator::did_deallocate);
64 		CHECK(a.data() == b_mem);
65 		CHECK(b.data() == nullptr);
66 		CHECK(a.size() == 20);
67 		CHECK(b.size() == 0);
68 	}
69 
70 	// Swap null with null
71 	{
72 		tracked_safe_allocation<T> a = nullptr;
73 		tracked_safe_allocation<T> b = nullptr;
74 		tracking_allocator::reset();
75 
76 		swap(a, b); // ADL call
77 
78 		CHECK(!tracking_allocator::did_allocate);
79 		CHECK(!tracking_allocator::did_deallocate);
80 		CHECK(a.data() == nullptr);
81 		CHECK(b.data() == nullptr);
82 		CHECK(a.size() == 0);
83 		CHECK(b.size() == 0);
84 	}
85 
86 	// Swap with self
87 	{
88 		tracked_safe_allocation<T> a(10, libkern::allocate_memory);
89 		T* a_mem = a.data();
90 		tracking_allocator::reset();
91 
92 		swap(a, a); // ADL call
93 
94 		CHECK(!tracking_allocator::did_allocate);
95 		CHECK(!tracking_allocator::did_deallocate);
96 		CHECK(a.data() == a_mem);
97 		CHECK(a.size() == 10);
98 	}
99 }
100 
101 T_DECL(swap, "safe_allocation.swap") {
102 	tests<T>();
103 	tests<T const>();
104 }
105