6397a0b9617ff25eefd28a9fb6f4d4982e419529
[folly.git] / folly / test / MemoryTest.cpp
1 /*
2  * Copyright 2013 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/Memory.h"
18 #include "folly/Arena.h"
19 #include "folly/String.h"
20
21 #include <glog/logging.h>
22 #include <gtest/gtest.h>
23
24 #include <type_traits>
25
26 using namespace folly;
27
28 template <std::size_t> struct T {};
29 template <std::size_t> struct S {};
30 template <std::size_t> struct P {};
31
32 TEST(as_stl_allocator, sanity_check) {
33   typedef StlAllocator<SysArena, int> stl_arena_alloc;
34
35   EXPECT_TRUE((std::is_same<
36     as_stl_allocator<int, SysArena>::type,
37     stl_arena_alloc
38   >::value));
39
40   EXPECT_TRUE((std::is_same<
41     as_stl_allocator<int, stl_arena_alloc>::type,
42     stl_arena_alloc
43   >::value));
44 }
45
46 TEST(StlAllocator, void_allocator) {
47   typedef StlAllocator<SysArena, void> void_allocator;
48   SysArena arena;
49   void_allocator valloc(&arena);
50
51   typedef void_allocator::rebind<int>::other int_allocator;
52   int_allocator ialloc(valloc);
53
54   auto i = std::allocate_shared<int>(ialloc, 10);
55   ASSERT_NE(nullptr, i.get());
56   EXPECT_EQ(10, *i);
57   i.reset();
58   ASSERT_EQ(nullptr, i.get());
59 }
60
61 TEST(rebind_allocator, sanity_check) {
62   std::allocator<long> alloc;
63
64   auto i = std::allocate_shared<int>(
65     rebind_allocator<int, decltype(alloc)>(alloc), 10
66   );
67   ASSERT_NE(nullptr, i.get());
68   EXPECT_EQ(10, *i);
69   i.reset();
70   ASSERT_EQ(nullptr, i.get());
71
72   auto d = std::allocate_shared<double>(
73     rebind_allocator<double>(alloc), 5.6
74   );
75   ASSERT_NE(nullptr, d.get());
76   EXPECT_EQ(5.6, *d);
77   d.reset();
78   ASSERT_EQ(nullptr, d.get());
79
80   auto s = std::allocate_shared<std::string>(
81     rebind_allocator<std::string>(alloc), "HELLO, WORLD"
82   );
83   ASSERT_NE(nullptr, s.get());
84   EXPECT_EQ("HELLO, WORLD", *s);
85   s.reset();
86   ASSERT_EQ(nullptr, s.get());
87 }
88
89 int main(int argc, char **argv) {
90   FLAGS_logtostderr = true;
91   google::InitGoogleLogging(argv[0]);
92   testing::InitGoogleTest(&argc, argv);
93
94   return RUN_ALL_TESTS();
95 }