• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_CONTAINERS_FLAT_MAP_H_
6 #define BASE_CONTAINERS_FLAT_MAP_H_
7 
8 #include <functional>
9 #include <tuple>
10 #include <type_traits>
11 #include <utility>
12 #include <vector>
13 
14 #include "base/check.h"
15 #include "base/containers/flat_tree.h"
16 
17 namespace base {
18 
19 namespace internal {
20 
21 // An implementation of the flat_tree GetKeyFromValue template parameter that
22 // extracts the key as the first element of a pair.
23 struct GetFirst {
24   template <class Key, class Mapped>
operatorGetFirst25   constexpr const Key& operator()(const std::pair<Key, Mapped>& p) const {
26     return p.first;
27   }
28 };
29 
30 }  // namespace internal
31 
32 // flat_map is a container with a std::map-like interface that stores its
33 // contents in a sorted container, by default a vector.
34 //
35 // Its implementation mostly tracks the corresponding standardization proposal
36 // https://wg21.link/P0429, except that the storage of keys and values is not
37 // split.
38 //
39 // Please see //base/containers/README.md for an overview of which container
40 // to select.
41 //
42 // PROS
43 //
44 //  - Good memory locality.
45 //  - Low overhead, especially for smaller maps.
46 //  - Performance is good for more workloads than you might expect (see
47 //    overview link above).
48 //  - Supports C++14 map interface.
49 //
50 // CONS
51 //
52 //  - Inserts and removals are O(n).
53 //
54 // IMPORTANT NOTES
55 //
56 //  - Iterators are invalidated across mutations. This means that the following
57 //    line of code has undefined behavior since adding a new element could
58 //    resize the container, invalidating all iterators:
59 //      container["new element"] = it.second;
60 //  - If possible, construct a flat_map in one operation by inserting into
61 //    a container and moving that container into the flat_map constructor.
62 //
63 // QUICK REFERENCE
64 //
65 // Most of the core functionality is inherited from flat_tree. Please see
66 // flat_tree.h for more details for most of these functions. As a quick
67 // reference, the functions available are:
68 //
69 // Constructors (inputs need not be sorted):
70 //   flat_map(const flat_map&);
71 //   flat_map(flat_map&&);
72 //   flat_map(InputIterator first, InputIterator last,
73 //            const Compare& compare = Compare());
74 //   flat_map(const container_type& items,
75 //            const Compare& compare = Compare());
76 //   flat_map(container_type&& items,
77 //            const Compare& compare = Compare()); // Re-use storage.
78 //   flat_map(std::initializer_list<value_type> ilist,
79 //            const Compare& comp = Compare());
80 //
81 // Constructors (inputs need to be sorted):
82 //   flat_map(sorted_unique_t,
83 //            InputIterator first, InputIterator last,
84 //            const Compare& compare = Compare());
85 //   flat_map(sorted_unique_t,
86 //            const container_type& items,
87 //            const Compare& compare = Compare());
88 //   flat_map(sorted_unique_t,
89 //            container_type&& items,
90 //            const Compare& compare = Compare());  // Re-use storage.
91 //   flat_map(sorted_unique_t,
92 //            std::initializer_list<value_type> ilist,
93 //            const Compare& comp = Compare());
94 //
95 // Assignment functions:
96 //   flat_map& operator=(const flat_map&);
97 //   flat_map& operator=(flat_map&&);
98 //   flat_map& operator=(initializer_list<value_type>);
99 //
100 // Memory management functions:
101 //   void   reserve(size_t);
102 //   size_t capacity() const;
103 //   void   shrink_to_fit();
104 //
105 // Size management functions:
106 //   void   clear();
107 //   size_t size() const;
108 //   size_t max_size() const;
109 //   bool   empty() const;
110 //
111 // Iterator functions:
112 //   iterator               begin();
113 //   const_iterator         begin() const;
114 //   const_iterator         cbegin() const;
115 //   iterator               end();
116 //   const_iterator         end() const;
117 //   const_iterator         cend() const;
118 //   reverse_iterator       rbegin();
119 //   const reverse_iterator rbegin() const;
120 //   const_reverse_iterator crbegin() const;
121 //   reverse_iterator       rend();
122 //   const_reverse_iterator rend() const;
123 //   const_reverse_iterator crend() const;
124 //
125 // Insert and accessor functions:
126 //   mapped_type&         operator[](const key_type&);
127 //   mapped_type&         operator[](key_type&&);
128 //   mapped_type&         at(const K&);
129 //   const mapped_type&   at(const K&) const;
130 //   pair<iterator, bool> insert(const value_type&);
131 //   pair<iterator, bool> insert(value_type&&);
132 //   iterator             insert(const_iterator hint, const value_type&);
133 //   iterator             insert(const_iterator hint, value_type&&);
134 //   void                 insert(InputIterator first, InputIterator last);
135 //   pair<iterator, bool> insert_or_assign(K&&, M&&);
136 //   iterator             insert_or_assign(const_iterator hint, K&&, M&&);
137 //   pair<iterator, bool> emplace(Args&&...);
138 //   iterator             emplace_hint(const_iterator, Args&&...);
139 //   pair<iterator, bool> try_emplace(K&&, Args&&...);
140 //   iterator             try_emplace(const_iterator hint, K&&, Args&&...);
141 
142 // Underlying type functions:
143 //   container_type       extract() &&;
144 //   void                 replace(container_type&&);
145 //
146 // Erase functions:
147 //   iterator erase(iterator);
148 //   iterator erase(const_iterator);
149 //   iterator erase(const_iterator first, const_iterator& last);
150 //   template <class K> size_t erase(const K& key);
151 //
152 // Comparators (see std::map documentation).
153 //   key_compare   key_comp() const;
154 //   value_compare value_comp() const;
155 //
156 // Search functions:
157 //   template <typename K> size_t                   count(const K&) const;
158 //   template <typename K> iterator                 find(const K&);
159 //   template <typename K> const_iterator           find(const K&) const;
160 //   template <typename K> bool                     contains(const K&) const;
161 //   template <typename K> pair<iterator, iterator> equal_range(const K&);
162 //   template <typename K> iterator                 lower_bound(const K&);
163 //   template <typename K> const_iterator           lower_bound(const K&) const;
164 //   template <typename K> iterator                 upper_bound(const K&);
165 //   template <typename K> const_iterator           upper_bound(const K&) const;
166 //
167 // General functions:
168 //   void swap(flat_map&);
169 //
170 // Non-member operators:
171 //   bool operator==(const flat_map&, const flat_map);
172 //   bool operator!=(const flat_map&, const flat_map);
173 //   bool operator<(const flat_map&, const flat_map);
174 //   bool operator>(const flat_map&, const flat_map);
175 //   bool operator>=(const flat_map&, const flat_map);
176 //   bool operator<=(const flat_map&, const flat_map);
177 //
178 template <class Key,
179           class Mapped,
180           class Compare = std::less<>,
181           class Container = std::vector<std::pair<Key, Mapped>>>
182 class flat_map : public ::base::internal::
183                      flat_tree<Key, internal::GetFirst, Compare, Container> {
184  private:
185   using tree = typename ::base::internal::
186       flat_tree<Key, internal::GetFirst, Compare, Container>;
187 
188  public:
189   using key_type = typename tree::key_type;
190   using mapped_type = Mapped;
191   using value_type = typename tree::value_type;
192   using reference = typename Container::reference;
193   using const_reference = typename Container::const_reference;
194   using size_type = typename Container::size_type;
195   using difference_type = typename Container::difference_type;
196   using iterator = typename tree::iterator;
197   using const_iterator = typename tree::const_iterator;
198   using reverse_iterator = typename tree::reverse_iterator;
199   using const_reverse_iterator = typename tree::const_reverse_iterator;
200   using container_type = typename tree::container_type;
201 
202   // --------------------------------------------------------------------------
203   // Lifetime and assignments.
204   //
205   // Note: we explicitly bring operator= in because otherwise
206   //   flat_map<...> x;
207   //   x = {...};
208   // Would first create a flat_map and then move assign it. This most likely
209   // would be optimized away but still affects our debug builds.
210 
211   using tree::tree;
212   using tree::operator=;
213 
214   // Out-of-bound calls to at() will CHECK.
215   template <class K>
216   mapped_type& at(const K& key);
217   template <class K>
218   const mapped_type& at(const K& key) const;
219 
220   // --------------------------------------------------------------------------
221   // Map-specific insert operations.
222   //
223   // Normal insert() functions are inherited from flat_tree.
224   //
225   // Assume that every operation invalidates iterators and references.
226   // Insertion of one element can take O(size).
227 
228   mapped_type& operator[](const key_type& key);
229   mapped_type& operator[](key_type&& key);
230 
231   template <class K, class M>
232   std::pair<iterator, bool> insert_or_assign(K&& key, M&& obj);
233   template <class K, class M>
234   iterator insert_or_assign(const_iterator hint, K&& key, M&& obj);
235 
236   template <class K, class... Args>
237   std::enable_if_t<std::is_constructible_v<key_type, K&&>,
238                    std::pair<iterator, bool>>
239   try_emplace(K&& key, Args&&... args);
240 
241   template <class K, class... Args>
242   std::enable_if_t<std::is_constructible_v<key_type, K&&>, iterator>
243   try_emplace(const_iterator hint, K&& key, Args&&... args);
244 
245   // --------------------------------------------------------------------------
246   // General operations.
247   //
248   // Assume that swap invalidates iterators and references.
249 
250   void swap(flat_map& other) noexcept;
251 
swap(flat_map & lhs,flat_map & rhs)252   friend void swap(flat_map& lhs, flat_map& rhs) noexcept { lhs.swap(rhs); }
253 };
254 
255 // ----------------------------------------------------------------------------
256 // Lookups.
257 
258 template <class Key, class Mapped, class Compare, class Container>
259 template <class K>
260 auto flat_map<Key, Mapped, Compare, Container>::at(const K& key)
261     -> mapped_type& {
262   iterator found = tree::find(key);
263   CHECK(found != tree::end());
264   return found->second;
265 }
266 
267 template <class Key, class Mapped, class Compare, class Container>
268 template <class K>
269 auto flat_map<Key, Mapped, Compare, Container>::at(const K& key) const
270     -> const mapped_type& {
271   const_iterator found = tree::find(key);
272   CHECK(found != tree::cend());
273   return found->second;
274 }
275 
276 // ----------------------------------------------------------------------------
277 // Insert operations.
278 
279 template <class Key, class Mapped, class Compare, class Container>
280 auto flat_map<Key, Mapped, Compare, Container>::operator[](const key_type& key)
281     -> mapped_type& {
282   iterator found = tree::lower_bound(key);
283   if (found == tree::end() || tree::key_comp()(key, found->first))
284     found = tree::unsafe_emplace(found, key, mapped_type());
285   return found->second;
286 }
287 
288 template <class Key, class Mapped, class Compare, class Container>
289 auto flat_map<Key, Mapped, Compare, Container>::operator[](key_type&& key)
290     -> mapped_type& {
291   iterator found = tree::lower_bound(key);
292   if (found == tree::end() || tree::key_comp()(key, found->first))
293     found = tree::unsafe_emplace(found, std::move(key), mapped_type());
294   return found->second;
295 }
296 
297 template <class Key, class Mapped, class Compare, class Container>
298 template <class K, class M>
299 auto flat_map<Key, Mapped, Compare, Container>::insert_or_assign(K&& key,
300                                                                  M&& obj)
301     -> std::pair<iterator, bool> {
302   auto result =
303       tree::emplace_key_args(key, std::forward<K>(key), std::forward<M>(obj));
304   if (!result.second)
305     result.first->second = std::forward<M>(obj);
306   return result;
307 }
308 
309 template <class Key, class Mapped, class Compare, class Container>
310 template <class K, class M>
311 auto flat_map<Key, Mapped, Compare, Container>::insert_or_assign(
312     const_iterator hint,
313     K&& key,
314     M&& obj) -> iterator {
315   auto result = tree::emplace_hint_key_args(hint, key, std::forward<K>(key),
316                                             std::forward<M>(obj));
317   if (!result.second)
318     result.first->second = std::forward<M>(obj);
319   return result.first;
320 }
321 
322 template <class Key, class Mapped, class Compare, class Container>
323 template <class K, class... Args>
324 auto flat_map<Key, Mapped, Compare, Container>::try_emplace(K&& key,
325                                                             Args&&... args)
326     -> std::enable_if_t<std::is_constructible_v<key_type, K&&>,
327                         std::pair<iterator, bool>> {
328   return tree::emplace_key_args(
329       key, std::piecewise_construct,
330       std::forward_as_tuple(std::forward<K>(key)),
331       std::forward_as_tuple(std::forward<Args>(args)...));
332 }
333 
334 template <class Key, class Mapped, class Compare, class Container>
335 template <class K, class... Args>
336 auto flat_map<Key, Mapped, Compare, Container>::try_emplace(const_iterator hint,
337                                                             K&& key,
338                                                             Args&&... args)
339     -> std::enable_if_t<std::is_constructible_v<key_type, K&&>, iterator> {
340   return tree::emplace_hint_key_args(
341              hint, key, std::piecewise_construct,
342              std::forward_as_tuple(std::forward<K>(key)),
343              std::forward_as_tuple(std::forward<Args>(args)...))
344       .first;
345 }
346 
347 // ----------------------------------------------------------------------------
348 // General operations.
349 
350 template <class Key, class Mapped, class Compare, class Container>
swap(flat_map & other)351 void flat_map<Key, Mapped, Compare, Container>::swap(flat_map& other) noexcept {
352   tree::swap(other);
353 }
354 
355 // ----------------------------------------------------------------------------
356 // Utility functions.
357 
358 // Utility function to simplify constructing a flat_set from a fixed list of
359 // keys and values. The key/value pairs are obtained by applying |proj| to the
360 // |unprojected_elements|. The map's keys are sorted by |comp|.
361 //
362 // Example usage (creates a set {{16, "4"}, {9, "3"}, {4, "2"}, {1, "1"}}):
363 //   auto map = base::MakeFlatMap<int, std::string>(
364 //       std::vector<int>{1, 2, 3, 4},
365 //       [](int i, int j) { return i > j; },
366 //       [](int i) { return std::make_pair(i * i, base::NumberToString(i)); });
367 template <class Key,
368           class Mapped,
369           class KeyCompare = std::less<>,
370           class Container = std::vector<std::pair<Key, Mapped>>,
371           class InputContainer,
372           class Projection = std::identity>
373 constexpr flat_map<Key, Mapped, KeyCompare, Container> MakeFlatMap(
374     const InputContainer& unprojected_elements,
375     const KeyCompare& comp = KeyCompare(),
376     const Projection& proj = Projection()) {
377   Container elements;
378   internal::ReserveIfSupported(elements, unprojected_elements);
379   base::ranges::transform(unprojected_elements, std::back_inserter(elements),
380                           proj);
381   return flat_map<Key, Mapped, KeyCompare, Container>(std::move(elements),
382                                                       comp);
383 }
384 
385 // Deduction guide to construct a flat_map from a Container of std::pair<Key,
386 // Mapped> elements. The container does not have to be sorted or contain only
387 // unique keys; construction will automatically discard duplicate keys, keeping
388 // only the first.
389 template <
390     class Container,
391     class Compare = std::less<>,
392     class Key = typename std::decay_t<Container>::value_type::first_type,
393     class Mapped = typename std::decay_t<Container>::value_type::second_type>
394 flat_map(Container&&, Compare comp = {})
395     -> flat_map<Key, Mapped, Compare, std::decay_t<Container>>;
396 
397 }  // namespace base
398 
399 #endif  // BASE_CONTAINERS_FLAT_MAP_H_
400