Fix the last issues with exception_wrapper under MSVC
[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 || __cpp_lib_make_unique >= 201304L || \
40     (__ANDROID__ && __cplusplus >= 201300L) || _MSC_VER >= 1900
41
42 /* using override */ using std::make_unique;
43
44 #else
45
46 template<typename T, typename... Args>
47 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
48 make_unique(Args&&... args) {
49   return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
50 }
51
52 // Allows 'make_unique<T[]>(10)'. (N3690 s20.9.1.4 p3-4)
53 template<typename T>
54 typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
55 make_unique(const size_t n) {
56   return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
57 }
58
59 // Disallows 'make_unique<T[10]>()'. (N3690 s20.9.1.4 p5)
60 template<typename T, typename... Args>
61 typename std::enable_if<
62   std::extent<T>::value != 0, std::unique_ptr<T>>::type
63 make_unique(Args&&...) = delete;
64
65 #endif
66
67 /**
68  * static_function_deleter
69  *
70  * So you can write this:
71  *
72  *      using RSA_deleter = folly::static_function_deleter<RSA, &RSA_free>;
73  *      auto rsa = std::unique_ptr<RSA, RSA_deleter>(RSA_new());
74  *      RSA_generate_key_ex(rsa.get(), bits, exponent, nullptr);
75  *      rsa = nullptr;  // calls RSA_free(rsa.get())
76  *
77  * This would be sweet as well for BIO, but unfortunately BIO_free has signature
78  * int(BIO*) while we require signature void(BIO*). So you would need to make a
79  * wrapper for it:
80  *
81  *      inline void BIO_free_fb(BIO* bio) { CHECK_EQ(1, BIO_free(bio)); }
82  *      using BIO_deleter = folly::static_function_deleter<BIO, &BIO_free_fb>;
83  *      auto buf = std::unique_ptr<BIO, BIO_deleter>(BIO_new(BIO_s_mem()));
84  *      buf = nullptr;  // calls BIO_free(buf.get())
85  */
86
87 template <typename T, void(*f)(T*)>
88 struct static_function_deleter {
89   void operator()(T* t) const {
90     f(t);
91   }
92 };
93
94 /**
95  *  to_shared_ptr
96  *
97  *  Convert unique_ptr to shared_ptr without specifying the template type
98  *  parameter and letting the compiler deduce it.
99  *
100  *  So you can write this:
101  *
102  *      auto sptr = to_shared_ptr(getSomethingUnique<T>());
103  *
104  *  Instead of this:
105  *
106  *      auto sptr = shared_ptr<T>(getSomethingUnique<T>());
107  *
108  *  Useful when `T` is long, such as:
109  *
110  *      using T = foobar::FooBarAsyncClient;
111  */
112 template <typename T, typename D>
113 std::shared_ptr<T> to_shared_ptr(std::unique_ptr<T, D>&& ptr) {
114   return std::shared_ptr<T>(std::move(ptr));
115 }
116
117 /**
118  *  to_weak_ptr
119  *
120  *  Make a weak_ptr and return it from a shared_ptr without specifying the
121  *  template type parameter and letting the compiler deduce it.
122  *
123  *  So you can write this:
124  *
125  *      auto wptr = to_weak_ptr(getSomethingShared<T>());
126  *
127  *  Instead of this:
128  *
129  *      auto wptr = weak_ptr<T>(getSomethingShared<T>());
130  *
131  *  Useful when `T` is long, such as:
132  *
133  *      using T = foobar::FooBarAsyncClient;
134  */
135 template <typename T>
136 std::weak_ptr<T> to_weak_ptr(const std::shared_ptr<T>& ptr) {
137   return std::weak_ptr<T>(ptr);
138 }
139
140 using SysBufferDeleter = static_function_deleter<void, ::free>;
141 using SysBufferUniquePtr = std::unique_ptr<void, SysBufferDeleter>;
142 inline SysBufferUniquePtr allocate_sys_buffer(size_t size) {
143   return SysBufferUniquePtr(::malloc(size));
144 }
145
146 /**
147  * A SimpleAllocator must provide two methods:
148  *
149  *    void* allocate(size_t size);
150  *    void deallocate(void* ptr);
151  *
152  * which, respectively, allocate a block of size bytes (aligned to the
153  * maximum alignment required on your system), throwing std::bad_alloc
154  * if the allocation can't be satisfied, and free a previously
155  * allocated block.
156  *
157  * SysAlloc resembles the standard allocator.
158  */
159 class SysAlloc {
160  public:
161   void* allocate(size_t size) {
162     void* p = ::malloc(size);
163     if (!p) throw std::bad_alloc();
164     return p;
165   }
166   void deallocate(void* p) {
167     ::free(p);
168   }
169 };
170
171 /**
172  * StlAllocator wraps a SimpleAllocator into a STL-compliant
173  * allocator, maintaining an instance pointer to the simple allocator
174  * object.  The underlying SimpleAllocator object must outlive all
175  * instances of StlAllocator using it.
176  *
177  * But note that if you pass StlAllocator<MallocAllocator,...> to a
178  * standard container it will be larger due to the contained state
179  * pointer.
180  *
181  * @author: Tudor Bosman <tudorb@fb.com>
182  */
183
184 // This would be so much simpler with std::allocator_traits, but gcc 4.6.2
185 // doesn't support it.
186 template <class Alloc, class T> class StlAllocator;
187
188 template <class Alloc> class StlAllocator<Alloc, void> {
189  public:
190   typedef void value_type;
191   typedef void* pointer;
192   typedef const void* const_pointer;
193
194   StlAllocator() : alloc_(nullptr) { }
195   explicit StlAllocator(Alloc* a) : alloc_(a) { }
196
197   Alloc* alloc() const {
198     return alloc_;
199   }
200
201   template <class U> struct rebind {
202     typedef StlAllocator<Alloc, U> other;
203   };
204
205   bool operator!=(const StlAllocator<Alloc, void>& other) const {
206     return alloc_ != other.alloc_;
207   }
208
209   bool operator==(const StlAllocator<Alloc, void>& other) const {
210     return alloc_ == other.alloc_;
211   }
212
213  private:
214   Alloc* alloc_;
215 };
216
217 template <class Alloc, class T>
218 class StlAllocator {
219  public:
220   typedef T value_type;
221   typedef T* pointer;
222   typedef const T* const_pointer;
223   typedef T& reference;
224   typedef const T& const_reference;
225
226   typedef ptrdiff_t difference_type;
227   typedef size_t size_type;
228
229   StlAllocator() : alloc_(nullptr) { }
230   explicit StlAllocator(Alloc* a) : alloc_(a) { }
231
232   template <class U> StlAllocator(const StlAllocator<Alloc, U>& other)
233     : alloc_(other.alloc()) { }
234
235   T* allocate(size_t n, const void* /* hint */ = nullptr) {
236     return static_cast<T*>(alloc_->allocate(n * sizeof(T)));
237   }
238
239   void deallocate(T* p, size_t /* n */) { alloc_->deallocate(p); }
240
241   size_t max_size() const {
242     return std::numeric_limits<size_t>::max();
243   }
244
245   T* address(T& x) const {
246     return std::addressof(x);
247   }
248
249   const T* address(const T& x) const {
250     return std::addressof(x);
251   }
252
253   template <class... Args>
254   void construct(T* p, Args&&... args) {
255     new (p) T(std::forward<Args>(args)...);
256   }
257
258   void destroy(T* p) {
259     p->~T();
260   }
261
262   Alloc* alloc() const {
263     return alloc_;
264   }
265
266   template <class U> struct rebind {
267     typedef StlAllocator<Alloc, U> other;
268   };
269
270   bool operator!=(const StlAllocator<Alloc, T>& other) const {
271     return alloc_ != other.alloc_;
272   }
273
274   bool operator==(const StlAllocator<Alloc, T>& other) const {
275     return alloc_ == other.alloc_;
276   }
277
278  private:
279   Alloc* alloc_;
280 };
281
282 /**
283  * Helper function to obtain rebound allocators
284  *
285  * @author: Marcelo Juchem <marcelo@fb.com>
286  */
287 template <typename T, typename Allocator>
288 typename Allocator::template rebind<T>::other rebind_allocator(
289   Allocator const& allocator
290 ) {
291   return typename Allocator::template rebind<T>::other(allocator);
292 }
293
294 /*
295  * Helper classes/functions for creating a unique_ptr using a custom
296  * allocator.
297  *
298  * @author: Marcelo Juchem <marcelo@fb.com>
299  */
300
301 // Derives from the allocator to take advantage of the empty base
302 // optimization when possible.
303 template <typename Allocator>
304 class allocator_delete
305   : private std::remove_reference<Allocator>::type
306 {
307   typedef typename std::remove_reference<Allocator>::type allocator_type;
308
309 public:
310   typedef typename Allocator::pointer pointer;
311
312   allocator_delete() = default;
313
314   explicit allocator_delete(const allocator_type& allocator)
315     : allocator_type(allocator)
316   {}
317
318   explicit allocator_delete(allocator_type&& allocator)
319     : allocator_type(std::move(allocator))
320   {}
321
322   template <typename U>
323   allocator_delete(const allocator_delete<U>& other)
324     : allocator_type(other.get_allocator())
325   {}
326
327   allocator_type& get_allocator() const {
328     return *const_cast<allocator_delete*>(this);
329   }
330
331   void operator()(pointer p) const {
332     if (!p) return;
333     const_cast<allocator_delete*>(this)->destroy(p);
334     const_cast<allocator_delete*>(this)->deallocate(p, 1);
335   }
336 };
337
338 template <typename T, typename Allocator>
339 class is_simple_allocator {
340   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_destroy, destroy);
341
342   typedef typename std::remove_const<
343     typename std::remove_reference<Allocator>::type
344   >::type allocator;
345   typedef typename std::remove_reference<T>::type value_type;
346   typedef value_type* pointer;
347
348 public:
349   constexpr static bool value = !has_destroy<allocator, void(pointer)>::value
350     && !has_destroy<allocator, void(void*)>::value;
351 };
352
353 template <typename T, typename Allocator>
354 struct as_stl_allocator {
355   typedef typename std::conditional<
356     is_simple_allocator<T, Allocator>::value,
357     folly::StlAllocator<
358       typename std::remove_reference<Allocator>::type,
359       typename std::remove_reference<T>::type
360     >,
361     typename std::remove_reference<Allocator>::type
362   >::type type;
363 };
364
365 template <typename T, typename Allocator>
366 typename std::enable_if<
367   is_simple_allocator<T, Allocator>::value,
368   folly::StlAllocator<
369     typename std::remove_reference<Allocator>::type,
370     typename std::remove_reference<T>::type
371   >
372 >::type make_stl_allocator(Allocator&& allocator) {
373   return folly::StlAllocator<
374     typename std::remove_reference<Allocator>::type,
375     typename std::remove_reference<T>::type
376   >(&allocator);
377 }
378
379 template <typename T, typename Allocator>
380 typename std::enable_if<
381   !is_simple_allocator<T, Allocator>::value,
382   typename std::remove_reference<Allocator>::type
383 >::type make_stl_allocator(Allocator&& allocator) {
384   return std::move(allocator);
385 }
386
387 /**
388  * AllocatorUniquePtr: a unique_ptr that supports both STL-style
389  * allocators and SimpleAllocator
390  *
391  * @author: Marcelo Juchem <marcelo@fb.com>
392  */
393
394 template <typename T, typename Allocator>
395 struct AllocatorUniquePtr {
396   typedef std::unique_ptr<T,
397     folly::allocator_delete<
398       typename std::conditional<
399         is_simple_allocator<T, Allocator>::value,
400         folly::StlAllocator<typename std::remove_reference<Allocator>::type, T>,
401         typename std::remove_reference<Allocator>::type
402       >::type
403     >
404   > type;
405 };
406
407 /**
408  * Functions to allocate a unique_ptr / shared_ptr, supporting both
409  * STL-style allocators and SimpleAllocator, analog to std::allocate_shared
410  *
411  * @author: Marcelo Juchem <marcelo@fb.com>
412  */
413
414 template <typename T, typename Allocator, typename ...Args>
415 typename AllocatorUniquePtr<T, Allocator>::type allocate_unique(
416   Allocator&& allocator, Args&&... args
417 ) {
418   auto stlAllocator = folly::make_stl_allocator<T>(
419     std::forward<Allocator>(allocator)
420   );
421   auto p = stlAllocator.allocate(1);
422
423   try {
424     stlAllocator.construct(p, std::forward<Args>(args)...);
425
426     return {p,
427       folly::allocator_delete<decltype(stlAllocator)>(std::move(stlAllocator))
428     };
429   } catch (...) {
430     stlAllocator.deallocate(p, 1);
431     throw;
432   }
433 }
434
435 template <typename T, typename Allocator, typename ...Args>
436 std::shared_ptr<T> allocate_shared(Allocator&& allocator, Args&&... args) {
437   return std::allocate_shared<T>(
438     folly::make_stl_allocator<T>(std::forward<Allocator>(allocator)),
439     std::forward<Args>(args)...
440   );
441 }
442
443 /**
444  * IsArenaAllocator<T>::value describes whether SimpleAllocator has
445  * no-op deallocate().
446  */
447 template <class T> struct IsArenaAllocator : std::false_type { };
448
449 /*
450  * folly::enable_shared_from_this
451  *
452  * To be removed once C++17 becomes a minimum requirement for folly.
453  */
454 #if __cplusplus >= 201700L || \
455     __cpp_lib_enable_shared_from_this >= 201603L
456
457 // Guaranteed to have std::enable_shared_from_this::weak_from_this(). Prefer
458 // type alias over our own class.
459 /* using override */ using std::enable_shared_from_this;
460
461 #else
462
463 /**
464  * Extends std::enabled_shared_from_this. Offers weak_from_this() to pre-C++17
465  * code. Use as drop-in replacement for std::enable_shared_from_this.
466  *
467  * C++14 has no direct means of creating a std::weak_ptr, one must always
468  * create a (temporary) std::shared_ptr first. C++17 adds weak_from_this() to
469  * std::enable_shared_from_this to avoid that overhead. Alas code that must
470  * compile under different language versions cannot call
471  * std::enable_shared_from_this::weak_from_this() directly. Hence this class.
472  *
473  * @example
474  *   class MyClass : public folly::enable_shared_from_this<MyClass> {};
475  *
476  *   int main() {
477  *     std::shared_ptr<MyClass> sp = std::make_shared<MyClass>();
478  *     std::weak_ptr<MyClass> wp = sp->weak_from_this();
479  *   }
480  */
481 template <typename T>
482 class enable_shared_from_this : public std::enable_shared_from_this<T> {
483 public:
484   constexpr enable_shared_from_this() noexcept = default;
485
486   std::weak_ptr<T> weak_from_this() noexcept {
487     return weak_from_this_<T>(this);
488   }
489
490   std::weak_ptr<T const> weak_from_this() const noexcept {
491     return weak_from_this_<T>(this);
492   }
493
494 private:
495   // Uses SFINAE to detect and call
496   // std::enable_shared_from_this<T>::weak_from_this() if available. Falls
497   // back to std::enable_shared_from_this<T>::shared_from_this() otherwise.
498   template <typename U>
499   auto weak_from_this_(std::enable_shared_from_this<U>* base_ptr)
500   noexcept -> decltype(base_ptr->weak_from_this()) {
501     return base_ptr->weak_from_this();
502   }
503
504   template <typename U>
505   auto weak_from_this_(std::enable_shared_from_this<U> const* base_ptr)
506   const noexcept -> decltype(base_ptr->weak_from_this()) {
507     return base_ptr->weak_from_this();
508   }
509
510   template <typename U>
511   std::weak_ptr<U> weak_from_this_(...) noexcept {
512     try {
513       return this->shared_from_this();
514     } catch (std::bad_weak_ptr const&) {
515       // C++17 requires that weak_from_this() on an object not owned by a
516       // shared_ptr returns an empty weak_ptr. Sadly, in C++14,
517       // shared_from_this() on such an object is undefined behavior, and there
518       // is nothing we can do to detect and handle the situation in a portable
519       // manner. But in case a compiler is nice enough to implement C++17
520       // semantics of shared_from_this() and throws a bad_weak_ptr, we catch it
521       // and return an empty weak_ptr.
522       return std::weak_ptr<U>{};
523     }
524   }
525
526   template <typename U>
527   std::weak_ptr<U const> weak_from_this_(...) const noexcept {
528     try {
529       return this->shared_from_this();
530     } catch (std::bad_weak_ptr const&) {
531       return std::weak_ptr<U const>{};
532     }
533   }
534 };
535
536 #endif
537
538 }  // namespace folly