folly: replace old-style header guards with "pragma once"
[folly.git] / folly / sorted_vector_types.h
1 /*
2  * Copyright 2016 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 <utility>
66 #include <vector>
67 #include <boost/operators.hpp>
68 #include <boost/bind.hpp>
69 #include <boost/type_traits/is_same.hpp>
70
71 namespace folly {
72
73 //////////////////////////////////////////////////////////////////////
74
75 namespace detail {
76
77   // This wrapper goes around a GrowthPolicy and provides iterator
78   // preservation semantics, but only if the growth policy is not the
79   // default (i.e. nothing).
80   template<class Policy>
81   struct growth_policy_wrapper : private Policy {
82     template<class Container, class Iterator>
83     Iterator increase_capacity(Container& c, Iterator desired_insertion)
84     {
85       typedef typename Container::difference_type diff_t;
86       diff_t d = desired_insertion - c.begin();
87       Policy::increase_capacity(c);
88       return c.begin() + d;
89     }
90   };
91   template<>
92   struct growth_policy_wrapper<void> {
93     template<class Container, class Iterator>
94     Iterator increase_capacity(Container&, Iterator it) {
95       return it;
96     }
97   };
98
99   /*
100    * This helper returns the distance between two iterators if it is
101    * possible to figure it out without messing up the range
102    * (i.e. unless they are InputIterators).  Otherwise this returns
103    * -1.
104    */
105   template<class Iterator>
106   int distance_if_multipass(Iterator first, Iterator last) {
107     typedef typename std::iterator_traits<Iterator>::iterator_category categ;
108     if (boost::is_same<categ,std::input_iterator_tag>::value)
109       return -1;
110     return std::distance(first, last);
111   }
112
113   template<class OurContainer, class Vector, class GrowthPolicy>
114   typename OurContainer::iterator
115   insert_with_hint(OurContainer& sorted,
116                    Vector& cont,
117                    typename OurContainer::iterator hint,
118                    typename OurContainer::value_type&& value,
119                    GrowthPolicy& po)
120   {
121     const typename OurContainer::value_compare& cmp(sorted.value_comp());
122     if (hint == cont.end() || cmp(value, *hint)) {
123       if (hint == cont.begin()) {
124         po.increase_capacity(cont, cont.begin());
125         return cont.insert(cont.begin(), std::move(value));
126       }
127       if (cmp(*(hint - 1), value)) {
128         hint = po.increase_capacity(cont, hint);
129         return cont.insert(hint, std::move(value));
130       }
131       return sorted.insert(std::move(value)).first;
132     }
133
134     if (cmp(*hint, value)) {
135       if (hint + 1 == cont.end() || cmp(value, *(hint + 1))) {
136         typename OurContainer::iterator it =
137           po.increase_capacity(cont, hint + 1);
138         return cont.insert(it, std::move(value));
139       }
140     }
141
142     // Value and *hint did not compare, so they are equal keys.
143     return hint;
144   }
145
146 }
147
148 //////////////////////////////////////////////////////////////////////
149
150 /**
151  * A sorted_vector_set is a container similar to std::set<>, but
152  * implemented as as a sorted array with std::vector<>.
153  *
154  * @param class T               Data type to store
155  * @param class Compare         Comparison function that imposes a
156  *                              strict weak ordering over instances of T
157  * @param class Allocator       allocation policy
158  * @param class GrowthPolicy    policy object to control growth
159  *
160  * @author Aditya Agarwal <aditya@fb.com>
161  * @author Akhil Wable    <akhil@fb.com>
162  * @author Jordan DeLong  <delong.j@fb.com>
163  */
164 template<class T,
165          class Compare      = std::less<T>,
166          class Allocator    = std::allocator<T>,
167          class GrowthPolicy = void>
168 class sorted_vector_set
169   : boost::totally_ordered1<
170       sorted_vector_set<T,Compare,Allocator,GrowthPolicy>
171     , detail::growth_policy_wrapper<GrowthPolicy> >
172 {
173   typedef std::vector<T,Allocator> ContainerT;
174
175   detail::growth_policy_wrapper<GrowthPolicy>&
176   get_growth_policy() { return *this; }
177
178 public:
179   typedef T       value_type;
180   typedef T       key_type;
181   typedef Compare key_compare;
182   typedef Compare value_compare;
183
184   typedef typename ContainerT::pointer                pointer;
185   typedef typename ContainerT::reference              reference;
186   typedef typename ContainerT::const_reference        const_reference;
187   /*
188    * XXX: Our normal iterator ought to also be a constant iterator
189    * (cf. Defect Report 103 for std::set), but this is a bit more of a
190    * pain.
191    */
192   typedef typename ContainerT::iterator               iterator;
193   typedef typename ContainerT::const_iterator         const_iterator;
194   typedef typename ContainerT::difference_type        difference_type;
195   typedef typename ContainerT::size_type              size_type;
196   typedef typename ContainerT::reverse_iterator       reverse_iterator;
197   typedef typename ContainerT::const_reverse_iterator const_reverse_iterator;
198
199   explicit sorted_vector_set(const Compare& comp = Compare(),
200                              const Allocator& alloc = Allocator())
201     : m_(comp, alloc)
202   {}
203
204   template<class InputIterator>
205   explicit sorted_vector_set(
206       InputIterator first,
207       InputIterator last,
208       const Compare& comp = Compare(),
209       const Allocator& alloc = Allocator())
210     : m_(comp, alloc)
211   {
212     // This is linear if [first, last) is already sorted (and if we
213     // can figure out the distance between the two iterators).
214     insert(first, last);
215   }
216
217   explicit sorted_vector_set(
218       std::initializer_list<value_type> list,
219       const Compare& comp = Compare(),
220       const Allocator& alloc = Allocator())
221     : m_(comp, alloc)
222   {
223     insert(list.begin(), list.end());
224   }
225
226   key_compare key_comp() const { return m_; }
227   value_compare value_comp() const { return m_; }
228
229   iterator begin()                      { return m_.cont_.begin();  }
230   iterator end()                        { return m_.cont_.end();    }
231   const_iterator begin() const          { return m_.cont_.begin();  }
232   const_iterator end() const            { return m_.cont_.end();    }
233   reverse_iterator rbegin()             { return m_.cont_.rbegin(); }
234   reverse_iterator rend()               { return m_.cont_.rend();   }
235   const_reverse_iterator rbegin() const { return m_.cont_.rbegin(); }
236   const_reverse_iterator rend() const   { return m_.cont_.rend();   }
237
238   void clear()                  { return m_.cont_.clear();    }
239   size_type size() const        { return m_.cont_.size();     }
240   size_type max_size() const    { return m_.cont_.max_size(); }
241   bool empty() const            { return m_.cont_.empty();    }
242   void reserve(size_type s)     { return m_.cont_.reserve(s); }
243   void shrink_to_fit()          { m_.cont_.shrink_to_fit();   }
244   size_type capacity() const    { return m_.cont_.capacity(); }
245
246   std::pair<iterator,bool> insert(const value_type& value) {
247     return insert(value_type(value));
248   }
249
250   std::pair<iterator,bool> insert(value_type&& value) {
251     iterator it = lower_bound(value);
252     if (it == end() || value_comp()(value, *it)) {
253       it = get_growth_policy().increase_capacity(m_.cont_, it);
254       return std::make_pair(m_.cont_.insert(it, std::move(value)), true);
255     }
256     return std::make_pair(it, false);
257   }
258
259   iterator insert(iterator hint, const value_type& value) {
260     return insert(hint, value_type(value));
261   }
262
263   iterator insert(iterator hint, value_type&& value) {
264     return detail::insert_with_hint(*this, m_.cont_, hint, std::move(value),
265       get_growth_policy());
266   }
267
268   template<class InputIterator>
269   void insert(InputIterator first, InputIterator last) {
270     int d = detail::distance_if_multipass(first, last);
271     if (d != -1) {
272       m_.cont_.reserve(m_.cont_.size() + d);
273     }
274     for (; first != last; ++first) {
275       insert(end(), *first);
276     }
277   }
278
279   size_type erase(const key_type& key) {
280     iterator it = lower_bound(key);
281     if (it == end()) {
282       return 0;
283     }
284     m_.cont_.erase(it);
285     return 1;
286   }
287
288   void erase(iterator it) {
289     m_.cont_.erase(it);
290   }
291
292   void erase(iterator first, iterator last) {
293     m_.cont_.erase(first, last);
294   }
295
296   iterator find(const key_type& key) {
297     iterator it = lower_bound(key);
298     if (it == end() || !key_comp()(key, *it))
299       return it;
300     return end();
301   }
302
303   const_iterator find(const key_type& key) const {
304     const_iterator it = lower_bound(key);
305     if (it == end() || !key_comp()(key, *it))
306       return it;
307     return end();
308   }
309
310   size_type count(const key_type& key) const {
311     return find(key) == end() ? 0 : 1;
312   }
313
314   iterator lower_bound(const key_type& key) {
315     return std::lower_bound(begin(), end(), key, key_comp());
316   }
317
318   const_iterator lower_bound(const key_type& key) const {
319     return std::lower_bound(begin(), end(), key, key_comp());
320   }
321
322   iterator upper_bound(const key_type& key) {
323     return std::upper_bound(begin(), end(), key, key_comp());
324   }
325
326   const_iterator upper_bound(const key_type& key) const {
327     return std::upper_bound(begin(), end(), key, key_comp());
328   }
329
330   std::pair<iterator,iterator> equal_range(const key_type& key) {
331     return std::equal_range(begin(), end(), key, key_comp());
332   }
333
334   std::pair<const_iterator,const_iterator>
335   equal_range(const key_type& key) const {
336     return std::equal_range(begin(), end(), key, key_comp());
337   }
338
339   // Nothrow as long as swap() on the Compare type is nothrow.
340   void swap(sorted_vector_set& o) {
341     using std::swap;  // Allow ADL for swap(); fall back to std::swap().
342     Compare& a = m_;
343     Compare& b = o.m_;
344     swap(a, b);
345     m_.cont_.swap(o.m_.cont_);
346   }
347
348   bool operator==(const sorted_vector_set& other) const {
349     return other.m_.cont_ == m_.cont_;
350   }
351
352   bool operator<(const sorted_vector_set& other) const {
353     return m_.cont_ < other.m_.cont_;
354   }
355
356 private:
357   /*
358    * This structure derives from the comparison object in order to
359    * make use of the empty base class optimization if our comparison
360    * functor is an empty class (usual case).
361    *
362    * Wrapping up this member like this is better than deriving from
363    * the Compare object ourselves (there are some perverse edge cases
364    * involving virtual functions).
365    *
366    * More info:  http://www.cantrip.org/emptyopt.html
367    */
368   struct EBO : Compare {
369     explicit EBO(const Compare& c, const Allocator& alloc)
370       : Compare(c)
371       , cont_(alloc)
372     {}
373     ContainerT cont_;
374   } m_;
375 };
376
377 // Swap function that can be found using ADL.
378 template<class T, class C, class A, class G>
379 inline void swap(sorted_vector_set<T,C,A,G>& a,
380                  sorted_vector_set<T,C,A,G>& b) {
381   return a.swap(b);
382 }
383
384 //////////////////////////////////////////////////////////////////////
385
386 /**
387  * A sorted_vector_map is similar to a sorted_vector_set but stores
388  * <key,value> pairs instead of single elements.
389  *
390  * @param class Key           Key type
391  * @param class Value         Value type
392  * @param class Compare       Function that can compare key types and impose
393  *                            a strict weak ordering over them.
394  * @param class Allocator     allocation policy
395  * @param class GrowthPolicy  policy object to control growth
396  *
397  * @author Aditya Agarwal <aditya@fb.com>
398  * @author Akhil Wable    <akhil@fb.com>
399  * @author Jordan DeLong  <delong.j@fb.com>
400  */
401 template<class Key,
402          class Value,
403          class Compare        = std::less<Key>,
404          class Allocator      = std::allocator<std::pair<Key,Value> >,
405          class GrowthPolicy   = void>
406 class sorted_vector_map
407   : boost::totally_ordered1<
408       sorted_vector_map<Key,Value,Compare,Allocator,GrowthPolicy>
409     , detail::growth_policy_wrapper<GrowthPolicy> >
410 {
411   typedef std::vector<std::pair<Key,Value>,Allocator> ContainerT;
412
413   detail::growth_policy_wrapper<GrowthPolicy>&
414   get_growth_policy() { return *this; }
415
416 public:
417   typedef Key                                       key_type;
418   typedef Value                                     mapped_type;
419   typedef std::pair<key_type,mapped_type>           value_type;
420   typedef Compare                                   key_compare;
421
422   struct value_compare
423     : std::binary_function<value_type,value_type,bool>
424     , private Compare
425   {
426     bool operator()(const value_type& a, const value_type& b) const {
427       return Compare::operator()(a.first, b.first);
428     }
429
430   protected:
431     friend class sorted_vector_map;
432     explicit value_compare(const Compare& c) : Compare(c) {}
433   };
434
435   typedef typename ContainerT::pointer                pointer;
436   typedef typename ContainerT::reference              reference;
437   typedef typename ContainerT::const_reference        const_reference;
438   typedef typename ContainerT::iterator               iterator;
439   typedef typename ContainerT::const_iterator         const_iterator;
440   typedef typename ContainerT::difference_type        difference_type;
441   typedef typename ContainerT::size_type              size_type;
442   typedef typename ContainerT::reverse_iterator       reverse_iterator;
443   typedef typename ContainerT::const_reverse_iterator const_reverse_iterator;
444
445   explicit sorted_vector_map(const Compare& comp = Compare(),
446                              const Allocator& alloc = Allocator())
447     : m_(value_compare(comp), alloc)
448   {}
449
450   template<class InputIterator>
451   explicit sorted_vector_map(
452       InputIterator first,
453       InputIterator last,
454       const Compare& comp = Compare(),
455       const Allocator& alloc = Allocator())
456     : m_(value_compare(comp), alloc)
457   {
458     insert(first, last);
459   }
460
461   explicit sorted_vector_map(
462       std::initializer_list<value_type> list,
463       const Compare& comp = Compare(),
464       const Allocator& alloc = Allocator())
465     : m_(value_compare(comp), alloc)
466   {
467     insert(list.begin(), list.end());
468   }
469
470   key_compare key_comp() const { return m_; }
471   value_compare value_comp() const { return m_; }
472
473   iterator begin()                      { return m_.cont_.begin();  }
474   iterator end()                        { return m_.cont_.end();    }
475   const_iterator begin() const          { return m_.cont_.begin();  }
476   const_iterator end() const            { return m_.cont_.end();    }
477   reverse_iterator rbegin()             { return m_.cont_.rbegin(); }
478   reverse_iterator rend()               { return m_.cont_.rend();   }
479   const_reverse_iterator rbegin() const { return m_.cont_.rbegin(); }
480   const_reverse_iterator rend() const   { return m_.cont_.rend();   }
481
482   void clear()                  { return m_.cont_.clear();    }
483   size_type size() const        { return m_.cont_.size();     }
484   size_type max_size() const    { return m_.cont_.max_size(); }
485   bool empty() const            { return m_.cont_.empty();    }
486   void reserve(size_type s)     { return m_.cont_.reserve(s); }
487   void shrink_to_fit()          { m_.cont_.shrink_to_fit();   }
488   size_type capacity() const    { return m_.cont_.capacity(); }
489
490   std::pair<iterator,bool> insert(const value_type& value) {
491     return insert(value_type(value));
492   }
493
494   std::pair<iterator,bool> insert(value_type&& value) {
495     iterator it = lower_bound(value.first);
496     if (it == end() || value_comp()(value, *it)) {
497       it = get_growth_policy().increase_capacity(m_.cont_, it);
498       return std::make_pair(m_.cont_.insert(it, std::move(value)), true);
499     }
500     return std::make_pair(it, false);
501   }
502
503   iterator insert(iterator hint, const value_type& value) {
504     return insert(hint, value_type(value));
505   }
506
507   iterator insert(iterator hint, value_type&& value) {
508     return detail::insert_with_hint(*this, m_.cont_, hint, std::move(value),
509       get_growth_policy());
510   }
511
512   template<class InputIterator>
513   void insert(InputIterator first, InputIterator last) {
514     int d = detail::distance_if_multipass(first, last);
515     if (d != -1) {
516       m_.cont_.reserve(m_.cont_.size() + d);
517     }
518     for (; first != last; ++first) {
519       insert(end(), *first);
520     }
521   }
522
523   size_type erase(const key_type& key) {
524     iterator it = find(key);
525     if (it == end()) {
526       return 0;
527     }
528     m_.cont_.erase(it);
529     return 1;
530   }
531
532   void erase(iterator it) {
533     m_.cont_.erase(it);
534   }
535
536   void erase(iterator first, iterator last) {
537     m_.cont_.erase(first, last);
538   }
539
540   iterator find(const key_type& key) {
541     iterator it = lower_bound(key);
542     if (it == end() || !key_comp()(key, it->first))
543       return it;
544     return end();
545   }
546
547   const_iterator find(const key_type& key) const {
548     const_iterator it = lower_bound(key);
549     if (it == end() || !key_comp()(key, it->first))
550       return it;
551     return end();
552   }
553
554   mapped_type& at(const key_type& key) {
555     iterator it = find(key);
556     if (it != end()) {
557       return it->second;
558     }
559     throw std::out_of_range("sorted_vector_map::at");
560   }
561
562   const mapped_type& at(const key_type& key) const {
563     const_iterator it = find(key);
564     if (it != end()) {
565       return it->second;
566     }
567     throw std::out_of_range("sorted_vector_map::at");
568   }
569
570   size_type count(const key_type& key) const {
571     return find(key) == end() ? 0 : 1;
572   }
573
574   iterator lower_bound(const key_type& key) {
575     return std::lower_bound(begin(), end(), key,
576       boost::bind(key_comp(), boost::bind(&value_type::first, _1), _2));
577   }
578
579   const_iterator lower_bound(const key_type& key) const {
580     return std::lower_bound(begin(), end(), key,
581       boost::bind(key_comp(), boost::bind(&value_type::first, _1), _2));
582   }
583
584   iterator upper_bound(const key_type& key) {
585     return std::upper_bound(begin(), end(), key,
586       boost::bind(key_comp(), _1, boost::bind(&value_type::first, _2)));
587   }
588
589   const_iterator upper_bound(const key_type& key) const {
590     return std::upper_bound(begin(), end(), key,
591       boost::bind(key_comp(), _1, boost::bind(&value_type::first, _2)));
592   }
593
594   std::pair<iterator,iterator> equal_range(const key_type& key) {
595     // Note: std::equal_range can't be passed a functor that takes
596     // argument types different from the iterator value_type, so we
597     // have to do this.
598     iterator low = lower_bound(key);
599     iterator high = std::upper_bound(low, end(), key,
600       boost::bind(key_comp(), _1, boost::bind(&value_type::first, _2)));
601     return std::make_pair(low, high);
602   }
603
604   std::pair<const_iterator,const_iterator>
605   equal_range(const key_type& key) const {
606     return const_cast<sorted_vector_map*>(this)->equal_range(key);
607   }
608
609   // Nothrow as long as swap() on the Compare type is nothrow.
610   void swap(sorted_vector_map& o) {
611     using std::swap; // Allow ADL for swap(); fall back to std::swap().
612     Compare& a = m_;
613     Compare& b = o.m_;
614     swap(a, b);
615     m_.cont_.swap(o.m_.cont_);
616   }
617
618   mapped_type& operator[](const key_type& key) {
619     iterator it = lower_bound(key);
620     if (it == end() || key_comp()(key, it->first)) {
621       return insert(it, value_type(key, mapped_type()))->second;
622     }
623     return it->second;
624   }
625
626   bool operator==(const sorted_vector_map& other) const {
627     return m_.cont_ == other.m_.cont_;
628   }
629
630   bool operator<(const sorted_vector_map& other) const {
631     return m_.cont_ < other.m_.cont_;
632   }
633
634 private:
635   // This is to get the empty base optimization; see the comment in
636   // sorted_vector_set.
637   struct EBO : value_compare {
638     explicit EBO(const value_compare& c, const Allocator& alloc)
639       : value_compare(c)
640       , cont_(alloc)
641     {}
642     ContainerT cont_;
643   } m_;
644 };
645
646 // Swap function that can be found using ADL.
647 template<class K, class V, class C, class A, class G>
648 inline void swap(sorted_vector_map<K,V,C,A,G>& a,
649                  sorted_vector_map<K,V,C,A,G>& b) {
650   return a.swap(b);
651 }
652
653 //////////////////////////////////////////////////////////////////////
654
655 }