make Range::size() constexpr
[folly.git] / folly / Memory.h
1 /*
2  * Copyright 2016 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 #include <folly/portability/Memory.h>
21
22 #include <cstddef>
23 #include <cstdlib>
24 #include <exception>
25 #include <limits>
26 #include <memory>
27 #include <stdexcept>
28 #include <utility>
29
30 namespace folly {
31
32 /**
33  * For exception safety and consistency with make_shared. Erase me when
34  * we have std::make_unique().
35  *
36  * @author Louis Brandy (ldbrandy@fb.com)
37  * @author Xu Ning (xning@fb.com)
38  */
39
40 #if __cplusplus >= 201402L ||                                              \
41     (defined __cpp_lib_make_unique && __cpp_lib_make_unique >= 201304L) || \
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) { f(t); }
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::cpp2::FooBarServiceAsyncClient;
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  * A SimpleAllocator must provide two methods:
119  *
120  *    void* allocate(size_t size);
121  *    void deallocate(void* ptr);
122  *
123  * which, respectively, allocate a block of size bytes (aligned to the
124  * maximum alignment required on your system), throwing std::bad_alloc
125  * if the allocation can't be satisfied, and free a previously
126  * allocated block.
127  *
128  * SysAlloc resembles the standard allocator.
129  */
130 class SysAlloc {
131  public:
132   void* allocate(size_t size) {
133     void* p = ::malloc(size);
134     if (!p) throw std::bad_alloc();
135     return p;
136   }
137   void deallocate(void* p) {
138     ::free(p);
139   }
140 };
141
142 /**
143  * StlAllocator wraps a SimpleAllocator into a STL-compliant
144  * allocator, maintaining an instance pointer to the simple allocator
145  * object.  The underlying SimpleAllocator object must outlive all
146  * instances of StlAllocator using it.
147  *
148  * But note that if you pass StlAllocator<MallocAllocator,...> to a
149  * standard container it will be larger due to the contained state
150  * pointer.
151  *
152  * @author: Tudor Bosman <tudorb@fb.com>
153  */
154
155 // This would be so much simpler with std::allocator_traits, but gcc 4.6.2
156 // doesn't support it.
157 template <class Alloc, class T> class StlAllocator;
158
159 template <class Alloc> class StlAllocator<Alloc, void> {
160  public:
161   typedef void value_type;
162   typedef void* pointer;
163   typedef const void* const_pointer;
164
165   StlAllocator() : alloc_(nullptr) { }
166   explicit StlAllocator(Alloc* a) : alloc_(a) { }
167
168   Alloc* alloc() const {
169     return alloc_;
170   }
171
172   template <class U> struct rebind {
173     typedef StlAllocator<Alloc, U> other;
174   };
175
176   bool operator!=(const StlAllocator<Alloc, void>& other) const {
177     return alloc_ != other.alloc_;
178   }
179
180   bool operator==(const StlAllocator<Alloc, void>& other) const {
181     return alloc_ == other.alloc_;
182   }
183
184  private:
185   Alloc* alloc_;
186 };
187
188 template <class Alloc, class T>
189 class StlAllocator {
190  public:
191   typedef T value_type;
192   typedef T* pointer;
193   typedef const T* const_pointer;
194   typedef T& reference;
195   typedef const T& const_reference;
196
197   typedef ptrdiff_t difference_type;
198   typedef size_t size_type;
199
200   StlAllocator() : alloc_(nullptr) { }
201   explicit StlAllocator(Alloc* a) : alloc_(a) { }
202
203   template <class U> StlAllocator(const StlAllocator<Alloc, U>& other)
204     : alloc_(other.alloc()) { }
205
206   T* allocate(size_t n, const void* /* hint */ = nullptr) {
207     return static_cast<T*>(alloc_->allocate(n * sizeof(T)));
208   }
209
210   void deallocate(T* p, size_t /* n */) { alloc_->deallocate(p); }
211
212   size_t max_size() const {
213     return std::numeric_limits<size_t>::max();
214   }
215
216   T* address(T& x) const {
217     return std::addressof(x);
218   }
219
220   const T* address(const T& x) const {
221     return std::addressof(x);
222   }
223
224   template <class... Args>
225   void construct(T* p, Args&&... args) {
226     new (p) T(std::forward<Args>(args)...);
227   }
228
229   void destroy(T* p) {
230     p->~T();
231   }
232
233   Alloc* alloc() const {
234     return alloc_;
235   }
236
237   template <class U> struct rebind {
238     typedef StlAllocator<Alloc, U> other;
239   };
240
241   bool operator!=(const StlAllocator<Alloc, T>& other) const {
242     return alloc_ != other.alloc_;
243   }
244
245   bool operator==(const StlAllocator<Alloc, T>& other) const {
246     return alloc_ == other.alloc_;
247   }
248
249  private:
250   Alloc* alloc_;
251 };
252
253 /**
254  * Helper function to obtain rebound allocators
255  *
256  * @author: Marcelo Juchem <marcelo@fb.com>
257  */
258 template <typename T, typename Allocator>
259 typename Allocator::template rebind<T>::other rebind_allocator(
260   Allocator const& allocator
261 ) {
262   return typename Allocator::template rebind<T>::other(allocator);
263 }
264
265 /*
266  * Helper classes/functions for creating a unique_ptr using a custom
267  * allocator.
268  *
269  * @author: Marcelo Juchem <marcelo@fb.com>
270  */
271
272 // Derives from the allocator to take advantage of the empty base
273 // optimization when possible.
274 template <typename Allocator>
275 class allocator_delete
276   : private std::remove_reference<Allocator>::type
277 {
278   typedef typename std::remove_reference<Allocator>::type allocator_type;
279
280 public:
281   typedef typename Allocator::pointer pointer;
282
283   allocator_delete() = default;
284
285   explicit allocator_delete(const allocator_type& allocator)
286     : allocator_type(allocator)
287   {}
288
289   explicit allocator_delete(allocator_type&& allocator)
290     : allocator_type(std::move(allocator))
291   {}
292
293   template <typename U>
294   allocator_delete(const allocator_delete<U>& other)
295     : allocator_type(other.get_allocator())
296   {}
297
298   allocator_type& get_allocator() const {
299     return *const_cast<allocator_delete*>(this);
300   }
301
302   void operator()(pointer p) const {
303     if (!p) return;
304     const_cast<allocator_delete*>(this)->destroy(p);
305     const_cast<allocator_delete*>(this)->deallocate(p, 1);
306   }
307 };
308
309 template <typename T, typename Allocator>
310 class is_simple_allocator {
311   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_destroy, destroy);
312
313   typedef typename std::remove_const<
314     typename std::remove_reference<Allocator>::type
315   >::type allocator;
316   typedef typename std::remove_reference<T>::type value_type;
317   typedef value_type* pointer;
318
319 public:
320   constexpr static bool value = !has_destroy<allocator, void(pointer)>::value
321     && !has_destroy<allocator, void(void*)>::value;
322 };
323
324 template <typename T, typename Allocator>
325 struct as_stl_allocator {
326   typedef typename std::conditional<
327     is_simple_allocator<T, Allocator>::value,
328     folly::StlAllocator<
329       typename std::remove_reference<Allocator>::type,
330       typename std::remove_reference<T>::type
331     >,
332     typename std::remove_reference<Allocator>::type
333   >::type type;
334 };
335
336 template <typename T, typename Allocator>
337 typename std::enable_if<
338   is_simple_allocator<T, Allocator>::value,
339   folly::StlAllocator<
340     typename std::remove_reference<Allocator>::type,
341     typename std::remove_reference<T>::type
342   >
343 >::type make_stl_allocator(Allocator&& allocator) {
344   return folly::StlAllocator<
345     typename std::remove_reference<Allocator>::type,
346     typename std::remove_reference<T>::type
347   >(&allocator);
348 }
349
350 template <typename T, typename Allocator>
351 typename std::enable_if<
352   !is_simple_allocator<T, Allocator>::value,
353   typename std::remove_reference<Allocator>::type
354 >::type make_stl_allocator(Allocator&& allocator) {
355   return std::move(allocator);
356 }
357
358 /**
359  * AllocatorUniquePtr: a unique_ptr that supports both STL-style
360  * allocators and SimpleAllocator
361  *
362  * @author: Marcelo Juchem <marcelo@fb.com>
363  */
364
365 template <typename T, typename Allocator>
366 struct AllocatorUniquePtr {
367   typedef std::unique_ptr<T,
368     folly::allocator_delete<
369       typename std::conditional<
370         is_simple_allocator<T, Allocator>::value,
371         folly::StlAllocator<typename std::remove_reference<Allocator>::type, T>,
372         typename std::remove_reference<Allocator>::type
373       >::type
374     >
375   > type;
376 };
377
378 /**
379  * Functions to allocate a unique_ptr / shared_ptr, supporting both
380  * STL-style allocators and SimpleAllocator, analog to std::allocate_shared
381  *
382  * @author: Marcelo Juchem <marcelo@fb.com>
383  */
384
385 template <typename T, typename Allocator, typename ...Args>
386 typename AllocatorUniquePtr<T, Allocator>::type allocate_unique(
387   Allocator&& allocator, Args&&... args
388 ) {
389   auto stlAllocator = folly::make_stl_allocator<T>(
390     std::forward<Allocator>(allocator)
391   );
392   auto p = stlAllocator.allocate(1);
393
394   try {
395     stlAllocator.construct(p, std::forward<Args>(args)...);
396
397     return {p,
398       folly::allocator_delete<decltype(stlAllocator)>(std::move(stlAllocator))
399     };
400   } catch (...) {
401     stlAllocator.deallocate(p, 1);
402     throw;
403   }
404 }
405
406 template <typename T, typename Allocator, typename ...Args>
407 std::shared_ptr<T> allocate_shared(Allocator&& allocator, Args&&... args) {
408   return std::allocate_shared<T>(
409     folly::make_stl_allocator<T>(std::forward<Allocator>(allocator)),
410     std::forward<Args>(args)...
411   );
412 }
413
414 /**
415  * IsArenaAllocator<T>::value describes whether SimpleAllocator has
416  * no-op deallocate().
417  */
418 template <class T> struct IsArenaAllocator : std::false_type { };
419
420 }  // namespace folly