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 * For high-level documentation and usage examples see
19 * folly/docs/small_vector.md
21 * @author Jordan DeLong <delong.j@fb.com>
32 #include <type_traits>
35 #include <boost/mpl/count.hpp>
36 #include <boost/mpl/empty.hpp>
37 #include <boost/mpl/eval_if.hpp>
38 #include <boost/mpl/filter_view.hpp>
39 #include <boost/mpl/front.hpp>
40 #include <boost/mpl/identity.hpp>
41 #include <boost/mpl/if.hpp>
42 #include <boost/mpl/placeholders.hpp>
43 #include <boost/mpl/size.hpp>
44 #include <boost/mpl/vector.hpp>
45 #include <boost/operators.hpp>
46 #include <boost/type_traits.hpp>
48 #include <folly/Assume.h>
49 #include <folly/ConstexprMath.h>
50 #include <folly/FormatTraits.h>
51 #include <folly/Malloc.h>
52 #include <folly/Portability.h>
53 #include <folly/SmallLocks.h>
54 #include <folly/Traits.h>
55 #include <folly/portability/BitsFunctexcept.h>
56 #include <folly/portability/Malloc.h>
57 #include <folly/portability/TypeTraits.h>
59 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
61 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
65 //////////////////////////////////////////////////////////////////////
67 namespace small_vector_policy {
69 //////////////////////////////////////////////////////////////////////
72 * A flag which makes us refuse to use the heap at all. If we
73 * overflow the in situ capacity we throw an exception.
77 //////////////////////////////////////////////////////////////////////
79 } // namespace small_vector_policy
81 //////////////////////////////////////////////////////////////////////
83 template <class T, std::size_t M, class A, class B, class C>
86 //////////////////////////////////////////////////////////////////////
91 * Move objects in memory to the right into some uninitialized
92 * memory, where the region overlaps. This doesn't just use
93 * std::move_backward because move_backward only works if all the
94 * memory is initialized to type T already.
97 typename std::enable_if<!FOLLY_IS_TRIVIALLY_COPYABLE(T)>::type
98 moveObjectsRight(T* first, T* lastConstructed, T* realLast) {
99 if (lastConstructed == realLast) {
103 T* end = first - 1; // Past the end going backwards.
104 T* out = realLast - 1;
105 T* in = lastConstructed - 1;
107 for (; in != end && out >= lastConstructed; --in, --out) {
108 new (out) T(std::move(*in));
110 for (; in != end; --in, --out) {
111 *out = std::move(*in);
113 for (; out >= lastConstructed; --out) {
117 // We want to make sure the same stuff is uninitialized memory
118 // if we exit via an exception (this is to make sure we provide
119 // the basic exception safety guarantee for insert functions).
120 if (out < lastConstructed) {
121 out = lastConstructed - 1;
123 for (auto it = out + 1; it != realLast; ++it) {
130 // Specialization for trivially copyable types. The call to
131 // std::move_backward here will just turn into a memmove. (TODO:
132 // change to std::is_trivially_copyable when that works.)
134 typename std::enable_if<FOLLY_IS_TRIVIALLY_COPYABLE(T)>::type
135 moveObjectsRight(T* first, T* lastConstructed, T* realLast) {
136 std::move_backward(first, lastConstructed, realLast);
140 * Populate a region of memory using `op' to construct elements. If
141 * anything throws, undo what we did.
143 template <class T, class Function>
144 void populateMemForward(T* mem, std::size_t n, Function const& op) {
147 for (size_t i = 0; i < n; ++i) {
152 for (std::size_t i = 0; i < idx; ++i) {
159 template <class SizeType, bool ShouldUseHeap>
160 struct IntegralSizePolicyBase {
161 typedef SizeType InternalSizeType;
163 IntegralSizePolicyBase() : size_(0) {}
166 static constexpr std::size_t policyMaxSize() {
167 return SizeType(~kExternMask);
170 std::size_t doSize() const {
171 return size_ & ~kExternMask;
174 std::size_t isExtern() const {
175 return kExternMask & size_;
178 void setExtern(bool b) {
180 size_ |= kExternMask;
182 size_ &= ~kExternMask;
186 void setSize(std::size_t sz) {
187 assert(sz <= policyMaxSize());
188 size_ = (kExternMask & size_) | SizeType(sz);
191 void swapSizePolicy(IntegralSizePolicyBase& o) {
192 std::swap(size_, o.size_);
196 static bool constexpr kShouldUseHeap = ShouldUseHeap;
199 static SizeType constexpr kExternMask =
200 kShouldUseHeap ? SizeType(1) << (sizeof(SizeType) * 8 - 1) : 0;
205 template <class SizeType, bool ShouldUseHeap>
206 struct IntegralSizePolicy;
208 template <class SizeType>
209 struct IntegralSizePolicy<SizeType, true>
210 : public IntegralSizePolicyBase<SizeType, true> {
213 * Move a range to a range of uninitialized memory. Assumes the
214 * ranges don't overlap.
217 typename std::enable_if<!FOLLY_IS_TRIVIALLY_COPYABLE(T)>::type
218 moveToUninitialized(T* first, T* last, T* out) {
221 for (; first != last; ++first, ++idx) {
222 new (&out[idx]) T(std::move(*first));
225 // Even for callers trying to give the strong guarantee
226 // (e.g. push_back) it's ok to assume here that we don't have to
227 // move things back and that it was a copy constructor that
228 // threw: if someone throws from a move constructor the effects
230 for (std::size_t i = 0; i < idx; ++i) {
237 // Specialization for trivially copyable types.
239 typename std::enable_if<FOLLY_IS_TRIVIALLY_COPYABLE(T)>::type
240 moveToUninitialized(T* first, T* last, T* out) {
241 std::memmove(out, first, (last - first) * sizeof *first);
245 * Move a range to a range of uninitialized memory. Assumes the
246 * ranges don't overlap. Inserts an element at out + pos using
247 * emplaceFunc(). out will contain (end - begin) + 1 elements on success and
248 * none on failure. If emplaceFunc() throws [begin, end) is unmodified.
250 template <class T, class EmplaceFunc>
251 void moveToUninitializedEmplace(
256 EmplaceFunc&& emplaceFunc) {
257 // Must be called first so that if it throws [begin, end) is unmodified.
258 // We have to support the strong exception guarantee for emplace_back().
259 emplaceFunc(out + pos);
260 // move old elements to the left of the new one
262 this->moveToUninitialized(begin, begin + pos, out);
267 // move old elements to the right of the new one
269 if (begin + pos < end) {
270 this->moveToUninitialized(begin + pos, end, out + pos + 1);
273 for (SizeType i = 0; i <= pos; ++i) {
281 template <class SizeType>
282 struct IntegralSizePolicy<SizeType, false>
283 : public IntegralSizePolicyBase<SizeType, false> {
286 void moveToUninitialized(T* /*first*/, T* /*last*/, T* /*out*/) {
287 assume_unreachable();
289 template <class T, class EmplaceFunc>
290 void moveToUninitializedEmplace(
295 EmplaceFunc&& /* emplaceFunc */) {
296 assume_unreachable();
301 * If you're just trying to use this class, ignore everything about
302 * this next small_vector_base class thing.
304 * The purpose of this junk is to minimize sizeof(small_vector<>)
305 * and allow specifying the template parameters in whatever order is
306 * convenient for the user. There's a few extra steps here to try
307 * to keep the error messages at least semi-reasonable.
309 * Apologies for all the black magic.
311 namespace mpl = boost::mpl;
314 std::size_t RequestedMaxInline,
318 struct small_vector_base {
319 typedef mpl::vector<InPolicyA, InPolicyB, InPolicyC> PolicyList;
322 * Determine the size type
324 typedef typename mpl::filter_view<
326 boost::is_integral<mpl::placeholders::_1>>::type Integrals;
327 typedef typename mpl::eval_if<
328 mpl::empty<Integrals>,
329 mpl::identity<std::size_t>,
330 mpl::front<Integrals>>::type SizeType;
333 std::is_unsigned<SizeType>::value,
334 "Size type should be an unsigned integral type");
336 mpl::size<Integrals>::value == 0 || mpl::size<Integrals>::value == 1,
337 "Multiple size types specified in small_vector<>");
340 * Determine whether we should allow spilling to the heap or not.
342 typedef typename mpl::count<PolicyList, small_vector_policy::NoHeap>::type
346 HasNoHeap::value == 0 || HasNoHeap::value == 1,
347 "Multiple copies of small_vector_policy::NoHeap "
348 "supplied; this is probably a mistake");
351 * Make the real policy base classes.
353 typedef IntegralSizePolicy<SizeType, !HasNoHeap::value> ActualSizePolicy;
356 * Now inherit from them all. This is done in such a convoluted
357 * way to make sure we get the empty base optimizaton on all these
358 * types to keep sizeof(small_vector<>) minimal.
360 typedef boost::totally_ordered1<
361 small_vector<Value, RequestedMaxInline, InPolicyA, InPolicyB, InPolicyC>,
367 T* pointerFlagSet(T* p) {
368 return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p) | 1);
371 bool pointerFlagGet(T* p) {
372 return reinterpret_cast<uintptr_t>(p) & 1;
375 T* pointerFlagClear(T* p) {
376 return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p) & ~uintptr_t(1));
378 inline void* shiftPointer(void* p, size_t sizeBytes) {
379 return static_cast<char*>(p) + sizeBytes;
383 //////////////////////////////////////////////////////////////////////
387 std::size_t RequestedMaxInline = 1,
388 class PolicyA = void,
389 class PolicyB = void,
390 class PolicyC = void>
391 class small_vector : public detail::small_vector_base<
397 typedef typename detail::
398 small_vector_base<Value, RequestedMaxInline, PolicyA, PolicyB, PolicyC>::
400 typedef typename BaseType::InternalSizeType InternalSizeType;
403 * Figure out the max number of elements we should inline. (If
404 * the user asks for less inlined elements than we can fit unioned
405 * into our value_type*, we will inline more than they asked.)
407 static constexpr std::size_t MaxInline{
408 constexpr_max(sizeof(Value*) / sizeof(Value), RequestedMaxInline)};
411 typedef std::size_t size_type;
412 typedef Value value_type;
413 typedef value_type& reference;
414 typedef value_type const& const_reference;
415 typedef value_type* iterator;
416 typedef value_type const* const_iterator;
417 typedef std::ptrdiff_t difference_type;
419 typedef std::reverse_iterator<iterator> reverse_iterator;
420 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
422 small_vector() = default;
424 small_vector(small_vector const& o) {
428 std::uninitialized_copy(o.begin(), o.end(), begin());
430 if (this->isExtern()) {
438 small_vector(small_vector&& o) noexcept(
439 std::is_nothrow_move_constructible<Value>::value) {
443 std::uninitialized_copy(
444 std::make_move_iterator(o.begin()),
445 std::make_move_iterator(o.end()),
447 this->setSize(o.size());
451 small_vector(std::initializer_list<value_type> il) {
452 constructImpl(il.begin(), il.end(), std::false_type());
455 explicit small_vector(size_type n) {
456 doConstruct(n, [&](void* p) { new (p) value_type(); });
459 small_vector(size_type n, value_type const& t) {
460 doConstruct(n, [&](void* p) { new (p) value_type(t); });
464 explicit small_vector(Arg arg1, Arg arg2) {
465 // Forward using std::is_arithmetic to get to the proper
466 // implementation; this disambiguates between the iterators and
467 // (size_t, value_type) meaning for this constructor.
468 constructImpl(arg1, arg2, std::is_arithmetic<Arg>());
472 for (auto& t : *this) {
475 if (this->isExtern()) {
480 small_vector& operator=(small_vector const& o) {
481 assign(o.begin(), o.end());
485 small_vector& operator=(small_vector&& o) {
486 // TODO: optimization:
487 // if both are internal, use move assignment where possible
496 bool operator==(small_vector const& o) const {
497 return size() == o.size() && std::equal(begin(), end(), o.begin());
500 bool operator<(small_vector const& o) const {
501 return std::lexicographical_compare(begin(), end(), o.begin(), o.end());
504 static constexpr size_type max_size() {
505 return !BaseType::kShouldUseHeap ? static_cast<size_type>(MaxInline)
506 : BaseType::policyMaxSize();
509 size_type size() const {
510 return this->doSize();
520 return data() + size();
522 const_iterator begin() const {
525 const_iterator end() const {
526 return data() + size();
528 const_iterator cbegin() const {
531 const_iterator cend() const {
535 reverse_iterator rbegin() {
536 return reverse_iterator(end());
538 reverse_iterator rend() {
539 return reverse_iterator(begin());
542 const_reverse_iterator rbegin() const {
543 return const_reverse_iterator(end());
546 const_reverse_iterator rend() const {
547 return const_reverse_iterator(begin());
550 const_reverse_iterator crbegin() const {
553 const_reverse_iterator crend() const {
558 * Usually one of the simplest functions in a Container-like class
559 * but a bit more complex here. We have to handle all combinations
560 * of in-place vs. heap between this and o.
562 * Basic guarantee only. Provides the nothrow guarantee iff our
563 * value_type has a nothrow move or copy constructor.
565 void swap(small_vector& o) {
566 using std::swap; // Allow ADL on swap for our value_type.
568 if (this->isExtern() && o.isExtern()) {
569 this->swapSizePolicy(o);
571 auto thisCapacity = this->capacity();
572 auto oCapacity = o.capacity();
574 auto* tmp = u.pdata_.heap_;
575 u.pdata_.heap_ = o.u.pdata_.heap_;
576 o.u.pdata_.heap_ = tmp;
578 this->setCapacity(oCapacity);
579 o.setCapacity(thisCapacity);
584 if (!this->isExtern() && !o.isExtern()) {
585 auto& oldSmall = size() < o.size() ? *this : o;
586 auto& oldLarge = size() < o.size() ? o : *this;
588 for (size_type i = 0; i < oldSmall.size(); ++i) {
589 swap(oldSmall[i], oldLarge[i]);
592 size_type i = oldSmall.size();
593 const size_type ci = i;
595 for (; i < oldLarge.size(); ++i) {
596 auto addr = oldSmall.begin() + i;
597 new (addr) value_type(std::move(oldLarge[i]));
598 oldLarge[i].~value_type();
602 for (; i < oldLarge.size(); ++i) {
603 oldLarge[i].~value_type();
605 oldLarge.setSize(ci);
609 oldLarge.setSize(ci);
613 // isExtern != o.isExtern()
614 auto& oldExtern = o.isExtern() ? o : *this;
615 auto& oldIntern = o.isExtern() ? *this : o;
617 auto oldExternCapacity = oldExtern.capacity();
618 auto oldExternHeap = oldExtern.u.pdata_.heap_;
620 auto buff = oldExtern.u.buffer();
623 for (; i < oldIntern.size(); ++i) {
624 new (&buff[i]) value_type(std::move(oldIntern[i]));
625 oldIntern[i].~value_type();
628 for (size_type kill = 0; kill < i; ++kill) {
629 buff[kill].~value_type();
631 for (; i < oldIntern.size(); ++i) {
632 oldIntern[i].~value_type();
634 oldIntern.setSize(0);
635 oldExtern.u.pdata_.heap_ = oldExternHeap;
636 oldExtern.setCapacity(oldExternCapacity);
639 oldIntern.u.pdata_.heap_ = oldExternHeap;
640 this->swapSizePolicy(o);
641 oldIntern.setCapacity(oldExternCapacity);
644 void resize(size_type sz) {
646 erase(begin() + sz, end());
650 detail::populateMemForward(
651 begin() + size(), sz - size(), [&](void* p) { new (p) value_type(); });
655 void resize(size_type sz, value_type const& v) {
657 erase(begin() + sz, end());
661 detail::populateMemForward(
662 begin() + size(), sz - size(), [&](void* p) { new (p) value_type(v); });
666 value_type* data() noexcept {
667 return this->isExtern() ? u.heap() : u.buffer();
670 value_type const* data() const noexcept {
671 return this->isExtern() ? u.heap() : u.buffer();
674 template <class... Args>
675 iterator emplace(const_iterator p, Args&&... args) {
677 emplace_back(std::forward<Args>(args)...);
682 * We implement emplace at places other than at the back with a
683 * temporary for exception safety reasons. It is possible to
684 * avoid having to do this, but it becomes hard to maintain the
685 * basic exception safety guarantee (unless you respond to a copy
686 * constructor throwing by clearing the whole vector).
688 * The reason for this is that otherwise you have to destruct an
689 * element before constructing this one in its place---if the
690 * constructor throws, you either need a nothrow default
691 * constructor or a nothrow copy/move to get something back in the
692 * "gap", and the vector requirements don't guarantee we have any
693 * of these. Clearing the whole vector is a legal response in
694 * this situation, but it seems like this implementation is easy
695 * enough and probably better.
697 return insert(p, value_type(std::forward<Args>(args)...));
700 void reserve(size_type sz) {
704 size_type capacity() const {
705 if (this->isExtern()) {
706 if (u.hasCapacity()) {
707 return u.getCapacity();
709 return malloc_usable_size(u.pdata_.heap_) / sizeof(value_type);
714 void shrink_to_fit() {
715 if (!this->isExtern()) {
719 small_vector tmp(begin(), end());
723 template <class... Args>
724 void emplace_back(Args&&... args) {
725 if (capacity() == size()) {
726 // Any of args may be references into the vector.
727 // When we are reallocating, we have to be careful to construct the new
728 // element before modifying the data in the old buffer.
731 [&](void* p) { new (p) value_type(std::forward<Args>(args)...); },
734 new (end()) value_type(std::forward<Args>(args)...);
736 this->setSize(size() + 1);
739 void push_back(value_type&& t) {
740 return emplace_back(std::move(t));
743 void push_back(value_type const& t) {
751 iterator insert(const_iterator constp, value_type&& t) {
752 iterator p = unconst(constp);
755 push_back(std::move(t));
759 auto offset = p - begin();
761 if (capacity() == size()) {
764 [&t](void* ptr) { new (ptr) value_type(std::move(t)); },
766 this->setSize(this->size() + 1);
768 detail::moveObjectsRight(
769 data() + offset, data() + size(), data() + size() + 1);
770 this->setSize(size() + 1);
771 data()[offset] = std::move(t);
773 return begin() + offset;
776 iterator insert(const_iterator p, value_type const& t) {
777 // Make a copy and forward to the rvalue value_type&& overload
779 return insert(p, value_type(t));
782 iterator insert(const_iterator pos, size_type n, value_type const& val) {
783 auto offset = pos - begin();
784 makeSize(size() + n);
785 detail::moveObjectsRight(
786 data() + offset, data() + size(), data() + size() + n);
787 this->setSize(size() + n);
788 std::generate_n(begin() + offset, n, [&] { return val; });
789 return begin() + offset;
793 iterator insert(const_iterator p, Arg arg1, Arg arg2) {
794 // Forward using std::is_arithmetic to get to the proper
795 // implementation; this disambiguates between the iterators and
796 // (size_t, value_type) meaning for this function.
797 return insertImpl(unconst(p), arg1, arg2, std::is_arithmetic<Arg>());
800 iterator insert(const_iterator p, std::initializer_list<value_type> il) {
801 return insert(p, il.begin(), il.end());
804 iterator erase(const_iterator q) {
805 std::move(unconst(q) + 1, end(), unconst(q));
806 (data() + size() - 1)->~value_type();
807 this->setSize(size() - 1);
811 iterator erase(const_iterator q1, const_iterator q2) {
815 std::move(unconst(q2), end(), unconst(q1));
816 for (auto it = (end() - std::distance(q1, q2)); it != end(); ++it) {
819 this->setSize(size() - (q2 - q1));
824 erase(begin(), end());
828 void assign(Arg first, Arg last) {
830 insert(end(), first, last);
833 void assign(std::initializer_list<value_type> il) {
834 assign(il.begin(), il.end());
837 void assign(size_type n, const value_type& t) {
850 const_reference front() const {
854 const_reference back() const {
859 reference operator[](size_type i) {
861 return *(begin() + i);
864 const_reference operator[](size_type i) const {
866 return *(begin() + i);
869 reference at(size_type i) {
871 std::__throw_out_of_range("index out of range");
876 const_reference at(size_type i) const {
878 std::__throw_out_of_range("index out of range");
884 static iterator unconst(const_iterator it) {
885 return const_cast<iterator>(it);
888 // The std::false_type argument is part of disambiguating the
889 // iterator insert functions from integral types (see insert().)
891 iterator insertImpl(iterator pos, It first, It last, std::false_type) {
892 typedef typename std::iterator_traits<It>::iterator_category categ;
893 if (std::is_same<categ, std::input_iterator_tag>::value) {
894 auto offset = pos - begin();
895 while (first != last) {
896 pos = insert(pos, *first++);
899 return begin() + offset;
902 auto distance = std::distance(first, last);
903 auto offset = pos - begin();
904 makeSize(size() + distance);
905 detail::moveObjectsRight(
906 data() + offset, data() + size(), data() + size() + distance);
907 this->setSize(size() + distance);
908 std::copy_n(first, distance, begin() + offset);
909 return begin() + offset;
913 insertImpl(iterator pos, size_type n, const value_type& val, std::true_type) {
914 // The true_type means this should call the size_t,value_type
915 // overload. (See insert().)
916 return insert(pos, n, val);
919 // The std::false_type argument came from std::is_arithmetic as part
920 // of disambiguating an overload (see the comment in the
923 void constructImpl(It first, It last, std::false_type) {
924 typedef typename std::iterator_traits<It>::iterator_category categ;
925 if (std::is_same<categ, std::input_iterator_tag>::value) {
926 // With iterators that only allow a single pass, we can't really
927 // do anything sane here.
928 while (first != last) {
929 emplace_back(*first++);
934 auto distance = std::distance(first, last);
936 this->setSize(distance);
938 detail::populateMemForward(
939 data(), distance, [&](void* p) { new (p) value_type(*first++); });
941 if (this->isExtern()) {
948 template <typename InitFunc>
949 void doConstruct(size_type n, InitFunc&& func) {
953 detail::populateMemForward(data(), n, std::forward<InitFunc>(func));
955 if (this->isExtern()) {
962 // The true_type means we should forward to the size_t,value_type
964 void constructImpl(size_type n, value_type const& val, std::true_type) {
965 doConstruct(n, [&](void* p) { new (p) value_type(val); });
969 * Compute the size after growth.
971 size_type computeNewSize() const {
972 return std::min((3 * capacity()) / 2 + 1, max_size());
975 void makeSize(size_type newSize) {
976 makeSizeInternal(newSize, false, [](void*) { assume_unreachable(); }, 0);
979 template <typename EmplaceFunc>
980 void makeSize(size_type newSize, EmplaceFunc&& emplaceFunc, size_type pos) {
981 assert(size() == capacity());
983 newSize, true, std::forward<EmplaceFunc>(emplaceFunc), pos);
987 * Ensure we have a large enough memory region to be size `newSize'.
988 * Will move/copy elements if we are spilling to heap_ or needed to
989 * allocate a new region, but if resized in place doesn't initialize
990 * anything in the new region. In any case doesn't change size().
991 * Supports insertion of new element during reallocation by given
992 * pointer to new element and position of new element.
993 * NOTE: If reallocation is not needed, insert must be false,
994 * because we only know how to emplace elements into new memory.
996 template <typename EmplaceFunc>
997 void makeSizeInternal(
1000 EmplaceFunc&& emplaceFunc,
1002 if (newSize > max_size()) {
1003 throw std::length_error("max_size exceeded in small_vector");
1005 if (newSize <= capacity()) {
1010 assert(this->kShouldUseHeap);
1011 // This branch isn't needed for correctness, but allows the optimizer to
1012 // skip generating code for the rest of this function in NoHeap
1014 if (!this->kShouldUseHeap) {
1018 newSize = std::max(newSize, computeNewSize());
1020 auto needBytes = newSize * sizeof(value_type);
1021 // If the capacity isn't explicitly stored inline, but the heap
1022 // allocation is grown to over some threshold, we should store
1023 // a capacity at the front of the heap allocation.
1024 bool heapifyCapacity =
1025 !kHasInlineCapacity && needBytes > kHeapifyCapacityThreshold;
1026 if (heapifyCapacity) {
1027 needBytes += kHeapifyCapacitySize;
1029 auto const sizeBytes = goodMallocSize(needBytes);
1030 void* newh = checkedMalloc(sizeBytes);
1031 // We expect newh to be at least 2-aligned, because we want to
1032 // use its least significant bit as a flag.
1033 assert(!detail::pointerFlagGet(newh));
1035 value_type* newp = static_cast<value_type*>(
1036 heapifyCapacity ? detail::shiftPointer(newh, kHeapifyCapacitySize)
1041 // move and insert the new element
1042 this->moveToUninitializedEmplace(
1043 begin(), end(), newp, pos, std::forward<EmplaceFunc>(emplaceFunc));
1045 // move without inserting new element
1046 this->moveToUninitialized(begin(), end(), newp);
1052 for (auto& val : *this) {
1056 if (this->isExtern()) {
1059 auto availableSizeBytes = sizeBytes;
1060 if (heapifyCapacity) {
1061 u.pdata_.heap_ = detail::pointerFlagSet(newh);
1062 availableSizeBytes -= kHeapifyCapacitySize;
1064 u.pdata_.heap_ = newh;
1066 this->setExtern(true);
1067 this->setCapacity(availableSizeBytes / sizeof(value_type));
1071 * This will set the capacity field, stored inline in the storage_ field
1072 * if there is sufficient room to store it.
1074 void setCapacity(size_type newCapacity) {
1075 assert(this->isExtern());
1076 if (u.hasCapacity()) {
1077 assert(newCapacity < std::numeric_limits<InternalSizeType>::max());
1078 u.setCapacity(newCapacity);
1083 struct HeapPtrWithCapacity {
1085 InternalSizeType capacity_;
1087 InternalSizeType getCapacity() const {
1090 void setCapacity(InternalSizeType c) {
1096 // Lower order bit of heap_ is used as flag to indicate whether capacity is
1097 // stored at the front of the heap allocation.
1100 InternalSizeType getCapacity() const {
1101 assert(detail::pointerFlagGet(heap_));
1102 return *static_cast<InternalSizeType*>(detail::pointerFlagClear(heap_));
1104 void setCapacity(InternalSizeType c) {
1105 *static_cast<InternalSizeType*>(detail::pointerFlagClear(heap_)) = c;
1109 #if (FOLLY_X64 || FOLLY_PPC64)
1110 typedef unsigned char InlineStorageDataType[sizeof(value_type) * MaxInline];
1112 typedef typename std::aligned_storage<
1113 sizeof(value_type) * MaxInline,
1114 alignof(value_type)>::type InlineStorageDataType;
1117 typedef typename std::conditional<
1118 sizeof(value_type) * MaxInline != 0,
1119 InlineStorageDataType,
1120 void*>::type InlineStorageType;
1122 static bool constexpr kHasInlineCapacity =
1123 sizeof(HeapPtrWithCapacity) < sizeof(InlineStorageType);
1125 // This value should we multiple of word size.
1126 static size_t constexpr kHeapifyCapacitySize = sizeof(
1128 aligned_storage<sizeof(InternalSizeType), alignof(value_type)>::type);
1130 // Threshold to control capacity heapifying.
1131 static size_t constexpr kHeapifyCapacityThreshold =
1132 100 * kHeapifyCapacitySize;
1134 typedef typename std::
1135 conditional<kHasInlineCapacity, HeapPtrWithCapacity, HeapPtr>::type
1144 InlineStorageType storage_;
1146 value_type* buffer() noexcept {
1147 void* vp = &storage_;
1148 return static_cast<value_type*>(vp);
1150 value_type const* buffer() const noexcept {
1151 return const_cast<Data*>(this)->buffer();
1153 value_type* heap() noexcept {
1154 if (kHasInlineCapacity || !detail::pointerFlagGet(pdata_.heap_)) {
1155 return static_cast<value_type*>(pdata_.heap_);
1157 return static_cast<value_type*>(detail::shiftPointer(
1158 detail::pointerFlagClear(pdata_.heap_), kHeapifyCapacitySize));
1161 value_type const* heap() const noexcept {
1162 return const_cast<Data*>(this)->heap();
1165 bool hasCapacity() const {
1166 return kHasInlineCapacity || detail::pointerFlagGet(pdata_.heap_);
1168 InternalSizeType getCapacity() const {
1169 return pdata_.getCapacity();
1171 void setCapacity(InternalSizeType c) {
1172 pdata_.setCapacity(c);
1176 auto vp = detail::pointerFlagClear(pdata_.heap_);
1179 } FOLLY_PACK_ATTR u;
1183 //////////////////////////////////////////////////////////////////////
1185 // Basic guarantee only, or provides the nothrow guarantee iff T has a
1186 // nothrow move or copy constructor.
1187 template <class T, std::size_t MaxInline, class A, class B, class C>
1189 small_vector<T, MaxInline, A, B, C>& a,
1190 small_vector<T, MaxInline, A, B, C>& b) {
1194 //////////////////////////////////////////////////////////////////////
1199 template <class T, size_t M, class A, class B, class C>
1200 struct IndexableTraits<small_vector<T, M, A, B, C>>
1201 : public IndexableTraitsSeq<small_vector<T, M, A, B, C>> {};
1203 } // namespace detail
1205 } // namespace folly