6ce239f450fc3af43132ca18472228aad09356d2
[folly.git] / folly / Memory.h
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 #ifndef FOLLY_MEMORY_H_
18 #define FOLLY_MEMORY_H_
19
20 #include "folly/Traits.h"
21
22 #include <memory>
23 #include <limits>
24 #include <utility>
25 #include <exception>
26 #include <stdexcept>
27
28 #include <cstddef>
29
30 namespace folly {
31
32 /**
33  * For exception safety and consistency with make_shared. Erase me when
34  * we have std::make_unique().
35  *
36  * @author Louis Brandy (ldbrandy@fb.com)
37  * @author Xu Ning (xning@fb.com)
38  */
39
40 template<typename T, typename Dp = std::default_delete<T>, typename... Args>
41 std::unique_ptr<T, Dp> make_unique(Args&&... args) {
42   return std::unique_ptr<T, Dp>(new T(std::forward<Args>(args)...));
43 }
44
45 /**
46  * Wrap a SimpleAllocator into a STL-compliant allocator.
47  *
48  * The SimpleAllocator must provide two methods:
49  *    void* allocate(size_t size);
50  *    void deallocate(void* ptr);
51  * which, respectively, allocate a block of size bytes (aligned to the maximum
52  * alignment required on your system), throwing std::bad_alloc if the
53  * allocation can't be satisfied, and free a previously allocated block.
54  *
55  * Note that the following allocator resembles the standard allocator
56  * quite well:
57  *
58  * class MallocAllocator {
59  *  public:
60  *   void* allocate(size_t size) {
61  *     void* p = malloc(size);
62  *     if (!p) throw std::bad_alloc();
63  *     return p;
64  *   }
65  *   void deallocate(void* p) {
66  *     free(p);
67  *   }
68  * };
69  *
70  * author: Tudor Bosman <tudorb@fb.com>
71  */
72
73 // This would be so much simpler with std::allocator_traits, but gcc 4.6.2
74 // doesn't support it
75 template <class Alloc, class T> class StlAllocator;
76
77 template <class Alloc> class StlAllocator<Alloc, void> {
78  public:
79   typedef void value_type;
80   typedef void* pointer;
81   typedef const void* const_pointer;
82
83   StlAllocator() : alloc_(nullptr) { }
84   explicit StlAllocator(Alloc* alloc) : alloc_(alloc) { }
85
86   Alloc* alloc() const {
87     return alloc_;
88   }
89
90   template <class U> struct rebind {
91     typedef StlAllocator<Alloc, U> other;
92   };
93
94   bool operator!=(const StlAllocator<Alloc, void>& other) const {
95     return alloc_ != other.alloc_;
96   }
97
98   bool operator==(const StlAllocator<Alloc, void>& other) const {
99     return alloc_ == other.alloc_;
100   }
101
102  private:
103   Alloc* alloc_;
104 };
105
106 template <class Alloc, class T>
107 class StlAllocator {
108  public:
109   typedef T value_type;
110   typedef T* pointer;
111   typedef const T* const_pointer;
112   typedef T& reference;
113   typedef const T& const_reference;
114
115   typedef ptrdiff_t difference_type;
116   typedef size_t size_type;
117
118   StlAllocator() : alloc_(nullptr) { }
119   explicit StlAllocator(Alloc* alloc) : alloc_(alloc) { }
120
121   template <class U> StlAllocator(const StlAllocator<Alloc, U>& other)
122     : alloc_(other.alloc()) { }
123
124   T* allocate(size_t n, const void* hint = nullptr) {
125     return static_cast<T*>(alloc_->allocate(n * sizeof(T)));
126   }
127
128   void deallocate(T* p, size_t n) {
129     alloc_->deallocate(p);
130   }
131
132   size_t max_size() const {
133     return std::numeric_limits<size_t>::max();
134   }
135
136   T* address(T& x) const {
137     return std::addressof(x);
138   }
139
140   const T* address(const T& x) const {
141     return std::addressof(x);
142   }
143
144   template <class... Args>
145   void construct(T* p, Args&&... args) {
146     new (p) T(std::forward<Args>(args)...);
147   }
148
149   void destroy(T* p) {
150     p->~T();
151   }
152
153   Alloc* alloc() const {
154     return alloc_;
155   }
156
157   template <class U> struct rebind {
158     typedef StlAllocator<Alloc, U> other;
159   };
160
161   bool operator!=(const StlAllocator<Alloc, T>& other) const {
162     return alloc_ != other.alloc_;
163   }
164
165   bool operator==(const StlAllocator<Alloc, T>& other) const {
166     return alloc_ == other.alloc_;
167   }
168
169  private:
170   Alloc* alloc_;
171 };
172
173 /**
174  * Helper function to obtain rebound allocators
175  *
176  * @author: Marcelo Juchem <marcelo@fb.com>
177  */
178 template <typename T, typename Allocator>
179 typename Allocator::template rebind<T>::other rebind_allocator(
180   Allocator const &allocator
181 ) {
182   return typename Allocator::template rebind<T>::other(allocator);
183 }
184
185 /*
186  * Helper classes/functions for creating a unique_ptr using a custom allocator
187  *
188  * @author: Marcelo Juchem <marcelo@fb.com>
189  */
190
191 // A deleter implementation based on std::default_delete,
192 // which uses a custom allocator to free memory
193 template <typename Allocator>
194 class allocator_delete {
195   typedef typename std::remove_reference<Allocator>::type allocator_type;
196
197 public:
198   allocator_delete() = default;
199
200   explicit allocator_delete(const allocator_type& allocator):
201     allocator_(allocator)
202   {}
203
204   explicit allocator_delete(allocator_type&& allocator):
205     allocator_(std::move(allocator))
206   {}
207
208   template <typename U>
209   allocator_delete(const allocator_delete<U>& other):
210     allocator_(other.get_allocator())
211   {}
212
213   allocator_type& get_allocator() const {
214     return allocator_;
215   }
216
217   void operator()(typename allocator_type::pointer p) const {
218     if (!p) {
219       return;
220     }
221
222     allocator_.destroy(p);
223     allocator_.deallocate(p, 1);
224   }
225
226 private:
227   mutable allocator_type allocator_;
228 };
229
230 template <typename T, typename Allocator>
231 class is_simple_allocator {
232   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_destroy, destroy);
233
234   typedef typename std::remove_const<
235     typename std::remove_reference<Allocator>::type
236   >::type allocator;
237   typedef typename std::remove_reference<T>::type value_type;
238   typedef value_type* pointer;
239
240 public:
241   constexpr static bool value = !has_destroy<allocator, void(pointer)>::value
242     && !has_destroy<allocator, void(void*)>::value;
243 };
244
245 template <typename T, typename Allocator>
246 struct as_stl_allocator {
247   typedef typename std::conditional<
248     is_simple_allocator<T, Allocator>::value,
249     folly::StlAllocator<
250       typename std::remove_reference<Allocator>::type,
251       typename std::remove_reference<T>::type
252     >,
253     typename std::remove_reference<Allocator>::type
254   >::type type;
255 };
256
257 template <typename T, typename Allocator>
258 typename std::enable_if<
259   is_simple_allocator<T, Allocator>::value,
260   folly::StlAllocator<
261     typename std::remove_reference<Allocator>::type,
262     typename std::remove_reference<T>::type
263   >
264 >::type make_stl_allocator(Allocator&& allocator) {
265   return folly::StlAllocator<
266     typename std::remove_reference<Allocator>::type,
267     typename std::remove_reference<T>::type
268   >(&allocator);
269 }
270
271 template <typename T, typename Allocator>
272 typename std::enable_if<
273   !is_simple_allocator<T, Allocator>::value,
274   typename std::remove_reference<Allocator>::type
275 >::type make_stl_allocator(Allocator&& allocator) {
276   return std::move(allocator);
277 }
278
279 /**
280  * AllocatorUniquePtr: a unique_ptr that supports both STL-style
281  * allocators and SimpleAllocator
282  *
283  * @author: Marcelo Juchem <marcelo@fb.com>
284  */
285
286 template <typename T, typename Allocator>
287 struct AllocatorUniquePtr {
288   typedef std::unique_ptr<T,
289     folly::allocator_delete<
290       typename std::conditional<
291         is_simple_allocator<T, Allocator>::value,
292         folly::StlAllocator<typename std::remove_reference<Allocator>::type, T>,
293         typename std::remove_reference<Allocator>::type
294       >::type
295     >
296   > type;
297 };
298
299 /**
300  * Functions to allocate a unique_ptr / shared_ptr, supporting both
301  * STL-style allocators and SimpleAllocator, analog to std::allocate_shared
302  *
303  * @author: Marcelo Juchem <marcelo@fb.com>
304  */
305
306 template <typename T, typename Allocator, typename ...Args>
307 typename AllocatorUniquePtr<T, Allocator>::type allocate_unique(
308   Allocator&& allocator, Args&&... args
309 ) {
310   auto stlAllocator = folly::make_stl_allocator<T>(
311     std::forward<Allocator>(allocator)
312   );
313   auto p = stlAllocator.allocate(1);
314
315   try {
316     stlAllocator.construct(p, std::forward<Args>(args)...);
317
318     return {p,
319       folly::allocator_delete<decltype(stlAllocator)>(std::move(stlAllocator))
320     };
321   } catch (...) {
322     stlAllocator.deallocate(p, 1);
323     throw;
324   }
325 }
326
327 template <typename T, typename Allocator, typename ...Args>
328 std::shared_ptr<T> allocate_shared(Allocator&& allocator, Args&&... args) {
329   return std::allocate_shared<T>(
330     folly::make_stl_allocator<T>(std::forward<Allocator>(allocator)),
331     std::forward<Args>(args)...
332   );
333 }
334
335 }  // namespace folly
336
337 #endif /* FOLLY_MEMORY_H_ */