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 //---------------------------------------------------------------------------
81 typedef std::allocator_traits<Allocator> A;
83 struct Impl : public Allocator {
85 typedef typename A::pointer pointer;
86 typedef typename A::size_type size_type;
92 Impl() : Allocator(), b_(nullptr), e_(nullptr), z_(nullptr) {}
93 /* implicit */ Impl(const Allocator& a)
94 : Allocator(a), b_(nullptr), e_(nullptr), z_(nullptr) {}
95 /* implicit */ Impl(Allocator&& a)
96 : Allocator(std::move(a)), b_(nullptr), e_(nullptr), z_(nullptr) {}
98 /* implicit */ Impl(size_type n, const Allocator& a = Allocator())
102 Impl(Impl&& other) noexcept
103 : Allocator(std::move(other)),
104 b_(other.b_), e_(other.e_), z_(other.z_)
105 { other.b_ = other.e_ = other.z_ = nullptr; }
113 // note that 'allocate' and 'deallocate' are inherited from Allocator
114 T* D_allocate(size_type n) {
115 if (usingStdAllocator::value) {
116 return static_cast<T*>(malloc(n * sizeof(T)));
118 return std::allocator_traits<Allocator>::allocate(*this, n);
122 void D_deallocate(T* p, size_type n) noexcept {
123 if (usingStdAllocator::value) {
126 std::allocator_traits<Allocator>::deallocate(*this, p, n);
131 void swapData(Impl& other) {
132 std::swap(b_, other.b_);
133 std::swap(e_, other.e_);
134 std::swap(z_, other.z_);
138 inline void destroy() noexcept {
140 // THIS DISPATCH CODE IS DUPLICATED IN fbvector::D_destroy_range_a.
141 // It has been inlined here for speed. It calls the static fbvector
142 // methods to perform the actual destruction.
143 if (usingStdAllocator::value) {
144 S_destroy_range(b_, e_);
146 S_destroy_range_a(*this, b_, e_);
149 D_deallocate(b_, size_type(z_ - b_));
153 void init(size_type n) {
154 if (UNLIKELY(n == 0)) {
155 b_ = e_ = z_ = nullptr;
157 size_type sz = folly::goodMallocSize(n * sizeof(T)) / sizeof(T);
164 void set(pointer newB, size_type newSize, size_type newCap) {
170 void reset(size_type newCap) {
179 void reset() { // same as reset(0)
181 b_ = e_ = z_ = nullptr;
185 static void swap(Impl& a, Impl& b) {
187 if (!usingStdAllocator::value) swap<Allocator>(a, b);
191 //===========================================================================
192 //---------------------------------------------------------------------------
193 // types and constants
195 typedef T value_type;
196 typedef value_type& reference;
197 typedef const value_type& const_reference;
199 typedef const T* const_iterator;
200 typedef size_t size_type;
201 typedef typename std::make_signed<size_type>::type difference_type;
202 typedef Allocator allocator_type;
203 typedef typename A::pointer pointer;
204 typedef typename A::const_pointer const_pointer;
205 typedef std::reverse_iterator<iterator> reverse_iterator;
206 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
209 typedef std::integral_constant<bool,
210 IsTriviallyCopyable<T>::value &&
211 sizeof(T) <= 16 // don't force large structures to be passed by value
212 > should_pass_by_value;
213 typedef typename std::conditional<
214 should_pass_by_value::value, T, const T&>::type VT;
215 typedef typename std::conditional<
216 should_pass_by_value::value, T, T&&>::type MT;
218 typedef std::integral_constant<bool,
219 std::is_same<Allocator, std::allocator<T>>::value> usingStdAllocator;
220 typedef std::integral_constant<bool,
221 usingStdAllocator::value ||
222 A::propagate_on_container_move_assignment::value> moveIsSwap;
224 //===========================================================================
225 //---------------------------------------------------------------------------
228 //---------------------------------------------------------------------------
231 T* M_allocate(size_type n) {
232 return impl_.D_allocate(n);
235 //---------------------------------------------------------------------------
238 void M_deallocate(T* p, size_type n) noexcept {
239 impl_.D_deallocate(p, n);
242 //---------------------------------------------------------------------------
245 // GCC is very sensitive to the exact way that construct is called. For
246 // that reason there are several different specializations of construct.
248 template <typename U, typename... Args>
249 void M_construct(U* p, Args&&... args) {
250 if (usingStdAllocator::value) {
251 new (p) U(std::forward<Args>(args)...);
253 std::allocator_traits<Allocator>::construct(
254 impl_, p, std::forward<Args>(args)...);
258 template <typename U, typename... Args>
259 static void S_construct(U* p, Args&&... args) {
260 new (p) U(std::forward<Args>(args)...);
263 template <typename U, typename... Args>
264 static void S_construct_a(Allocator& a, U* p, Args&&... args) {
265 std::allocator_traits<Allocator>::construct(
266 a, p, std::forward<Args>(args)...);
269 // scalar optimization
270 // TODO we can expand this optimization to: default copyable and assignable
271 template <typename U, typename Enable = typename
272 std::enable_if<std::is_scalar<U>::value>::type>
273 void M_construct(U* p, U arg) {
274 if (usingStdAllocator::value) {
277 std::allocator_traits<Allocator>::construct(impl_, p, arg);
281 template <typename U, typename Enable = typename
282 std::enable_if<std::is_scalar<U>::value>::type>
283 static void S_construct(U* p, U arg) {
287 template <typename U, typename Enable = typename
288 std::enable_if<std::is_scalar<U>::value>::type>
289 static void S_construct_a(Allocator& a, U* p, U arg) {
290 std::allocator_traits<Allocator>::construct(a, p, arg);
293 // const& optimization
294 template <typename U, typename Enable = typename
295 std::enable_if<!std::is_scalar<U>::value>::type>
296 void M_construct(U* p, const U& value) {
297 if (usingStdAllocator::value) {
300 std::allocator_traits<Allocator>::construct(impl_, p, value);
304 template <typename U, typename Enable = typename
305 std::enable_if<!std::is_scalar<U>::value>::type>
306 static void S_construct(U* p, const U& value) {
310 template <typename U, typename Enable = typename
311 std::enable_if<!std::is_scalar<U>::value>::type>
312 static void S_construct_a(Allocator& a, U* p, const U& value) {
313 std::allocator_traits<Allocator>::construct(a, p, value);
316 //---------------------------------------------------------------------------
319 void M_destroy(T* p) noexcept {
320 if (usingStdAllocator::value) {
321 if (!std::is_trivially_destructible<T>::value)
324 std::allocator_traits<Allocator>::destroy(impl_, p);
328 //===========================================================================
329 //---------------------------------------------------------------------------
330 // algorithmic helpers
332 //---------------------------------------------------------------------------
336 void M_destroy_range_e(T* pos) noexcept {
337 D_destroy_range_a(pos, impl_.e_);
342 // THIS DISPATCH CODE IS DUPLICATED IN IMPL. SEE IMPL FOR DETAILS.
343 void D_destroy_range_a(T* first, T* last) noexcept {
344 if (usingStdAllocator::value) {
345 S_destroy_range(first, last);
347 S_destroy_range_a(impl_, first, last);
352 static void S_destroy_range_a(Allocator& a, T* first, T* last) noexcept {
353 for (; first != last; ++first)
354 std::allocator_traits<Allocator>::destroy(a, first);
358 static void S_destroy_range(T* first, T* last) noexcept {
359 if (!std::is_trivially_destructible<T>::value) {
360 // EXPERIMENTAL DATA on fbvector<vector<int>> (where each vector<int> has
362 // The unrolled version seems to work faster for small to medium sized
363 // fbvectors. It gets a 10% speedup on fbvectors of size 1024, 64, and
365 // The simple loop version seems to work faster for large fbvectors. The
366 // unrolled version is about 6% slower on fbvectors on size 16384.
367 // The two methods seem tied for very large fbvectors. The unrolled
368 // version is about 0.5% slower on size 262144.
370 // for (; first != last; ++first) first->~T();
371 #define FOLLY_FBV_OP(p) (p)->~T()
372 FOLLY_FBV_UNROLL_PTR(first, last, FOLLY_FBV_OP)
377 //---------------------------------------------------------------------------
378 // uninitialized_fill_n
381 void M_uninitialized_fill_n_e(size_type sz) {
382 D_uninitialized_fill_n_a(impl_.e_, sz);
386 void M_uninitialized_fill_n_e(size_type sz, VT value) {
387 D_uninitialized_fill_n_a(impl_.e_, sz, value);
392 void D_uninitialized_fill_n_a(T* dest, size_type sz) {
393 if (usingStdAllocator::value) {
394 S_uninitialized_fill_n(dest, sz);
396 S_uninitialized_fill_n_a(impl_, dest, sz);
400 void D_uninitialized_fill_n_a(T* dest, size_type sz, VT value) {
401 if (usingStdAllocator::value) {
402 S_uninitialized_fill_n(dest, sz, value);
404 S_uninitialized_fill_n_a(impl_, dest, sz, value);
409 template <typename... Args>
410 static void S_uninitialized_fill_n_a(Allocator& a, T* dest,
411 size_type sz, Args&&... args) {
416 std::allocator_traits<Allocator>::construct(a, b,
417 std::forward<Args>(args)...);
419 S_destroy_range_a(a, dest, b);
425 static void S_uninitialized_fill_n(T* dest, size_type n) {
426 if (folly::IsZeroInitializable<T>::value) {
427 if (LIKELY(n != 0)) {
428 std::memset(dest, 0, sizeof(T) * n);
434 for (; b != e; ++b) S_construct(b);
437 for (; b >= dest; --b) b->~T();
443 static void S_uninitialized_fill_n(T* dest, size_type n, const T& value) {
447 for (; b != e; ++b) S_construct(b, value);
449 S_destroy_range(dest, b);
454 //---------------------------------------------------------------------------
455 // uninitialized_copy
457 // it is possible to add an optimization for the case where
458 // It = move(T*) and IsRelocatable<T> and Is0Initiailizable<T>
461 template <typename It>
462 void M_uninitialized_copy_e(It first, It last) {
463 D_uninitialized_copy_a(impl_.e_, first, last);
464 impl_.e_ += std::distance(first, last);
467 template <typename It>
468 void M_uninitialized_move_e(It first, It last) {
469 D_uninitialized_move_a(impl_.e_, first, last);
470 impl_.e_ += std::distance(first, last);
474 template <typename It>
475 void D_uninitialized_copy_a(T* dest, It first, It last) {
476 if (usingStdAllocator::value) {
477 if (folly::IsTriviallyCopyable<T>::value) {
478 S_uninitialized_copy_bits(dest, first, last);
480 S_uninitialized_copy(dest, first, last);
483 S_uninitialized_copy_a(impl_, dest, first, last);
487 template <typename It>
488 void D_uninitialized_move_a(T* dest, It first, It last) {
489 D_uninitialized_copy_a(dest,
490 std::make_move_iterator(first), std::make_move_iterator(last));
494 template <typename It>
496 S_uninitialized_copy_a(Allocator& a, T* dest, It first, It last) {
499 for (; first != last; ++first, ++b)
500 std::allocator_traits<Allocator>::construct(a, b, *first);
502 S_destroy_range_a(a, dest, b);
508 template <typename It>
509 static void S_uninitialized_copy(T* dest, It first, It last) {
512 for (; first != last; ++first, ++b)
513 S_construct(b, *first);
515 S_destroy_range(dest, b);
521 S_uninitialized_copy_bits(T* dest, const T* first, const T* last) {
523 std::memcpy((void*)dest, (void*)first, (last - first) * sizeof(T));
528 S_uninitialized_copy_bits(T* dest, std::move_iterator<T*> first,
529 std::move_iterator<T*> last) {
530 T* bFirst = first.base();
531 T* bLast = last.base();
532 if (bLast != bFirst) {
533 std::memcpy((void*)dest, (void*)bFirst, (bLast - bFirst) * sizeof(T));
537 template <typename It>
539 S_uninitialized_copy_bits(T* dest, It first, It last) {
540 S_uninitialized_copy(dest, first, last);
543 //---------------------------------------------------------------------------
546 // This function is "unsafe": it assumes that the iterator can be advanced at
547 // least n times. However, as a private function, that unsafety is managed
548 // wholly by fbvector itself.
550 template <typename It>
551 static It S_copy_n(T* dest, It first, size_type n) {
553 for (; dest != e; ++dest, ++first) *dest = *first;
557 static const T* S_copy_n(T* dest, const T* first, size_type n) {
558 if (folly::IsTriviallyCopyable<T>::value) {
559 std::memcpy((void*)dest, (void*)first, n * sizeof(T));
562 return S_copy_n<const T*>(dest, first, n);
566 static std::move_iterator<T*>
567 S_copy_n(T* dest, std::move_iterator<T*> mIt, size_type n) {
568 if (folly::IsTriviallyCopyable<T>::value) {
569 T* first = mIt.base();
570 std::memcpy((void*)dest, (void*)first, n * sizeof(T));
571 return std::make_move_iterator(first + n);
573 return S_copy_n<std::move_iterator<T*>>(dest, mIt, n);
577 //===========================================================================
578 //---------------------------------------------------------------------------
579 // relocation helpers
581 // Relocation is divided into three parts:
584 // Performs the actual movement of data from point a to point b.
587 // Destroys the old data.
590 // Destoys the new data and restores the old data.
592 // The three steps are used because there may be an exception after part 1
593 // has completed. If that is the case, then relocate_undo can nullify the
594 // initial move. Otherwise, relocate_done performs the last bit of tidying
597 // The relocation trio may use either memcpy, move, or copy. It is decided
598 // by the following case statement:
600 // IsRelocatable && usingStdAllocator -> memcpy
601 // has_nothrow_move && usingStdAllocator -> move
602 // cannot copy -> move
605 // If the class is non-copyable then it must be movable. However, if the
606 // move constructor is not noexcept, i.e. an error could be thrown, then
607 // relocate_undo will be unable to restore the old data, for fear of a
608 // second exception being thrown. This is a known and unavoidable
609 // deficiency. In lieu of a strong exception guarantee, relocate_undo does
610 // the next best thing: it provides a weak exception guarantee by
611 // destorying the new data, but leaving the old data in an indeterminate
612 // state. Note that that indeterminate state will be valid, since the
613 // old data has not been destroyed; it has merely been the source of a
614 // move, which is required to leave the source in a valid state.
617 void M_relocate(T* newB) {
618 relocate_move(newB, impl_.b_, impl_.e_);
619 relocate_done(newB, impl_.b_, impl_.e_);
622 // dispatch type trait
623 typedef std::integral_constant<bool,
624 folly::IsRelocatable<T>::value && usingStdAllocator::value
625 > relocate_use_memcpy;
627 typedef std::integral_constant<bool,
628 (std::is_nothrow_move_constructible<T>::value
629 && usingStdAllocator::value)
630 || !std::is_copy_constructible<T>::value
634 void relocate_move(T* dest, T* first, T* last) {
635 relocate_move_or_memcpy(dest, first, last, relocate_use_memcpy());
638 void relocate_move_or_memcpy(T* dest, T* first, T* last, std::true_type) {
639 if (first != nullptr) {
640 std::memcpy((void*)dest, (void*)first, (last - first) * sizeof(T));
644 void relocate_move_or_memcpy(T* dest, T* first, T* last, std::false_type) {
645 relocate_move_or_copy(dest, first, last, relocate_use_move());
648 void relocate_move_or_copy(T* dest, T* first, T* last, std::true_type) {
649 D_uninitialized_move_a(dest, first, last);
652 void relocate_move_or_copy(T* dest, T* first, T* last, std::false_type) {
653 D_uninitialized_copy_a(dest, first, last);
657 void relocate_done(T* /*dest*/, T* first, T* last) noexcept {
658 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
659 // used memcpy; data has been relocated, do not call destructor
661 D_destroy_range_a(first, last);
666 void relocate_undo(T* dest, T* first, T* last) noexcept {
667 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
668 // used memcpy, old data is still valid, nothing to do
669 } else if (std::is_nothrow_move_constructible<T>::value &&
670 usingStdAllocator::value) {
671 // noexcept move everything back, aka relocate_move
672 relocate_move(first, dest, dest + (last - first));
673 } else if (!std::is_copy_constructible<T>::value) {
675 D_destroy_range_a(dest, dest + (last - first));
677 // used copy, old data is still valid
678 D_destroy_range_a(dest, dest + (last - first));
683 //===========================================================================
684 //---------------------------------------------------------------------------
685 // construct/copy/destroy
687 fbvector() = default;
689 explicit fbvector(const Allocator& a) : impl_(a) {}
691 explicit fbvector(size_type n, const Allocator& a = Allocator())
693 { M_uninitialized_fill_n_e(n); }
695 fbvector(size_type n, VT value, const Allocator& a = Allocator())
697 { M_uninitialized_fill_n_e(n, value); }
699 template <class It, class Category = typename
700 std::iterator_traits<It>::iterator_category>
701 fbvector(It first, It last, const Allocator& a = Allocator())
702 : fbvector(first, last, a, Category()) {}
704 fbvector(const fbvector& other)
705 : impl_(other.size(), A::select_on_container_copy_construction(other.impl_))
706 { M_uninitialized_copy_e(other.begin(), other.end()); }
708 fbvector(fbvector&& other) noexcept : impl_(std::move(other.impl_)) {}
710 fbvector(const fbvector& other, const Allocator& a)
711 : fbvector(other.begin(), other.end(), a) {}
713 /* may throw */ fbvector(fbvector&& other, const Allocator& a) : impl_(a) {
714 if (impl_ == other.impl_) {
715 impl_.swapData(other.impl_);
717 impl_.init(other.size());
718 M_uninitialized_move_e(other.begin(), other.end());
722 fbvector(std::initializer_list<T> il, const Allocator& a = Allocator())
723 : fbvector(il.begin(), il.end(), a) {}
725 ~fbvector() = default; // the cleanup occurs in impl_
727 fbvector& operator=(const fbvector& other) {
728 if (UNLIKELY(this == &other)) return *this;
730 if (!usingStdAllocator::value &&
731 A::propagate_on_container_copy_assignment::value) {
732 if (impl_ != other.impl_) {
733 // can't use other's different allocator to clean up self
736 (Allocator&)impl_ = (Allocator&)other.impl_;
739 assign(other.begin(), other.end());
743 fbvector& operator=(fbvector&& other) {
744 if (UNLIKELY(this == &other)) return *this;
745 moveFrom(std::move(other), moveIsSwap());
749 fbvector& operator=(std::initializer_list<T> il) {
750 assign(il.begin(), il.end());
754 template <class It, class Category = typename
755 std::iterator_traits<It>::iterator_category>
756 void assign(It first, It last) {
757 assign(first, last, Category());
760 void assign(size_type n, VT value) {
761 if (n > capacity()) {
762 // Not enough space. Do not reserve in place, since we will
763 // discard the old values anyways.
764 if (dataIsInternalAndNotVT(value)) {
765 T copy(std::move(value));
767 M_uninitialized_fill_n_e(n, copy);
770 M_uninitialized_fill_n_e(n, value);
772 } else if (n <= size()) {
773 auto newE = impl_.b_ + n;
774 std::fill(impl_.b_, newE, value);
775 M_destroy_range_e(newE);
777 std::fill(impl_.b_, impl_.e_, value);
778 M_uninitialized_fill_n_e(n - size(), value);
782 void assign(std::initializer_list<T> il) {
783 assign(il.begin(), il.end());
786 allocator_type get_allocator() const noexcept {
791 // contract dispatch for iterator types fbvector(It first, It last)
792 template <class ForwardIterator>
793 fbvector(ForwardIterator first, ForwardIterator last,
794 const Allocator& a, std::forward_iterator_tag)
795 : impl_(size_type(std::distance(first, last)), a)
796 { M_uninitialized_copy_e(first, last); }
798 template <class InputIterator>
799 fbvector(InputIterator first, InputIterator last,
800 const Allocator& a, std::input_iterator_tag)
802 { for (; first != last; ++first) emplace_back(*first); }
804 // contract dispatch for allocator movement in operator=(fbvector&&)
806 moveFrom(fbvector&& other, std::true_type) {
807 swap(impl_, other.impl_);
809 void moveFrom(fbvector&& other, std::false_type) {
810 if (impl_ == other.impl_) {
811 impl_.swapData(other.impl_);
813 impl_.reset(other.size());
814 M_uninitialized_move_e(other.begin(), other.end());
818 // contract dispatch for iterator types in assign(It first, It last)
819 template <class ForwardIterator>
820 void assign(ForwardIterator first, ForwardIterator last,
821 std::forward_iterator_tag) {
822 const auto newSize = size_type(std::distance(first, last));
823 if (newSize > capacity()) {
824 impl_.reset(newSize);
825 M_uninitialized_copy_e(first, last);
826 } else if (newSize <= size()) {
827 auto newEnd = std::copy(first, last, impl_.b_);
828 M_destroy_range_e(newEnd);
830 auto mid = S_copy_n(impl_.b_, first, size());
831 M_uninitialized_copy_e<decltype(last)>(mid, last);
835 template <class InputIterator>
836 void assign(InputIterator first, InputIterator last,
837 std::input_iterator_tag) {
839 for (; first != last && p != impl_.e_; ++first, ++p) {
843 M_destroy_range_e(p);
845 for (; first != last; ++first) emplace_back(*first);
849 // contract dispatch for aliasing under VT optimization
850 bool dataIsInternalAndNotVT(const T& t) {
851 if (should_pass_by_value::value) return false;
852 return dataIsInternal(t);
854 bool dataIsInternal(const T& t) {
855 return UNLIKELY(impl_.b_ <= std::addressof(t) &&
856 std::addressof(t) < impl_.e_);
860 //===========================================================================
861 //---------------------------------------------------------------------------
864 iterator begin() noexcept {
867 const_iterator begin() const noexcept {
870 iterator end() noexcept {
873 const_iterator end() const noexcept {
876 reverse_iterator rbegin() noexcept {
877 return reverse_iterator(end());
879 const_reverse_iterator rbegin() const noexcept {
880 return const_reverse_iterator(end());
882 reverse_iterator rend() noexcept {
883 return reverse_iterator(begin());
885 const_reverse_iterator rend() const noexcept {
886 return const_reverse_iterator(begin());
889 const_iterator cbegin() const noexcept {
892 const_iterator cend() const noexcept {
895 const_reverse_iterator crbegin() const noexcept {
896 return const_reverse_iterator(end());
898 const_reverse_iterator crend() const noexcept {
899 return const_reverse_iterator(begin());
902 //===========================================================================
903 //---------------------------------------------------------------------------
906 size_type size() const noexcept {
907 return size_type(impl_.e_ - impl_.b_);
910 size_type max_size() const noexcept {
911 // good luck gettin' there
912 return ~size_type(0);
915 void resize(size_type n) {
917 M_destroy_range_e(impl_.b_ + n);
920 M_uninitialized_fill_n_e(n - size());
924 void resize(size_type n, VT t) {
926 M_destroy_range_e(impl_.b_ + n);
927 } else if (dataIsInternalAndNotVT(t) && n > capacity()) {
930 M_uninitialized_fill_n_e(n - size(), copy);
933 M_uninitialized_fill_n_e(n - size(), t);
937 size_type capacity() const noexcept {
938 return size_type(impl_.z_ - impl_.b_);
941 bool empty() const noexcept {
942 return impl_.b_ == impl_.e_;
945 void reserve(size_type n) {
946 if (n <= capacity()) return;
947 if (impl_.b_ && reserve_in_place(n)) return;
949 auto newCap = folly::goodMallocSize(n * sizeof(T)) / sizeof(T);
950 auto newB = M_allocate(newCap);
954 M_deallocate(newB, newCap);
958 M_deallocate(impl_.b_, size_type(impl_.z_ - impl_.b_));
959 impl_.z_ = newB + newCap;
960 impl_.e_ = newB + (impl_.e_ - impl_.b_);
964 void shrink_to_fit() noexcept {
970 auto const newCapacityBytes = folly::goodMallocSize(size() * sizeof(T));
971 auto const newCap = newCapacityBytes / sizeof(T);
972 auto const oldCap = capacity();
974 if (newCap >= oldCap) return;
977 // xallocx() will shrink to precisely newCapacityBytes (which was generated
978 // by goodMallocSize()) if it successfully shrinks in place.
979 if ((usingJEMalloc() && usingStdAllocator::value) &&
980 newCapacityBytes >= folly::jemallocMinInPlaceExpandable &&
981 xallocx(p, newCapacityBytes, 0, 0) == newCapacityBytes) {
982 impl_.z_ += newCap - oldCap;
984 T* newB; // intentionally uninitialized
986 newB = M_allocate(newCap);
990 M_deallocate(newB, newCap);
991 return; // swallow the error
997 M_deallocate(impl_.b_, size_type(impl_.z_ - impl_.b_));
998 impl_.z_ = newB + newCap;
999 impl_.e_ = newB + (impl_.e_ - impl_.b_);
1005 bool reserve_in_place(size_type n) {
1006 if (!usingStdAllocator::value || !usingJEMalloc()) return false;
1008 // jemalloc can never grow in place blocks smaller than 4096 bytes.
1009 if ((impl_.z_ - impl_.b_) * sizeof(T) <
1010 folly::jemallocMinInPlaceExpandable) return false;
1012 auto const newCapacityBytes = folly::goodMallocSize(n * sizeof(T));
1014 if (xallocx(p, newCapacityBytes, 0, 0) == newCapacityBytes) {
1015 impl_.z_ = impl_.b_ + newCapacityBytes / sizeof(T);
1021 //===========================================================================
1022 //---------------------------------------------------------------------------
1025 reference operator[](size_type n) {
1029 const_reference operator[](size_type n) const {
1033 const_reference at(size_type n) const {
1034 if (UNLIKELY(n >= size())) {
1035 std::__throw_out_of_range("fbvector: index is greater than size.");
1039 reference at(size_type n) {
1040 auto const& cThis = *this;
1041 return const_cast<reference>(cThis.at(n));
1047 const_reference front() const {
1053 return impl_.e_[-1];
1055 const_reference back() const {
1057 return impl_.e_[-1];
1060 //===========================================================================
1061 //---------------------------------------------------------------------------
1064 T* data() noexcept {
1067 const T* data() const noexcept {
1071 //===========================================================================
1072 //---------------------------------------------------------------------------
1073 // modifiers (common)
1075 template <class... Args>
1076 void emplace_back(Args&&... args) {
1077 if (impl_.e_ != impl_.z_) {
1078 M_construct(impl_.e_, std::forward<Args>(args)...);
1081 emplace_back_aux(std::forward<Args>(args)...);
1086 push_back(const T& value) {
1087 if (impl_.e_ != impl_.z_) {
1088 M_construct(impl_.e_, value);
1091 emplace_back_aux(value);
1096 push_back(T&& value) {
1097 if (impl_.e_ != impl_.z_) {
1098 M_construct(impl_.e_, std::move(value));
1101 emplace_back_aux(std::move(value));
1108 M_destroy(impl_.e_);
1111 void swap(fbvector& other) noexcept {
1112 if (!usingStdAllocator::value &&
1113 A::propagate_on_container_swap::value)
1114 swap(impl_, other.impl_);
1115 else impl_.swapData(other.impl_);
1118 void clear() noexcept {
1119 M_destroy_range_e(impl_.b_);
1123 // std::vector implements a similar function with a different growth
1124 // strategy: empty() ? 1 : capacity() * 2.
1126 // fbvector grows differently on two counts:
1129 // Instead of growing to size 1 from empty, fbvector allocates at least
1130 // 64 bytes. You may still use reserve to reserve a lesser amount of
1133 // For medium-sized vectors, the growth strategy is 1.5x. See the docs
1135 // This does not apply to very small or very large fbvectors. This is a
1137 // A nice addition to fbvector would be the capability of having a user-
1138 // defined growth strategy, probably as part of the allocator.
1141 size_type computePushBackCapacity() const {
1142 if (capacity() == 0) {
1143 return std::max(64 / sizeof(T), size_type(1));
1145 if (capacity() < folly::jemallocMinInPlaceExpandable / sizeof(T)) {
1146 return capacity() * 2;
1148 if (capacity() > 4096 * 32 / sizeof(T)) {
1149 return capacity() * 2;
1151 return (capacity() * 3 + 1) / 2;
1154 template <class... Args>
1155 void emplace_back_aux(Args&&... args);
1157 //===========================================================================
1158 //---------------------------------------------------------------------------
1159 // modifiers (erase)
1161 iterator erase(const_iterator position) {
1162 return erase(position, position + 1);
1165 iterator erase(const_iterator first, const_iterator last) {
1166 assert(isValid(first) && isValid(last));
1167 assert(first <= last);
1168 if (first != last) {
1169 if (last == end()) {
1170 M_destroy_range_e((iterator)first);
1172 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
1173 D_destroy_range_a((iterator)first, (iterator)last);
1174 if (last - first >= cend() - last) {
1175 std::memcpy((void*)first, (void*)last, (cend() - last) * sizeof(T));
1177 std::memmove((iterator)first, last, (cend() - last) * sizeof(T));
1179 impl_.e_ -= (last - first);
1181 std::copy(std::make_move_iterator((iterator)last),
1182 std::make_move_iterator(end()), (iterator)first);
1183 auto newEnd = impl_.e_ - std::distance(first, last);
1184 M_destroy_range_e(newEnd);
1188 return (iterator)first;
1191 //===========================================================================
1192 //---------------------------------------------------------------------------
1193 // modifiers (insert)
1194 private: // we have the private section first because it defines some macros
1195 bool isValid(const_iterator it) {
1196 return cbegin() <= it && it <= cend();
1199 size_type computeInsertCapacity(size_type n) {
1200 size_type nc = std::max(computePushBackCapacity(), size() + n);
1201 size_type ac = folly::goodMallocSize(nc * sizeof(T)) / sizeof(T);
1205 //---------------------------------------------------------------------------
1207 // make_window takes an fbvector, and creates an uninitialized gap (a
1208 // window) at the given position, of the given size. The fbvector must
1209 // have enough capacity.
1211 // Explanation by picture.
1215 // make_window here of size 3
1219 // If something goes wrong and the window must be destroyed, use
1220 // undo_window to provide a weak exception guarantee. It destroys
1225 //---------------------------------------------------------------------------
1227 // wrap_frame takes an inverse window and relocates an fbvector around it.
1228 // The fbvector must have at least as many elements as the left ledge.
1230 // Explanation by picture.
1233 // fbvector: inverse window:
1234 // 123456789______ _____abcde_______
1238 // _______________ 12345abcde6789___
1240 //---------------------------------------------------------------------------
1242 // insert_use_fresh_memory returns true iff the fbvector should use a fresh
1243 // block of memory for the insertion. If the fbvector does not have enough
1244 // spare capacity, then it must return true. Otherwise either true or false
1247 //---------------------------------------------------------------------------
1249 // These three functions, make_window, wrap_frame, and
1250 // insert_use_fresh_memory, can be combined into a uniform interface.
1251 // Since that interface involves a lot of case-work, it is built into
1252 // some macros: FOLLY_FBVECTOR_INSERT_(PRE|START|TRY|END)
1253 // Macros are used in an attempt to let GCC perform better optimizations,
1254 // especially control flow optimization.
1257 //---------------------------------------------------------------------------
1260 void make_window(iterator position, size_type n) {
1261 // The result is guaranteed to be non-negative, so use an unsigned type:
1262 size_type tail = size_type(std::distance(position, impl_.e_));
1265 relocate_move(position + n, position, impl_.e_);
1266 relocate_done(position + n, position, impl_.e_);
1269 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
1270 std::memmove(position + n, position, tail * sizeof(T));
1273 D_uninitialized_move_a(impl_.e_, impl_.e_ - n, impl_.e_);
1275 std::copy_backward(std::make_move_iterator(position),
1276 std::make_move_iterator(impl_.e_ - n), impl_.e_);
1278 D_destroy_range_a(impl_.e_ - n, impl_.e_ + n);
1283 D_destroy_range_a(position, position + n);
1288 void undo_window(iterator position, size_type n) noexcept {
1289 D_destroy_range_a(position + n, impl_.e_);
1290 impl_.e_ = position;
1293 //---------------------------------------------------------------------------
1296 void wrap_frame(T* ledge, size_type idx, size_type n) {
1297 assert(size() >= idx);
1300 relocate_move(ledge, impl_.b_, impl_.b_ + idx);
1302 relocate_move(ledge + idx + n, impl_.b_ + idx, impl_.e_);
1304 relocate_undo(ledge, impl_.b_, impl_.b_ + idx);
1307 relocate_done(ledge, impl_.b_, impl_.b_ + idx);
1308 relocate_done(ledge + idx + n, impl_.b_ + idx, impl_.e_);
1311 //---------------------------------------------------------------------------
1314 bool insert_use_fresh(bool at_end, size_type n) {
1316 if (size() + n <= capacity()) return false;
1317 if (reserve_in_place(size() + n)) return false;
1321 if (size() + n > capacity()) return true;
1326 //---------------------------------------------------------------------------
1330 typename IsInternalFunc,
1331 typename InsertInternalFunc,
1332 typename ConstructFunc,
1333 typename DestroyFunc>
1334 iterator do_real_insert(
1335 const_iterator cpos,
1337 IsInternalFunc&& isInternalFunc,
1338 InsertInternalFunc&& insertInternalFunc,
1339 ConstructFunc&& constructFunc,
1340 DestroyFunc&& destroyFunc) {
1342 return iterator(cpos);
1344 bool at_end = cpos == cend();
1345 bool fresh = insert_use_fresh(at_end, n);
1347 if (!fresh && isInternalFunc()) {
1348 // check for internal data (technically not required by the standard)
1349 return insertInternalFunc();
1351 assert(isValid(cpos));
1353 T* position = const_cast<T*>(cpos);
1354 size_type idx = size_type(std::distance(impl_.b_, position));
1356 size_type newCap; /* intentionally uninitialized */
1359 newCap = computeInsertCapacity(n);
1360 b = M_allocate(newCap);
1363 make_window(position, n);
1372 // construct the inserted elements
1373 constructFunc(start);
1376 M_deallocate(b, newCap);
1379 undo_window(position, n);
1389 wrap_frame(b, idx, n);
1391 // delete the inserted elements (exception has been thrown)
1393 M_deallocate(b, newCap);
1397 M_deallocate(impl_.b_, capacity());
1399 impl_.set(b, size() + n, newCap);
1400 return impl_.b_ + idx;
1407 template <class... Args>
1408 iterator emplace(const_iterator cpos, Args&&... args) {
1409 return do_real_insert(
1412 [&] { return false; },
1413 [&] { return iterator{}; },
1414 [&](iterator start) {
1415 M_construct(start, std::forward<Args>(args)...);
1417 [&](iterator start) { M_destroy(start); });
1420 iterator insert(const_iterator cpos, const T& value) {
1421 return do_real_insert(
1424 [&] { return dataIsInternal(value); },
1425 [&] { return insert(cpos, T(value)); },
1426 [&](iterator start) { M_construct(start, value); },
1427 [&](iterator start) { M_destroy(start); });
1430 iterator insert(const_iterator cpos, T&& value) {
1431 return do_real_insert(
1434 [&] { return dataIsInternal(value); },
1435 [&] { return insert(cpos, T(std::move(value))); },
1436 [&](iterator start) { M_construct(start, std::move(value)); },
1437 [&](iterator start) { M_destroy(start); });
1440 iterator insert(const_iterator cpos, size_type n, VT value) {
1441 return do_real_insert(
1444 [&] { return dataIsInternalAndNotVT(value); },
1445 [&] { return insert(cpos, n, T(value)); },
1446 [&](iterator start) { D_uninitialized_fill_n_a(start, n, value); },
1447 [&](iterator start) { D_destroy_range_a(start, start + n); });
1450 template <class It, class Category = typename
1451 std::iterator_traits<It>::iterator_category>
1452 iterator insert(const_iterator cpos, It first, It last) {
1453 return insert(cpos, first, last, Category());
1456 iterator insert(const_iterator cpos, std::initializer_list<T> il) {
1457 return insert(cpos, il.begin(), il.end());
1460 //---------------------------------------------------------------------------
1461 // insert dispatch for iterator types
1463 template <class FIt>
1464 iterator insert(const_iterator cpos, FIt first, FIt last,
1465 std::forward_iterator_tag) {
1466 size_type n = size_type(std::distance(first, last));
1467 return do_real_insert(
1470 [&] { return false; },
1471 [&] { return iterator{}; },
1472 [&](iterator start) { D_uninitialized_copy_a(start, first, last); },
1473 [&](iterator start) { D_destroy_range_a(start, start + n); });
1476 template <class IIt>
1477 iterator insert(const_iterator cpos, IIt first, IIt last,
1478 std::input_iterator_tag) {
1479 T* position = const_cast<T*>(cpos);
1480 assert(isValid(position));
1481 size_type idx = std::distance(begin(), position);
1483 fbvector storage(std::make_move_iterator(position),
1484 std::make_move_iterator(end()),
1485 A::select_on_container_copy_construction(impl_));
1486 M_destroy_range_e(position);
1487 for (; first != last; ++first) emplace_back(*first);
1488 insert(cend(), std::make_move_iterator(storage.begin()),
1489 std::make_move_iterator(storage.end()));
1490 return impl_.b_ + idx;
1493 //===========================================================================
1494 //---------------------------------------------------------------------------
1495 // lexicographical functions
1497 bool operator==(const fbvector& other) const {
1498 return size() == other.size() && std::equal(begin(), end(), other.begin());
1501 bool operator!=(const fbvector& other) const {
1502 return !(*this == other);
1505 bool operator<(const fbvector& other) const {
1506 return std::lexicographical_compare(
1507 begin(), end(), other.begin(), other.end());
1510 bool operator>(const fbvector& other) const {
1511 return other < *this;
1514 bool operator<=(const fbvector& other) const {
1515 return !(*this > other);
1518 bool operator>=(const fbvector& other) const {
1519 return !(*this < other);
1522 //===========================================================================
1523 //---------------------------------------------------------------------------
1526 template <class _T, class _A>
1527 friend _T* relinquish(fbvector<_T, _A>&);
1529 template <class _T, class _A>
1530 friend void attach(fbvector<_T, _A>&, _T* data, size_t sz, size_t cap);
1532 }; // class fbvector
1535 //=============================================================================
1536 //-----------------------------------------------------------------------------
1537 // outlined functions (gcc, you finicky compiler you)
1539 template <typename T, typename Allocator>
1540 template <class... Args>
1541 void fbvector<T, Allocator>::emplace_back_aux(Args&&... args) {
1542 size_type byte_sz = folly::goodMallocSize(
1543 computePushBackCapacity() * sizeof(T));
1544 if (usingStdAllocator::value
1546 && ((impl_.z_ - impl_.b_) * sizeof(T) >=
1547 folly::jemallocMinInPlaceExpandable)) {
1548 // Try to reserve in place.
1549 // Ask xallocx to allocate in place at least size()+1 and at most sz space.
1550 // xallocx will allocate as much as possible within that range, which
1551 // is the best possible outcome: if sz space is available, take it all,
1552 // otherwise take as much as possible. If nothing is available, then fail.
1553 // In this fashion, we never relocate if there is a possibility of
1554 // expanding in place, and we never reallocate by less than the desired
1555 // amount unless we cannot expand further. Hence we will not reallocate
1556 // sub-optimally twice in a row (modulo the blocking memory being freed).
1557 size_type lower = folly::goodMallocSize(sizeof(T) + size() * sizeof(T));
1558 size_type upper = byte_sz;
1559 size_type extra = upper - lower;
1564 if ((actual = xallocx(p, lower, extra, 0)) >= lower) {
1565 impl_.z_ = impl_.b_ + actual / sizeof(T);
1566 M_construct(impl_.e_, std::forward<Args>(args)...);
1572 // Reallocation failed. Perform a manual relocation.
1573 size_type sz = byte_sz / sizeof(T);
1574 auto newB = M_allocate(sz);
1575 auto newE = newB + size();
1577 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
1578 // For linear memory access, relocate before construction.
1579 // By the test condition, relocate is noexcept.
1580 // Note that there is no cleanup to do if M_construct throws - that's
1581 // one of the beauties of relocation.
1582 // Benchmarks for this code have high variance, and seem to be close.
1583 relocate_move(newB, impl_.b_, impl_.e_);
1584 M_construct(newE, std::forward<Args>(args)...);
1587 M_construct(newE, std::forward<Args>(args)...);
1592 M_destroy(newE - 1);
1597 M_deallocate(newB, sz);
1600 if (impl_.b_) M_deallocate(impl_.b_, size());
1603 impl_.z_ = newB + sz;
1606 //=============================================================================
1607 //-----------------------------------------------------------------------------
1608 // specialized functions
1610 template <class T, class A>
1611 void swap(fbvector<T, A>& lhs, fbvector<T, A>& rhs) noexcept {
1615 //=============================================================================
1616 //-----------------------------------------------------------------------------
1622 template <class T, class A>
1623 struct IndexableTraits<fbvector<T, A>>
1624 : public IndexableTraitsSeq<fbvector<T, A>> {
1627 } // namespace detail
1629 template <class T, class A>
1630 void compactResize(fbvector<T, A>* v, size_t sz) {
1637 // relinquish and attach are not a members function specifically so that it is
1638 // awkward to call them. It is very easy to shoot yourself in the foot with
1641 // If you call relinquish, then it is your responsibility to free the data
1642 // and the storage, both of which may have been generated in a non-standard
1643 // way through the fbvector's allocator.
1645 // If you call attach, it is your responsibility to ensure that the fbvector
1646 // is fresh (size and capacity both zero), and that the supplied data is
1647 // capable of being manipulated by the allocator.
1648 // It is acceptable to supply a stack pointer IF:
1649 // (1) The vector's data does not outlive the stack pointer. This includes
1650 // extension of the data's life through a move operation.
1651 // (2) The pointer has enough capacity that the vector will never be
1653 // (3) Insert is not called on the vector; these functions have leeway to
1654 // relocate the vector even if there is enough capacity.
1655 // (4) A stack pointer is compatible with the fbvector's allocator.
1658 template <class T, class A>
1659 T* relinquish(fbvector<T, A>& v) {
1661 v.impl_.b_ = v.impl_.e_ = v.impl_.z_ = nullptr;
1665 template <class T, class A>
1666 void attach(fbvector<T, A>& v, T* data, size_t sz, size_t cap) {
1667 assert(v.data() == nullptr);
1669 v.impl_.e_ = data + sz;
1670 v.impl_.z_ = data + cap;
1673 } // namespace folly