1 // Copyright 2016 The Fuchsia 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 <fbl/intrusive_container_utils.h>
6 #include <fbl/tests/intrusive_containers/objects.h>
7 #include <unittest/unittest.h>
8 
9 namespace fbl {
10 namespace tests {
11 namespace intrusive_containers {
12 
13 size_t TestObjBase::live_obj_count_ = 0;
14 
15 template <typename T>
swap_test(const T initial_a,const T initial_b)16 bool swap_test(const T initial_a, const T initial_b) {
17     BEGIN_HELPER;
18 
19     // Starting A and B need to be different in order for us to know that swap
20     // worked.
21     EXPECT_NE(::memcmp(&initial_a, &initial_b, sizeof(T)), 0);
22 
23     T a = initial_a;
24     T b = initial_b;
25     ::fbl::internal::Swap(a, b);
26 
27     EXPECT_EQ(::memcmp(&a, &initial_b, sizeof(T)), 0);
28     EXPECT_EQ(::memcmp(&b, &initial_a, sizeof(T)), 0);
29 
30     END_HELPER;
31 }
32 
swap_test()33 bool swap_test() {
34     BEGIN_TEST;
35 
36     struct SimpleSmallStruct { uint8_t a, b; };
37     struct SimpleBigStruct   { uint32_t a, b; };
38     struct SimpleHugeStruct  { uint64_t a, b; };
39 
40     EXPECT_TRUE(swap_test<char>('a', 'b'));
41     EXPECT_TRUE(swap_test<int8_t>(-5, 10));
42     EXPECT_TRUE(swap_test<uint8_t>(5, 10));
43     EXPECT_TRUE(swap_test<int16_t>(-12345, 12345));
44     EXPECT_TRUE(swap_test<uint16_t>(12345, 54321));
45     EXPECT_TRUE(swap_test<int32_t>(-1234567890, 123456789));
46     EXPECT_TRUE(swap_test<uint32_t>(1234567890, 987654321));
47     EXPECT_TRUE(swap_test<int64_t>(-12345678901234567, 12345678901234567));
48     EXPECT_TRUE(swap_test<uint64_t>(12345678901234567, 98765432109876543));
49     EXPECT_TRUE(swap_test<float>(-0.1234567f, 0.7654321f));
50     EXPECT_TRUE(swap_test<double>(-0.12345678901234567890, 0.98765432109876543210));
51     EXPECT_TRUE(swap_test<SimpleSmallStruct>({ 5, 4 }, { 2, 9 }));
52     EXPECT_TRUE(swap_test<SimpleBigStruct>({ 5, 4 }, { 2, 9 }));
53 #if TEST_WILL_NOT_COMPILE || 0
54     EXPECT_TRUE(swap_test<SimpleHugeStruct>({ 5, 4 }, { 2, 9 }));
55 #endif
56 
57     SimpleBigStruct a = {};
58     SimpleBigStruct b = {};
59     EXPECT_TRUE(swap_test<void*>(&a, &b));
60     EXPECT_TRUE(swap_test<SimpleBigStruct*>(&a, &b));
61 
62     END_TEST;
63 }
64 
65 
66 BEGIN_TEST_CASE(container_utils_tests)
67 RUN_NAMED_TEST("swap test", swap_test)
68 END_TEST_CASE(container_utils_tests)
69 
70 }  // namespace intrusive_containers
71 }  // namespace tests
72 }  // namespace fbl
73