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