fix gcc-5 build
[folly.git] / folly / Memory.h
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 #pragma once
18
19 #include <folly/Traits.h>
20
21 #include <cstddef>
22 #include <cstdlib>
23 #include <exception>
24 #include <limits>
25 #include <memory>
26 #include <stdexcept>
27 #include <utility>
28
29 namespace folly {
30
31 /**
32  * For exception safety and consistency with make_shared. Erase me when
33  * we have std::make_unique().
34  *
35  * @author Louis Brandy (ldbrandy@fb.com)
36  * @author Xu Ning (xning@fb.com)
37  */
38
39 #if __cplusplus >= 201402L ||                                              \
40     (defined __cpp_lib_make_unique && __cpp_lib_make_unique >= 201304L) || \
41     (defined __ANDROID__ && __cplusplus >= 201300L) ||                     \
42     (defined(_MSC_VER) && _MSC_VER >= 1900)
43
44 /* using override */ using std::make_unique;
45
46 #else
47
48 template<typename T, typename... Args>
49 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
50 make_unique(Args&&... args) {
51   return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
52 }
53
54 // Allows 'make_unique<T[]>(10)'. (N3690 s20.9.1.4 p3-4)
55 template<typename T>
56 typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
57 make_unique(const size_t n) {
58   return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
59 }
60
61 // Disallows 'make_unique<T[10]>()'. (N3690 s20.9.1.4 p5)
62 template<typename T, typename... Args>
63 typename std::enable_if<
64   std::extent<T>::value != 0, std::unique_ptr<T>>::type
65 make_unique(Args&&...) = delete;
66
67 #endif
68
69 /**
70  * static_function_deleter
71  *
72  * So you can write this:
73  *
74  *      using RSA_deleter = folly::static_function_deleter<RSA, &RSA_free>;
75  *      auto rsa = std::unique_ptr<RSA, RSA_deleter>(RSA_new());
76  *      RSA_generate_key_ex(rsa.get(), bits, exponent, nullptr);
77  *      rsa = nullptr;  // calls RSA_free(rsa.get())
78  *
79  * This would be sweet as well for BIO, but unfortunately BIO_free has signature
80  * int(BIO*) while we require signature void(BIO*). So you would need to make a
81  * wrapper for it:
82  *
83  *      inline void BIO_free_fb(BIO* bio) { CHECK_EQ(1, BIO_free(bio)); }
84  *      using BIO_deleter = folly::static_function_deleter<BIO, &BIO_free_fb>;
85  *      auto buf = std::unique_ptr<BIO, BIO_deleter>(BIO_new(BIO_s_mem()));
86  *      buf = nullptr;  // calls BIO_free(buf.get())
87  */
88
89 template <typename T, void(*f)(T*)>
90 struct static_function_deleter {
91   void operator()(T* t) const {
92     f(t);
93   }
94 };
95
96 /**
97  *  to_shared_ptr
98  *
99  *  Convert unique_ptr to shared_ptr without specifying the template type
100  *  parameter and letting the compiler deduce it.
101  *
102  *  So you can write this:
103  *
104  *      auto sptr = to_shared_ptr(getSomethingUnique<T>());
105  *
106  *  Instead of this:
107  *
108  *      auto sptr = shared_ptr<T>(getSomethingUnique<T>());
109  *
110  *  Useful when `T` is long, such as:
111  *
112  *      using T = foobar::FooBarAsyncClient;
113  */
114 template <typename T, typename D>
115 std::shared_ptr<T> to_shared_ptr(std::unique_ptr<T, D>&& ptr) {
116   return std::shared_ptr<T>(std::move(ptr));
117 }
118
119 /**
120  *  to_weak_ptr
121  *
122  *  Make a weak_ptr and return it from a shared_ptr without specifying the
123  *  template type parameter and letting the compiler deduce it.
124  *
125  *  So you can write this:
126  *
127  *      auto wptr = to_weak_ptr(getSomethingShared<T>());
128  *
129  *  Instead of this:
130  *
131  *      auto wptr = weak_ptr<T>(getSomethingShared<T>());
132  *
133  *  Useful when `T` is long, such as:
134  *
135  *      using T = foobar::FooBarAsyncClient;
136  */
137 template <typename T>
138 std::weak_ptr<T> to_weak_ptr(const std::shared_ptr<T>& ptr) {
139   return std::weak_ptr<T>(ptr);
140 }
141
142 using SysBufferDeleter = static_function_deleter<void, ::free>;
143 using SysBufferUniquePtr = std::unique_ptr<void, SysBufferDeleter>;
144 inline SysBufferUniquePtr allocate_sys_buffer(size_t size) {
145   return SysBufferUniquePtr(::malloc(size));
146 }
147
148 /**
149  * A SimpleAllocator must provide two methods:
150  *
151  *    void* allocate(size_t size);
152  *    void deallocate(void* ptr);
153  *
154  * which, respectively, allocate a block of size bytes (aligned to the
155  * maximum alignment required on your system), throwing std::bad_alloc
156  * if the allocation can't be satisfied, and free a previously
157  * allocated block.
158  *
159  * SysAlloc resembles the standard allocator.
160  */
161 class SysAlloc {
162  public:
163   void* allocate(size_t size) {
164     void* p = ::malloc(size);
165     if (!p) throw std::bad_alloc();
166     return p;
167   }
168   void deallocate(void* p) {
169     ::free(p);
170   }
171 };
172
173 /**
174  * StlAllocator wraps a SimpleAllocator into a STL-compliant
175  * allocator, maintaining an instance pointer to the simple allocator
176  * object.  The underlying SimpleAllocator object must outlive all
177  * instances of StlAllocator using it.
178  *
179  * But note that if you pass StlAllocator<MallocAllocator,...> to a
180  * standard container it will be larger due to the contained state
181  * pointer.
182  *
183  * @author: Tudor Bosman <tudorb@fb.com>
184  */
185
186 // This would be so much simpler with std::allocator_traits, but gcc 4.6.2
187 // doesn't support it.
188 template <class Alloc, class T> class StlAllocator;
189
190 template <class Alloc> class StlAllocator<Alloc, void> {
191  public:
192   typedef void value_type;
193   typedef void* pointer;
194   typedef const void* const_pointer;
195
196   StlAllocator() : alloc_(nullptr) { }
197   explicit StlAllocator(Alloc* a) : alloc_(a) { }
198
199   Alloc* alloc() const {
200     return alloc_;
201   }
202
203   template <class U> struct rebind {
204     typedef StlAllocator<Alloc, U> other;
205   };
206
207   bool operator!=(const StlAllocator<Alloc, void>& other) const {
208     return alloc_ != other.alloc_;
209   }
210
211   bool operator==(const StlAllocator<Alloc, void>& other) const {
212     return alloc_ == other.alloc_;
213   }
214
215  private:
216   Alloc* alloc_;
217 };
218
219 template <class Alloc, class T>
220 class StlAllocator {
221  public:
222   typedef T value_type;
223   typedef T* pointer;
224   typedef const T* const_pointer;
225   typedef T& reference;
226   typedef const T& const_reference;
227
228   typedef ptrdiff_t difference_type;
229   typedef size_t size_type;
230
231   StlAllocator() : alloc_(nullptr) { }
232   explicit StlAllocator(Alloc* a) : alloc_(a) { }
233
234   template <class U> StlAllocator(const StlAllocator<Alloc, U>& other)
235     : alloc_(other.alloc()) { }
236
237   T* allocate(size_t n, const void* /* hint */ = nullptr) {
238     return static_cast<T*>(alloc_->allocate(n * sizeof(T)));
239   }
240
241   void deallocate(T* p, size_t /* n */) { alloc_->deallocate(p); }
242
243   size_t max_size() const {
244     return std::numeric_limits<size_t>::max();
245   }
246
247   T* address(T& x) const {
248     return std::addressof(x);
249   }
250
251   const T* address(const T& x) const {
252     return std::addressof(x);
253   }
254
255   template <class... Args>
256   void construct(T* p, Args&&... args) {
257     new (p) T(std::forward<Args>(args)...);
258   }
259
260   void destroy(T* p) {
261     p->~T();
262   }
263
264   Alloc* alloc() const {
265     return alloc_;
266   }
267
268   template <class U> struct rebind {
269     typedef StlAllocator<Alloc, U> other;
270   };
271
272   bool operator!=(const StlAllocator<Alloc, T>& other) const {
273     return alloc_ != other.alloc_;
274   }
275
276   bool operator==(const StlAllocator<Alloc, T>& other) const {
277     return alloc_ == other.alloc_;
278   }
279
280  private:
281   Alloc* alloc_;
282 };
283
284 /**
285  * Helper function to obtain rebound allocators
286  *
287  * @author: Marcelo Juchem <marcelo@fb.com>
288  */
289 template <typename T, typename Allocator>
290 typename Allocator::template rebind<T>::other rebind_allocator(
291   Allocator const& allocator
292 ) {
293   return typename Allocator::template rebind<T>::other(allocator);
294 }
295
296 /*
297  * Helper classes/functions for creating a unique_ptr using a custom
298  * allocator.
299  *
300  * @author: Marcelo Juchem <marcelo@fb.com>
301  */
302
303 // Derives from the allocator to take advantage of the empty base
304 // optimization when possible.
305 template <typename Allocator>
306 class allocator_delete
307   : private std::remove_reference<Allocator>::type
308 {
309   typedef typename std::remove_reference<Allocator>::type allocator_type;
310
311 public:
312   typedef typename Allocator::pointer pointer;
313
314   allocator_delete() = default;
315
316   explicit allocator_delete(const allocator_type& allocator)
317     : allocator_type(allocator)
318   {}
319
320   explicit allocator_delete(allocator_type&& allocator)
321     : allocator_type(std::move(allocator))
322   {}
323
324   template <typename U>
325   allocator_delete(const allocator_delete<U>& other)
326     : allocator_type(other.get_allocator())
327   {}
328
329   allocator_type& get_allocator() const {
330     return *const_cast<allocator_delete*>(this);
331   }
332
333   void operator()(pointer p) const {
334     if (!p) return;
335     const_cast<allocator_delete*>(this)->destroy(p);
336     const_cast<allocator_delete*>(this)->deallocate(p, 1);
337   }
338 };
339
340 template <typename T, typename Allocator>
341 class is_simple_allocator {
342   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_destroy, destroy);
343
344   typedef typename std::remove_const<
345     typename std::remove_reference<Allocator>::type
346   >::type allocator;
347   typedef typename std::remove_reference<T>::type value_type;
348   typedef value_type* pointer;
349
350 public:
351   constexpr static bool value = !has_destroy<allocator, void(pointer)>::value
352     && !has_destroy<allocator, void(void*)>::value;
353 };
354
355 template <typename T, typename Allocator>
356 struct as_stl_allocator {
357   typedef typename std::conditional<
358     is_simple_allocator<T, Allocator>::value,
359     folly::StlAllocator<
360       typename std::remove_reference<Allocator>::type,
361       typename std::remove_reference<T>::type
362     >,
363     typename std::remove_reference<Allocator>::type
364   >::type type;
365 };
366
367 template <typename T, typename Allocator>
368 typename std::enable_if<
369   is_simple_allocator<T, Allocator>::value,
370   folly::StlAllocator<
371     typename std::remove_reference<Allocator>::type,
372     typename std::remove_reference<T>::type
373   >
374 >::type make_stl_allocator(Allocator&& allocator) {
375   return folly::StlAllocator<
376     typename std::remove_reference<Allocator>::type,
377     typename std::remove_reference<T>::type
378   >(&allocator);
379 }
380
381 template <typename T, typename Allocator>
382 typename std::enable_if<
383   !is_simple_allocator<T, Allocator>::value,
384   typename std::remove_reference<Allocator>::type
385 >::type make_stl_allocator(Allocator&& allocator) {
386   return std::move(allocator);
387 }
388
389 /**
390  * AllocatorUniquePtr: a unique_ptr that supports both STL-style
391  * allocators and SimpleAllocator
392  *
393  * @author: Marcelo Juchem <marcelo@fb.com>
394  */
395
396 template <typename T, typename Allocator>
397 struct AllocatorUniquePtr {
398   typedef std::unique_ptr<T,
399     folly::allocator_delete<
400       typename std::conditional<
401         is_simple_allocator<T, Allocator>::value,
402         folly::StlAllocator<typename std::remove_reference<Allocator>::type, T>,
403         typename std::remove_reference<Allocator>::type
404       >::type
405     >
406   > type;
407 };
408
409 /**
410  * Functions to allocate a unique_ptr / shared_ptr, supporting both
411  * STL-style allocators and SimpleAllocator, analog to std::allocate_shared
412  *
413  * @author: Marcelo Juchem <marcelo@fb.com>
414  */
415
416 template <typename T, typename Allocator, typename ...Args>
417 typename AllocatorUniquePtr<T, Allocator>::type allocate_unique(
418   Allocator&& allocator, Args&&... args
419 ) {
420   auto stlAllocator = folly::make_stl_allocator<T>(
421     std::forward<Allocator>(allocator)
422   );
423   auto p = stlAllocator.allocate(1);
424
425   try {
426     stlAllocator.construct(p, std::forward<Args>(args)...);
427
428     return {p,
429       folly::allocator_delete<decltype(stlAllocator)>(std::move(stlAllocator))
430     };
431   } catch (...) {
432     stlAllocator.deallocate(p, 1);
433     throw;
434   }
435 }
436
437 template <typename T, typename Allocator, typename ...Args>
438 std::shared_ptr<T> allocate_shared(Allocator&& allocator, Args&&... args) {
439   return std::allocate_shared<T>(
440     folly::make_stl_allocator<T>(std::forward<Allocator>(allocator)),
441     std::forward<Args>(args)...
442   );
443 }
444
445 /**
446  * IsArenaAllocator<T>::value describes whether SimpleAllocator has
447  * no-op deallocate().
448  */
449 template <class T> struct IsArenaAllocator : std::false_type { };
450
451 }  // namespace folly