Expected coroutines support
[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 namespace detail {
141 /**
142  * Not all STL implementations define ::free in a way that its address can be
143  * determined at compile time. So we must wrap ::free in a function whose
144  * address can be determined.
145  */
146 inline void SysFree(void* p) {
147   ::free(p);
148 }
149 } // namespace detail
150
151 using SysBufferDeleter = static_function_deleter<void, &detail::SysFree>;
152 using SysBufferUniquePtr = std::unique_ptr<void, SysBufferDeleter>;
153 inline SysBufferUniquePtr allocate_sys_buffer(size_t size) {
154   return SysBufferUniquePtr(::malloc(size));
155 }
156
157 /**
158  * A SimpleAllocator must provide two methods:
159  *
160  *    void* allocate(size_t size);
161  *    void deallocate(void* ptr);
162  *
163  * which, respectively, allocate a block of size bytes (aligned to the
164  * maximum alignment required on your system), throwing std::bad_alloc
165  * if the allocation can't be satisfied, and free a previously
166  * allocated block.
167  *
168  * SysAlloc resembles the standard allocator.
169  */
170 class SysAlloc {
171  public:
172   void* allocate(size_t size) {
173     void* p = ::malloc(size);
174     if (!p) {
175       throw std::bad_alloc();
176     }
177     return p;
178   }
179   void deallocate(void* p) {
180     ::free(p);
181   }
182 };
183
184 /**
185  * StlAllocator wraps a SimpleAllocator into a STL-compliant
186  * allocator, maintaining an instance pointer to the simple allocator
187  * object.  The underlying SimpleAllocator object must outlive all
188  * instances of StlAllocator using it.
189  *
190  * But note that if you pass StlAllocator<MallocAllocator,...> to a
191  * standard container it will be larger due to the contained state
192  * pointer.
193  *
194  * @author: Tudor Bosman <tudorb@fb.com>
195  */
196
197 // This would be so much simpler with std::allocator_traits, but gcc 4.6.2
198 // doesn't support it.
199 template <class Alloc, class T> class StlAllocator;
200
201 template <class Alloc> class StlAllocator<Alloc, void> {
202  public:
203   typedef void value_type;
204   typedef void* pointer;
205   typedef const void* const_pointer;
206
207   StlAllocator() : alloc_(nullptr) { }
208   explicit StlAllocator(Alloc* a) : alloc_(a) { }
209
210   Alloc* alloc() const {
211     return alloc_;
212   }
213
214   template <class U> struct rebind {
215     typedef StlAllocator<Alloc, U> other;
216   };
217
218   bool operator!=(const StlAllocator<Alloc, void>& other) const {
219     return alloc_ != other.alloc_;
220   }
221
222   bool operator==(const StlAllocator<Alloc, void>& other) const {
223     return alloc_ == other.alloc_;
224   }
225
226  private:
227   Alloc* alloc_;
228 };
229
230 template <class Alloc, class T>
231 class StlAllocator {
232  public:
233   typedef T value_type;
234   typedef T* pointer;
235   typedef const T* const_pointer;
236   typedef T& reference;
237   typedef const T& const_reference;
238
239   typedef ptrdiff_t difference_type;
240   typedef size_t size_type;
241
242   StlAllocator() : alloc_(nullptr) { }
243   explicit StlAllocator(Alloc* a) : alloc_(a) { }
244
245   template <class U> StlAllocator(const StlAllocator<Alloc, U>& other)
246     : alloc_(other.alloc()) { }
247
248   T* allocate(size_t n, const void* /* hint */ = nullptr) {
249     return static_cast<T*>(alloc_->allocate(n * sizeof(T)));
250   }
251
252   void deallocate(T* p, size_t /* n */) { alloc_->deallocate(p); }
253
254   size_t max_size() const {
255     return std::numeric_limits<size_t>::max();
256   }
257
258   T* address(T& x) const {
259     return std::addressof(x);
260   }
261
262   const T* address(const T& x) const {
263     return std::addressof(x);
264   }
265
266   template <class... Args>
267   void construct(T* p, Args&&... args) {
268     new (p) T(std::forward<Args>(args)...);
269   }
270
271   void destroy(T* p) {
272     p->~T();
273   }
274
275   Alloc* alloc() const {
276     return alloc_;
277   }
278
279   template <class U> struct rebind {
280     typedef StlAllocator<Alloc, U> other;
281   };
282
283   bool operator!=(const StlAllocator<Alloc, T>& other) const {
284     return alloc_ != other.alloc_;
285   }
286
287   bool operator==(const StlAllocator<Alloc, T>& other) const {
288     return alloc_ == other.alloc_;
289   }
290
291  private:
292   Alloc* alloc_;
293 };
294
295 /**
296  * Helper function to obtain rebound allocators
297  *
298  * @author: Marcelo Juchem <marcelo@fb.com>
299  */
300 template <typename T, typename Allocator>
301 typename Allocator::template rebind<T>::other rebind_allocator(
302   Allocator const& allocator
303 ) {
304   return typename Allocator::template rebind<T>::other(allocator);
305 }
306
307 /*
308  * Helper classes/functions for creating a unique_ptr using a custom
309  * allocator.
310  *
311  * @author: Marcelo Juchem <marcelo@fb.com>
312  */
313
314 // Derives from the allocator to take advantage of the empty base
315 // optimization when possible.
316 template <typename Allocator>
317 class allocator_delete
318   : private std::remove_reference<Allocator>::type
319 {
320   typedef typename std::remove_reference<Allocator>::type allocator_type;
321
322  public:
323   typedef typename Allocator::pointer pointer;
324
325   allocator_delete() = default;
326
327   explicit allocator_delete(const allocator_type& allocator)
328     : allocator_type(allocator)
329   {}
330
331   explicit allocator_delete(allocator_type&& allocator)
332     : allocator_type(std::move(allocator))
333   {}
334
335   template <typename U>
336   allocator_delete(const allocator_delete<U>& other)
337     : allocator_type(other.get_allocator())
338   {}
339
340   allocator_type& get_allocator() const {
341     return *const_cast<allocator_delete*>(this);
342   }
343
344   void operator()(pointer p) const {
345     if (!p) {
346       return;
347     }
348     const_cast<allocator_delete*>(this)->destroy(p);
349     const_cast<allocator_delete*>(this)->deallocate(p, 1);
350   }
351 };
352
353 template <typename T, typename Allocator>
354 class is_simple_allocator {
355   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_destroy, destroy);
356
357   typedef typename std::remove_const<
358     typename std::remove_reference<Allocator>::type
359   >::type allocator;
360   typedef typename std::remove_reference<T>::type value_type;
361   typedef value_type* pointer;
362
363  public:
364   constexpr static bool value = !has_destroy<allocator, void(pointer)>::value
365     && !has_destroy<allocator, void(void*)>::value;
366 };
367
368 template <typename T, typename Allocator>
369 struct as_stl_allocator {
370   typedef typename std::conditional<
371     is_simple_allocator<T, Allocator>::value,
372     folly::StlAllocator<
373       typename std::remove_reference<Allocator>::type,
374       typename std::remove_reference<T>::type
375     >,
376     typename std::remove_reference<Allocator>::type
377   >::type type;
378 };
379
380 template <typename T, typename Allocator>
381 typename std::enable_if<
382   is_simple_allocator<T, Allocator>::value,
383   folly::StlAllocator<
384     typename std::remove_reference<Allocator>::type,
385     typename std::remove_reference<T>::type
386   >
387 >::type make_stl_allocator(Allocator&& allocator) {
388   return folly::StlAllocator<
389     typename std::remove_reference<Allocator>::type,
390     typename std::remove_reference<T>::type
391   >(&allocator);
392 }
393
394 template <typename T, typename Allocator>
395 typename std::enable_if<
396   !is_simple_allocator<T, Allocator>::value,
397   typename std::remove_reference<Allocator>::type
398 >::type make_stl_allocator(Allocator&& allocator) {
399   return std::move(allocator);
400 }
401
402 /**
403  * AllocatorUniquePtr: a unique_ptr that supports both STL-style
404  * allocators and SimpleAllocator
405  *
406  * @author: Marcelo Juchem <marcelo@fb.com>
407  */
408
409 template <typename T, typename Allocator>
410 struct AllocatorUniquePtr {
411   typedef std::unique_ptr<T,
412     folly::allocator_delete<
413       typename std::conditional<
414         is_simple_allocator<T, Allocator>::value,
415         folly::StlAllocator<typename std::remove_reference<Allocator>::type, T>,
416         typename std::remove_reference<Allocator>::type
417       >::type
418     >
419   > type;
420 };
421
422 /**
423  * Functions to allocate a unique_ptr / shared_ptr, supporting both
424  * STL-style allocators and SimpleAllocator, analog to std::allocate_shared
425  *
426  * @author: Marcelo Juchem <marcelo@fb.com>
427  */
428
429 template <typename T, typename Allocator, typename ...Args>
430 typename AllocatorUniquePtr<T, Allocator>::type allocate_unique(
431   Allocator&& allocator, Args&&... args
432 ) {
433   auto stlAllocator = folly::make_stl_allocator<T>(
434     std::forward<Allocator>(allocator)
435   );
436   auto p = stlAllocator.allocate(1);
437
438   try {
439     stlAllocator.construct(p, std::forward<Args>(args)...);
440
441     return {p,
442       folly::allocator_delete<decltype(stlAllocator)>(std::move(stlAllocator))
443     };
444   } catch (...) {
445     stlAllocator.deallocate(p, 1);
446     throw;
447   }
448 }
449
450 template <typename T, typename Allocator, typename ...Args>
451 std::shared_ptr<T> allocate_shared(Allocator&& allocator, Args&&... args) {
452   return std::allocate_shared<T>(
453     folly::make_stl_allocator<T>(std::forward<Allocator>(allocator)),
454     std::forward<Args>(args)...
455   );
456 }
457
458 /**
459  * IsArenaAllocator<T>::value describes whether SimpleAllocator has
460  * no-op deallocate().
461  */
462 template <class T> struct IsArenaAllocator : std::false_type { };
463
464 /*
465  * folly::enable_shared_from_this
466  *
467  * To be removed once C++17 becomes a minimum requirement for folly.
468  */
469 #if __cplusplus >= 201700L || \
470     __cpp_lib_enable_shared_from_this >= 201603L
471
472 // Guaranteed to have std::enable_shared_from_this::weak_from_this(). Prefer
473 // type alias over our own class.
474 /* using override */ using std::enable_shared_from_this;
475
476 #else
477
478 /**
479  * Extends std::enabled_shared_from_this. Offers weak_from_this() to pre-C++17
480  * code. Use as drop-in replacement for std::enable_shared_from_this.
481  *
482  * C++14 has no direct means of creating a std::weak_ptr, one must always
483  * create a (temporary) std::shared_ptr first. C++17 adds weak_from_this() to
484  * std::enable_shared_from_this to avoid that overhead. Alas code that must
485  * compile under different language versions cannot call
486  * std::enable_shared_from_this::weak_from_this() directly. Hence this class.
487  *
488  * @example
489  *   class MyClass : public folly::enable_shared_from_this<MyClass> {};
490  *
491  *   int main() {
492  *     std::shared_ptr<MyClass> sp = std::make_shared<MyClass>();
493  *     std::weak_ptr<MyClass> wp = sp->weak_from_this();
494  *   }
495  */
496 template <typename T>
497 class enable_shared_from_this : public std::enable_shared_from_this<T> {
498  public:
499   constexpr enable_shared_from_this() noexcept = default;
500
501   std::weak_ptr<T> weak_from_this() noexcept {
502     return weak_from_this_<T>(this);
503   }
504
505   std::weak_ptr<T const> weak_from_this() const noexcept {
506     return weak_from_this_<T>(this);
507   }
508
509  private:
510   // Uses SFINAE to detect and call
511   // std::enable_shared_from_this<T>::weak_from_this() if available. Falls
512   // back to std::enable_shared_from_this<T>::shared_from_this() otherwise.
513   template <typename U>
514   auto weak_from_this_(std::enable_shared_from_this<U>* base_ptr)
515   noexcept -> decltype(base_ptr->weak_from_this()) {
516     return base_ptr->weak_from_this();
517   }
518
519   template <typename U>
520   auto weak_from_this_(std::enable_shared_from_this<U> const* base_ptr)
521   const noexcept -> decltype(base_ptr->weak_from_this()) {
522     return base_ptr->weak_from_this();
523   }
524
525   template <typename U>
526   std::weak_ptr<U> weak_from_this_(...) noexcept {
527     try {
528       return this->shared_from_this();
529     } catch (std::bad_weak_ptr const&) {
530       // C++17 requires that weak_from_this() on an object not owned by a
531       // shared_ptr returns an empty weak_ptr. Sadly, in C++14,
532       // shared_from_this() on such an object is undefined behavior, and there
533       // is nothing we can do to detect and handle the situation in a portable
534       // manner. But in case a compiler is nice enough to implement C++17
535       // semantics of shared_from_this() and throws a bad_weak_ptr, we catch it
536       // and return an empty weak_ptr.
537       return std::weak_ptr<U>{};
538     }
539   }
540
541   template <typename U>
542   std::weak_ptr<U const> weak_from_this_(...) const noexcept {
543     try {
544       return this->shared_from_this();
545     } catch (std::bad_weak_ptr const&) {
546       return std::weak_ptr<U const>{};
547     }
548   }
549 };
550
551 #endif
552
553 } // namespace folly