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>
32 * For exception safety and consistency with make_shared. Erase me when
33 * we have std::make_unique().
35 * @author Louis Brandy (ldbrandy@fb.com)
36 * @author Xu Ning (xning@fb.com)
39 #if __cplusplus >= 201402L || __cpp_lib_make_unique >= 201304L || \
40 (__ANDROID__ && __cplusplus >= 201300L) || _MSC_VER >= 1900
42 /* using override */ using std::make_unique;
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)...));
52 // Allows 'make_unique<T[]>(10)'. (N3690 s20.9.1.4 p3-4)
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]());
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;
68 * static_function_deleter
70 * So you can write this:
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())
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
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())
87 template <typename T, void(*f)(T*)>
88 struct static_function_deleter {
89 void operator()(T* t) const {
97 * Convert unique_ptr to shared_ptr without specifying the template type
98 * parameter and letting the compiler deduce it.
100 * So you can write this:
102 * auto sptr = to_shared_ptr(getSomethingUnique<T>());
106 * auto sptr = shared_ptr<T>(getSomethingUnique<T>());
108 * Useful when `T` is long, such as:
110 * using T = foobar::FooBarAsyncClient;
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));
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.
123 * So you can write this:
125 * auto wptr = to_weak_ptr(getSomethingShared<T>());
129 * auto wptr = weak_ptr<T>(getSomethingShared<T>());
131 * Useful when `T` is long, such as:
133 * using T = foobar::FooBarAsyncClient;
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);
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.
146 inline void SysFree(void* p) {
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));
158 * A SimpleAllocator must provide two methods:
160 * void* allocate(size_t size);
161 * void deallocate(void* ptr);
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
168 * SysAlloc resembles the standard allocator.
172 void* allocate(size_t size) {
173 void* p = ::malloc(size);
175 throw std::bad_alloc();
179 void deallocate(void* p) {
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.
190 * But note that if you pass StlAllocator<MallocAllocator,...> to a
191 * standard container it will be larger due to the contained state
194 * @author: Tudor Bosman <tudorb@fb.com>
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;
201 template <class Alloc> class StlAllocator<Alloc, void> {
203 typedef void value_type;
204 typedef void* pointer;
205 typedef const void* const_pointer;
207 StlAllocator() : alloc_(nullptr) { }
208 explicit StlAllocator(Alloc* a) : alloc_(a) { }
210 Alloc* alloc() const {
214 template <class U> struct rebind {
215 typedef StlAllocator<Alloc, U> other;
218 bool operator!=(const StlAllocator<Alloc, void>& other) const {
219 return alloc_ != other.alloc_;
222 bool operator==(const StlAllocator<Alloc, void>& other) const {
223 return alloc_ == other.alloc_;
230 template <class Alloc, class T>
233 typedef T value_type;
235 typedef const T* const_pointer;
236 typedef T& reference;
237 typedef const T& const_reference;
239 typedef ptrdiff_t difference_type;
240 typedef size_t size_type;
242 StlAllocator() : alloc_(nullptr) { }
243 explicit StlAllocator(Alloc* a) : alloc_(a) { }
245 template <class U> StlAllocator(const StlAllocator<Alloc, U>& other)
246 : alloc_(other.alloc()) { }
248 T* allocate(size_t n, const void* /* hint */ = nullptr) {
249 return static_cast<T*>(alloc_->allocate(n * sizeof(T)));
252 void deallocate(T* p, size_t /* n */) { alloc_->deallocate(p); }
254 size_t max_size() const {
255 return std::numeric_limits<size_t>::max();
258 T* address(T& x) const {
259 return std::addressof(x);
262 const T* address(const T& x) const {
263 return std::addressof(x);
266 template <class... Args>
267 void construct(T* p, Args&&... args) {
268 new (p) T(std::forward<Args>(args)...);
275 Alloc* alloc() const {
279 template <class U> struct rebind {
280 typedef StlAllocator<Alloc, U> other;
283 bool operator!=(const StlAllocator<Alloc, T>& other) const {
284 return alloc_ != other.alloc_;
287 bool operator==(const StlAllocator<Alloc, T>& other) const {
288 return alloc_ == other.alloc_;
296 * Helper function to obtain rebound allocators
298 * @author: Marcelo Juchem <marcelo@fb.com>
300 template <typename T, typename Allocator>
301 typename Allocator::template rebind<T>::other rebind_allocator(
302 Allocator const& allocator
304 return typename Allocator::template rebind<T>::other(allocator);
308 * Helper classes/functions for creating a unique_ptr using a custom
311 * @author: Marcelo Juchem <marcelo@fb.com>
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
320 typedef typename std::remove_reference<Allocator>::type allocator_type;
323 typedef typename Allocator::pointer pointer;
325 allocator_delete() = default;
327 explicit allocator_delete(const allocator_type& allocator)
328 : allocator_type(allocator)
331 explicit allocator_delete(allocator_type&& allocator)
332 : allocator_type(std::move(allocator))
335 template <typename U>
336 allocator_delete(const allocator_delete<U>& other)
337 : allocator_type(other.get_allocator())
340 allocator_type& get_allocator() const {
341 return *const_cast<allocator_delete*>(this);
344 void operator()(pointer p) const {
348 const_cast<allocator_delete*>(this)->destroy(p);
349 const_cast<allocator_delete*>(this)->deallocate(p, 1);
353 template <typename T, typename Allocator>
354 class is_simple_allocator {
355 FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_destroy, destroy);
357 typedef typename std::remove_const<
358 typename std::remove_reference<Allocator>::type
360 typedef typename std::remove_reference<T>::type value_type;
361 typedef value_type* pointer;
364 constexpr static bool value = !has_destroy<allocator, void(pointer)>::value
365 && !has_destroy<allocator, void(void*)>::value;
368 template <typename T, typename Allocator>
369 struct as_stl_allocator {
370 typedef typename std::conditional<
371 is_simple_allocator<T, Allocator>::value,
373 typename std::remove_reference<Allocator>::type,
374 typename std::remove_reference<T>::type
376 typename std::remove_reference<Allocator>::type
380 template <typename T, typename Allocator>
381 typename std::enable_if<
382 is_simple_allocator<T, Allocator>::value,
384 typename std::remove_reference<Allocator>::type,
385 typename std::remove_reference<T>::type
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
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);
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<
414 is_simple_allocator<T, Allocator>::value,
415 folly::StlAllocator<typename std::remove_reference<Allocator>::type, T>,
416 typename std::remove_reference<Allocator>::type
423 * Functions to allocate a unique_ptr / shared_ptr, supporting both
424 * STL-style allocators and SimpleAllocator, analog to std::allocate_shared
426 * @author: Marcelo Juchem <marcelo@fb.com>
429 template <typename T, typename Allocator, typename ...Args>
430 typename AllocatorUniquePtr<T, Allocator>::type allocate_unique(
431 Allocator&& allocator, Args&&... args
433 auto stlAllocator = folly::make_stl_allocator<T>(
434 std::forward<Allocator>(allocator)
436 auto p = stlAllocator.allocate(1);
439 stlAllocator.construct(p, std::forward<Args>(args)...);
442 folly::allocator_delete<decltype(stlAllocator)>(std::move(stlAllocator))
445 stlAllocator.deallocate(p, 1);
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)...
459 * IsArenaAllocator<T>::value describes whether SimpleAllocator has
460 * no-op deallocate().
462 template <class T> struct IsArenaAllocator : std::false_type { };
465 * folly::enable_shared_from_this
467 * To be removed once C++17 becomes a minimum requirement for folly.
469 #if __cplusplus >= 201700L || \
470 __cpp_lib_enable_shared_from_this >= 201603L
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;
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.
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.
489 * class MyClass : public folly::enable_shared_from_this<MyClass> {};
492 * std::shared_ptr<MyClass> sp = std::make_shared<MyClass>();
493 * std::weak_ptr<MyClass> wp = sp->weak_from_this();
496 template <typename T>
497 class enable_shared_from_this : public std::enable_shared_from_this<T> {
499 constexpr enable_shared_from_this() noexcept = default;
501 std::weak_ptr<T> weak_from_this() noexcept {
502 return weak_from_this_<T>(this);
505 std::weak_ptr<T const> weak_from_this() const noexcept {
506 return weak_from_this_<T>(this);
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();
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();
525 template <typename U>
526 std::weak_ptr<U> weak_from_this_(...) noexcept {
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>{};
541 template <typename U>
542 std::weak_ptr<U const> weak_from_this_(...) const noexcept {
544 return this->shared_from_this();
545 } catch (std::bad_weak_ptr const&) {
546 return std::weak_ptr<U const>{};