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