Consistency in namespace-closing comments
[folly.git] / folly / small_vector.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /*
18  * For high-level documentation and usage examples see
19  * folly/docs/small_vector.md
20  *
21  * @author Jordan DeLong <delong.j@fb.com>
22  */
23
24 #pragma once
25
26 #include <algorithm>
27 #include <cassert>
28 #include <cstdlib>
29 #include <iterator>
30 #include <stdexcept>
31 #include <type_traits>
32
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>
45
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>
56
57 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
58 FOLLY_PUSH_WARNING
59 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
60
61 namespace folly {
62
63 //////////////////////////////////////////////////////////////////////
64
65 namespace small_vector_policy {
66
67 //////////////////////////////////////////////////////////////////////
68
69 /*
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.
72  */
73 struct NoHeap;
74
75 //////////////////////////////////////////////////////////////////////
76
77 } // namespace small_vector_policy
78
79 //////////////////////////////////////////////////////////////////////
80
81 template <class T, std::size_t M, class A, class B, class C>
82 class small_vector;
83
84 //////////////////////////////////////////////////////////////////////
85
86 namespace detail {
87
88   /*
89    * Move a range to a range of uninitialized memory.  Assumes the
90    * ranges don't overlap.
91    */
92   template <class T>
93   typename std::enable_if<
94     !FOLLY_IS_TRIVIALLY_COPYABLE(T)
95   >::type
96   moveToUninitialized(T* first, T* last, T* out) {
97     std::size_t idx = 0;
98     try {
99       for (; first != last; ++first, ++idx) {
100         new (&out[idx]) T(std::move(*first));
101       }
102     } catch (...) {
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
107       // are unspecified.
108       for (std::size_t i = 0; i < idx; ++i) {
109         out[i].~T();
110       }
111       throw;
112     }
113   }
114
115   // Specialization for trivially copyable types.
116   template <class T>
117   typename std::enable_if<
118     FOLLY_IS_TRIVIALLY_COPYABLE(T)
119   >::type
120   moveToUninitialized(T* first, T* last, T* out) {
121     std::memmove(out, first, (last - first) * sizeof *first);
122   }
123
124   /*
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.
129    */
130   template <class T, class Size, class EmplaceFunc>
131   void moveToUninitializedEmplace(
132       T* begin,
133       T* end,
134       T* out,
135       Size pos,
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
141     try {
142       detail::moveToUninitialized(begin, begin + pos, out);
143     } catch (...) {
144       out[pos].~T();
145       throw;
146     }
147     // move old elements to the right of the new one
148     try {
149       if (begin + pos < end) {
150         detail::moveToUninitialized(begin + pos, end, out + pos + 1);
151       }
152     } catch (...) {
153       for (Size i = 0; i <= pos; ++i) {
154         out[i].~T();
155       }
156       throw;
157     }
158   }
159
160   /*
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.
165    */
166   template <class T>
167   typename std::enable_if<
168     !FOLLY_IS_TRIVIALLY_COPYABLE(T)
169   >::type
170   moveObjectsRight(T* first, T* lastConstructed, T* realLast) {
171     if (lastConstructed == realLast) {
172       return;
173     }
174
175     T* end = first - 1; // Past the end going backwards.
176     T* out = realLast - 1;
177     T* in = lastConstructed - 1;
178     try {
179       for (; in != end && out >= lastConstructed; --in, --out) {
180         new (out) T(std::move(*in));
181       }
182       for (; in != end; --in, --out) {
183         *out = std::move(*in);
184       }
185       for (; out >= lastConstructed; --out) {
186         new (out) T();
187       }
188     } catch (...) {
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;
194       }
195       for (auto it = out + 1; it != realLast; ++it) {
196         it->~T();
197       }
198       throw;
199     }
200   }
201
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.)
205   template <class T>
206   typename std::enable_if<
207     FOLLY_IS_TRIVIALLY_COPYABLE(T)
208   >::type
209   moveObjectsRight(T* first, T* lastConstructed, T* realLast) {
210     std::move_backward(first, lastConstructed, realLast);
211   }
212
213   /*
214    * Populate a region of memory using `op' to construct elements.  If
215    * anything throws, undo what we did.
216    */
217   template <class T, class Function>
218   void populateMemForward(T* mem, std::size_t n, Function const& op) {
219     std::size_t idx = 0;
220     try {
221       for (size_t i = 0; i < n; ++i) {
222         op(&mem[idx]);
223         ++idx;
224       }
225     } catch (...) {
226       for (std::size_t i = 0; i < idx; ++i) {
227         mem[i].~T();
228       }
229       throw;
230     }
231   }
232
233   template <class SizeType, bool ShouldUseHeap>
234   struct IntegralSizePolicy {
235     typedef SizeType InternalSizeType;
236
237     IntegralSizePolicy() : size_(0) {}
238
239    protected:
240     static constexpr std::size_t policyMaxSize() {
241       return SizeType(~kExternMask);
242     }
243
244     std::size_t doSize() const {
245       return size_ & ~kExternMask;
246     }
247
248     std::size_t isExtern() const {
249       return kExternMask & size_;
250     }
251
252     void setExtern(bool b) {
253       if (b) {
254         size_ |= kExternMask;
255       } else {
256         size_ &= ~kExternMask;
257       }
258     }
259
260     void setSize(std::size_t sz) {
261       assert(sz <= policyMaxSize());
262       size_ = (kExternMask & size_) | SizeType(sz);
263     }
264
265     void swapSizePolicy(IntegralSizePolicy& o) {
266       std::swap(size_, o.size_);
267     }
268
269    protected:
270     static bool const kShouldUseHeap = ShouldUseHeap;
271
272    private:
273     static SizeType const kExternMask =
274       kShouldUseHeap ? SizeType(1) << (sizeof(SizeType) * 8 - 1)
275                      : 0;
276
277     SizeType size_;
278   };
279
280   /*
281    * If you're just trying to use this class, ignore everything about
282    * this next small_vector_base class thing.
283    *
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.
288    *
289    * Apologies for all the black magic.
290    */
291   namespace mpl = boost::mpl;
292   template <
293       class Value,
294       std::size_t RequestedMaxInline,
295       class InPolicyA,
296       class InPolicyB,
297       class InPolicyC>
298   struct small_vector_base {
299     typedef mpl::vector<InPolicyA,InPolicyB,InPolicyC> PolicyList;
300
301     /*
302      * Determine the size type
303      */
304     typedef typename mpl::filter_view<
305       PolicyList,
306       boost::is_integral<mpl::placeholders::_1>
307     >::type Integrals;
308     typedef typename mpl::eval_if<
309       mpl::empty<Integrals>,
310       mpl::identity<std::size_t>,
311       mpl::front<Integrals>
312     >::type SizeType;
313
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<>");
319
320     /*
321      * Determine whether we should allow spilling to the heap or not.
322      */
323     typedef typename mpl::count<
324       PolicyList,small_vector_policy::NoHeap
325     >::type HasNoHeap;
326
327     static_assert(HasNoHeap::value == 0 || HasNoHeap::value == 1,
328                   "Multiple copies of small_vector_policy::NoHeap "
329                   "supplied; this is probably a mistake");
330
331     /*
332      * Make the real policy base classes.
333      */
334     typedef IntegralSizePolicy<SizeType,!HasNoHeap::value>
335       ActualSizePolicy;
336
337     /*
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.
341      */
342     typedef boost::totally_ordered1<
343       small_vector<Value,RequestedMaxInline,InPolicyA,InPolicyB,InPolicyC>,
344       ActualSizePolicy
345     > type;
346   };
347
348   template <class T>
349   T* pointerFlagSet(T* p) {
350     return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p) | 1);
351   }
352   template <class T>
353   bool pointerFlagGet(T* p) {
354     return reinterpret_cast<uintptr_t>(p) & 1;
355   }
356   template <class T>
357   T* pointerFlagClear(T* p) {
358     return reinterpret_cast<T*>(
359       reinterpret_cast<uintptr_t>(p) & ~uintptr_t(1));
360   }
361   inline void* shiftPointer(void* p, size_t sizeBytes) {
362     return static_cast<char*>(p) + sizeBytes;
363   }
364 }
365
366 //////////////////////////////////////////////////////////////////////
367 FOLLY_PACK_PUSH
368 template <
369     class Value,
370     std::size_t RequestedMaxInline = 1,
371     class PolicyA = void,
372     class PolicyB = void,
373     class PolicyC = void>
374 class small_vector
375   : public detail::small_vector_base<
376       Value,RequestedMaxInline,PolicyA,PolicyB,PolicyC
377     >::type
378 {
379   typedef typename detail::small_vector_base<
380     Value,RequestedMaxInline,PolicyA,PolicyB,PolicyC
381   >::type BaseType;
382   typedef typename BaseType::InternalSizeType InternalSizeType;
383
384   /*
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.)
388    */
389   static constexpr std::size_t MaxInline{
390       constexpr_max(sizeof(Value*) / sizeof(Value), RequestedMaxInline)};
391
392  public:
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;
400
401   typedef std::reverse_iterator<iterator>       reverse_iterator;
402   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
403
404   explicit small_vector() = default;
405
406   small_vector(small_vector const& o) {
407     auto n = o.size();
408     makeSize(n);
409     try {
410       std::uninitialized_copy(o.begin(), o.end(), begin());
411     } catch (...) {
412       if (this->isExtern()) {
413         u.freeHeap();
414       }
415       throw;
416     }
417     this->setSize(n);
418   }
419
420   small_vector(small_vector&& o)
421   noexcept(std::is_nothrow_move_constructible<Value>::value) {
422     if (o.isExtern()) {
423       swap(o);
424     } else {
425       std::uninitialized_copy(std::make_move_iterator(o.begin()),
426                               std::make_move_iterator(o.end()),
427                               begin());
428       this->setSize(o.size());
429     }
430   }
431
432   small_vector(std::initializer_list<value_type> il) {
433     constructImpl(il.begin(), il.end(), std::false_type());
434   }
435
436   explicit small_vector(size_type n) {
437     doConstruct(n, [&](void* p) { new (p) value_type(); });
438   }
439
440   small_vector(size_type n, value_type const& t) {
441     doConstruct(n, [&](void* p) { new (p) value_type(t); });
442   }
443
444   template <class Arg>
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>());
450   }
451
452   ~small_vector() {
453     for (auto& t : *this) {
454       (&t)->~value_type();
455     }
456     if (this->isExtern()) {
457       u.freeHeap();
458     }
459   }
460
461   small_vector& operator=(small_vector const& o) {
462     assign(o.begin(), o.end());
463     return *this;
464   }
465
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;
470     clear();
471     swap(o);
472     return *this;
473   }
474
475   bool operator==(small_vector const& o) const {
476     return size() == o.size() && std::equal(begin(), end(), o.begin());
477   }
478
479   bool operator<(small_vector const& o) const {
480     return std::lexicographical_compare(begin(), end(), o.begin(), o.end());
481   }
482
483   static constexpr size_type max_size() {
484     return !BaseType::kShouldUseHeap ? static_cast<size_type>(MaxInline)
485                                      : BaseType::policyMaxSize();
486   }
487
488   size_type size()         const { return this->doSize(); }
489   bool      empty()        const { return !size(); }
490
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(); }
497
498   reverse_iterator       rbegin()        { return reverse_iterator(end()); }
499   reverse_iterator       rend()          { return reverse_iterator(begin()); }
500
501   const_reverse_iterator rbegin() const {
502     return const_reverse_iterator(end());
503   }
504
505   const_reverse_iterator rend() const {
506     return const_reverse_iterator(begin());
507   }
508
509   const_reverse_iterator crbegin() const { return rbegin(); }
510   const_reverse_iterator crend()   const { return rend(); }
511
512   /*
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.
516    *
517    * Basic guarantee only.  Provides the nothrow guarantee iff our
518    * value_type has a nothrow move or copy constructor.
519    */
520   void swap(small_vector& o) {
521     using std::swap; // Allow ADL on swap for our value_type.
522
523     if (this->isExtern() && o.isExtern()) {
524       this->swapSizePolicy(o);
525
526       auto thisCapacity = this->capacity();
527       auto oCapacity = o.capacity();
528
529       auto* tmp = u.pdata_.heap_;
530       u.pdata_.heap_ = o.u.pdata_.heap_;
531       o.u.pdata_.heap_ = tmp;
532
533       this->setCapacity(oCapacity);
534       o.setCapacity(thisCapacity);
535
536       return;
537     }
538
539     if (!this->isExtern() && !o.isExtern()) {
540       auto& oldSmall = size() < o.size() ? *this : o;
541       auto& oldLarge = size() < o.size() ? o : *this;
542
543       for (size_type i = 0; i < oldSmall.size(); ++i) {
544         swap(oldSmall[i], oldLarge[i]);
545       }
546
547       size_type i = oldSmall.size();
548       const size_type ci = i;
549       try {
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();
554         }
555       } catch (...) {
556         oldSmall.setSize(i);
557         for (; i < oldLarge.size(); ++i) {
558           oldLarge[i].~value_type();
559         }
560         oldLarge.setSize(ci);
561         throw;
562       }
563       oldSmall.setSize(i);
564       oldLarge.setSize(ci);
565       return;
566     }
567
568     // isExtern != o.isExtern()
569     auto& oldExtern = o.isExtern() ? o : *this;
570     auto& oldIntern = o.isExtern() ? *this : o;
571
572     auto oldExternCapacity = oldExtern.capacity();
573     auto oldExternHeap     = oldExtern.u.pdata_.heap_;
574
575     auto buff = oldExtern.u.buffer();
576     size_type i = 0;
577     try {
578       for (; i < oldIntern.size(); ++i) {
579         new (&buff[i]) value_type(std::move(oldIntern[i]));
580         oldIntern[i].~value_type();
581       }
582     } catch (...) {
583       for (size_type kill = 0; kill < i; ++kill) {
584         buff[kill].~value_type();
585       }
586       for (; i < oldIntern.size(); ++i) {
587         oldIntern[i].~value_type();
588       }
589       oldIntern.setSize(0);
590       oldExtern.u.pdata_.heap_ = oldExternHeap;
591       oldExtern.setCapacity(oldExternCapacity);
592       throw;
593     }
594     oldIntern.u.pdata_.heap_ = oldExternHeap;
595     this->swapSizePolicy(o);
596     oldIntern.setCapacity(oldExternCapacity);
597   }
598
599   void resize(size_type sz) {
600     if (sz < size()) {
601       erase(begin() + sz, end());
602       return;
603     }
604     makeSize(sz);
605     detail::populateMemForward(begin() + size(), sz - size(),
606       [&] (void* p) { new (p) value_type(); }
607     );
608     this->setSize(sz);
609   }
610
611   void resize(size_type sz, value_type const& v) {
612     if (sz < size()) {
613       erase(begin() + sz, end());
614       return;
615     }
616     makeSize(sz);
617     detail::populateMemForward(begin() + size(), sz - size(),
618       [&] (void* p) { new (p) value_type(v); }
619     );
620     this->setSize(sz);
621   }
622
623   value_type* data() noexcept {
624     return this->isExtern() ? u.heap() : u.buffer();
625   }
626
627   value_type const* data() const noexcept {
628     return this->isExtern() ? u.heap() : u.buffer();
629   }
630
631   template <class... Args>
632   iterator emplace(const_iterator p, Args&&... args) {
633     if (p == cend()) {
634       emplace_back(std::forward<Args>(args)...);
635       return end() - 1;
636     }
637
638     /*
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).
644      *
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.
653      */
654     return insert(p, value_type(std::forward<Args>(args)...));
655   }
656
657   void reserve(size_type sz) {
658     makeSize(sz);
659   }
660
661   size_type capacity() const {
662     if (this->isExtern()) {
663       if (u.hasCapacity()) {
664         return u.getCapacity();
665       }
666       return malloc_usable_size(u.pdata_.heap_) / sizeof(value_type);
667     }
668     return MaxInline;
669   }
670
671   void shrink_to_fit() {
672     if (!this->isExtern()) {
673       return;
674     }
675
676     small_vector tmp(begin(), end());
677     tmp.swap(*this);
678   }
679
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.
686       makeSize(
687           size() + 1,
688           [&](void* p) { new (p) value_type(std::forward<Args>(args)...); },
689           size());
690     } else {
691       new (end()) value_type(std::forward<Args>(args)...);
692     }
693     this->setSize(size() + 1);
694   }
695
696   void push_back(value_type&& t) {
697     return emplace_back(std::move(t));
698   }
699
700   void push_back(value_type const& t) {
701     emplace_back(t);
702   }
703
704   void pop_back() {
705     erase(end() - 1);
706   }
707
708   iterator insert(const_iterator constp, value_type&& t) {
709     iterator p = unconst(constp);
710
711     if (p == end()) {
712       push_back(std::move(t));
713       return end() - 1;
714     }
715
716     auto offset = p - begin();
717
718     if (capacity() == size()) {
719       makeSize(
720           size() + 1,
721           [&t](void* ptr) { new (ptr) value_type(std::move(t)); },
722           offset);
723       this->setSize(this->size() + 1);
724     } else {
725       detail::moveObjectsRight(data() + offset,
726                                data() + size(),
727                                data() + size() + 1);
728       this->setSize(size() + 1);
729       data()[offset] = std::move(t);
730     }
731     return begin() + offset;
732
733   }
734
735   iterator insert(const_iterator p, value_type const& t) {
736     // Make a copy and forward to the rvalue value_type&& overload
737     // above.
738     return insert(p, value_type(t));
739   }
740
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,
745                              data() + size(),
746                              data() + size() + n);
747     this->setSize(size() + n);
748     std::generate_n(begin() + offset, n, [&] { return val; });
749     return begin() + offset;
750   }
751
752   template <class Arg>
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>());
758   }
759
760   iterator insert(const_iterator p, std::initializer_list<value_type> il) {
761     return insert(p, il.begin(), il.end());
762   }
763
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);
768     return unconst(q);
769   }
770
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) {
775       it->~value_type();
776     }
777     this->setSize(size() - (q2 - q1));
778     return unconst(q1);
779   }
780
781   void clear() {
782     erase(begin(), end());
783   }
784
785   template <class Arg>
786   void assign(Arg first, Arg last) {
787     clear();
788     insert(end(), first, last);
789   }
790
791   void assign(std::initializer_list<value_type> il) {
792     assign(il.begin(), il.end());
793   }
794
795   void assign(size_type n, const value_type& t) {
796     clear();
797     insert(end(), n, t);
798   }
799
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); }
804
805   reference operator[](size_type i) {
806     assert(i < size());
807     return *(begin() + i);
808   }
809
810   const_reference operator[](size_type i) const {
811     assert(i < size());
812     return *(begin() + i);
813   }
814
815   reference at(size_type i) {
816     if (i >= size()) {
817       std::__throw_out_of_range("index out of range");
818     }
819     return (*this)[i];
820   }
821
822   const_reference at(size_type i) const {
823     if (i >= size()) {
824       std::__throw_out_of_range("index out of range");
825     }
826     return (*this)[i];
827   }
828
829  private:
830   static iterator unconst(const_iterator it) {
831     return const_cast<iterator>(it);
832   }
833
834   // The std::false_type argument is part of disambiguating the
835   // iterator insert functions from integral types (see insert().)
836   template <class It>
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++);
843         ++pos;
844       }
845       return begin() + offset;
846     }
847
848     auto distance = std::distance(first, last);
849     auto offset = pos - begin();
850     makeSize(size() + distance);
851     detail::moveObjectsRight(data() + offset,
852                              data() + size(),
853                              data() + size() + distance);
854     this->setSize(size() + distance);
855     std::copy_n(first, distance, begin() + offset);
856     return begin() + offset;
857   }
858
859   iterator insertImpl(iterator pos, size_type n, const value_type& val,
860       std::true_type) {
861     // The true_type means this should call the size_t,value_type
862     // overload.  (See insert().)
863     return insert(pos, n, val);
864   }
865
866   // The std::false_type argument came from std::is_arithmetic as part
867   // of disambiguating an overload (see the comment in the
868   // constructor).
869   template <class It>
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++);
877       }
878       return;
879     }
880
881     auto distance = std::distance(first, last);
882     makeSize(distance);
883     this->setSize(distance);
884     try {
885       detail::populateMemForward(data(), distance,
886         [&] (void* p) { new (p) value_type(*first++); }
887       );
888     } catch (...) {
889       if (this->isExtern()) {
890         u.freeHeap();
891       }
892       throw;
893     }
894   }
895
896   template <typename InitFunc>
897   void doConstruct(size_type n, InitFunc&& func) {
898     makeSize(n);
899     this->setSize(n);
900     try {
901       detail::populateMemForward(data(), n, std::forward<InitFunc>(func));
902     } catch (...) {
903       if (this->isExtern()) {
904         u.freeHeap();
905       }
906       throw;
907     }
908   }
909
910   // The true_type means we should forward to the size_t,value_type
911   // overload.
912   void constructImpl(size_type n, value_type const& val, std::true_type) {
913     doConstruct(n, [&](void* p) { new (p) value_type(val); });
914   }
915
916   /*
917    * Compute the size after growth.
918    */
919   size_type computeNewSize() const {
920     return std::min((3 * capacity()) / 2 + 1, max_size());
921   }
922
923   void makeSize(size_type newSize) {
924     makeSizeInternal(newSize, false, [](void*) { assume_unreachable(); }, 0);
925   }
926
927   template <typename EmplaceFunc>
928   void makeSize(size_type newSize, EmplaceFunc&& emplaceFunc, size_type pos) {
929     assert(size() == capacity());
930     makeSizeInternal(
931         newSize, true, std::forward<EmplaceFunc>(emplaceFunc), pos);
932   }
933
934   /*
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.
943    */
944   template <typename EmplaceFunc>
945   void makeSizeInternal(
946       size_type newSize,
947       bool insert,
948       EmplaceFunc&& emplaceFunc,
949       size_type pos) {
950     if (newSize > max_size()) {
951       throw std::length_error("max_size exceeded in small_vector");
952     }
953     if (newSize <= capacity()) {
954       assert(!insert);
955       return;
956     }
957     newSize = std::max(newSize, computeNewSize());
958
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;
967     }
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));
973
974     value_type* newp = static_cast<value_type*>(
975       heapifyCapacity ?
976         detail::shiftPointer(newh, kHeapifyCapacitySize) :
977         newh);
978
979     try {
980       if (insert) {
981         // move and insert the new element
982         detail::moveToUninitializedEmplace(
983             begin(), end(), newp, pos, std::forward<EmplaceFunc>(emplaceFunc));
984       } else {
985         // move without inserting new element
986         detail::moveToUninitialized(begin(), end(), newp);
987       }
988     } catch (...) {
989       free(newh);
990       throw;
991     }
992     for (auto& val : *this) {
993       val.~value_type();
994     }
995
996     if (this->isExtern()) {
997       u.freeHeap();
998     }
999     auto availableSizeBytes = sizeBytes;
1000     if (heapifyCapacity) {
1001       u.pdata_.heap_ = detail::pointerFlagSet(newh);
1002       availableSizeBytes -= kHeapifyCapacitySize;
1003     } else {
1004       u.pdata_.heap_ = newh;
1005     }
1006     this->setExtern(true);
1007     this->setCapacity(availableSizeBytes / sizeof(value_type));
1008   }
1009
1010   /*
1011    * This will set the capacity field, stored inline in the storage_ field
1012    * if there is sufficient room to store it.
1013    */
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);
1019     }
1020   }
1021
1022  private:
1023   struct HeapPtrWithCapacity {
1024     void* heap_;
1025     InternalSizeType capacity_;
1026
1027     InternalSizeType getCapacity() const {
1028       return capacity_;
1029     }
1030     void setCapacity(InternalSizeType c) {
1031       capacity_ = c;
1032     }
1033   } FOLLY_PACK_ATTR;
1034
1035   struct HeapPtr {
1036     // Lower order bit of heap_ is used as flag to indicate whether capacity is
1037     // stored at the front of the heap allocation.
1038     void* heap_;
1039
1040     InternalSizeType getCapacity() const {
1041       assert(detail::pointerFlagGet(heap_));
1042       return *static_cast<InternalSizeType*>(detail::pointerFlagClear(heap_));
1043     }
1044     void setCapacity(InternalSizeType c) {
1045       *static_cast<InternalSizeType*>(detail::pointerFlagClear(heap_)) = c;
1046     }
1047   } FOLLY_PACK_ATTR;
1048
1049 #if (FOLLY_X64 || FOLLY_PPC64)
1050   typedef unsigned char InlineStorageDataType[sizeof(value_type) * MaxInline];
1051 #else
1052   typedef typename std::aligned_storage<
1053     sizeof(value_type) * MaxInline,
1054     alignof(value_type)
1055   >::type InlineStorageDataType;
1056 #endif
1057
1058   typedef typename std::conditional<
1059     sizeof(value_type) * MaxInline != 0,
1060     InlineStorageDataType,
1061     void*
1062   >::type InlineStorageType;
1063
1064   static bool const kHasInlineCapacity =
1065     sizeof(HeapPtrWithCapacity) < sizeof(InlineStorageType);
1066
1067   // This value should we multiple of word size.
1068   static size_t const kHeapifyCapacitySize = sizeof(
1069     typename std::aligned_storage<
1070       sizeof(InternalSizeType),
1071       alignof(value_type)
1072     >::type);
1073   // Threshold to control capacity heapifying.
1074   static size_t const kHeapifyCapacityThreshold =
1075     100 * kHeapifyCapacitySize;
1076
1077   typedef typename std::conditional<
1078     kHasInlineCapacity,
1079     HeapPtrWithCapacity,
1080     HeapPtr
1081   >::type PointerType;
1082
1083   union Data {
1084     explicit Data() { pdata_.heap_ = 0; }
1085
1086     PointerType pdata_;
1087     InlineStorageType storage_;
1088
1089     value_type* buffer() noexcept {
1090       void* vp = &storage_;
1091       return static_cast<value_type*>(vp);
1092     }
1093     value_type const* buffer() const noexcept {
1094       return const_cast<Data*>(this)->buffer();
1095     }
1096     value_type* heap() noexcept {
1097       if (kHasInlineCapacity || !detail::pointerFlagGet(pdata_.heap_)) {
1098         return static_cast<value_type*>(pdata_.heap_);
1099       } else {
1100         return static_cast<value_type*>(detail::shiftPointer(
1101             detail::pointerFlagClear(pdata_.heap_), kHeapifyCapacitySize));
1102       }
1103     }
1104     value_type const* heap() const noexcept {
1105       return const_cast<Data*>(this)->heap();
1106     }
1107
1108     bool hasCapacity() const {
1109       return kHasInlineCapacity || detail::pointerFlagGet(pdata_.heap_);
1110     }
1111     InternalSizeType getCapacity() const {
1112       return pdata_.getCapacity();
1113     }
1114     void setCapacity(InternalSizeType c) {
1115       pdata_.setCapacity(c);
1116     }
1117
1118     void freeHeap() {
1119       auto vp = detail::pointerFlagClear(pdata_.heap_);
1120       free(vp);
1121     }
1122   } FOLLY_PACK_ATTR u;
1123 } FOLLY_PACK_ATTR;
1124 FOLLY_PACK_POP
1125
1126 //////////////////////////////////////////////////////////////////////
1127
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) {
1133   a.swap(b);
1134 }
1135
1136 //////////////////////////////////////////////////////////////////////
1137
1138 namespace detail {
1139
1140 // Format support.
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>> {
1144 };
1145
1146 } // namespace detail
1147
1148 } // namespace folly
1149
1150 FOLLY_POP_WARNING