2 * Copyright 2016 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>
43 #include <boost/operators.hpp>
45 //=============================================================================
46 // forward declaration
49 template <class T, class Allocator = std::allocator<T>>
53 //=============================================================================
56 #define FOLLY_FBV_UNROLL_PTR(first, last, OP) do { \
57 for (; (last) - (first) >= 4; (first) += 4) { \
63 for (; (first) != (last); ++(first)) OP((first)); \
66 //=============================================================================
67 ///////////////////////////////////////////////////////////////////////////////
71 ///////////////////////////////////////////////////////////////////////////////
75 template <class T, class Allocator>
76 class fbvector : private boost::totally_ordered<fbvector<T, Allocator>> {
78 //===========================================================================
79 //---------------------------------------------------------------------------
83 typedef std::allocator_traits<Allocator> A;
85 struct Impl : public Allocator {
87 typedef typename A::pointer pointer;
88 typedef typename A::size_type size_type;
94 Impl() : Allocator(), b_(nullptr), e_(nullptr), z_(nullptr) {}
95 /* implicit */ Impl(const Allocator& a)
96 : Allocator(a), b_(nullptr), e_(nullptr), z_(nullptr) {}
97 /* implicit */ Impl(Allocator&& a)
98 : Allocator(std::move(a)), b_(nullptr), e_(nullptr), z_(nullptr) {}
100 /* implicit */ Impl(size_type n, const Allocator& a = Allocator())
104 Impl(Impl&& other) noexcept
105 : Allocator(std::move(other)),
106 b_(other.b_), e_(other.e_), z_(other.z_)
107 { other.b_ = other.e_ = other.z_ = nullptr; }
115 // note that 'allocate' and 'deallocate' are inherited from Allocator
116 T* D_allocate(size_type n) {
117 if (usingStdAllocator::value) {
118 return static_cast<T*>(malloc(n * sizeof(T)));
120 return std::allocator_traits<Allocator>::allocate(*this, n);
124 void D_deallocate(T* p, size_type n) noexcept {
125 if (usingStdAllocator::value) {
128 std::allocator_traits<Allocator>::deallocate(*this, p, n);
133 void swapData(Impl& other) {
134 std::swap(b_, other.b_);
135 std::swap(e_, other.e_);
136 std::swap(z_, other.z_);
140 inline void destroy() noexcept {
142 // THIS DISPATCH CODE IS DUPLICATED IN fbvector::D_destroy_range_a.
143 // It has been inlined here for speed. It calls the static fbvector
144 // methods to perform the actual destruction.
145 if (usingStdAllocator::value) {
146 S_destroy_range(b_, e_);
148 S_destroy_range_a(*this, b_, e_);
151 D_deallocate(b_, z_ - b_);
155 void init(size_type n) {
156 if (UNLIKELY(n == 0)) {
157 b_ = e_ = z_ = nullptr;
159 size_type sz = folly::goodMallocSize(n * sizeof(T)) / sizeof(T);
166 void set(pointer newB, size_type newSize, size_type newCap) {
172 void reset(size_type newCap) {
181 void reset() { // same as reset(0)
183 b_ = e_ = z_ = nullptr;
187 static void swap(Impl& a, Impl& b) {
189 if (!usingStdAllocator::value) swap<Allocator>(a, b);
193 //===========================================================================
194 //---------------------------------------------------------------------------
195 // types and constants
198 typedef T value_type;
199 typedef value_type& reference;
200 typedef const value_type& const_reference;
202 typedef const T* const_iterator;
203 typedef size_t size_type;
204 typedef typename std::make_signed<size_type>::type difference_type;
205 typedef Allocator allocator_type;
206 typedef typename A::pointer pointer;
207 typedef typename A::const_pointer const_pointer;
208 typedef std::reverse_iterator<iterator> reverse_iterator;
209 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
213 typedef std::integral_constant<bool,
214 boost::has_trivial_copy_constructor<T>::value &&
215 sizeof(T) <= 16 // don't force large structures to be passed by value
216 > should_pass_by_value;
217 typedef typename std::conditional<
218 should_pass_by_value::value, T, const T&>::type VT;
219 typedef typename std::conditional<
220 should_pass_by_value::value, T, T&&>::type MT;
222 typedef std::integral_constant<bool,
223 std::is_same<Allocator, std::allocator<T>>::value> usingStdAllocator;
224 typedef std::integral_constant<bool,
225 usingStdAllocator::value ||
226 A::propagate_on_container_move_assignment::value> moveIsSwap;
228 //===========================================================================
229 //---------------------------------------------------------------------------
233 //---------------------------------------------------------------------------
236 T* M_allocate(size_type n) {
237 return impl_.D_allocate(n);
240 //---------------------------------------------------------------------------
243 void M_deallocate(T* p, size_type n) noexcept {
244 impl_.D_deallocate(p, n);
247 //---------------------------------------------------------------------------
250 // GCC is very sensitive to the exact way that construct is called. For
251 // that reason there are several different specializations of construct.
253 template <typename U, typename... Args>
254 void M_construct(U* p, Args&&... args) {
255 if (usingStdAllocator::value) {
256 new (p) U(std::forward<Args>(args)...);
258 std::allocator_traits<Allocator>::construct(
259 impl_, p, std::forward<Args>(args)...);
263 template <typename U, typename... Args>
264 static void S_construct(U* p, Args&&... args) {
265 new (p) U(std::forward<Args>(args)...);
268 template <typename U, typename... Args>
269 static void S_construct_a(Allocator& a, U* p, Args&&... args) {
270 std::allocator_traits<Allocator>::construct(
271 a, p, std::forward<Args>(args)...);
274 // scalar optimization
275 // TODO we can expand this optimization to: default copyable and assignable
276 template <typename U, typename Enable = typename
277 std::enable_if<std::is_scalar<U>::value>::type>
278 void M_construct(U* p, U arg) {
279 if (usingStdAllocator::value) {
282 std::allocator_traits<Allocator>::construct(impl_, p, arg);
286 template <typename U, typename Enable = typename
287 std::enable_if<std::is_scalar<U>::value>::type>
288 static void S_construct(U* p, U arg) {
292 template <typename U, typename Enable = typename
293 std::enable_if<std::is_scalar<U>::value>::type>
294 static void S_construct_a(Allocator& a, U* p, U arg) {
295 std::allocator_traits<Allocator>::construct(a, p, arg);
298 // const& optimization
299 template <typename U, typename Enable = typename
300 std::enable_if<!std::is_scalar<U>::value>::type>
301 void M_construct(U* p, const U& value) {
302 if (usingStdAllocator::value) {
305 std::allocator_traits<Allocator>::construct(impl_, p, value);
309 template <typename U, typename Enable = typename
310 std::enable_if<!std::is_scalar<U>::value>::type>
311 static void S_construct(U* p, const U& value) {
315 template <typename U, typename Enable = typename
316 std::enable_if<!std::is_scalar<U>::value>::type>
317 static void S_construct_a(Allocator& a, U* p, const U& value) {
318 std::allocator_traits<Allocator>::construct(a, p, value);
321 //---------------------------------------------------------------------------
324 void M_destroy(T* p) noexcept {
325 if (usingStdAllocator::value) {
326 if (!boost::has_trivial_destructor<T>::value) p->~T();
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 (!boost::has_trivial_destructor<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 std::memset(dest, 0, sizeof(T) * n);
437 for (; b != e; ++b) S_construct(b);
440 for (; b >= dest; --b) b->~T();
446 static void S_uninitialized_fill_n(T* dest, size_type n, const T& value) {
450 for (; b != e; ++b) S_construct(b, value);
452 S_destroy_range(dest, b);
457 //---------------------------------------------------------------------------
458 // uninitialized_copy
460 // it is possible to add an optimization for the case where
461 // It = move(T*) and IsRelocatable<T> and Is0Initiailizable<T>
464 template <typename It>
465 void M_uninitialized_copy_e(It first, It last) {
466 D_uninitialized_copy_a(impl_.e_, first, last);
467 impl_.e_ += std::distance(first, last);
470 template <typename It>
471 void M_uninitialized_move_e(It first, It last) {
472 D_uninitialized_move_a(impl_.e_, first, last);
473 impl_.e_ += std::distance(first, last);
477 template <typename It>
478 void D_uninitialized_copy_a(T* dest, It first, It last) {
479 if (usingStdAllocator::value) {
480 if (folly::IsTriviallyCopyable<T>::value) {
481 S_uninitialized_copy_bits(dest, first, last);
483 S_uninitialized_copy(dest, first, last);
486 S_uninitialized_copy_a(impl_, dest, first, last);
490 template <typename It>
491 void D_uninitialized_move_a(T* dest, It first, It last) {
492 D_uninitialized_copy_a(dest,
493 std::make_move_iterator(first), std::make_move_iterator(last));
497 template <typename It>
499 S_uninitialized_copy_a(Allocator& a, T* dest, It first, It last) {
502 for (; first != last; ++first, ++b)
503 std::allocator_traits<Allocator>::construct(a, b, *first);
505 S_destroy_range_a(a, dest, b);
511 template <typename It>
512 static void S_uninitialized_copy(T* dest, It first, It last) {
515 for (; first != last; ++first, ++b)
516 S_construct(b, *first);
518 S_destroy_range(dest, b);
524 S_uninitialized_copy_bits(T* dest, const T* first, const T* last) {
525 std::memcpy((void*)dest, (void*)first, (last - first) * sizeof(T));
529 S_uninitialized_copy_bits(T* dest, std::move_iterator<T*> first,
530 std::move_iterator<T*> last) {
531 T* bFirst = first.base();
532 T* bLast = last.base();
533 std::memcpy((void*)dest, (void*)bFirst, (bLast - bFirst) * sizeof(T));
536 template <typename It>
538 S_uninitialized_copy_bits(T* dest, It first, It last) {
539 S_uninitialized_copy(dest, first, last);
542 //---------------------------------------------------------------------------
545 // This function is "unsafe": it assumes that the iterator can be advanced at
546 // least n times. However, as a private function, that unsafety is managed
547 // wholly by fbvector itself.
549 template <typename It>
550 static It S_copy_n(T* dest, It first, size_type n) {
552 for (; dest != e; ++dest, ++first) *dest = *first;
556 static const T* S_copy_n(T* dest, const T* first, size_type n) {
557 if (folly::IsTriviallyCopyable<T>::value) {
558 std::memcpy((void*)dest, (void*)first, n * sizeof(T));
561 return S_copy_n<const T*>(dest, first, n);
565 static std::move_iterator<T*>
566 S_copy_n(T* dest, std::move_iterator<T*> mIt, size_type n) {
567 if (folly::IsTriviallyCopyable<T>::value) {
568 T* first = mIt.base();
569 std::memcpy((void*)dest, (void*)first, n * sizeof(T));
570 return std::make_move_iterator(first + n);
572 return S_copy_n<std::move_iterator<T*>>(dest, mIt, n);
576 //===========================================================================
577 //---------------------------------------------------------------------------
578 // 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
688 fbvector() = default;
690 explicit fbvector(const Allocator& a) : impl_(a) {}
692 explicit fbvector(size_type n, const Allocator& a = Allocator())
694 { M_uninitialized_fill_n_e(n); }
696 fbvector(size_type n, VT value, const Allocator& a = Allocator())
698 { M_uninitialized_fill_n_e(n, value); }
700 template <class It, class Category = typename
701 std::iterator_traits<It>::iterator_category>
702 fbvector(It first, It last, const Allocator& a = Allocator())
703 : fbvector(first, last, a, Category()) {}
705 fbvector(const fbvector& other)
706 : impl_(other.size(), A::select_on_container_copy_construction(other.impl_))
707 { M_uninitialized_copy_e(other.begin(), other.end()); }
709 fbvector(fbvector&& other) noexcept : impl_(std::move(other.impl_)) {}
711 fbvector(const fbvector& other, const Allocator& a)
712 : fbvector(other.begin(), other.end(), a) {}
714 /* may throw */ fbvector(fbvector&& other, const Allocator& a) : impl_(a) {
715 if (impl_ == other.impl_) {
716 impl_.swapData(other.impl_);
718 impl_.init(other.size());
719 M_uninitialized_move_e(other.begin(), other.end());
723 fbvector(std::initializer_list<T> il, const Allocator& a = Allocator())
724 : fbvector(il.begin(), il.end(), a) {}
726 ~fbvector() = default; // the cleanup occurs in impl_
728 fbvector& operator=(const fbvector& other) {
729 if (UNLIKELY(this == &other)) return *this;
731 if (!usingStdAllocator::value &&
732 A::propagate_on_container_copy_assignment::value) {
733 if (impl_ != other.impl_) {
734 // can't use other's different allocator to clean up self
737 (Allocator&)impl_ = (Allocator&)other.impl_;
740 assign(other.begin(), other.end());
744 fbvector& operator=(fbvector&& other) {
745 if (UNLIKELY(this == &other)) return *this;
746 moveFrom(std::move(other), moveIsSwap());
750 fbvector& operator=(std::initializer_list<T> il) {
751 assign(il.begin(), il.end());
755 template <class It, class Category = typename
756 std::iterator_traits<It>::iterator_category>
757 void assign(It first, It last) {
758 assign(first, last, Category());
761 void assign(size_type n, VT value) {
762 if (n > capacity()) {
763 // Not enough space. Do not reserve in place, since we will
764 // discard the old values anyways.
765 if (dataIsInternalAndNotVT(value)) {
766 T copy(std::move(value));
768 M_uninitialized_fill_n_e(n, copy);
771 M_uninitialized_fill_n_e(n, value);
773 } else if (n <= size()) {
774 auto newE = impl_.b_ + n;
775 std::fill(impl_.b_, newE, value);
776 M_destroy_range_e(newE);
778 std::fill(impl_.b_, impl_.e_, value);
779 M_uninitialized_fill_n_e(n - size(), value);
783 void assign(std::initializer_list<T> il) {
784 assign(il.begin(), il.end());
787 allocator_type get_allocator() const noexcept {
793 // contract dispatch for iterator types fbvector(It first, It last)
794 template <class ForwardIterator>
795 fbvector(ForwardIterator first, ForwardIterator last,
796 const Allocator& a, std::forward_iterator_tag)
797 : impl_(std::distance(first, last), a)
798 { M_uninitialized_copy_e(first, last); }
800 template <class InputIterator>
801 fbvector(InputIterator first, InputIterator last,
802 const Allocator& a, std::input_iterator_tag)
804 { for (; first != last; ++first) emplace_back(*first); }
806 // contract dispatch for allocator movement in operator=(fbvector&&)
808 moveFrom(fbvector&& other, std::true_type) {
809 swap(impl_, other.impl_);
811 void moveFrom(fbvector&& other, std::false_type) {
812 if (impl_ == other.impl_) {
813 impl_.swapData(other.impl_);
815 impl_.reset(other.size());
816 M_uninitialized_move_e(other.begin(), other.end());
820 // contract dispatch for iterator types in assign(It first, It last)
821 template <class ForwardIterator>
822 void assign(ForwardIterator first, ForwardIterator last,
823 std::forward_iterator_tag) {
824 const size_t newSize = std::distance(first, last);
825 if (newSize > capacity()) {
826 impl_.reset(newSize);
827 M_uninitialized_copy_e(first, last);
828 } else if (newSize <= size()) {
829 auto newEnd = std::copy(first, last, impl_.b_);
830 M_destroy_range_e(newEnd);
832 auto mid = S_copy_n(impl_.b_, first, size());
833 M_uninitialized_copy_e<decltype(last)>(mid, last);
837 template <class InputIterator>
838 void assign(InputIterator first, InputIterator last,
839 std::input_iterator_tag) {
841 for (; first != last && p != impl_.e_; ++first, ++p) {
845 M_destroy_range_e(p);
847 for (; first != last; ++first) emplace_back(*first);
851 // contract dispatch for aliasing under VT optimization
852 bool dataIsInternalAndNotVT(const T& t) {
853 if (should_pass_by_value::value) return false;
854 return dataIsInternal(t);
856 bool dataIsInternal(const T& t) {
857 return UNLIKELY(impl_.b_ <= std::addressof(t) &&
858 std::addressof(t) < impl_.e_);
862 //===========================================================================
863 //---------------------------------------------------------------------------
867 iterator begin() noexcept {
870 const_iterator begin() const noexcept {
873 iterator end() noexcept {
876 const_iterator end() const noexcept {
879 reverse_iterator rbegin() noexcept {
880 return reverse_iterator(end());
882 const_reverse_iterator rbegin() const noexcept {
883 return const_reverse_iterator(end());
885 reverse_iterator rend() noexcept {
886 return reverse_iterator(begin());
888 const_reverse_iterator rend() const noexcept {
889 return const_reverse_iterator(begin());
892 const_iterator cbegin() const noexcept {
895 const_iterator cend() const noexcept {
898 const_reverse_iterator crbegin() const noexcept {
899 return const_reverse_iterator(end());
901 const_reverse_iterator crend() const noexcept {
902 return const_reverse_iterator(begin());
905 //===========================================================================
906 //---------------------------------------------------------------------------
910 size_type size() const noexcept {
911 return impl_.e_ - impl_.b_;
914 size_type max_size() const noexcept {
915 // good luck gettin' there
916 return ~size_type(0);
919 void resize(size_type n) {
921 M_destroy_range_e(impl_.b_ + n);
924 M_uninitialized_fill_n_e(n - size());
928 void resize(size_type n, VT t) {
930 M_destroy_range_e(impl_.b_ + n);
931 } else if (dataIsInternalAndNotVT(t) && n > capacity()) {
934 M_uninitialized_fill_n_e(n - size(), copy);
937 M_uninitialized_fill_n_e(n - size(), t);
941 size_type capacity() const noexcept {
942 return impl_.z_ - impl_.b_;
945 bool empty() const noexcept {
946 return impl_.b_ == impl_.e_;
949 void reserve(size_type n) {
950 if (n <= capacity()) return;
951 if (impl_.b_ && reserve_in_place(n)) return;
953 auto newCap = folly::goodMallocSize(n * sizeof(T)) / sizeof(T);
954 auto newB = M_allocate(newCap);
958 M_deallocate(newB, newCap);
962 M_deallocate(impl_.b_, impl_.z_ - impl_.b_);
963 impl_.z_ = newB + newCap;
964 impl_.e_ = newB + (impl_.e_ - impl_.b_);
968 void shrink_to_fit() noexcept {
974 auto const newCapacityBytes = folly::goodMallocSize(size() * sizeof(T));
975 auto const newCap = newCapacityBytes / sizeof(T);
976 auto const oldCap = capacity();
978 if (newCap >= oldCap) return;
981 // xallocx() will shrink to precisely newCapacityBytes (which was generated
982 // by goodMallocSize()) if it successfully shrinks in place.
983 if ((usingJEMalloc() && usingStdAllocator::value) &&
984 newCapacityBytes >= folly::jemallocMinInPlaceExpandable &&
985 xallocx(p, newCapacityBytes, 0, 0) == newCapacityBytes) {
986 impl_.z_ += newCap - oldCap;
988 T* newB; // intentionally uninitialized
990 newB = M_allocate(newCap);
994 M_deallocate(newB, newCap);
995 return; // swallow the error
1001 M_deallocate(impl_.b_, impl_.z_ - impl_.b_);
1002 impl_.z_ = newB + newCap;
1003 impl_.e_ = newB + (impl_.e_ - impl_.b_);
1010 bool reserve_in_place(size_type n) {
1011 if (!usingStdAllocator::value || !usingJEMalloc()) return false;
1013 // jemalloc can never grow in place blocks smaller than 4096 bytes.
1014 if ((impl_.z_ - impl_.b_) * sizeof(T) <
1015 folly::jemallocMinInPlaceExpandable) return false;
1017 auto const newCapacityBytes = folly::goodMallocSize(n * sizeof(T));
1019 if (xallocx(p, newCapacityBytes, 0, 0) == newCapacityBytes) {
1020 impl_.z_ = impl_.b_ + newCapacityBytes / sizeof(T);
1026 //===========================================================================
1027 //---------------------------------------------------------------------------
1031 reference operator[](size_type n) {
1035 const_reference operator[](size_type n) const {
1039 const_reference at(size_type n) const {
1040 if (UNLIKELY(n >= size())) {
1041 throw std::out_of_range("fbvector: index is greater than size.");
1045 reference at(size_type n) {
1046 auto const& cThis = *this;
1047 return const_cast<reference>(cThis.at(n));
1053 const_reference front() const {
1059 return impl_.e_[-1];
1061 const_reference back() const {
1063 return impl_.e_[-1];
1066 //===========================================================================
1067 //---------------------------------------------------------------------------
1071 T* data() noexcept {
1074 const T* data() const noexcept {
1078 //===========================================================================
1079 //---------------------------------------------------------------------------
1080 // modifiers (common)
1083 template <class... Args>
1084 void emplace_back(Args&&... args) {
1085 if (impl_.e_ != impl_.z_) {
1086 M_construct(impl_.e_, std::forward<Args>(args)...);
1089 emplace_back_aux(std::forward<Args>(args)...);
1094 push_back(const T& value) {
1095 if (impl_.e_ != impl_.z_) {
1096 M_construct(impl_.e_, value);
1099 emplace_back_aux(value);
1104 push_back(T&& value) {
1105 if (impl_.e_ != impl_.z_) {
1106 M_construct(impl_.e_, std::move(value));
1109 emplace_back_aux(std::move(value));
1116 M_destroy(impl_.e_);
1119 void swap(fbvector& other) noexcept {
1120 if (!usingStdAllocator::value &&
1121 A::propagate_on_container_swap::value)
1122 swap(impl_, other.impl_);
1123 else impl_.swapData(other.impl_);
1126 void clear() noexcept {
1127 M_destroy_range_e(impl_.b_);
1132 // std::vector implements a similar function with a different growth
1133 // strategy: empty() ? 1 : capacity() * 2.
1135 // fbvector grows differently on two counts:
1138 // Instead of grwoing to size 1 from empty, and fbvector allocates at
1139 // least 64 bytes. You may still use reserve to reserve a lesser amount
1142 // For medium-sized vectors, the growth strategy is 1.5x. See the docs
1144 // This does not apply to very small or very large fbvectors. This is a
1146 // A nice addition to fbvector would be the capability of having a user-
1147 // defined growth strategy, probably as part of the allocator.
1150 size_type computePushBackCapacity() const {
1151 if (capacity() == 0) {
1152 return std::max(64 / sizeof(T), size_type(1));
1154 if (capacity() < folly::jemallocMinInPlaceExpandable / sizeof(T)) {
1155 return capacity() * 2;
1157 if (capacity() > 4096 * 32 / sizeof(T)) {
1158 return capacity() * 2;
1160 return (capacity() * 3 + 1) / 2;
1163 template <class... Args>
1164 void emplace_back_aux(Args&&... args);
1166 //===========================================================================
1167 //---------------------------------------------------------------------------
1168 // modifiers (erase)
1171 iterator erase(const_iterator position) {
1172 return erase(position, position + 1);
1175 iterator erase(const_iterator first, const_iterator last) {
1176 assert(isValid(first) && isValid(last));
1177 assert(first <= last);
1178 if (first != last) {
1179 if (last == end()) {
1180 M_destroy_range_e((iterator)first);
1182 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
1183 D_destroy_range_a((iterator)first, (iterator)last);
1184 if (last - first >= cend() - last) {
1185 std::memcpy((void*)first, (void*)last, (cend() - last) * sizeof(T));
1187 std::memmove((iterator)first, last, (cend() - last) * sizeof(T));
1189 impl_.e_ -= (last - first);
1191 std::copy(std::make_move_iterator((iterator)last),
1192 std::make_move_iterator(end()), (iterator)first);
1193 auto newEnd = impl_.e_ - std::distance(first, last);
1194 M_destroy_range_e(newEnd);
1198 return (iterator)first;
1201 //===========================================================================
1202 //---------------------------------------------------------------------------
1203 // modifiers (insert)
1204 private: // we have the private section first because it defines some macros
1206 bool isValid(const_iterator it) {
1207 return cbegin() <= it && it <= cend();
1210 size_type computeInsertCapacity(size_type n) {
1211 size_type nc = std::max(computePushBackCapacity(), size() + n);
1212 size_type ac = folly::goodMallocSize(nc * sizeof(T)) / sizeof(T);
1216 //---------------------------------------------------------------------------
1218 // make_window takes an fbvector, and creates an uninitialized gap (a
1219 // window) at the given position, of the given size. The fbvector must
1220 // have enough capacity.
1222 // Explanation by picture.
1226 // make_window here of size 3
1230 // If something goes wrong and the window must be destroyed, use
1231 // undo_window to provide a weak exception guarantee. It destroys
1236 //---------------------------------------------------------------------------
1238 // wrap_frame takes an inverse window and relocates an fbvector around it.
1239 // The fbvector must have at least as many elements as the left ledge.
1241 // Explanation by picture.
1244 // fbvector: inverse window:
1245 // 123456789______ _____abcde_______
1249 // _______________ 12345abcde6789___
1251 //---------------------------------------------------------------------------
1253 // insert_use_fresh_memory returns true iff the fbvector should use a fresh
1254 // block of memory for the insertion. If the fbvector does not have enough
1255 // spare capacity, then it must return true. Otherwise either true or false
1258 //---------------------------------------------------------------------------
1260 // These three functions, make_window, wrap_frame, and
1261 // insert_use_fresh_memory, can be combined into a uniform interface.
1262 // Since that interface involves a lot of case-work, it is built into
1263 // some macros: FOLLY_FBVECTOR_INSERT_(PRE|START|TRY|END)
1264 // Macros are used in an attempt to let GCC perform better optimizations,
1265 // especially control flow optimization.
1268 //---------------------------------------------------------------------------
1271 void make_window(iterator position, size_type n) {
1272 // The result is guaranteed to be non-negative, so use an unsigned type:
1273 size_type tail = std::distance(position, impl_.e_);
1276 relocate_move(position + n, position, impl_.e_);
1277 relocate_done(position + n, position, impl_.e_);
1280 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
1281 std::memmove(position + n, position, tail * sizeof(T));
1284 D_uninitialized_move_a(impl_.e_, impl_.e_ - n, impl_.e_);
1286 std::copy_backward(std::make_move_iterator(position),
1287 std::make_move_iterator(impl_.e_ - n), impl_.e_);
1289 D_destroy_range_a(impl_.e_ - n, impl_.e_ + n);
1294 D_destroy_range_a(position, position + n);
1299 void undo_window(iterator position, size_type n) noexcept {
1300 D_destroy_range_a(position + n, impl_.e_);
1301 impl_.e_ = position;
1304 //---------------------------------------------------------------------------
1307 void wrap_frame(T* ledge, size_type idx, size_type n) {
1308 assert(size() >= idx);
1311 relocate_move(ledge, impl_.b_, impl_.b_ + idx);
1313 relocate_move(ledge + idx + n, impl_.b_ + idx, impl_.e_);
1315 relocate_undo(ledge, impl_.b_, impl_.b_ + idx);
1318 relocate_done(ledge, impl_.b_, impl_.b_ + idx);
1319 relocate_done(ledge + idx + n, impl_.b_ + idx, impl_.e_);
1322 //---------------------------------------------------------------------------
1325 bool insert_use_fresh(bool at_end, size_type n) {
1327 if (size() + n <= capacity()) return false;
1328 if (reserve_in_place(size() + n)) return false;
1332 if (size() + n > capacity()) return true;
1337 //---------------------------------------------------------------------------
1340 #define FOLLY_FBVECTOR_INSERT_PRE(cpos, n) \
1341 if (n == 0) return (iterator)cpos; \
1342 bool at_end = cpos == cend(); \
1343 bool fresh = insert_use_fresh(at_end, n); \
1347 // check for internal data (technically not required by the standard)
1349 #define FOLLY_FBVECTOR_INSERT_START(cpos, n) \
1351 assert(isValid(cpos)); \
1353 T* position = const_cast<T*>(cpos); \
1354 size_type idx = 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); \
1370 T* start = b + idx; \
1374 // construct the inserted elements
1376 #define FOLLY_FBVECTOR_INSERT_TRY(cpos, n) \
1379 M_deallocate(b, newCap); \
1382 undo_window(position, n); \
1392 wrap_frame(b, idx, n); \
1396 // delete the inserted elements (exception has been thrown)
1398 #define FOLLY_FBVECTOR_INSERT_END(cpos, n) \
1399 M_deallocate(b, newCap); \
1402 if (impl_.b_) M_deallocate(impl_.b_, capacity()); \
1403 impl_.set(b, size() + n, newCap); \
1404 return impl_.b_ + idx; \
1409 //---------------------------------------------------------------------------
1413 template <class... Args>
1414 iterator emplace(const_iterator cpos, Args&&... args) {
1415 FOLLY_FBVECTOR_INSERT_PRE(cpos, 1)
1416 FOLLY_FBVECTOR_INSERT_START(cpos, 1)
1417 M_construct(start, std::forward<Args>(args)...);
1418 FOLLY_FBVECTOR_INSERT_TRY(cpos, 1)
1420 FOLLY_FBVECTOR_INSERT_END(cpos, 1)
1423 iterator insert(const_iterator cpos, const T& value) {
1424 FOLLY_FBVECTOR_INSERT_PRE(cpos, 1)
1425 if (dataIsInternal(value)) return insert(cpos, T(value));
1426 FOLLY_FBVECTOR_INSERT_START(cpos, 1)
1427 M_construct(start, value);
1428 FOLLY_FBVECTOR_INSERT_TRY(cpos, 1)
1430 FOLLY_FBVECTOR_INSERT_END(cpos, 1)
1433 iterator insert(const_iterator cpos, T&& value) {
1434 FOLLY_FBVECTOR_INSERT_PRE(cpos, 1)
1435 if (dataIsInternal(value)) return insert(cpos, T(std::move(value)));
1436 FOLLY_FBVECTOR_INSERT_START(cpos, 1)
1437 M_construct(start, std::move(value));
1438 FOLLY_FBVECTOR_INSERT_TRY(cpos, 1)
1440 FOLLY_FBVECTOR_INSERT_END(cpos, 1)
1443 iterator insert(const_iterator cpos, size_type n, VT value) {
1444 FOLLY_FBVECTOR_INSERT_PRE(cpos, n)
1445 if (dataIsInternalAndNotVT(value)) return insert(cpos, n, T(value));
1446 FOLLY_FBVECTOR_INSERT_START(cpos, n)
1447 D_uninitialized_fill_n_a(start, n, value);
1448 FOLLY_FBVECTOR_INSERT_TRY(cpos, n)
1449 D_destroy_range_a(start, start + n);
1450 FOLLY_FBVECTOR_INSERT_END(cpos, n)
1453 template <class It, class Category = typename
1454 std::iterator_traits<It>::iterator_category>
1455 iterator insert(const_iterator cpos, It first, It last) {
1456 return insert(cpos, first, last, Category());
1459 iterator insert(const_iterator cpos, std::initializer_list<T> il) {
1460 return insert(cpos, il.begin(), il.end());
1463 //---------------------------------------------------------------------------
1464 // insert dispatch for iterator types
1467 template <class FIt>
1468 iterator insert(const_iterator cpos, FIt first, FIt last,
1469 std::forward_iterator_tag) {
1470 size_type n = std::distance(first, last);
1471 FOLLY_FBVECTOR_INSERT_PRE(cpos, n)
1472 FOLLY_FBVECTOR_INSERT_START(cpos, n)
1473 D_uninitialized_copy_a(start, first, last);
1474 FOLLY_FBVECTOR_INSERT_TRY(cpos, n)
1475 D_destroy_range_a(start, start + n);
1476 FOLLY_FBVECTOR_INSERT_END(cpos, n)
1479 template <class IIt>
1480 iterator insert(const_iterator cpos, IIt first, IIt last,
1481 std::input_iterator_tag) {
1482 T* position = const_cast<T*>(cpos);
1483 assert(isValid(position));
1484 size_type idx = std::distance(begin(), position);
1486 fbvector storage(std::make_move_iterator(position),
1487 std::make_move_iterator(end()),
1488 A::select_on_container_copy_construction(impl_));
1489 M_destroy_range_e(position);
1490 for (; first != last; ++first) emplace_back(*first);
1491 insert(cend(), std::make_move_iterator(storage.begin()),
1492 std::make_move_iterator(storage.end()));
1493 return impl_.b_ + idx;
1496 //===========================================================================
1497 //---------------------------------------------------------------------------
1498 // lexicographical functions (others from boost::totally_ordered superclass)
1501 bool operator==(const fbvector& other) const {
1502 return size() == other.size() && std::equal(begin(), end(), other.begin());
1505 bool operator<(const fbvector& other) const {
1506 return std::lexicographical_compare(
1507 begin(), end(), other.begin(), other.end());
1510 //===========================================================================
1511 //---------------------------------------------------------------------------
1515 template <class _T, class _A>
1516 friend _T* relinquish(fbvector<_T, _A>&);
1518 template <class _T, class _A>
1519 friend void attach(fbvector<_T, _A>&, _T* data, size_t sz, size_t cap);
1521 }; // class fbvector
1524 //=============================================================================
1525 //-----------------------------------------------------------------------------
1526 // outlined functions (gcc, you finicky compiler you)
1528 template <typename T, typename Allocator>
1529 template <class... Args>
1530 void fbvector<T, Allocator>::emplace_back_aux(Args&&... args) {
1531 size_type byte_sz = folly::goodMallocSize(
1532 computePushBackCapacity() * sizeof(T));
1533 if (usingStdAllocator::value
1535 && ((impl_.z_ - impl_.b_) * sizeof(T) >=
1536 folly::jemallocMinInPlaceExpandable)) {
1537 // Try to reserve in place.
1538 // Ask xallocx to allocate in place at least size()+1 and at most sz space.
1539 // xallocx will allocate as much as possible within that range, which
1540 // is the best possible outcome: if sz space is available, take it all,
1541 // otherwise take as much as possible. If nothing is available, then fail.
1542 // In this fashion, we never relocate if there is a possibility of
1543 // expanding in place, and we never reallocate by less than the desired
1544 // amount unless we cannot expand further. Hence we will not reallocate
1545 // sub-optimally twice in a row (modulo the blocking memory being freed).
1546 size_type lower = folly::goodMallocSize(sizeof(T) + size() * sizeof(T));
1547 size_type upper = byte_sz;
1548 size_type extra = upper - lower;
1553 if ((actual = xallocx(p, lower, extra, 0)) >= lower) {
1554 impl_.z_ = impl_.b_ + actual / sizeof(T);
1555 M_construct(impl_.e_, std::forward<Args>(args)...);
1561 // Reallocation failed. Perform a manual relocation.
1562 size_type sz = byte_sz / sizeof(T);
1563 auto newB = M_allocate(sz);
1564 auto newE = newB + size();
1566 if (folly::IsRelocatable<T>::value && usingStdAllocator::value) {
1567 // For linear memory access, relocate before construction.
1568 // By the test condition, relocate is noexcept.
1569 // Note that there is no cleanup to do if M_construct throws - that's
1570 // one of the beauties of relocation.
1571 // Benchmarks for this code have high variance, and seem to be close.
1572 relocate_move(newB, impl_.b_, impl_.e_);
1573 M_construct(newE, std::forward<Args>(args)...);
1576 M_construct(newE, std::forward<Args>(args)...);
1581 M_destroy(newE - 1);
1586 M_deallocate(newB, sz);
1589 if (impl_.b_) M_deallocate(impl_.b_, size());
1592 impl_.z_ = newB + sz;
1595 //=============================================================================
1596 //-----------------------------------------------------------------------------
1597 // specialized functions
1599 template <class T, class A>
1600 void swap(fbvector<T, A>& lhs, fbvector<T, A>& rhs) noexcept {
1604 //=============================================================================
1605 //-----------------------------------------------------------------------------
1611 template <class T, class A>
1612 struct IndexableTraits<fbvector<T, A>>
1613 : public IndexableTraitsSeq<fbvector<T, A>> {
1616 } // namespace detail
1618 template <class T, class A>
1619 void compactResize(fbvector<T, A>* v, size_t sz) {
1626 // relinquish and attach are not a members function specifically so that it is
1627 // awkward to call them. It is very easy to shoot yourself in the foot with
1630 // If you call relinquish, then it is your responsibility to free the data
1631 // and the storage, both of which may have been generated in a non-standard
1632 // way through the fbvector's allocator.
1634 // If you call attach, it is your responsibility to ensure that the fbvector
1635 // is fresh (size and capacity both zero), and that the supplied data is
1636 // capable of being manipulated by the allocator.
1637 // It is acceptable to supply a stack pointer IF:
1638 // (1) The vector's data does not outlive the stack pointer. This includes
1639 // extension of the data's life through a move operation.
1640 // (2) The pointer has enough capacity that the vector will never be
1642 // (3) Insert is not called on the vector; these functions have leeway to
1643 // relocate the vector even if there is enough capacity.
1644 // (4) A stack pointer is compatible with the fbvector's allocator.
1647 template <class T, class A>
1648 T* relinquish(fbvector<T, A>& v) {
1650 v.impl_.b_ = v.impl_.e_ = v.impl_.z_ = nullptr;
1654 template <class T, class A>
1655 void attach(fbvector<T, A>& v, T* data, size_t sz, size_t cap) {
1656 assert(v.data() == nullptr);
1658 v.impl_.e_ = data + sz;
1659 v.impl_.z_ = data + cap;
1662 } // namespace folly