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>
31 #include <type_traits>
33 #include <boost/mpl/count.hpp>
34 #include <boost/mpl/empty.hpp>
35 #include <boost/mpl/eval_if.hpp>
36 #include <boost/mpl/filter_view.hpp>
37 #include <boost/mpl/front.hpp>
38 #include <boost/mpl/identity.hpp>
39 #include <boost/mpl/if.hpp>
40 #include <boost/mpl/placeholders.hpp>
41 #include <boost/mpl/size.hpp>
42 #include <boost/mpl/vector.hpp>
43 #include <boost/operators.hpp>
44 #include <boost/type_traits.hpp>
46 #include <folly/Assume.h>
47 #include <folly/FormatTraits.h>
48 #include <folly/Malloc.h>
49 #include <folly/Portability.h>
50 #include <folly/SmallLocks.h>
51 #include <folly/Traits.h>
52 #include <folly/portability/BitsFunctexcept.h>
53 #include <folly/portability/Constexpr.h>
54 #include <folly/portability/Malloc.h>
55 #include <folly/portability/TypeTraits.h>
57 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
59 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
63 //////////////////////////////////////////////////////////////////////
65 namespace small_vector_policy {
67 //////////////////////////////////////////////////////////////////////
70 * A flag which makes us refuse to use the heap at all. If we
71 * overflow the in situ capacity we throw an exception.
75 //////////////////////////////////////////////////////////////////////
77 } // namespace small_vector_policy
79 //////////////////////////////////////////////////////////////////////
81 template <class T, std::size_t M, class A, class B, class C>
84 //////////////////////////////////////////////////////////////////////
89 * Move a range to a range of uninitialized memory. Assumes the
90 * ranges don't overlap.
93 typename std::enable_if<
94 !FOLLY_IS_TRIVIALLY_COPYABLE(T)
96 moveToUninitialized(T* first, T* last, T* out) {
99 for (; first != last; ++first, ++idx) {
100 new (&out[idx]) T(std::move(*first));
103 // Even for callers trying to give the strong guarantee
104 // (e.g. push_back) it's ok to assume here that we don't have to
105 // move things back and that it was a copy constructor that
106 // threw: if someone throws from a move constructor the effects
108 for (std::size_t i = 0; i < idx; ++i) {
115 // Specialization for trivially copyable types.
117 typename std::enable_if<
118 FOLLY_IS_TRIVIALLY_COPYABLE(T)
120 moveToUninitialized(T* first, T* last, T* out) {
121 std::memmove(out, first, (last - first) * sizeof *first);
125 * Move a range to a range of uninitialized memory. Assumes the
126 * ranges don't overlap. Inserts an element at out + pos using emplaceFunc().
127 * out will contain (end - begin) + 1 elements on success and none on failure.
128 * If emplaceFunc() throws [begin, end) is unmodified.
130 template <class T, class Size, class EmplaceFunc>
131 void moveToUninitializedEmplace(
136 EmplaceFunc&& emplaceFunc) {
137 // Must be called first so that if it throws [begin, end) is unmodified.
138 // We have to support the strong exception guarantee for emplace_back().
139 emplaceFunc(out + pos);
140 // move old elements to the left of the new one
142 detail::moveToUninitialized(begin, begin + pos, out);
147 // move old elements to the right of the new one
149 if (begin + pos < end) {
150 detail::moveToUninitialized(begin + pos, end, out + pos + 1);
153 for (Size i = 0; i <= pos; ++i) {
161 * Move objects in memory to the right into some uninitialized
162 * memory, where the region overlaps. This doesn't just use
163 * std::move_backward because move_backward only works if all the
164 * memory is initialized to type T already.
167 typename std::enable_if<
168 !FOLLY_IS_TRIVIALLY_COPYABLE(T)
170 moveObjectsRight(T* first, T* lastConstructed, T* realLast) {
171 if (lastConstructed == realLast) {
175 T* end = first - 1; // Past the end going backwards.
176 T* out = realLast - 1;
177 T* in = lastConstructed - 1;
179 for (; in != end && out >= lastConstructed; --in, --out) {
180 new (out) T(std::move(*in));
182 for (; in != end; --in, --out) {
183 *out = std::move(*in);
185 for (; out >= lastConstructed; --out) {
189 // We want to make sure the same stuff is uninitialized memory
190 // if we exit via an exception (this is to make sure we provide
191 // the basic exception safety guarantee for insert functions).
192 if (out < lastConstructed) {
193 out = lastConstructed - 1;
195 for (auto it = out + 1; it != realLast; ++it) {
202 // Specialization for trivially copyable types. The call to
203 // std::move_backward here will just turn into a memmove. (TODO:
204 // change to std::is_trivially_copyable when that works.)
206 typename std::enable_if<
207 FOLLY_IS_TRIVIALLY_COPYABLE(T)
209 moveObjectsRight(T* first, T* lastConstructed, T* realLast) {
210 std::move_backward(first, lastConstructed, realLast);
214 * Populate a region of memory using `op' to construct elements. If
215 * anything throws, undo what we did.
217 template <class T, class Function>
218 void populateMemForward(T* mem, std::size_t n, Function const& op) {
221 for (size_t i = 0; i < n; ++i) {
226 for (std::size_t i = 0; i < idx; ++i) {
233 template <class SizeType, bool ShouldUseHeap>
234 struct IntegralSizePolicy {
235 typedef SizeType InternalSizeType;
237 IntegralSizePolicy() : size_(0) {}
240 static constexpr std::size_t policyMaxSize() {
241 return SizeType(~kExternMask);
244 std::size_t doSize() const {
245 return size_ & ~kExternMask;
248 std::size_t isExtern() const {
249 return kExternMask & size_;
252 void setExtern(bool b) {
254 size_ |= kExternMask;
256 size_ &= ~kExternMask;
260 void setSize(std::size_t sz) {
261 assert(sz <= policyMaxSize());
262 size_ = (kExternMask & size_) | SizeType(sz);
265 void swapSizePolicy(IntegralSizePolicy& o) {
266 std::swap(size_, o.size_);
270 static bool const kShouldUseHeap = ShouldUseHeap;
273 static SizeType const kExternMask =
274 kShouldUseHeap ? SizeType(1) << (sizeof(SizeType) * 8 - 1)
281 * If you're just trying to use this class, ignore everything about
282 * this next small_vector_base class thing.
284 * The purpose of this junk is to minimize sizeof(small_vector<>)
285 * and allow specifying the template parameters in whatever order is
286 * convenient for the user. There's a few extra steps here to try
287 * to keep the error messages at least semi-reasonable.
289 * Apologies for all the black magic.
291 namespace mpl = boost::mpl;
294 std::size_t RequestedMaxInline,
298 struct small_vector_base {
299 typedef mpl::vector<InPolicyA,InPolicyB,InPolicyC> PolicyList;
302 * Determine the size type
304 typedef typename mpl::filter_view<
306 boost::is_integral<mpl::placeholders::_1>
308 typedef typename mpl::eval_if<
309 mpl::empty<Integrals>,
310 mpl::identity<std::size_t>,
311 mpl::front<Integrals>
314 static_assert(std::is_unsigned<SizeType>::value,
315 "Size type should be an unsigned integral type");
316 static_assert(mpl::size<Integrals>::value == 0 ||
317 mpl::size<Integrals>::value == 1,
318 "Multiple size types specified in small_vector<>");
321 * Determine whether we should allow spilling to the heap or not.
323 typedef typename mpl::count<
324 PolicyList,small_vector_policy::NoHeap
327 static_assert(HasNoHeap::value == 0 || HasNoHeap::value == 1,
328 "Multiple copies of small_vector_policy::NoHeap "
329 "supplied; this is probably a mistake");
332 * Make the real policy base classes.
334 typedef IntegralSizePolicy<SizeType,!HasNoHeap::value>
338 * Now inherit from them all. This is done in such a convoluted
339 * way to make sure we get the empty base optimizaton on all these
340 * types to keep sizeof(small_vector<>) minimal.
342 typedef boost::totally_ordered1<
343 small_vector<Value,RequestedMaxInline,InPolicyA,InPolicyB,InPolicyC>,
349 T* pointerFlagSet(T* p) {
350 return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p) | 1);
353 bool pointerFlagGet(T* p) {
354 return reinterpret_cast<uintptr_t>(p) & 1;
357 T* pointerFlagClear(T* p) {
358 return reinterpret_cast<T*>(
359 reinterpret_cast<uintptr_t>(p) & ~uintptr_t(1));
361 inline void* shiftPointer(void* p, size_t sizeBytes) {
362 return static_cast<char*>(p) + sizeBytes;
366 //////////////////////////////////////////////////////////////////////
370 std::size_t RequestedMaxInline = 1,
371 class PolicyA = void,
372 class PolicyB = void,
373 class PolicyC = void>
375 : public detail::small_vector_base<
376 Value,RequestedMaxInline,PolicyA,PolicyB,PolicyC
379 typedef typename detail::small_vector_base<
380 Value,RequestedMaxInline,PolicyA,PolicyB,PolicyC
382 typedef typename BaseType::InternalSizeType InternalSizeType;
385 * Figure out the max number of elements we should inline. (If
386 * the user asks for less inlined elements than we can fit unioned
387 * into our value_type*, we will inline more than they asked.)
389 static constexpr std::size_t MaxInline{
390 constexpr_max(sizeof(Value*) / sizeof(Value), RequestedMaxInline)};
393 typedef std::size_t size_type;
394 typedef Value value_type;
395 typedef value_type& reference;
396 typedef value_type const& const_reference;
397 typedef value_type* iterator;
398 typedef value_type const* const_iterator;
399 typedef std::ptrdiff_t difference_type;
401 typedef std::reverse_iterator<iterator> reverse_iterator;
402 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
404 explicit small_vector() = default;
406 small_vector(small_vector const& o) {
410 std::uninitialized_copy(o.begin(), o.end(), begin());
412 if (this->isExtern()) {
420 small_vector(small_vector&& o)
421 noexcept(std::is_nothrow_move_constructible<Value>::value) {
425 std::uninitialized_copy(std::make_move_iterator(o.begin()),
426 std::make_move_iterator(o.end()),
428 this->setSize(o.size());
432 small_vector(std::initializer_list<value_type> il) {
433 constructImpl(il.begin(), il.end(), std::false_type());
436 explicit small_vector(size_type n) {
437 doConstruct(n, [&](void* p) { new (p) value_type(); });
440 small_vector(size_type n, value_type const& t) {
441 doConstruct(n, [&](void* p) { new (p) value_type(t); });
445 explicit small_vector(Arg arg1, Arg arg2) {
446 // Forward using std::is_arithmetic to get to the proper
447 // implementation; this disambiguates between the iterators and
448 // (size_t, value_type) meaning for this constructor.
449 constructImpl(arg1, arg2, std::is_arithmetic<Arg>());
453 for (auto& t : *this) {
456 if (this->isExtern()) {
461 small_vector& operator=(small_vector const& o) {
462 assign(o.begin(), o.end());
466 small_vector& operator=(small_vector&& o) {
467 // TODO: optimization:
468 // if both are internal, use move assignment where possible
469 if (this == &o) return *this;
475 bool operator==(small_vector const& o) const {
476 return size() == o.size() && std::equal(begin(), end(), o.begin());
479 bool operator<(small_vector const& o) const {
480 return std::lexicographical_compare(begin(), end(), o.begin(), o.end());
483 static constexpr size_type max_size() {
484 return !BaseType::kShouldUseHeap ? static_cast<size_type>(MaxInline)
485 : BaseType::policyMaxSize();
488 size_type size() const { return this->doSize(); }
489 bool empty() const { return !size(); }
491 iterator begin() { return data(); }
492 iterator end() { return data() + size(); }
493 const_iterator begin() const { return data(); }
494 const_iterator end() const { return data() + size(); }
495 const_iterator cbegin() const { return begin(); }
496 const_iterator cend() const { return end(); }
498 reverse_iterator rbegin() { return reverse_iterator(end()); }
499 reverse_iterator rend() { return reverse_iterator(begin()); }
501 const_reverse_iterator rbegin() const {
502 return const_reverse_iterator(end());
505 const_reverse_iterator rend() const {
506 return const_reverse_iterator(begin());
509 const_reverse_iterator crbegin() const { return rbegin(); }
510 const_reverse_iterator crend() const { return rend(); }
513 * Usually one of the simplest functions in a Container-like class
514 * but a bit more complex here. We have to handle all combinations
515 * of in-place vs. heap between this and o.
517 * Basic guarantee only. Provides the nothrow guarantee iff our
518 * value_type has a nothrow move or copy constructor.
520 void swap(small_vector& o) {
521 using std::swap; // Allow ADL on swap for our value_type.
523 if (this->isExtern() && o.isExtern()) {
524 this->swapSizePolicy(o);
526 auto thisCapacity = this->capacity();
527 auto oCapacity = o.capacity();
529 auto* tmp = u.pdata_.heap_;
530 u.pdata_.heap_ = o.u.pdata_.heap_;
531 o.u.pdata_.heap_ = tmp;
533 this->setCapacity(oCapacity);
534 o.setCapacity(thisCapacity);
539 if (!this->isExtern() && !o.isExtern()) {
540 auto& oldSmall = size() < o.size() ? *this : o;
541 auto& oldLarge = size() < o.size() ? o : *this;
543 for (size_type i = 0; i < oldSmall.size(); ++i) {
544 swap(oldSmall[i], oldLarge[i]);
547 size_type i = oldSmall.size();
548 const size_type ci = i;
550 for (; i < oldLarge.size(); ++i) {
551 auto addr = oldSmall.begin() + i;
552 new (addr) value_type(std::move(oldLarge[i]));
553 oldLarge[i].~value_type();
557 for (; i < oldLarge.size(); ++i) {
558 oldLarge[i].~value_type();
560 oldLarge.setSize(ci);
564 oldLarge.setSize(ci);
568 // isExtern != o.isExtern()
569 auto& oldExtern = o.isExtern() ? o : *this;
570 auto& oldIntern = o.isExtern() ? *this : o;
572 auto oldExternCapacity = oldExtern.capacity();
573 auto oldExternHeap = oldExtern.u.pdata_.heap_;
575 auto buff = oldExtern.u.buffer();
578 for (; i < oldIntern.size(); ++i) {
579 new (&buff[i]) value_type(std::move(oldIntern[i]));
580 oldIntern[i].~value_type();
583 for (size_type kill = 0; kill < i; ++kill) {
584 buff[kill].~value_type();
586 for (; i < oldIntern.size(); ++i) {
587 oldIntern[i].~value_type();
589 oldIntern.setSize(0);
590 oldExtern.u.pdata_.heap_ = oldExternHeap;
591 oldExtern.setCapacity(oldExternCapacity);
594 oldIntern.u.pdata_.heap_ = oldExternHeap;
595 this->swapSizePolicy(o);
596 oldIntern.setCapacity(oldExternCapacity);
599 void resize(size_type sz) {
601 erase(begin() + sz, end());
605 detail::populateMemForward(begin() + size(), sz - size(),
606 [&] (void* p) { new (p) value_type(); }
611 void resize(size_type sz, value_type const& v) {
613 erase(begin() + sz, end());
617 detail::populateMemForward(begin() + size(), sz - size(),
618 [&] (void* p) { new (p) value_type(v); }
623 value_type* data() noexcept {
624 return this->isExtern() ? u.heap() : u.buffer();
627 value_type const* data() const noexcept {
628 return this->isExtern() ? u.heap() : u.buffer();
631 template <class... Args>
632 iterator emplace(const_iterator p, Args&&... args) {
634 emplace_back(std::forward<Args>(args)...);
639 * We implement emplace at places other than at the back with a
640 * temporary for exception safety reasons. It is possible to
641 * avoid having to do this, but it becomes hard to maintain the
642 * basic exception safety guarantee (unless you respond to a copy
643 * constructor throwing by clearing the whole vector).
645 * The reason for this is that otherwise you have to destruct an
646 * element before constructing this one in its place---if the
647 * constructor throws, you either need a nothrow default
648 * constructor or a nothrow copy/move to get something back in the
649 * "gap", and the vector requirements don't guarantee we have any
650 * of these. Clearing the whole vector is a legal response in
651 * this situation, but it seems like this implementation is easy
652 * enough and probably better.
654 return insert(p, value_type(std::forward<Args>(args)...));
657 void reserve(size_type sz) {
661 size_type capacity() const {
662 if (this->isExtern()) {
663 if (u.hasCapacity()) {
664 return u.getCapacity();
666 return malloc_usable_size(u.pdata_.heap_) / sizeof(value_type);
671 void shrink_to_fit() {
672 if (!this->isExtern()) {
676 small_vector tmp(begin(), end());
680 template <class... Args>
681 void emplace_back(Args&&... args) {
682 if (capacity() == size()) {
683 // Any of args may be references into the vector.
684 // When we are reallocating, we have to be careful to construct the new
685 // element before modifying the data in the old buffer.
688 [&](void* p) { new (p) value_type(std::forward<Args>(args)...); },
691 new (end()) value_type(std::forward<Args>(args)...);
693 this->setSize(size() + 1);
696 void push_back(value_type&& t) {
697 return emplace_back(std::move(t));
700 void push_back(value_type const& t) {
708 iterator insert(const_iterator constp, value_type&& t) {
709 iterator p = unconst(constp);
712 push_back(std::move(t));
716 auto offset = p - begin();
718 if (capacity() == size()) {
721 [&t](void* ptr) { new (ptr) value_type(std::move(t)); },
723 this->setSize(this->size() + 1);
725 detail::moveObjectsRight(data() + offset,
727 data() + size() + 1);
728 this->setSize(size() + 1);
729 data()[offset] = std::move(t);
731 return begin() + offset;
735 iterator insert(const_iterator p, value_type const& t) {
736 // Make a copy and forward to the rvalue value_type&& overload
738 return insert(p, value_type(t));
741 iterator insert(const_iterator pos, size_type n, value_type const& val) {
742 auto offset = pos - begin();
743 makeSize(size() + n);
744 detail::moveObjectsRight(data() + offset,
746 data() + size() + n);
747 this->setSize(size() + n);
748 std::generate_n(begin() + offset, n, [&] { return val; });
749 return begin() + offset;
753 iterator insert(const_iterator p, Arg arg1, Arg arg2) {
754 // Forward using std::is_arithmetic to get to the proper
755 // implementation; this disambiguates between the iterators and
756 // (size_t, value_type) meaning for this function.
757 return insertImpl(unconst(p), arg1, arg2, std::is_arithmetic<Arg>());
760 iterator insert(const_iterator p, std::initializer_list<value_type> il) {
761 return insert(p, il.begin(), il.end());
764 iterator erase(const_iterator q) {
765 std::move(unconst(q) + 1, end(), unconst(q));
766 (data() + size() - 1)->~value_type();
767 this->setSize(size() - 1);
771 iterator erase(const_iterator q1, const_iterator q2) {
772 if (q1 == q2) return unconst(q1);
773 std::move(unconst(q2), end(), unconst(q1));
774 for (auto it = (end() - std::distance(q1, q2)); it != end(); ++it) {
777 this->setSize(size() - (q2 - q1));
782 erase(begin(), end());
786 void assign(Arg first, Arg last) {
788 insert(end(), first, last);
791 void assign(std::initializer_list<value_type> il) {
792 assign(il.begin(), il.end());
795 void assign(size_type n, const value_type& t) {
800 reference front() { assert(!empty()); return *begin(); }
801 reference back() { assert(!empty()); return *(end() - 1); }
802 const_reference front() const { assert(!empty()); return *begin(); }
803 const_reference back() const { assert(!empty()); return *(end() - 1); }
805 reference operator[](size_type i) {
807 return *(begin() + i);
810 const_reference operator[](size_type i) const {
812 return *(begin() + i);
815 reference at(size_type i) {
817 std::__throw_out_of_range("index out of range");
822 const_reference at(size_type i) const {
824 std::__throw_out_of_range("index out of range");
830 static iterator unconst(const_iterator it) {
831 return const_cast<iterator>(it);
834 // The std::false_type argument is part of disambiguating the
835 // iterator insert functions from integral types (see insert().)
837 iterator insertImpl(iterator pos, It first, It last, std::false_type) {
838 typedef typename std::iterator_traits<It>::iterator_category categ;
839 if (std::is_same<categ,std::input_iterator_tag>::value) {
840 auto offset = pos - begin();
841 while (first != last) {
842 pos = insert(pos, *first++);
845 return begin() + offset;
848 auto distance = std::distance(first, last);
849 auto offset = pos - begin();
850 makeSize(size() + distance);
851 detail::moveObjectsRight(data() + offset,
853 data() + size() + distance);
854 this->setSize(size() + distance);
855 std::copy_n(first, distance, begin() + offset);
856 return begin() + offset;
859 iterator insertImpl(iterator pos, size_type n, const value_type& val,
861 // The true_type means this should call the size_t,value_type
862 // overload. (See insert().)
863 return insert(pos, n, val);
866 // The std::false_type argument came from std::is_arithmetic as part
867 // of disambiguating an overload (see the comment in the
870 void constructImpl(It first, It last, std::false_type) {
871 typedef typename std::iterator_traits<It>::iterator_category categ;
872 if (std::is_same<categ,std::input_iterator_tag>::value) {
873 // With iterators that only allow a single pass, we can't really
874 // do anything sane here.
875 while (first != last) {
876 emplace_back(*first++);
881 auto distance = std::distance(first, last);
883 this->setSize(distance);
885 detail::populateMemForward(data(), distance,
886 [&] (void* p) { new (p) value_type(*first++); }
889 if (this->isExtern()) {
896 template <typename InitFunc>
897 void doConstruct(size_type n, InitFunc&& func) {
901 detail::populateMemForward(data(), n, std::forward<InitFunc>(func));
903 if (this->isExtern()) {
910 // The true_type means we should forward to the size_t,value_type
912 void constructImpl(size_type n, value_type const& val, std::true_type) {
913 doConstruct(n, [&](void* p) { new (p) value_type(val); });
917 * Compute the size after growth.
919 size_type computeNewSize() const {
920 return std::min((3 * capacity()) / 2 + 1, max_size());
923 void makeSize(size_type newSize) {
924 makeSizeInternal(newSize, false, [](void*) { assume_unreachable(); }, 0);
927 template <typename EmplaceFunc>
928 void makeSize(size_type newSize, EmplaceFunc&& emplaceFunc, size_type pos) {
929 assert(size() == capacity());
931 newSize, true, std::forward<EmplaceFunc>(emplaceFunc), pos);
935 * Ensure we have a large enough memory region to be size `newSize'.
936 * Will move/copy elements if we are spilling to heap_ or needed to
937 * allocate a new region, but if resized in place doesn't initialize
938 * anything in the new region. In any case doesn't change size().
939 * Supports insertion of new element during reallocation by given
940 * pointer to new element and position of new element.
941 * NOTE: If reallocation is not needed, insert must be false,
942 * because we only know how to emplace elements into new memory.
944 template <typename EmplaceFunc>
945 void makeSizeInternal(
948 EmplaceFunc&& emplaceFunc,
950 if (newSize > max_size()) {
951 throw std::length_error("max_size exceeded in small_vector");
953 if (newSize <= capacity()) {
957 newSize = std::max(newSize, computeNewSize());
959 auto needBytes = newSize * sizeof(value_type);
960 // If the capacity isn't explicitly stored inline, but the heap
961 // allocation is grown to over some threshold, we should store
962 // a capacity at the front of the heap allocation.
963 bool heapifyCapacity =
964 !kHasInlineCapacity && needBytes > kHeapifyCapacityThreshold;
965 if (heapifyCapacity) {
966 needBytes += kHeapifyCapacitySize;
968 auto const sizeBytes = goodMallocSize(needBytes);
969 void* newh = checkedMalloc(sizeBytes);
970 // We expect newh to be at least 2-aligned, because we want to
971 // use its least significant bit as a flag.
972 assert(!detail::pointerFlagGet(newh));
974 value_type* newp = static_cast<value_type*>(
976 detail::shiftPointer(newh, kHeapifyCapacitySize) :
981 // move and insert the new element
982 detail::moveToUninitializedEmplace(
983 begin(), end(), newp, pos, std::forward<EmplaceFunc>(emplaceFunc));
985 // move without inserting new element
986 detail::moveToUninitialized(begin(), end(), newp);
992 for (auto& val : *this) {
996 if (this->isExtern()) {
999 auto availableSizeBytes = sizeBytes;
1000 if (heapifyCapacity) {
1001 u.pdata_.heap_ = detail::pointerFlagSet(newh);
1002 availableSizeBytes -= kHeapifyCapacitySize;
1004 u.pdata_.heap_ = newh;
1006 this->setExtern(true);
1007 this->setCapacity(availableSizeBytes / sizeof(value_type));
1011 * This will set the capacity field, stored inline in the storage_ field
1012 * if there is sufficient room to store it.
1014 void setCapacity(size_type newCapacity) {
1015 assert(this->isExtern());
1016 if (u.hasCapacity()) {
1017 assert(newCapacity < std::numeric_limits<InternalSizeType>::max());
1018 u.setCapacity(newCapacity);
1023 struct HeapPtrWithCapacity {
1025 InternalSizeType capacity_;
1027 InternalSizeType getCapacity() const {
1030 void setCapacity(InternalSizeType c) {
1036 // Lower order bit of heap_ is used as flag to indicate whether capacity is
1037 // stored at the front of the heap allocation.
1040 InternalSizeType getCapacity() const {
1041 assert(detail::pointerFlagGet(heap_));
1042 return *static_cast<InternalSizeType*>(detail::pointerFlagClear(heap_));
1044 void setCapacity(InternalSizeType c) {
1045 *static_cast<InternalSizeType*>(detail::pointerFlagClear(heap_)) = c;
1049 #if (FOLLY_X64 || FOLLY_PPC64)
1050 typedef unsigned char InlineStorageDataType[sizeof(value_type) * MaxInline];
1052 typedef typename std::aligned_storage<
1053 sizeof(value_type) * MaxInline,
1055 >::type InlineStorageDataType;
1058 typedef typename std::conditional<
1059 sizeof(value_type) * MaxInline != 0,
1060 InlineStorageDataType,
1062 >::type InlineStorageType;
1064 static bool const kHasInlineCapacity =
1065 sizeof(HeapPtrWithCapacity) < sizeof(InlineStorageType);
1067 // This value should we multiple of word size.
1068 static size_t const kHeapifyCapacitySize = sizeof(
1069 typename std::aligned_storage<
1070 sizeof(InternalSizeType),
1073 // Threshold to control capacity heapifying.
1074 static size_t const kHeapifyCapacityThreshold =
1075 100 * kHeapifyCapacitySize;
1077 typedef typename std::conditional<
1079 HeapPtrWithCapacity,
1081 >::type PointerType;
1084 explicit Data() { pdata_.heap_ = 0; }
1087 InlineStorageType storage_;
1089 value_type* buffer() noexcept {
1090 void* vp = &storage_;
1091 return static_cast<value_type*>(vp);
1093 value_type const* buffer() const noexcept {
1094 return const_cast<Data*>(this)->buffer();
1096 value_type* heap() noexcept {
1097 if (kHasInlineCapacity || !detail::pointerFlagGet(pdata_.heap_)) {
1098 return static_cast<value_type*>(pdata_.heap_);
1100 return static_cast<value_type*>(detail::shiftPointer(
1101 detail::pointerFlagClear(pdata_.heap_), kHeapifyCapacitySize));
1104 value_type const* heap() const noexcept {
1105 return const_cast<Data*>(this)->heap();
1108 bool hasCapacity() const {
1109 return kHasInlineCapacity || detail::pointerFlagGet(pdata_.heap_);
1111 InternalSizeType getCapacity() const {
1112 return pdata_.getCapacity();
1114 void setCapacity(InternalSizeType c) {
1115 pdata_.setCapacity(c);
1119 auto vp = detail::pointerFlagClear(pdata_.heap_);
1122 } FOLLY_PACK_ATTR u;
1126 //////////////////////////////////////////////////////////////////////
1128 // Basic guarantee only, or provides the nothrow guarantee iff T has a
1129 // nothrow move or copy constructor.
1130 template <class T, std::size_t MaxInline, class A, class B, class C>
1131 void swap(small_vector<T,MaxInline,A,B,C>& a,
1132 small_vector<T,MaxInline,A,B,C>& b) {
1136 //////////////////////////////////////////////////////////////////////
1141 template <class T, size_t M, class A, class B, class C>
1142 struct IndexableTraits<small_vector<T, M, A, B, C>>
1143 : public IndexableTraitsSeq<small_vector<T, M, A, B, C>> {
1146 } // namespace detail
1148 } // namespace folly