9b77e170099aacf96ec1b887f33eec0731f6d4ba
[folly.git] / folly / test / UtilityTest.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
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 <folly/Utility.h>
18
19 #include <folly/portability/GTest.h>
20
21 namespace {
22
23 class UtilityTest : public testing::Test {};
24 }
25
26 TEST_F(UtilityTest, copy) {
27   struct MyData {};
28   struct Worker {
29     size_t rrefs = 0, crefs = 0;
30     void something(MyData&&) {
31       ++rrefs;
32     }
33     void something(const MyData&) {
34       ++crefs;
35     }
36   };
37
38   MyData data;
39   Worker worker;
40   worker.something(folly::copy(data));
41   worker.something(std::move(data));
42   worker.something(data);
43   EXPECT_EQ(2, worker.rrefs);
44   EXPECT_EQ(1, worker.crefs);
45 }
46
47 TEST_F(UtilityTest, copy_noexcept_spec) {
48   struct MyNoexceptCopyable {};
49   MyNoexceptCopyable noe;
50   EXPECT_TRUE(noexcept(folly::copy(noe)));
51   EXPECT_TRUE(noexcept(folly::copy(std::move(noe))));
52
53   struct MyThrowingCopyable {
54     MyThrowingCopyable() {}
55     MyThrowingCopyable(const MyThrowingCopyable&) noexcept(false) {}
56     MyThrowingCopyable(MyThrowingCopyable&&) = default;
57   };
58   MyThrowingCopyable thr;
59   EXPECT_FALSE(noexcept(folly::copy(thr)));
60   EXPECT_TRUE(noexcept(folly::copy(std::move(thr)))); // note: does not copy
61 }
62
63 TEST_F(UtilityTest, as_const) {
64   struct S {
65     bool member() {
66       return false;
67     }
68     bool member() const {
69       return true;
70     }
71   };
72   S s;
73   EXPECT_FALSE(s.member());
74   EXPECT_TRUE(folly::as_const(s).member());
75   EXPECT_EQ(&s, &folly::as_const(s));
76   EXPECT_TRUE(noexcept(folly::as_const(s)));
77 }
78
79 TEST(FollyIntegerSequence, core) {
80   constexpr auto seq = folly::integer_sequence<int, 0, 3, 2>();
81   static_assert(seq.size() == 3, "");
82   EXPECT_EQ(3, seq.size());
83
84   auto seq2 = folly::index_sequence<0, 4, 3>();
85   EXPECT_EQ(3, seq2.size());
86
87   constexpr auto seq3 = folly::make_index_sequence<3>();
88   static_assert(seq3.size() == 3, "");
89   EXPECT_EQ(3, seq3.size());
90 }