RCU
[folly.git] / folly / sorted_vector_types.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  * This header defines two classes that very nearly model
19  * AssociativeContainer (but not quite).  These implement set-like and
20  * map-like behavior on top of a sorted vector, instead of using
21  * rb-trees like std::set and std::map.
22  *
23  * This is potentially useful in cases where the number of elements in
24  * the set or map is small, or when you want to avoid using more
25  * memory than necessary and insertions/deletions are much more rare
26  * than lookups (these classes have O(N) insertions/deletions).
27  *
28  * In the interest of using these in conditions where the goal is to
29  * minimize memory usage, they support a GrowthPolicy parameter, which
30  * is a class defining a single function called increase_capacity,
31  * which will be called whenever we are about to insert something: you
32  * can then decide to call reserve() based on the current capacity()
33  * and size() of the passed in vector-esque Container type.  An
34  * example growth policy that grows one element at a time:
35  *
36  *    struct OneAtATimePolicy {
37  *      template <class Container>
38  *      void increase_capacity(Container& c) {
39  *        if (c.size() == c.capacity()) {
40  *          c.reserve(c.size() + 1);
41  *        }
42  *      }
43  *    };
44  *
45  *    typedef sorted_vector_set<int,
46  *                              std::less<int>,
47  *                              std::allocator<int>,
48  *                              OneAtATimePolicy>
49  *            OneAtATimeIntSet;
50  *
51  * Important differences from std::set and std::map:
52  *   - insert() and erase() invalidate iterators and references
53  *   - insert() and erase() are O(N)
54  *   - our iterators model RandomAccessIterator
55  *   - sorted_vector_map::value_type is pair<K,V>, not pair<const K,V>.
56  *     (This is basically because we want to store the value_type in
57  *     std::vector<>, which requires it to be Assignable.)
58  */
59
60 #pragma once
61
62 #include <algorithm>
63 #include <initializer_list>
64 #include <iterator>
65 #include <stdexcept>
66 #include <type_traits>
67 #include <utility>
68 #include <vector>
69
70 #include <boost/operators.hpp>
71
72 #include <folly/Traits.h>
73 #include <folly/portability/BitsFunctexcept.h>
74
75 namespace folly {
76
77 //////////////////////////////////////////////////////////////////////
78
79 namespace detail {
80
81 template <typename, typename Compare, typename Key, typename T>
82 struct sorted_vector_enable_if_is_transparent {};
83
84 template <typename Compare, typename Key, typename T>
85 struct sorted_vector_enable_if_is_transparent<
86     void_t<typename Compare::is_transparent>,
87     Compare,
88     Key,
89     T> {
90   using type = T;
91 };
92
93 // This wrapper goes around a GrowthPolicy and provides iterator
94 // preservation semantics, but only if the growth policy is not the
95 // default (i.e. nothing).
96 template <class Policy>
97 struct growth_policy_wrapper : private Policy {
98   template <class Container, class Iterator>
99   Iterator increase_capacity(Container& c, Iterator desired_insertion) {
100     typedef typename Container::difference_type diff_t;
101     diff_t d = desired_insertion - c.begin();
102     Policy::increase_capacity(c);
103     return c.begin() + d;
104   }
105 };
106 template <>
107 struct growth_policy_wrapper<void> {
108   template <class Container, class Iterator>
109   Iterator increase_capacity(Container&, Iterator it) {
110     return it;
111   }
112 };
113
114 /*
115  * This helper returns the distance between two iterators if it is
116  * possible to figure it out without messing up the range
117  * (i.e. unless they are InputIterators).  Otherwise this returns
118  * -1.
119  */
120 template <class Iterator>
121 int distance_if_multipass(Iterator first, Iterator last) {
122   typedef typename std::iterator_traits<Iterator>::iterator_category categ;
123   if (std::is_same<categ, std::input_iterator_tag>::value) {
124     return -1;
125   }
126   return std::distance(first, last);
127 }
128
129 template <class OurContainer, class Vector, class GrowthPolicy>
130 typename OurContainer::iterator insert_with_hint(
131     OurContainer& sorted,
132     Vector& cont,
133     typename OurContainer::iterator hint,
134     typename OurContainer::value_type&& value,
135     GrowthPolicy& po) {
136   const typename OurContainer::value_compare& cmp(sorted.value_comp());
137   if (hint == cont.end() || cmp(value, *hint)) {
138     if (hint == cont.begin() || cmp(*(hint - 1), value)) {
139       hint = po.increase_capacity(cont, hint);
140       return cont.insert(hint, std::move(value));
141     } else {
142       return sorted.insert(std::move(value)).first;
143     }
144   }
145
146   if (cmp(*hint, value)) {
147     if (hint + 1 == cont.end() || cmp(value, *(hint + 1))) {
148       hint = po.increase_capacity(cont, hint + 1);
149       return cont.insert(hint, std::move(value));
150     } else {
151       return sorted.insert(std::move(value)).first;
152     }
153   }
154
155   // Value and *hint did not compare, so they are equal keys.
156   return hint;
157 }
158
159 template <class OurContainer, class Vector, class InputIterator>
160 void bulk_insert(
161     OurContainer& sorted,
162     Vector& cont,
163     InputIterator first,
164     InputIterator last) {
165   // prevent deref of middle where middle == cont.end()
166   if (first == last) {
167     return;
168   }
169
170   auto const& cmp(sorted.value_comp());
171
172   int const d = distance_if_multipass(first, last);
173   if (d != -1) {
174     cont.reserve(cont.size() + d);
175   }
176   auto const prev_size = cont.size();
177
178   std::copy(first, last, std::back_inserter(cont));
179   auto const middle = cont.begin() + prev_size;
180   if (!std::is_sorted(middle, cont.end(), cmp)) {
181     std::sort(middle, cont.end(), cmp);
182   }
183   if (middle != cont.begin() && !cmp(*(middle - 1), *middle)) {
184     std::inplace_merge(cont.begin(), middle, cont.end(), cmp);
185     cont.erase(
186         std::unique(
187             cont.begin(),
188             cont.end(),
189             [&](typename OurContainer::value_type const& a,
190                 typename OurContainer::value_type const& b) {
191               return !cmp(a, b) && !cmp(b, a);
192             }),
193         cont.end());
194   }
195 }
196 } // namespace detail
197
198 //////////////////////////////////////////////////////////////////////
199
200 /**
201  * A sorted_vector_set is a container similar to std::set<>, but
202  * implemented as as a sorted array with std::vector<>.
203  *
204  * @param class T               Data type to store
205  * @param class Compare         Comparison function that imposes a
206  *                              strict weak ordering over instances of T
207  * @param class Allocator       allocation policy
208  * @param class GrowthPolicy    policy object to control growth
209  *
210  * @author Aditya Agarwal <aditya@fb.com>
211  * @author Akhil Wable    <akhil@fb.com>
212  * @author Jordan DeLong  <delong.j@fb.com>
213  */
214 template <
215     class T,
216     class Compare = std::less<T>,
217     class Allocator = std::allocator<T>,
218     class GrowthPolicy = void,
219     class Container = std::vector<T, Allocator>>
220 class sorted_vector_set
221     : boost::totally_ordered1<
222           sorted_vector_set<T, Compare, Allocator, GrowthPolicy>,
223           detail::growth_policy_wrapper<GrowthPolicy>> {
224   detail::growth_policy_wrapper<GrowthPolicy>&
225   get_growth_policy() { return *this; }
226
227   template <typename K, typename V, typename C = Compare>
228   using if_is_transparent =
229       _t<detail::sorted_vector_enable_if_is_transparent<void, C, K, V>>;
230
231  public:
232   typedef T       value_type;
233   typedef T       key_type;
234   typedef Compare key_compare;
235   typedef Compare value_compare;
236
237   typedef typename Container::pointer pointer;
238   typedef typename Container::reference reference;
239   typedef typename Container::const_reference const_reference;
240   /*
241    * XXX: Our normal iterator ought to also be a constant iterator
242    * (cf. Defect Report 103 for std::set), but this is a bit more of a
243    * pain.
244    */
245   typedef typename Container::iterator iterator;
246   typedef typename Container::const_iterator const_iterator;
247   typedef typename Container::difference_type difference_type;
248   typedef typename Container::size_type size_type;
249   typedef typename Container::reverse_iterator reverse_iterator;
250   typedef typename Container::const_reverse_iterator const_reverse_iterator;
251
252   explicit sorted_vector_set(const Compare& comp = Compare(),
253                              const Allocator& alloc = Allocator())
254     : m_(comp, alloc)
255   {}
256
257   template <class InputIterator>
258   explicit sorted_vector_set(
259       InputIterator first,
260       InputIterator last,
261       const Compare& comp = Compare(),
262       const Allocator& alloc = Allocator())
263     : m_(comp, alloc)
264   {
265     // This is linear if [first, last) is already sorted (and if we
266     // can figure out the distance between the two iterators).
267     insert(first, last);
268   }
269
270   /* implicit */ sorted_vector_set(
271       std::initializer_list<value_type> list,
272       const Compare& comp = Compare(),
273       const Allocator& alloc = Allocator())
274     : m_(comp, alloc)
275   {
276     insert(list.begin(), list.end());
277   }
278
279   // Construct a sorted_vector_set by stealing the storage of a prefilled
280   // container. The container need not be sorted already. This supports
281   // bulk construction of sorted_vector_set with zero allocations, not counting
282   // those performed by the caller. (The iterator range constructor performs at
283   // least one allocation).
284   //
285   // Note that `sorted_vector_set(const Container& container)` is not provided,
286   // since the purpose of this constructor is to avoid an unnecessary copy.
287   explicit sorted_vector_set(
288       Container&& container,
289       const Compare& comp = Compare())
290       : m_(comp, container.get_allocator()) {
291     std::sort(container.begin(), container.end(), value_comp());
292     m_.cont_.swap(container);
293   }
294
295   key_compare key_comp() const { return m_; }
296   value_compare value_comp() const { return m_; }
297
298   iterator begin()                      { return m_.cont_.begin();  }
299   iterator end()                        { return m_.cont_.end();    }
300   const_iterator cbegin() const         { return m_.cont_.cbegin(); }
301   const_iterator begin() const          { return m_.cont_.begin();  }
302   const_iterator cend() const           { return m_.cont_.cend();   }
303   const_iterator end() const            { return m_.cont_.end();    }
304   reverse_iterator rbegin()             { return m_.cont_.rbegin(); }
305   reverse_iterator rend()               { return m_.cont_.rend();   }
306   const_reverse_iterator rbegin() const { return m_.cont_.rbegin(); }
307   const_reverse_iterator rend() const   { return m_.cont_.rend();   }
308
309   void clear()                  { return m_.cont_.clear();    }
310   size_type size() const        { return m_.cont_.size();     }
311   size_type max_size() const    { return m_.cont_.max_size(); }
312   bool empty() const            { return m_.cont_.empty();    }
313   void reserve(size_type s)     { return m_.cont_.reserve(s); }
314   void shrink_to_fit()          { m_.cont_.shrink_to_fit();   }
315   size_type capacity() const    { return m_.cont_.capacity(); }
316
317   std::pair<iterator,bool> insert(const value_type& value) {
318     return insert(std::move(value_type(value)));
319   }
320
321   std::pair<iterator,bool> insert(value_type&& value) {
322     iterator it = lower_bound(value);
323     if (it == end() || value_comp()(value, *it)) {
324       it = get_growth_policy().increase_capacity(m_.cont_, it);
325       return std::make_pair(m_.cont_.insert(it, std::move(value)), true);
326     }
327     return std::make_pair(it, false);
328   }
329
330   iterator insert(iterator hint, const value_type& value) {
331     return insert(hint, std::move(value_type(value)));
332   }
333
334   iterator insert(iterator hint, value_type&& value) {
335     return detail::insert_with_hint(*this, m_.cont_, hint, std::move(value),
336       get_growth_policy());
337   }
338
339   template <class InputIterator>
340   void insert(InputIterator first, InputIterator last) {
341     detail::bulk_insert(*this, m_.cont_, first, last);
342   }
343
344   size_type erase(const key_type& key) {
345     iterator it = find(key);
346     if (it == end()) {
347       return 0;
348     }
349     m_.cont_.erase(it);
350     return 1;
351   }
352
353   void erase(iterator it) {
354     m_.cont_.erase(it);
355   }
356
357   void erase(iterator first, iterator last) {
358     m_.cont_.erase(first, last);
359   }
360
361   iterator find(const key_type& key) {
362     return find(*this, key);
363   }
364
365   const_iterator find(const key_type& key) const {
366     return find(*this, key);
367   }
368
369   template <typename K>
370   if_is_transparent<K, iterator> find(const K& key) {
371     return find(*this, key);
372   }
373
374   template <typename K>
375   if_is_transparent<K, const_iterator> find(const K& key) const {
376     return find(*this, key);
377   }
378
379   size_type count(const key_type& key) const {
380     return find(key) == end() ? 0 : 1;
381   }
382
383   template <typename K>
384   if_is_transparent<K, size_type> count(const K& key) const {
385     return find(key) == end() ? 0 : 1;
386   }
387
388   iterator lower_bound(const key_type& key) {
389     return std::lower_bound(begin(), end(), key, key_comp());
390   }
391
392   const_iterator lower_bound(const key_type& key) const {
393     return std::lower_bound(begin(), end(), key, key_comp());
394   }
395
396   template <typename K>
397   if_is_transparent<K, iterator> lower_bound(const K& key) {
398     return std::lower_bound(begin(), end(), key, key_comp());
399   }
400
401   template <typename K>
402   if_is_transparent<K, const_iterator> lower_bound(const K& key) const {
403     return std::lower_bound(begin(), end(), key, key_comp());
404   }
405
406   iterator upper_bound(const key_type& key) {
407     return std::upper_bound(begin(), end(), key, key_comp());
408   }
409
410   const_iterator upper_bound(const key_type& key) const {
411     return std::upper_bound(begin(), end(), key, key_comp());
412   }
413
414   template <typename K>
415   if_is_transparent<K, iterator> upper_bound(const K& key) {
416     return std::upper_bound(begin(), end(), key, key_comp());
417   }
418
419   template <typename K>
420   if_is_transparent<K, const_iterator> upper_bound(const K& key) const {
421     return std::upper_bound(begin(), end(), key, key_comp());
422   }
423
424   std::pair<iterator, iterator> equal_range(const key_type& key) {
425     return std::equal_range(begin(), end(), key, key_comp());
426   }
427
428   std::pair<const_iterator, const_iterator> equal_range(
429       const key_type& key) const {
430     return std::equal_range(begin(), end(), key, key_comp());
431   }
432
433   template <typename K>
434   if_is_transparent<K, std::pair<iterator, iterator>> equal_range(
435       const K& key) {
436     return std::equal_range(begin(), end(), key, key_comp());
437   }
438
439   template <typename K>
440   if_is_transparent<K, std::pair<const_iterator, const_iterator>> equal_range(
441       const K& key) const {
442     return std::equal_range(begin(), end(), key, key_comp());
443   }
444
445   // Nothrow as long as swap() on the Compare type is nothrow.
446   void swap(sorted_vector_set& o) {
447     using std::swap;  // Allow ADL for swap(); fall back to std::swap().
448     Compare& a = m_;
449     Compare& b = o.m_;
450     swap(a, b);
451     m_.cont_.swap(o.m_.cont_);
452   }
453
454   bool operator==(const sorted_vector_set& other) const {
455     return other.m_.cont_ == m_.cont_;
456   }
457
458   bool operator<(const sorted_vector_set& other) const {
459     return m_.cont_ < other.m_.cont_;
460   }
461
462  private:
463   /*
464    * This structure derives from the comparison object in order to
465    * make use of the empty base class optimization if our comparison
466    * functor is an empty class (usual case).
467    *
468    * Wrapping up this member like this is better than deriving from
469    * the Compare object ourselves (there are some perverse edge cases
470    * involving virtual functions).
471    *
472    * More info:  http://www.cantrip.org/emptyopt.html
473    */
474   struct EBO : Compare {
475     explicit EBO(const Compare& c, const Allocator& alloc)
476       : Compare(c)
477       , cont_(alloc)
478     {}
479     Container cont_;
480   } m_;
481
482   template <typename Self>
483   using self_iterator_t = _t<
484       std::conditional<std::is_const<Self>::value, const_iterator, iterator>>;
485
486   template <typename Self, typename K>
487   static self_iterator_t<Self> find(Self& self, K const& key) {
488     auto end = self.end();
489     auto it = self.lower_bound(key);
490     if (it == end || !self.key_comp()(key, *it)) {
491       return it;
492     }
493     return end;
494   }
495 };
496
497 // Swap function that can be found using ADL.
498 template <class T, class C, class A, class G>
499 inline void swap(sorted_vector_set<T,C,A,G>& a,
500                  sorted_vector_set<T,C,A,G>& b) {
501   return a.swap(b);
502 }
503
504 //////////////////////////////////////////////////////////////////////
505
506 /**
507  * A sorted_vector_map is similar to a sorted_vector_set but stores
508  * <key,value> pairs instead of single elements.
509  *
510  * @param class Key           Key type
511  * @param class Value         Value type
512  * @param class Compare       Function that can compare key types and impose
513  *                            a strict weak ordering over them.
514  * @param class Allocator     allocation policy
515  * @param class GrowthPolicy  policy object to control growth
516  *
517  * @author Aditya Agarwal <aditya@fb.com>
518  * @author Akhil Wable    <akhil@fb.com>
519  * @author Jordan DeLong  <delong.j@fb.com>
520  */
521 template <
522     class Key,
523     class Value,
524     class Compare = std::less<Key>,
525     class Allocator = std::allocator<std::pair<Key, Value>>,
526     class GrowthPolicy = void,
527     class Container = std::vector<std::pair<Key, Value>, Allocator>>
528 class sorted_vector_map
529     : boost::totally_ordered1<
530           sorted_vector_map<Key, Value, Compare, Allocator, GrowthPolicy>,
531           detail::growth_policy_wrapper<GrowthPolicy>> {
532   detail::growth_policy_wrapper<GrowthPolicy>&
533   get_growth_policy() { return *this; }
534
535   template <typename K, typename V, typename C = Compare>
536   using if_is_transparent =
537       _t<detail::sorted_vector_enable_if_is_transparent<void, C, K, V>>;
538
539  public:
540   typedef Key                                       key_type;
541   typedef Value                                     mapped_type;
542   typedef std::pair<key_type,mapped_type>           value_type;
543   typedef Compare                                   key_compare;
544
545   struct value_compare : private Compare {
546     bool operator()(const value_type& a, const value_type& b) const {
547       return Compare::operator()(a.first, b.first);
548     }
549
550    protected:
551     friend class sorted_vector_map;
552     explicit value_compare(const Compare& c) : Compare(c) {}
553   };
554
555   typedef typename Container::pointer pointer;
556   typedef typename Container::reference reference;
557   typedef typename Container::const_reference const_reference;
558   typedef typename Container::iterator iterator;
559   typedef typename Container::const_iterator const_iterator;
560   typedef typename Container::difference_type difference_type;
561   typedef typename Container::size_type size_type;
562   typedef typename Container::reverse_iterator reverse_iterator;
563   typedef typename Container::const_reverse_iterator const_reverse_iterator;
564
565   explicit sorted_vector_map(const Compare& comp = Compare(),
566                              const Allocator& alloc = Allocator())
567     : m_(value_compare(comp), alloc)
568   {}
569
570   template <class InputIterator>
571   explicit sorted_vector_map(
572       InputIterator first,
573       InputIterator last,
574       const Compare& comp = Compare(),
575       const Allocator& alloc = Allocator())
576     : m_(value_compare(comp), alloc)
577   {
578     insert(first, last);
579   }
580
581   explicit sorted_vector_map(
582       std::initializer_list<value_type> list,
583       const Compare& comp = Compare(),
584       const Allocator& alloc = Allocator())
585     : m_(value_compare(comp), alloc)
586   {
587     insert(list.begin(), list.end());
588   }
589
590   // Construct a sorted_vector_map by stealing the storage of a prefilled
591   // container. The container need not be sorted already. This supports
592   // bulk construction of sorted_vector_map with zero allocations, not counting
593   // those performed by the caller. (The iterator range constructor performs at
594   // least one allocation).
595   //
596   // Note that `sorted_vector_map(const Container& container)` is not provided,
597   // since the purpose of this constructor is to avoid an unnecessary copy.
598   explicit sorted_vector_map(
599       Container&& container,
600       const Compare& comp = Compare())
601       : m_(value_compare(comp), container.get_allocator()) {
602     std::sort(container.begin(), container.end(), value_comp());
603     m_.cont_.swap(container);
604   }
605
606   key_compare key_comp() const { return m_; }
607   value_compare value_comp() const { return m_; }
608
609   iterator begin()                      { return m_.cont_.begin();  }
610   iterator end()                        { return m_.cont_.end();    }
611   const_iterator cbegin() const         { return m_.cont_.cbegin(); }
612   const_iterator begin() const          { return m_.cont_.begin();  }
613   const_iterator cend() const           { return m_.cont_.cend();   }
614   const_iterator end() const            { return m_.cont_.end();    }
615   reverse_iterator rbegin()             { return m_.cont_.rbegin(); }
616   reverse_iterator rend()               { return m_.cont_.rend();   }
617   const_reverse_iterator rbegin() const { return m_.cont_.rbegin(); }
618   const_reverse_iterator rend() const   { return m_.cont_.rend();   }
619
620   void clear()                  { return m_.cont_.clear();    }
621   size_type size() const        { return m_.cont_.size();     }
622   size_type max_size() const    { return m_.cont_.max_size(); }
623   bool empty() const            { return m_.cont_.empty();    }
624   void reserve(size_type s)     { return m_.cont_.reserve(s); }
625   void shrink_to_fit()          { m_.cont_.shrink_to_fit();   }
626   size_type capacity() const    { return m_.cont_.capacity(); }
627
628   std::pair<iterator,bool> insert(const value_type& value) {
629     return insert(std::move(value_type(value)));
630   }
631
632   std::pair<iterator,bool> insert(value_type&& value) {
633     iterator it = lower_bound(value.first);
634     if (it == end() || value_comp()(value, *it)) {
635       it = get_growth_policy().increase_capacity(m_.cont_, it);
636       return std::make_pair(m_.cont_.insert(it, std::move(value)), true);
637     }
638     return std::make_pair(it, false);
639   }
640
641   iterator insert(iterator hint, const value_type& value) {
642     return insert(hint, std::move(value_type(value)));
643   }
644
645   iterator insert(iterator hint, value_type&& value) {
646     return detail::insert_with_hint(*this, m_.cont_, hint, std::move(value),
647       get_growth_policy());
648   }
649
650   template <class InputIterator>
651   void insert(InputIterator first, InputIterator last) {
652     detail::bulk_insert(*this, m_.cont_, first, last);
653   }
654
655   size_type erase(const key_type& key) {
656     iterator it = find(key);
657     if (it == end()) {
658       return 0;
659     }
660     m_.cont_.erase(it);
661     return 1;
662   }
663
664   void erase(iterator it) {
665     m_.cont_.erase(it);
666   }
667
668   void erase(iterator first, iterator last) {
669     m_.cont_.erase(first, last);
670   }
671
672   iterator find(const key_type& key) {
673     return find(*this, key);
674   }
675
676   const_iterator find(const key_type& key) const {
677     return find(*this, key);
678   }
679
680   template <typename K>
681   if_is_transparent<K, iterator> find(const K& key) {
682     return find(*this, key);
683   }
684
685   template <typename K>
686   if_is_transparent<K, const_iterator> find(const K& key) const {
687     return find(*this, key);
688   }
689
690   mapped_type& at(const key_type& key) {
691     iterator it = find(key);
692     if (it != end()) {
693       return it->second;
694     }
695     std::__throw_out_of_range("sorted_vector_map::at");
696   }
697
698   const mapped_type& at(const key_type& key) const {
699     const_iterator it = find(key);
700     if (it != end()) {
701       return it->second;
702     }
703     std::__throw_out_of_range("sorted_vector_map::at");
704   }
705
706   size_type count(const key_type& key) const {
707     return find(key) == end() ? 0 : 1;
708   }
709
710   template <typename K>
711   if_is_transparent<K, size_type> count(const K& key) const {
712     return find(key) == end() ? 0 : 1;
713   }
714
715   iterator lower_bound(const key_type& key) {
716     return lower_bound(*this, key);
717   }
718
719   const_iterator lower_bound(const key_type& key) const {
720     return lower_bound(*this, key);
721   }
722
723   template <typename K>
724   if_is_transparent<K, iterator> lower_bound(const K& key) {
725     return lower_bound(*this, key);
726   }
727
728   template <typename K>
729   if_is_transparent<K, const_iterator> lower_bound(const K& key) const {
730     return lower_bound(*this, key);
731   }
732
733   iterator upper_bound(const key_type& key) {
734     return upper_bound(*this, key);
735   }
736
737   const_iterator upper_bound(const key_type& key) const {
738     return upper_bound(*this, key);
739   }
740
741   template <typename K>
742   if_is_transparent<K, iterator> upper_bound(const K& key) {
743     return upper_bound(*this, key);
744   }
745
746   template <typename K>
747   if_is_transparent<K, const_iterator> upper_bound(const K& key) const {
748     return upper_bound(*this, key);
749   }
750
751   std::pair<iterator, iterator> equal_range(const key_type& key) {
752     return equal_range(*this, key);
753   }
754
755   std::pair<const_iterator, const_iterator> equal_range(
756       const key_type& key) const {
757     return equal_range(*this, key);
758   }
759
760   template <typename K>
761   if_is_transparent<K, std::pair<iterator, iterator>> equal_range(
762       const K& key) {
763     return equal_range(*this, key);
764   }
765
766   template <typename K>
767   if_is_transparent<K, std::pair<const_iterator, const_iterator>> equal_range(
768       const K& key) const {
769     return equal_range(*this, key);
770   }
771
772   // Nothrow as long as swap() on the Compare type is nothrow.
773   void swap(sorted_vector_map& o) {
774     using std::swap; // Allow ADL for swap(); fall back to std::swap().
775     Compare& a = m_;
776     Compare& b = o.m_;
777     swap(a, b);
778     m_.cont_.swap(o.m_.cont_);
779   }
780
781   mapped_type& operator[](const key_type& key) {
782     iterator it = lower_bound(key);
783     if (it == end() || key_comp()(key, it->first)) {
784       return insert(it, value_type(key, mapped_type()))->second;
785     }
786     return it->second;
787   }
788
789   bool operator==(const sorted_vector_map& other) const {
790     return m_.cont_ == other.m_.cont_;
791   }
792
793   bool operator<(const sorted_vector_map& other) const {
794     return m_.cont_ < other.m_.cont_;
795   }
796
797  private:
798   // This is to get the empty base optimization; see the comment in
799   // sorted_vector_set.
800   struct EBO : value_compare {
801     explicit EBO(const value_compare& c, const Allocator& alloc)
802       : value_compare(c)
803       , cont_(alloc)
804     {}
805     Container cont_;
806   } m_;
807
808   template <typename Self>
809   using self_iterator_t = _t<
810       std::conditional<std::is_const<Self>::value, const_iterator, iterator>>;
811
812   template <typename Self, typename K>
813   static self_iterator_t<Self> find(Self& self, K const& key) {
814     auto end = self.end();
815     auto it = self.lower_bound(key);
816     if (it == end || !self.key_comp()(key, it->first)) {
817       return it;
818     }
819     return end;
820   }
821
822   template <typename Self, typename K>
823   static self_iterator_t<Self> lower_bound(Self& self, K const& key) {
824     auto f = [c = self.key_comp()](value_type const& a, K const& b) {
825       return c(a.first, b);
826     };
827     return std::lower_bound(self.begin(), self.end(), key, f);
828   }
829
830   template <typename Self, typename K>
831   static self_iterator_t<Self> upper_bound(Self& self, K const& key) {
832     auto f = [c = self.key_comp()](K const& a, value_type const& b) {
833       return c(a, b.first);
834     };
835     return std::upper_bound(self.begin(), self.end(), key, f);
836   }
837
838   template <typename Self, typename K>
839   static std::pair<self_iterator_t<Self>, self_iterator_t<Self>> equal_range(
840       Self& self,
841       K const& key) {
842     // Note: std::equal_range can't be passed a functor that takes
843     // argument types different from the iterator value_type, so we
844     // have to do this.
845     return {lower_bound(self, key), upper_bound(self, key)};
846   }
847 };
848
849 // Swap function that can be found using ADL.
850 template <class K, class V, class C, class A, class G>
851 inline void swap(sorted_vector_map<K,V,C,A,G>& a,
852                  sorted_vector_map<K,V,C,A,G>& b) {
853   return a.swap(b);
854 }
855
856 //////////////////////////////////////////////////////////////////////
857
858 } // namespace folly