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.
18 * Nicholas Ormrod (njormrod)
19 * Andrei Alexandrescu (aalexandre)
21 * FBVector is Facebook's drop-in implementation of std::vector. It has special
22 * optimizations for use with relocatable types and jemalloc.
27 //=============================================================================
35 #include <type_traits>
38 #include <folly/FormatTraits.h>
39 #include <folly/Likely.h>
40 #include <folly/Malloc.h>
41 #include <folly/Traits.h>
42 #include <folly/portability/BitsFunctexcept.h>
44 //=============================================================================
45 // forward declaration
48 template <class T, class Allocator = std::allocator<T>>
52 //=============================================================================
55 #define FOLLY_FBV_UNROLL_PTR(first, last, OP) do { \
56 for (; (last) - (first) >= 4; (first) += 4) { \
62 for (; (first) != (last); ++(first)) OP((first)); \
65 //=============================================================================
66 ///////////////////////////////////////////////////////////////////////////////
70 ///////////////////////////////////////////////////////////////////////////////
74 template <class T, class Allocator>
77 //===========================================================================
78 //---------------------------------------------------------------------------
82 typedef std::allocator_traits<Allocator> A;
84 struct Impl : public Allocator {
86 typedef typename A::pointer pointer;
87 typedef typename A::size_type size_type;
93 Impl() : Allocator(), b_(nullptr), e_(nullptr), z_(nullptr) {}
94 /* implicit */ Impl(const Allocator& a)
95 : Allocator(a), b_(nullptr), e_(nullptr), z_(nullptr) {}
96 /* implicit */ Impl(Allocator&& a)
97 : Allocator(std::move(a)), b_(nullptr), e_(nullptr), z_(nullptr) {}
99 /* implicit */ Impl(size_type n, const Allocator& a = Allocator())
103 Impl(Impl&& other) noexcept
104 : Allocator(std::move(other)),
105 b_(other.b_), e_(other.e_), z_(other.z_)
106 { other.b_ = other.e_ = other.z_ = nullptr; }
114 // note that 'allocate' and 'deallocate' are inherited from Allocator
115 T* D_allocate(size_type n) {
116 if (usingStdAllocator::value) {
117 return static_cast<T*>(malloc(n * sizeof(T)));
119 return std::allocator_traits<Allocator>::allocate(*this, n);
123 void D_deallocate(T* p, size_type n) noexcept {
124 if (usingStdAllocator::value) {
127 std::allocator_traits<Allocator>::deallocate(*this, p, n);
132 void swapData(Impl& other) {
133 std::swap(b_, other.b_);
134 std::swap(e_, other.e_);
135 std::swap(z_, other.z_);
139 inline void destroy() noexcept {
141 // THIS DISPATCH CODE IS DUPLICATED IN fbvector::D_destroy_range_a.
142 // It has been inlined here for speed. It calls the static fbvector
143 // methods to perform the actual destruction.
144 if (usingStdAllocator::value) {
145 S_destroy_range(b_, e_);
147 S_destroy_range_a(*this, b_, e_);
150 D_deallocate(b_, size_type(z_ - b_));
154 void init(size_type n) {
155 if (UNLIKELY(n == 0)) {
156 b_ = e_ = z_ = nullptr;
158 size_type sz = folly::goodMallocSize(n * sizeof(T)) / sizeof(T);
165 void set(pointer newB, size_type newSize, size_type newCap) {
171 void reset(size_type newCap) {
180 void reset() { // same as reset(0)
182 b_ = e_ = z_ = nullptr;
186 static void swap(Impl& a, Impl& b) {
188 if (!usingStdAllocator::value) swap<Allocator>(a, b);
192 //===========================================================================
193 //---------------------------------------------------------------------------
194 // types and constants
197 typedef T value_type;
198 typedef value_type& reference;
199 typedef const value_type& const_reference;
201 typedef const T* const_iterator;
202 typedef size_t size_type;
203 typedef typename std::make_signed<size_type>::type difference_type;
204 typedef Allocator allocator_type;
205 typedef typename A::pointer pointer;
206 typedef typename A::const_pointer const_pointer;
207 typedef std::reverse_iterator<iterator> reverse_iterator;
208 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
212 typedef std::integral_constant<bool,
213 IsTriviallyCopyable<T>::value &&
214 sizeof(T) <= 16 // don't force large structures to be passed by value
215 > should_pass_by_value;
216 typedef typename std::conditional<
217 should_pass_by_value::value, T, const T&>::type VT;
218 typedef typename std::conditional<
219 should_pass_by_value::value, T, T&&>::type MT;
221 typedef std::integral_constant<bool,
222 std::is_same<Allocator, std::allocator<T>>::value> usingStdAllocator;
223 typedef std::integral_constant<bool,
224 usingStdAllocator::value ||
225 A::propagate_on_container_move_assignment::value> moveIsSwap;
227 //===========================================================================
228 //---------------------------------------------------------------------------
232 //---------------------------------------------------------------------------
235 T* M_allocate(size_type n) {
236 return impl_.D_allocate(n);
239 //---------------------------------------------------------------------------
242 void M_deallocate(T* p, size_type n) noexcept {
243 impl_.D_deallocate(p, n);
246 //---------------------------------------------------------------------------
249 // GCC is very sensitive to the exact way that construct is called. For
250 // that reason there are several different specializations of construct.
252 template <typename U, typename... Args>
253 void M_construct(U* p, Args&&... args) {
254 if (usingStdAllocator::value) {
255 new (p) U(std::forward<Args>(args)...);
257 std::allocator_traits<Allocator>::construct(
258 impl_, p, std::forward<Args>(args)...);
262 template <typename U, typename... Args>
263 static void S_construct(U* p, Args&&... args) {
264 new (p) U(std::forward<Args>(args)...);
267 template <typename U, typename... Args>
268 static void S_construct_a(Allocator& a, U* p, Args&&... args) {
269 std::allocator_traits<Allocator>::construct(
270 a, p, std::forward<Args>(args)...);
273 // scalar optimization
274 // TODO we can expand this optimization to: default copyable and assignable
275 template <typename U, typename Enable = typename
276 std::enable_if<std::is_scalar<U>::value>::type>
277 void M_construct(U* p, U arg) {
278 if (usingStdAllocator::value) {
281 std::allocator_traits<Allocator>::construct(impl_, p, arg);
285 template <typename U, typename Enable = typename
286 std::enable_if<std::is_scalar<U>::value>::type>
287 static void S_construct(U* p, U arg) {
291 template <typename U, typename Enable = typename
292 std::enable_if<std::is_scalar<U>::value>::type>
293 static void S_construct_a(Allocator& a, U* p, U arg) {
294 std::allocator_traits<Allocator>::construct(a, p, arg);
297 // const& optimization
298 template <typename U, typename Enable = typename
299 std::enable_if<!std::is_scalar<U>::value>::type>
300 void M_construct(U* p, const U& value) {
301 if (usingStdAllocator::value) {
304 std::allocator_traits<Allocator>::construct(impl_, p, value);
308 template <typename U, typename Enable = typename
309 std::enable_if<!std::is_scalar<U>::value>::type>
310 static void S_construct(U* p, const U& value) {
314 template <typename U, typename Enable = typename
315 std::enable_if<!std::is_scalar<U>::value>::type>
316 static void S_construct_a(Allocator& a, U* p, const U& value) {
317 std::allocator_traits<Allocator>::construct(a, p, value);
320 //---------------------------------------------------------------------------
323 void M_destroy(T* p) noexcept {
324 if (usingStdAllocator::value) {
325 if (!std::is_trivially_destructible<T>::value)
328 std::allocator_traits<Allocator>::destroy(impl_, p);
332 //===========================================================================
333 //---------------------------------------------------------------------------
334 // algorithmic helpers
337 //---------------------------------------------------------------------------
341 void M_destroy_range_e(T* pos) noexcept {
342 D_destroy_range_a(pos, impl_.e_);
347 // THIS DISPATCH CODE IS DUPLICATED IN IMPL. SEE IMPL FOR DETAILS.
348 void D_destroy_range_a(T* first, T* last) noexcept {
349 if (usingStdAllocator::value) {
350 S_destroy_range(first, last);
352 S_destroy_range_a(impl_, first, last);
357 static void S_destroy_range_a(Allocator& a, T* first, T* last) noexcept {
358 for (; first != last; ++first)
359 std::allocator_traits<Allocator>::destroy(a, first);
363 static void S_destroy_range(T* first, T* last) noexcept {
364 if (!std::is_trivially_destructible<T>::value) {
365 // EXPERIMENTAL DATA on fbvector<vector<int>> (where each vector<int> has
367 // The unrolled version seems to work faster for small to medium sized
368 // fbvectors. It gets a 10% speedup on fbvectors of size 1024, 64, and
370 // The simple loop version seems to work faster for large fbvectors. The
371 // unrolled version is about 6% slower on fbvectors on size 16384.
372 // The two methods seem tied for very large fbvectors. The unrolled
373 // version is about 0.5% slower on size 262144.
375 // for (; first != last; ++first) first->~T();
376 #define FOLLY_FBV_OP(p) (p)->~T()
377 FOLLY_FBV_UNROLL_PTR(first, last, FOLLY_FBV_OP)
382 //---------------------------------------------------------------------------
383 // uninitialized_fill_n
386 void M_uninitialized_fill_n_e(size_type sz) {
387 D_uninitialized_fill_n_a(impl_.e_, sz);
391 void M_uninitialized_fill_n_e(size_type sz, VT value) {
392 D_uninitialized_fill_n_a(impl_.e_, sz, value);
397 void D_uninitialized_fill_n_a(T* dest, size_type sz) {
398 if (usingStdAllocator::value) {
399 S_uninitialized_fill_n(dest, sz);
401 S_uninitialized_fill_n_a(impl_, dest, sz);
405 void D_uninitialized_fill_n_a(T* dest, size_type sz, VT value) {
406 if (usingStdAllocator::value) {
407 S_uninitialized_fill_n(dest, sz, value);
409 S_uninitialized_fill_n_a(impl_, dest, sz, value);
414 template <typename... Args>
415 static void S_uninitialized_fill_n_a(Allocator& a, T* dest,
416 size_type sz, Args&&... args) {
421 std::allocator_traits<Allocator>::construct(a, b,
422 std::forward<Args>(args)...);
424 S_destroy_range_a(a, dest, b);
430 static void S_uninitialized_fill_n(T* dest, size_type n) {
431 if (folly::IsZeroInitializable<T>::value) {
432 if (LIKELY(n != 0)) {
433 std::memset(dest, 0, sizeof(T) * n);
439 for (; b != e; ++b) S_construct(b);
442 for (; b >= dest; --b) b->~T();
448 static void S_uninitialized_fill_n(T* dest, size_type n, const T& value) {
452 for (; b != e; ++b) S_construct(b, value);
454 S_destroy_range(dest, b);
459 //---------------------------------------------------------------------------
460 // uninitialized_copy
462 // it is possible to add an optimization for the case where
463 // It = move(T*) and IsRelocatable<T> and Is0Initiailizable<T>
466 template <typename It>
467 void M_uninitialized_copy_e(It first, It last) {
468 D_uninitialized_copy_a(impl_.e_, first, last);
469 impl_.e_ += std::distance(first, last);
472 template <typename It>
473 void M_uninitialized_move_e(It first, It last) {
474 D_uninitialized_move_a(impl_.e_, first, last);
475 impl_.e_ += std::distance(first, last);
479 template <typename It>
480 void D_uninitialized_copy_a(T* dest, It first, It last) {
481 if (usingStdAllocator::value) {
482 if (folly::IsTriviallyCopyable<T>::value) {
483 S_uninitialized_copy_bits(dest, first, last);
485 S_uninitialized_copy(dest, first, last);
488 S_uninitialized_copy_a(impl_, dest, first, last);
492 template <typename It>
493 void D_uninitialized_move_a(T* dest, It first, It last) {
494 D_uninitialized_copy_a(dest,
495 std::make_move_iterator(first), std::make_move_iterator(last));
499 template <typename It>
501 S_uninitialized_copy_a(Allocator& a, T* dest, It first, It last) {
504 for (; first != last; ++first, ++b)
505 std::allocator_traits<Allocator>::construct(a, b, *first);
507 S_destroy_range_a(a, dest, b);
513 template <typename It>
514 static void S_uninitialized_copy(T* dest, It first, It last) {
517 for (; first != last; ++first, ++b)
518 S_construct(b, *first);
520 S_destroy_range(dest, b);
526 S_uninitialized_copy_bits(T* dest, const T* first, const T* last) {
528 std::memcpy((void*)dest, (void*)first, (last - first) * sizeof(T));
533 S_uninitialized_copy_bits(T* dest, std::move_iterator<T*> first,
534 std::move_iterator<T*> last) {
535 T* bFirst = first.base();
536 T* bLast = last.base();
537 if (bLast != bFirst) {
538 std::memcpy((void*)dest, (void*)bFirst, (bLast - bFirst) * sizeof(T));
542 template <typename It>
544 S_uninitialized_copy_bits(T* dest, It first, It last) {
545 S_uninitialized_copy(dest, first, last);
548 //---------------------------------------------------------------------------
551 // This function is "unsafe": it assumes that the iterator can be advanced at
552 // least n times. However, as a private function, that unsafety is managed
553 // wholly by fbvector itself.
555 template <typename It>
556 static It S_copy_n(T* dest, It first, size_type n) {
558 for (; dest != e; ++dest, ++first) *dest = *first;
562 static const T* S_copy_n(T* dest, const T* first, size_type n) {
563 if (folly::IsTriviallyCopyable<T>::value) {
564 std::memcpy((void*)dest, (void*)first, n * sizeof(T));
567 return S_copy_n<const T*>(dest, first, n);
571 static std::move_iterator<T*>
572 S_copy_n(T* dest, std::move_iterator<T*> mIt, size_type n) {
573 if (folly::IsTriviallyCopyable<T>::value) {
574 T* first = mIt.base();
575 std::memcpy((void*)dest, (void*)first, n * sizeof(T));
576 return std::make_move_iterator(first + n);
578 return S_copy_n<std::move_iterator<T*>>(dest, mIt, n);
582 //===========================================================================
583 //---------------------------------------------------------------------------
584 // relocation helpers
587 // Relocation is divided into three parts:
590 // Performs the actual movement of data from point a to point b.
593 // Destroys the old data.
596 // Destoys the new data and restores the old data.
598 // The three steps are used because there may be an exception after part 1
599 // has completed. If that is the case, then relocate_undo can nullify the
600 // initial move. Otherwise, relocate_done performs the last bit of tidying
603 // The relocation trio may use either memcpy, move, or copy. It is decided
604 // by the following case statement:
606 // IsRelocatable && usingStdAllocator -> memcpy
607 // has_nothrow_move && usingStdAllocator -> move
608 // cannot copy -> move
611 // If the class is non-copyable then it must be movable. However, if the
612 // move constructor is not noexcept, i.e. an error could be thrown, then
613 // relocate_undo will be unable to restore the old data, for fear of a
614 // second exception being thrown. This is a known and unavoidable
615 // deficiency. In lieu of a strong exception guarantee, relocate_undo does
616 // the next best thing: it provides a weak exception guarantee by
617 // destorying the new data, but leaving the old data in an indeterminate
618 // state. Note that that indeterminate state will be valid, since the
619 // old data has not been destroyed; it has merely been the source of a
620 // move, which is required to leave the source in a valid state.
623 void M_relocate(T* newB) {
624 relocate_move(newB, impl_.b_, impl_.e_);
625 relocate_done(newB, impl_.b_, impl_.e_);
628 // dispatch type trait
629 typedef std::integral_constant<bool,
630 folly::IsRelocatable<T>::value && usingStdAllocator::value
631 > relocate_use_memcpy;
633 typedef std::integral_constant<bool,
634 (std::is_nothrow_move_constructible<T>::value
635 && usingStdAllocator::value)
636 || !std::is_copy_constructible<T>::value
640 void relocate_move(T* dest, T* first, T* last) {
641 relocate_move_or_memcpy(dest, first, last, relocate_use_memcpy());
644 void relocate_move_or_memcpy(T* dest, T* first, T* last, std::true_type) {
645 if (first != nullptr) {
646 std::memcpy((void*)dest, (void*)first, (last - first) * sizeof(T));
650 void relocate_move_or_memcpy(T* dest, T* first, T* last, std::false_type) {
651 relocate_move_or_copy(dest, first, last, relocate_use_move());
654 void relocate_move_or_copy(T* dest, T* first, T* last, std::true_type) {
655 D_uninitialized_move_a(dest, first, last);
658 void relocate_move_or_copy(T* dest, T* first, T* last, std::false_type) {
659 D_uninitialized_copy_a(dest, first, last);
663 void relocate_done(T* /*dest*/, T* first, T* last) noexcept {
664 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
665 // used memcpy; data has been relocated, do not call destructor
667 D_destroy_range_a(first, last);
672 void relocate_undo(T* dest, T* first, T* last) noexcept {
673 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
674 // used memcpy, old data is still valid, nothing to do
675 } else if (std::is_nothrow_move_constructible<T>::value &&
676 usingStdAllocator::value) {
677 // noexcept move everything back, aka relocate_move
678 relocate_move(first, dest, dest + (last - first));
679 } else if (!std::is_copy_constructible<T>::value) {
681 D_destroy_range_a(dest, dest + (last - first));
683 // used copy, old data is still valid
684 D_destroy_range_a(dest, dest + (last - first));
689 //===========================================================================
690 //---------------------------------------------------------------------------
691 // construct/copy/destroy
694 fbvector() = default;
696 explicit fbvector(const Allocator& a) : impl_(a) {}
698 explicit fbvector(size_type n, const Allocator& a = Allocator())
700 { M_uninitialized_fill_n_e(n); }
702 fbvector(size_type n, VT value, const Allocator& a = Allocator())
704 { M_uninitialized_fill_n_e(n, value); }
706 template <class It, class Category = typename
707 std::iterator_traits<It>::iterator_category>
708 fbvector(It first, It last, const Allocator& a = Allocator())
709 : fbvector(first, last, a, Category()) {}
711 fbvector(const fbvector& other)
712 : impl_(other.size(), A::select_on_container_copy_construction(other.impl_))
713 { M_uninitialized_copy_e(other.begin(), other.end()); }
715 fbvector(fbvector&& other) noexcept : impl_(std::move(other.impl_)) {}
717 fbvector(const fbvector& other, const Allocator& a)
718 : fbvector(other.begin(), other.end(), a) {}
720 /* may throw */ fbvector(fbvector&& other, const Allocator& a) : impl_(a) {
721 if (impl_ == other.impl_) {
722 impl_.swapData(other.impl_);
724 impl_.init(other.size());
725 M_uninitialized_move_e(other.begin(), other.end());
729 fbvector(std::initializer_list<T> il, const Allocator& a = Allocator())
730 : fbvector(il.begin(), il.end(), a) {}
732 ~fbvector() = default; // the cleanup occurs in impl_
734 fbvector& operator=(const fbvector& other) {
735 if (UNLIKELY(this == &other)) return *this;
737 if (!usingStdAllocator::value &&
738 A::propagate_on_container_copy_assignment::value) {
739 if (impl_ != other.impl_) {
740 // can't use other's different allocator to clean up self
743 (Allocator&)impl_ = (Allocator&)other.impl_;
746 assign(other.begin(), other.end());
750 fbvector& operator=(fbvector&& other) {
751 if (UNLIKELY(this == &other)) return *this;
752 moveFrom(std::move(other), moveIsSwap());
756 fbvector& operator=(std::initializer_list<T> il) {
757 assign(il.begin(), il.end());
761 template <class It, class Category = typename
762 std::iterator_traits<It>::iterator_category>
763 void assign(It first, It last) {
764 assign(first, last, Category());
767 void assign(size_type n, VT value) {
768 if (n > capacity()) {
769 // Not enough space. Do not reserve in place, since we will
770 // discard the old values anyways.
771 if (dataIsInternalAndNotVT(value)) {
772 T copy(std::move(value));
774 M_uninitialized_fill_n_e(n, copy);
777 M_uninitialized_fill_n_e(n, value);
779 } else if (n <= size()) {
780 auto newE = impl_.b_ + n;
781 std::fill(impl_.b_, newE, value);
782 M_destroy_range_e(newE);
784 std::fill(impl_.b_, impl_.e_, value);
785 M_uninitialized_fill_n_e(n - size(), value);
789 void assign(std::initializer_list<T> il) {
790 assign(il.begin(), il.end());
793 allocator_type get_allocator() const noexcept {
799 // contract dispatch for iterator types fbvector(It first, It last)
800 template <class ForwardIterator>
801 fbvector(ForwardIterator first, ForwardIterator last,
802 const Allocator& a, std::forward_iterator_tag)
803 : impl_(size_type(std::distance(first, last)), a)
804 { M_uninitialized_copy_e(first, last); }
806 template <class InputIterator>
807 fbvector(InputIterator first, InputIterator last,
808 const Allocator& a, std::input_iterator_tag)
810 { for (; first != last; ++first) emplace_back(*first); }
812 // contract dispatch for allocator movement in operator=(fbvector&&)
814 moveFrom(fbvector&& other, std::true_type) {
815 swap(impl_, other.impl_);
817 void moveFrom(fbvector&& other, std::false_type) {
818 if (impl_ == other.impl_) {
819 impl_.swapData(other.impl_);
821 impl_.reset(other.size());
822 M_uninitialized_move_e(other.begin(), other.end());
826 // contract dispatch for iterator types in assign(It first, It last)
827 template <class ForwardIterator>
828 void assign(ForwardIterator first, ForwardIterator last,
829 std::forward_iterator_tag) {
830 const auto newSize = size_type(std::distance(first, last));
831 if (newSize > capacity()) {
832 impl_.reset(newSize);
833 M_uninitialized_copy_e(first, last);
834 } else if (newSize <= size()) {
835 auto newEnd = std::copy(first, last, impl_.b_);
836 M_destroy_range_e(newEnd);
838 auto mid = S_copy_n(impl_.b_, first, size());
839 M_uninitialized_copy_e<decltype(last)>(mid, last);
843 template <class InputIterator>
844 void assign(InputIterator first, InputIterator last,
845 std::input_iterator_tag) {
847 for (; first != last && p != impl_.e_; ++first, ++p) {
851 M_destroy_range_e(p);
853 for (; first != last; ++first) emplace_back(*first);
857 // contract dispatch for aliasing under VT optimization
858 bool dataIsInternalAndNotVT(const T& t) {
859 if (should_pass_by_value::value) return false;
860 return dataIsInternal(t);
862 bool dataIsInternal(const T& t) {
863 return UNLIKELY(impl_.b_ <= std::addressof(t) &&
864 std::addressof(t) < impl_.e_);
868 //===========================================================================
869 //---------------------------------------------------------------------------
873 iterator begin() noexcept {
876 const_iterator begin() const noexcept {
879 iterator end() noexcept {
882 const_iterator end() const noexcept {
885 reverse_iterator rbegin() noexcept {
886 return reverse_iterator(end());
888 const_reverse_iterator rbegin() const noexcept {
889 return const_reverse_iterator(end());
891 reverse_iterator rend() noexcept {
892 return reverse_iterator(begin());
894 const_reverse_iterator rend() const noexcept {
895 return const_reverse_iterator(begin());
898 const_iterator cbegin() const noexcept {
901 const_iterator cend() const noexcept {
904 const_reverse_iterator crbegin() const noexcept {
905 return const_reverse_iterator(end());
907 const_reverse_iterator crend() const noexcept {
908 return const_reverse_iterator(begin());
911 //===========================================================================
912 //---------------------------------------------------------------------------
916 size_type size() const noexcept {
917 return size_type(impl_.e_ - impl_.b_);
920 size_type max_size() const noexcept {
921 // good luck gettin' there
922 return ~size_type(0);
925 void resize(size_type n) {
927 M_destroy_range_e(impl_.b_ + n);
930 M_uninitialized_fill_n_e(n - size());
934 void resize(size_type n, VT t) {
936 M_destroy_range_e(impl_.b_ + n);
937 } else if (dataIsInternalAndNotVT(t) && n > capacity()) {
940 M_uninitialized_fill_n_e(n - size(), copy);
943 M_uninitialized_fill_n_e(n - size(), t);
947 size_type capacity() const noexcept {
948 return size_type(impl_.z_ - impl_.b_);
951 bool empty() const noexcept {
952 return impl_.b_ == impl_.e_;
955 void reserve(size_type n) {
956 if (n <= capacity()) return;
957 if (impl_.b_ && reserve_in_place(n)) return;
959 auto newCap = folly::goodMallocSize(n * sizeof(T)) / sizeof(T);
960 auto newB = M_allocate(newCap);
964 M_deallocate(newB, newCap);
968 M_deallocate(impl_.b_, size_type(impl_.z_ - impl_.b_));
969 impl_.z_ = newB + newCap;
970 impl_.e_ = newB + (impl_.e_ - impl_.b_);
974 void shrink_to_fit() noexcept {
980 auto const newCapacityBytes = folly::goodMallocSize(size() * sizeof(T));
981 auto const newCap = newCapacityBytes / sizeof(T);
982 auto const oldCap = capacity();
984 if (newCap >= oldCap) return;
987 // xallocx() will shrink to precisely newCapacityBytes (which was generated
988 // by goodMallocSize()) if it successfully shrinks in place.
989 if ((usingJEMalloc() && usingStdAllocator::value) &&
990 newCapacityBytes >= folly::jemallocMinInPlaceExpandable &&
991 xallocx(p, newCapacityBytes, 0, 0) == newCapacityBytes) {
992 impl_.z_ += newCap - oldCap;
994 T* newB; // intentionally uninitialized
996 newB = M_allocate(newCap);
1000 M_deallocate(newB, newCap);
1001 return; // swallow the error
1007 M_deallocate(impl_.b_, size_type(impl_.z_ - impl_.b_));
1008 impl_.z_ = newB + newCap;
1009 impl_.e_ = newB + (impl_.e_ - impl_.b_);
1016 bool reserve_in_place(size_type n) {
1017 if (!usingStdAllocator::value || !usingJEMalloc()) return false;
1019 // jemalloc can never grow in place blocks smaller than 4096 bytes.
1020 if ((impl_.z_ - impl_.b_) * sizeof(T) <
1021 folly::jemallocMinInPlaceExpandable) return false;
1023 auto const newCapacityBytes = folly::goodMallocSize(n * sizeof(T));
1025 if (xallocx(p, newCapacityBytes, 0, 0) == newCapacityBytes) {
1026 impl_.z_ = impl_.b_ + newCapacityBytes / sizeof(T);
1032 //===========================================================================
1033 //---------------------------------------------------------------------------
1037 reference operator[](size_type n) {
1041 const_reference operator[](size_type n) const {
1045 const_reference at(size_type n) const {
1046 if (UNLIKELY(n >= size())) {
1047 std::__throw_out_of_range("fbvector: index is greater than size.");
1051 reference at(size_type n) {
1052 auto const& cThis = *this;
1053 return const_cast<reference>(cThis.at(n));
1059 const_reference front() const {
1065 return impl_.e_[-1];
1067 const_reference back() const {
1069 return impl_.e_[-1];
1072 //===========================================================================
1073 //---------------------------------------------------------------------------
1077 T* data() noexcept {
1080 const T* data() const noexcept {
1084 //===========================================================================
1085 //---------------------------------------------------------------------------
1086 // modifiers (common)
1089 template <class... Args>
1090 void emplace_back(Args&&... args) {
1091 if (impl_.e_ != impl_.z_) {
1092 M_construct(impl_.e_, std::forward<Args>(args)...);
1095 emplace_back_aux(std::forward<Args>(args)...);
1100 push_back(const T& value) {
1101 if (impl_.e_ != impl_.z_) {
1102 M_construct(impl_.e_, value);
1105 emplace_back_aux(value);
1110 push_back(T&& value) {
1111 if (impl_.e_ != impl_.z_) {
1112 M_construct(impl_.e_, std::move(value));
1115 emplace_back_aux(std::move(value));
1122 M_destroy(impl_.e_);
1125 void swap(fbvector& other) noexcept {
1126 if (!usingStdAllocator::value &&
1127 A::propagate_on_container_swap::value)
1128 swap(impl_, other.impl_);
1129 else impl_.swapData(other.impl_);
1132 void clear() noexcept {
1133 M_destroy_range_e(impl_.b_);
1138 // std::vector implements a similar function with a different growth
1139 // strategy: empty() ? 1 : capacity() * 2.
1141 // fbvector grows differently on two counts:
1144 // Instead of growing to size 1 from empty, fbvector allocates at least
1145 // 64 bytes. You may still use reserve to reserve a lesser amount of
1148 // For medium-sized vectors, the growth strategy is 1.5x. See the docs
1150 // This does not apply to very small or very large fbvectors. This is a
1152 // A nice addition to fbvector would be the capability of having a user-
1153 // defined growth strategy, probably as part of the allocator.
1156 size_type computePushBackCapacity() const {
1157 if (capacity() == 0) {
1158 return std::max(64 / sizeof(T), size_type(1));
1160 if (capacity() < folly::jemallocMinInPlaceExpandable / sizeof(T)) {
1161 return capacity() * 2;
1163 if (capacity() > 4096 * 32 / sizeof(T)) {
1164 return capacity() * 2;
1166 return (capacity() * 3 + 1) / 2;
1169 template <class... Args>
1170 void emplace_back_aux(Args&&... args);
1172 //===========================================================================
1173 //---------------------------------------------------------------------------
1174 // modifiers (erase)
1177 iterator erase(const_iterator position) {
1178 return erase(position, position + 1);
1181 iterator erase(const_iterator first, const_iterator last) {
1182 assert(isValid(first) && isValid(last));
1183 assert(first <= last);
1184 if (first != last) {
1185 if (last == end()) {
1186 M_destroy_range_e((iterator)first);
1188 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
1189 D_destroy_range_a((iterator)first, (iterator)last);
1190 if (last - first >= cend() - last) {
1191 std::memcpy((void*)first, (void*)last, (cend() - last) * sizeof(T));
1193 std::memmove((iterator)first, last, (cend() - last) * sizeof(T));
1195 impl_.e_ -= (last - first);
1197 std::copy(std::make_move_iterator((iterator)last),
1198 std::make_move_iterator(end()), (iterator)first);
1199 auto newEnd = impl_.e_ - std::distance(first, last);
1200 M_destroy_range_e(newEnd);
1204 return (iterator)first;
1207 //===========================================================================
1208 //---------------------------------------------------------------------------
1209 // modifiers (insert)
1210 private: // we have the private section first because it defines some macros
1212 bool isValid(const_iterator it) {
1213 return cbegin() <= it && it <= cend();
1216 size_type computeInsertCapacity(size_type n) {
1217 size_type nc = std::max(computePushBackCapacity(), size() + n);
1218 size_type ac = folly::goodMallocSize(nc * sizeof(T)) / sizeof(T);
1222 //---------------------------------------------------------------------------
1224 // make_window takes an fbvector, and creates an uninitialized gap (a
1225 // window) at the given position, of the given size. The fbvector must
1226 // have enough capacity.
1228 // Explanation by picture.
1232 // make_window here of size 3
1236 // If something goes wrong and the window must be destroyed, use
1237 // undo_window to provide a weak exception guarantee. It destroys
1242 //---------------------------------------------------------------------------
1244 // wrap_frame takes an inverse window and relocates an fbvector around it.
1245 // The fbvector must have at least as many elements as the left ledge.
1247 // Explanation by picture.
1250 // fbvector: inverse window:
1251 // 123456789______ _____abcde_______
1255 // _______________ 12345abcde6789___
1257 //---------------------------------------------------------------------------
1259 // insert_use_fresh_memory returns true iff the fbvector should use a fresh
1260 // block of memory for the insertion. If the fbvector does not have enough
1261 // spare capacity, then it must return true. Otherwise either true or false
1264 //---------------------------------------------------------------------------
1266 // These three functions, make_window, wrap_frame, and
1267 // insert_use_fresh_memory, can be combined into a uniform interface.
1268 // Since that interface involves a lot of case-work, it is built into
1269 // some macros: FOLLY_FBVECTOR_INSERT_(PRE|START|TRY|END)
1270 // Macros are used in an attempt to let GCC perform better optimizations,
1271 // especially control flow optimization.
1274 //---------------------------------------------------------------------------
1277 void make_window(iterator position, size_type n) {
1278 // The result is guaranteed to be non-negative, so use an unsigned type:
1279 size_type tail = size_type(std::distance(position, impl_.e_));
1282 relocate_move(position + n, position, impl_.e_);
1283 relocate_done(position + n, position, impl_.e_);
1286 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
1287 std::memmove(position + n, position, tail * sizeof(T));
1290 D_uninitialized_move_a(impl_.e_, impl_.e_ - n, impl_.e_);
1292 std::copy_backward(std::make_move_iterator(position),
1293 std::make_move_iterator(impl_.e_ - n), impl_.e_);
1295 D_destroy_range_a(impl_.e_ - n, impl_.e_ + n);
1300 D_destroy_range_a(position, position + n);
1305 void undo_window(iterator position, size_type n) noexcept {
1306 D_destroy_range_a(position + n, impl_.e_);
1307 impl_.e_ = position;
1310 //---------------------------------------------------------------------------
1313 void wrap_frame(T* ledge, size_type idx, size_type n) {
1314 assert(size() >= idx);
1317 relocate_move(ledge, impl_.b_, impl_.b_ + idx);
1319 relocate_move(ledge + idx + n, impl_.b_ + idx, impl_.e_);
1321 relocate_undo(ledge, impl_.b_, impl_.b_ + idx);
1324 relocate_done(ledge, impl_.b_, impl_.b_ + idx);
1325 relocate_done(ledge + idx + n, impl_.b_ + idx, impl_.e_);
1328 //---------------------------------------------------------------------------
1331 bool insert_use_fresh(bool at_end, size_type n) {
1333 if (size() + n <= capacity()) return false;
1334 if (reserve_in_place(size() + n)) return false;
1338 if (size() + n > capacity()) return true;
1343 //---------------------------------------------------------------------------
1347 typename IsInternalFunc,
1348 typename InsertInternalFunc,
1349 typename ConstructFunc,
1350 typename DestroyFunc>
1351 iterator do_real_insert(
1352 const_iterator cpos,
1354 IsInternalFunc&& isInternalFunc,
1355 InsertInternalFunc&& insertInternalFunc,
1356 ConstructFunc&& constructFunc,
1357 DestroyFunc&& destroyFunc) {
1359 return iterator(cpos);
1361 bool at_end = cpos == cend();
1362 bool fresh = insert_use_fresh(at_end, n);
1364 if (!fresh && isInternalFunc()) {
1365 // check for internal data (technically not required by the standard)
1366 return insertInternalFunc();
1368 assert(isValid(cpos));
1370 T* position = const_cast<T*>(cpos);
1371 size_type idx = size_type(std::distance(impl_.b_, position));
1373 size_type newCap; /* intentionally uninitialized */
1376 newCap = computeInsertCapacity(n);
1377 b = M_allocate(newCap);
1380 make_window(position, n);
1389 // construct the inserted elements
1390 constructFunc(start);
1393 M_deallocate(b, newCap);
1396 undo_window(position, n);
1406 wrap_frame(b, idx, n);
1408 // delete the inserted elements (exception has been thrown)
1410 M_deallocate(b, newCap);
1414 M_deallocate(impl_.b_, capacity());
1416 impl_.set(b, size() + n, newCap);
1417 return impl_.b_ + idx;
1424 template <class... Args>
1425 iterator emplace(const_iterator cpos, Args&&... args) {
1426 return do_real_insert(
1429 [&] { return false; },
1430 [&] { return iterator{}; },
1431 [&](iterator start) {
1432 M_construct(start, std::forward<Args>(args)...);
1434 [&](iterator start) { M_destroy(start); });
1437 iterator insert(const_iterator cpos, const T& value) {
1438 return do_real_insert(
1441 [&] { return dataIsInternal(value); },
1442 [&] { return insert(cpos, T(value)); },
1443 [&](iterator start) { M_construct(start, value); },
1444 [&](iterator start) { M_destroy(start); });
1447 iterator insert(const_iterator cpos, T&& value) {
1448 return do_real_insert(
1451 [&] { return dataIsInternal(value); },
1452 [&] { return insert(cpos, T(std::move(value))); },
1453 [&](iterator start) { M_construct(start, std::move(value)); },
1454 [&](iterator start) { M_destroy(start); });
1457 iterator insert(const_iterator cpos, size_type n, VT value) {
1458 return do_real_insert(
1461 [&] { return dataIsInternalAndNotVT(value); },
1462 [&] { return insert(cpos, n, T(value)); },
1463 [&](iterator start) { D_uninitialized_fill_n_a(start, n, value); },
1464 [&](iterator start) { D_destroy_range_a(start, start + n); });
1467 template <class It, class Category = typename
1468 std::iterator_traits<It>::iterator_category>
1469 iterator insert(const_iterator cpos, It first, It last) {
1470 return insert(cpos, first, last, Category());
1473 iterator insert(const_iterator cpos, std::initializer_list<T> il) {
1474 return insert(cpos, il.begin(), il.end());
1477 //---------------------------------------------------------------------------
1478 // insert dispatch for iterator types
1481 template <class FIt>
1482 iterator insert(const_iterator cpos, FIt first, FIt last,
1483 std::forward_iterator_tag) {
1484 size_type n = size_type(std::distance(first, last));
1485 return do_real_insert(
1488 [&] { return false; },
1489 [&] { return iterator{}; },
1490 [&](iterator start) { D_uninitialized_copy_a(start, first, last); },
1491 [&](iterator start) { D_destroy_range_a(start, start + n); });
1494 template <class IIt>
1495 iterator insert(const_iterator cpos, IIt first, IIt last,
1496 std::input_iterator_tag) {
1497 T* position = const_cast<T*>(cpos);
1498 assert(isValid(position));
1499 size_type idx = std::distance(begin(), position);
1501 fbvector storage(std::make_move_iterator(position),
1502 std::make_move_iterator(end()),
1503 A::select_on_container_copy_construction(impl_));
1504 M_destroy_range_e(position);
1505 for (; first != last; ++first) emplace_back(*first);
1506 insert(cend(), std::make_move_iterator(storage.begin()),
1507 std::make_move_iterator(storage.end()));
1508 return impl_.b_ + idx;
1511 //===========================================================================
1512 //---------------------------------------------------------------------------
1513 // lexicographical functions
1516 bool operator==(const fbvector& other) const {
1517 return size() == other.size() && std::equal(begin(), end(), other.begin());
1520 bool operator!=(const fbvector& other) const {
1521 return !(*this == other);
1524 bool operator<(const fbvector& other) const {
1525 return std::lexicographical_compare(
1526 begin(), end(), other.begin(), other.end());
1529 bool operator>(const fbvector& other) const {
1530 return other < *this;
1533 bool operator<=(const fbvector& other) const {
1534 return !(*this > other);
1537 bool operator>=(const fbvector& other) const {
1538 return !(*this < other);
1541 //===========================================================================
1542 //---------------------------------------------------------------------------
1546 template <class _T, class _A>
1547 friend _T* relinquish(fbvector<_T, _A>&);
1549 template <class _T, class _A>
1550 friend void attach(fbvector<_T, _A>&, _T* data, size_t sz, size_t cap);
1552 }; // class fbvector
1555 //=============================================================================
1556 //-----------------------------------------------------------------------------
1557 // outlined functions (gcc, you finicky compiler you)
1559 template <typename T, typename Allocator>
1560 template <class... Args>
1561 void fbvector<T, Allocator>::emplace_back_aux(Args&&... args) {
1562 size_type byte_sz = folly::goodMallocSize(
1563 computePushBackCapacity() * sizeof(T));
1564 if (usingStdAllocator::value
1566 && ((impl_.z_ - impl_.b_) * sizeof(T) >=
1567 folly::jemallocMinInPlaceExpandable)) {
1568 // Try to reserve in place.
1569 // Ask xallocx to allocate in place at least size()+1 and at most sz space.
1570 // xallocx will allocate as much as possible within that range, which
1571 // is the best possible outcome: if sz space is available, take it all,
1572 // otherwise take as much as possible. If nothing is available, then fail.
1573 // In this fashion, we never relocate if there is a possibility of
1574 // expanding in place, and we never reallocate by less than the desired
1575 // amount unless we cannot expand further. Hence we will not reallocate
1576 // sub-optimally twice in a row (modulo the blocking memory being freed).
1577 size_type lower = folly::goodMallocSize(sizeof(T) + size() * sizeof(T));
1578 size_type upper = byte_sz;
1579 size_type extra = upper - lower;
1584 if ((actual = xallocx(p, lower, extra, 0)) >= lower) {
1585 impl_.z_ = impl_.b_ + actual / sizeof(T);
1586 M_construct(impl_.e_, std::forward<Args>(args)...);
1592 // Reallocation failed. Perform a manual relocation.
1593 size_type sz = byte_sz / sizeof(T);
1594 auto newB = M_allocate(sz);
1595 auto newE = newB + size();
1597 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
1598 // For linear memory access, relocate before construction.
1599 // By the test condition, relocate is noexcept.
1600 // Note that there is no cleanup to do if M_construct throws - that's
1601 // one of the beauties of relocation.
1602 // Benchmarks for this code have high variance, and seem to be close.
1603 relocate_move(newB, impl_.b_, impl_.e_);
1604 M_construct(newE, std::forward<Args>(args)...);
1607 M_construct(newE, std::forward<Args>(args)...);
1612 M_destroy(newE - 1);
1617 M_deallocate(newB, sz);
1620 if (impl_.b_) M_deallocate(impl_.b_, size());
1623 impl_.z_ = newB + sz;
1626 //=============================================================================
1627 //-----------------------------------------------------------------------------
1628 // specialized functions
1630 template <class T, class A>
1631 void swap(fbvector<T, A>& lhs, fbvector<T, A>& rhs) noexcept {
1635 //=============================================================================
1636 //-----------------------------------------------------------------------------
1642 template <class T, class A>
1643 struct IndexableTraits<fbvector<T, A>>
1644 : public IndexableTraitsSeq<fbvector<T, A>> {
1647 } // namespace detail
1649 template <class T, class A>
1650 void compactResize(fbvector<T, A>* v, size_t sz) {
1657 // relinquish and attach are not a members function specifically so that it is
1658 // awkward to call them. It is very easy to shoot yourself in the foot with
1661 // If you call relinquish, then it is your responsibility to free the data
1662 // and the storage, both of which may have been generated in a non-standard
1663 // way through the fbvector's allocator.
1665 // If you call attach, it is your responsibility to ensure that the fbvector
1666 // is fresh (size and capacity both zero), and that the supplied data is
1667 // capable of being manipulated by the allocator.
1668 // It is acceptable to supply a stack pointer IF:
1669 // (1) The vector's data does not outlive the stack pointer. This includes
1670 // extension of the data's life through a move operation.
1671 // (2) The pointer has enough capacity that the vector will never be
1673 // (3) Insert is not called on the vector; these functions have leeway to
1674 // relocate the vector even if there is enough capacity.
1675 // (4) A stack pointer is compatible with the fbvector's allocator.
1678 template <class T, class A>
1679 T* relinquish(fbvector<T, A>& v) {
1681 v.impl_.b_ = v.impl_.e_ = v.impl_.z_ = nullptr;
1685 template <class T, class A>
1686 void attach(fbvector<T, A>& v, T* data, size_t sz, size_t cap) {
1687 assert(v.data() == nullptr);
1689 v.impl_.e_ = data + sz;
1690 v.impl_.z_ = data + cap;
1693 } // namespace folly