swift
mapbuilder.h
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: Copyright (C) 2021 swift Project Community / Contributors
2 // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3 
5 
6 #ifndef SWIFT_MISC_MAPBUILDER_H
7 #define SWIFT_MISC_MAPBUILDER_H
8 
9 #include <algorithm>
10 #include <iterator>
11 #include <map>
12 
13 #include <QHash>
14 #include <QList>
15 #include <QMap>
16 
17 #include "misc/range.h"
18 
19 namespace swift::misc
20 {
24  template <typename K, typename V>
26  {
27  public:
29  template <typename... Ts>
30  void insert(Ts &&...keyAndValue)
31  {
32  m_list.push_back(std::make_pair(std::forward<Ts>(keyAndValue)...));
33  }
34 
36  bool isEmpty() const { return m_list.isEmpty(); }
37 
40  operator QMap<K, V>() const & { return convertToMap(sortAndDeduplicate(m_list)); }
41  operator QMap<K, V>() && { return convertToMap(sortAndDeduplicate(std::move(m_list))); }
42  operator QHash<K, V>() const & { return convertTo<QHash>(sortAndDeduplicate(m_list)); }
43  operator QHash<K, V>() && { return convertTo<QHash>(sortAndDeduplicate(std::move(m_list))); }
44  operator std::map<K, V>() const & { return convertTo<std::map>(sortAndDeduplicate(m_list)); }
45  operator std::map<K, V>() && { return convertTo<std::map>(sortAndDeduplicate(std::move(m_list))); }
47 
48  private:
49  QList<std::pair<K, V>> m_list;
50 
51  static QList<std::pair<K, V>> sortAndDeduplicate(QList<std::pair<K, V>> list)
52  {
53  std::sort(list.begin(), list.end(), [](auto &&a, auto &&b) { return std::less<>()(a.first, b.first); });
54  list.erase(std::unique(list.begin(), list.end(), [](auto &&a, auto &&b) { return a.first == b.first; }),
55  list.end());
56  return list;
57  }
58 
59  template <template <typename...> class C>
60  static C<K, V> convertTo(QList<std::pair<K, V>> &&list)
61  {
62  return C<K, V>(std::make_move_iterator(list.begin()), std::make_move_iterator(list.end()));
63  }
64 
65  static QMap<K, V> convertToMap(QList<std::pair<K, V>> &&list)
66  {
67  QMap<K, V> map;
68  for (auto &pair : makeRange(list).reverse())
69  {
70  map.insert(map.cbegin(), std::move(pair.first), std::move(pair.second));
71  }
72  return map;
73  }
74  };
75 } // namespace swift::misc
76 
77 #endif // SWIFT_MISC_MAPBUILDER_H
Build a QMap more efficiently when calling insert() in a for loop.
Definition: mapbuilder.h:26
bool isEmpty() const
True if no pairs have been inserted.
Definition: mapbuilder.h:36
void insert(Ts &&...keyAndValue)
Add an key/value pair to the map. Runs in amortized constant time.
Definition: mapbuilder.h:30
Free functions in swift::misc.
auto makeRange(I begin, I2 end) -> CRange< I >
Returns a CRange constructed from begin and end iterators of deduced types.
Definition: range.h:316