2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <folly/Traits.h>
20 #include <folly/functional/Invoke.h>
28 #include <type_traits>
34 * For exception safety and consistency with make_shared. Erase me when
35 * we have std::make_unique().
37 * @author Louis Brandy (ldbrandy@fb.com)
38 * @author Xu Ning (xning@fb.com)
41 #if __cplusplus >= 201402L || __cpp_lib_make_unique >= 201304L || \
42 (__ANDROID__ && __cplusplus >= 201300L) || _MSC_VER >= 1900
44 /* using override */ using std::make_unique;
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)...));
54 // Allows 'make_unique<T[]>(10)'. (N3690 s20.9.1.4 p3-4)
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]());
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;
70 * static_function_deleter
72 * So you can write this:
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())
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
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())
89 template <typename T, void(*f)(T*)>
90 struct static_function_deleter {
91 void operator()(T* t) const {
99 * Convert unique_ptr to shared_ptr without specifying the template type
100 * parameter and letting the compiler deduce it.
102 * So you can write this:
104 * auto sptr = to_shared_ptr(getSomethingUnique<T>());
108 * auto sptr = shared_ptr<T>(getSomethingUnique<T>());
110 * Useful when `T` is long, such as:
112 * using T = foobar::FooBarAsyncClient;
114 template <typename T, typename D>
115 std::shared_ptr<T> to_shared_ptr(std::unique_ptr<T, D>&& ptr) {
116 return std::shared_ptr<T>(std::move(ptr));
122 * Make a weak_ptr and return it from a shared_ptr without specifying the
123 * template type parameter and letting the compiler deduce it.
125 * So you can write this:
127 * auto wptr = to_weak_ptr(getSomethingShared<T>());
131 * auto wptr = weak_ptr<T>(getSomethingShared<T>());
133 * Useful when `T` is long, such as:
135 * using T = foobar::FooBarAsyncClient;
137 template <typename T>
138 std::weak_ptr<T> to_weak_ptr(const std::shared_ptr<T>& ptr) {
139 return std::weak_ptr<T>(ptr);
142 struct SysBufferDeleter {
143 void operator()(void* p) const {
148 using SysBufferUniquePtr = std::unique_ptr<void, SysBufferDeleter>;
149 inline SysBufferUniquePtr allocate_sys_buffer(size_t size) {
150 return SysBufferUniquePtr(::malloc(size));
154 * A SimpleAllocator must provide two methods:
156 * void* allocate(size_t size);
157 * void deallocate(void* ptr);
159 * which, respectively, allocate a block of size bytes (aligned to the
160 * maximum alignment required on your system), throwing std::bad_alloc
161 * if the allocation can't be satisfied, and free a previously
164 * SysAlloc resembles the standard allocator.
168 void* allocate(size_t size) {
169 void* p = ::malloc(size);
171 throw std::bad_alloc();
175 void deallocate(void* p) {
181 * StlAllocator wraps a SimpleAllocator into a STL-compliant
182 * allocator, maintaining an instance pointer to the simple allocator
183 * object. The underlying SimpleAllocator object must outlive all
184 * instances of StlAllocator using it.
186 * But note that if you pass StlAllocator<MallocAllocator,...> to a
187 * standard container it will be larger due to the contained state
190 * @author: Tudor Bosman <tudorb@fb.com>
193 // This would be so much simpler with std::allocator_traits, but gcc 4.6.2
194 // doesn't support it.
195 template <class Alloc, class T> class StlAllocator;
197 template <class Alloc> class StlAllocator<Alloc, void> {
199 typedef void value_type;
200 typedef void* pointer;
201 typedef const void* const_pointer;
203 StlAllocator() : alloc_(nullptr) { }
204 explicit StlAllocator(Alloc* a) : alloc_(a) { }
206 Alloc* alloc() const {
210 template <class U> struct rebind {
211 typedef StlAllocator<Alloc, U> other;
214 bool operator!=(const StlAllocator<Alloc, void>& other) const {
215 return alloc_ != other.alloc_;
218 bool operator==(const StlAllocator<Alloc, void>& other) const {
219 return alloc_ == other.alloc_;
226 template <class Alloc, class T>
229 typedef T value_type;
231 typedef const T* const_pointer;
232 typedef T& reference;
233 typedef const T& const_reference;
235 typedef ptrdiff_t difference_type;
236 typedef size_t size_type;
238 StlAllocator() : alloc_(nullptr) { }
239 explicit StlAllocator(Alloc* a) : alloc_(a) { }
241 template <class U> StlAllocator(const StlAllocator<Alloc, U>& other)
242 : alloc_(other.alloc()) { }
244 T* allocate(size_t n, const void* /* hint */ = nullptr) {
245 return static_cast<T*>(alloc_->allocate(n * sizeof(T)));
248 void deallocate(T* p, size_t /* n */) { alloc_->deallocate(p); }
250 size_t max_size() const {
251 return std::numeric_limits<size_t>::max();
254 T* address(T& x) const {
255 return std::addressof(x);
258 const T* address(const T& x) const {
259 return std::addressof(x);
262 template <class... Args>
263 void construct(T* p, Args&&... args) {
264 new (p) T(std::forward<Args>(args)...);
271 Alloc* alloc() const {
275 template <class U> struct rebind {
276 typedef StlAllocator<Alloc, U> other;
279 bool operator!=(const StlAllocator<Alloc, T>& other) const {
280 return alloc_ != other.alloc_;
283 bool operator==(const StlAllocator<Alloc, T>& other) const {
284 return alloc_ == other.alloc_;
292 * Helper function to obtain rebound allocators
294 * @author: Marcelo Juchem <marcelo@fb.com>
296 template <typename T, typename Allocator>
297 typename Allocator::template rebind<T>::other rebind_allocator(
298 Allocator const& allocator
300 return typename Allocator::template rebind<T>::other(allocator);
304 * Helper classes/functions for creating a unique_ptr using a custom
307 * @author: Marcelo Juchem <marcelo@fb.com>
310 // Derives from the allocator to take advantage of the empty base
311 // optimization when possible.
312 template <typename Allocator>
313 class allocator_delete
314 : private std::remove_reference<Allocator>::type
316 typedef typename std::remove_reference<Allocator>::type allocator_type;
319 typedef typename Allocator::pointer pointer;
321 allocator_delete() = default;
323 explicit allocator_delete(const allocator_type& allocator)
324 : allocator_type(allocator)
327 explicit allocator_delete(allocator_type&& allocator)
328 : allocator_type(std::move(allocator))
331 template <typename U>
332 allocator_delete(const allocator_delete<U>& other)
333 : allocator_type(other.get_allocator())
336 allocator_type& get_allocator() const {
337 return *const_cast<allocator_delete*>(this);
340 void operator()(pointer p) const {
344 const_cast<allocator_delete*>(this)->destroy(p);
345 const_cast<allocator_delete*>(this)->deallocate(p, 1);
351 FOLLY_CREATE_MEMBER_INVOKE_TRAITS(destroy_invoke_traits, destroy);
353 } // namespace detail
355 template <typename Allocator, typename Value>
356 using is_simple_allocator =
357 Negation<detail::destroy_invoke_traits::is_invocable<Allocator, Value*>>;
359 template <typename T, typename Allocator>
360 struct as_stl_allocator {
361 typedef typename std::conditional<
363 typename std::remove_reference<Allocator>::type,
364 typename std::remove_reference<T>::type
367 typename std::remove_reference<Allocator>::type,
368 typename std::remove_reference<T>::type
370 typename std::remove_reference<Allocator>::type
374 template <typename T, typename Allocator>
375 typename std::enable_if<
377 typename std::remove_reference<Allocator>::type,
378 typename std::remove_reference<T>::type
381 typename std::remove_reference<Allocator>::type,
382 typename std::remove_reference<T>::type
384 >::type make_stl_allocator(Allocator&& allocator) {
385 return folly::StlAllocator<
386 typename std::remove_reference<Allocator>::type,
387 typename std::remove_reference<T>::type
391 template <typename T, typename Allocator>
392 typename std::enable_if<
393 !is_simple_allocator<
394 typename std::remove_reference<Allocator>::type,
395 typename std::remove_reference<T>::type
397 typename std::remove_reference<Allocator>::type
398 >::type make_stl_allocator(Allocator&& allocator) {
399 return std::move(allocator);
403 * AllocatorUniquePtr: a unique_ptr that supports both STL-style
404 * allocators and SimpleAllocator
406 * @author: Marcelo Juchem <marcelo@fb.com>
409 template <typename T, typename Allocator>
410 struct AllocatorUniquePtr {
411 typedef std::unique_ptr<T,
412 folly::allocator_delete<
413 typename std::conditional<
415 typename std::remove_reference<Allocator>::type,
416 typename std::remove_reference<T>::type
418 folly::StlAllocator<typename std::remove_reference<Allocator>::type, T>,
419 typename std::remove_reference<Allocator>::type
426 * Functions to allocate a unique_ptr / shared_ptr, supporting both
427 * STL-style allocators and SimpleAllocator, analog to std::allocate_shared
429 * @author: Marcelo Juchem <marcelo@fb.com>
432 template <typename T, typename Allocator, typename ...Args>
433 typename AllocatorUniquePtr<T, Allocator>::type allocate_unique(
434 Allocator&& allocator, Args&&... args
436 auto stlAllocator = folly::make_stl_allocator<T>(
437 std::forward<Allocator>(allocator)
439 auto p = stlAllocator.allocate(1);
442 stlAllocator.construct(p, std::forward<Args>(args)...);
445 folly::allocator_delete<decltype(stlAllocator)>(std::move(stlAllocator))
448 stlAllocator.deallocate(p, 1);
453 template <typename T, typename Allocator, typename ...Args>
454 std::shared_ptr<T> allocate_shared(Allocator&& allocator, Args&&... args) {
455 return std::allocate_shared<T>(
456 folly::make_stl_allocator<T>(std::forward<Allocator>(allocator)),
457 std::forward<Args>(args)...
462 * IsArenaAllocator<T>::value describes whether SimpleAllocator has
463 * no-op deallocate().
465 template <class T> struct IsArenaAllocator : std::false_type { };
468 * folly::enable_shared_from_this
470 * To be removed once C++17 becomes a minimum requirement for folly.
472 #if __cplusplus >= 201700L || \
473 __cpp_lib_enable_shared_from_this >= 201603L
475 // Guaranteed to have std::enable_shared_from_this::weak_from_this(). Prefer
476 // type alias over our own class.
477 /* using override */ using std::enable_shared_from_this;
482 * Extends std::enabled_shared_from_this. Offers weak_from_this() to pre-C++17
483 * code. Use as drop-in replacement for std::enable_shared_from_this.
485 * C++14 has no direct means of creating a std::weak_ptr, one must always
486 * create a (temporary) std::shared_ptr first. C++17 adds weak_from_this() to
487 * std::enable_shared_from_this to avoid that overhead. Alas code that must
488 * compile under different language versions cannot call
489 * std::enable_shared_from_this::weak_from_this() directly. Hence this class.
492 * class MyClass : public folly::enable_shared_from_this<MyClass> {};
495 * std::shared_ptr<MyClass> sp = std::make_shared<MyClass>();
496 * std::weak_ptr<MyClass> wp = sp->weak_from_this();
499 template <typename T>
500 class enable_shared_from_this : public std::enable_shared_from_this<T> {
502 constexpr enable_shared_from_this() noexcept = default;
504 std::weak_ptr<T> weak_from_this() noexcept {
505 return weak_from_this_<T>(this);
508 std::weak_ptr<T const> weak_from_this() const noexcept {
509 return weak_from_this_<T>(this);
513 // Uses SFINAE to detect and call
514 // std::enable_shared_from_this<T>::weak_from_this() if available. Falls
515 // back to std::enable_shared_from_this<T>::shared_from_this() otherwise.
516 template <typename U>
517 auto weak_from_this_(std::enable_shared_from_this<U>* base_ptr)
518 noexcept -> decltype(base_ptr->weak_from_this()) {
519 return base_ptr->weak_from_this();
522 template <typename U>
523 auto weak_from_this_(std::enable_shared_from_this<U> const* base_ptr)
524 const noexcept -> decltype(base_ptr->weak_from_this()) {
525 return base_ptr->weak_from_this();
528 template <typename U>
529 std::weak_ptr<U> weak_from_this_(...) noexcept {
531 return this->shared_from_this();
532 } catch (std::bad_weak_ptr const&) {
533 // C++17 requires that weak_from_this() on an object not owned by a
534 // shared_ptr returns an empty weak_ptr. Sadly, in C++14,
535 // shared_from_this() on such an object is undefined behavior, and there
536 // is nothing we can do to detect and handle the situation in a portable
537 // manner. But in case a compiler is nice enough to implement C++17
538 // semantics of shared_from_this() and throws a bad_weak_ptr, we catch it
539 // and return an empty weak_ptr.
540 return std::weak_ptr<U>{};
544 template <typename U>
545 std::weak_ptr<U const> weak_from_this_(...) const noexcept {
547 return this->shared_from_this();
548 } catch (std::bad_weak_ptr const&) {
549 return std::weak_ptr<U const>{};