File: variant_map.h

package info (click to toggle)
chromium 145.0.7632.159-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 5,976,224 kB
  • sloc: cpp: 36,198,469; ansic: 7,634,080; javascript: 3,564,060; python: 1,649,622; xml: 838,470; asm: 717,087; pascal: 185,708; sh: 88,786; perl: 88,718; objc: 79,984; sql: 59,811; cs: 42,452; fortran: 24,101; makefile: 21,144; tcl: 15,277; php: 14,022; yacc: 9,066; ruby: 7,553; awk: 3,720; lisp: 3,233; lex: 1,328; ada: 727; jsp: 228; sed: 36
file content (320 lines) | stat: -rw-r--r-- 10,105 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_CONTAINERS_VARIANT_MAP_H_
#define BASE_CONTAINERS_VARIANT_MAP_H_

#include <map>
#include <type_traits>

#include "base/check_op.h"
#include "base/features.h"
#include "base/gtest_prod_util.h"
#include "base/notreached.h"
#include "base/types/pass_key.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/container/flat_hash_map.h"

namespace metrics {
class SubprocessMetricsProvider;
}

namespace mojo {
template <typename ContextType>
class BinderMapWithContext;

class ReceiverSetState;

template <typename ReceiverType, typename ContextType>
class ReceiverSetBase;
}

namespace resource_attribution {
class CPUMeasurementMonitor;
class FakeMemoryMeasurementDelegateFactory;
class MemoryMeasurementDelegate;
class QueryResultMap;
}  // namespace resource_attribution

namespace base {

// Enum to specify which underlying map implementation to use.
enum class MapType {
  // See StdMapVariant
  kStdMap,
  // See FlatHashMapVariant
  kFlatHashMap,
};

// Whether the AbslFlatMapInVariantMap feature is enabled.
BASE_EXPORT bool IsAbslFlatMapInVariantMapEnabled();

// Initializes VariantMap features. See `base::features::Init()`.
BASE_EXPORT void InitializeVariantMapFeatures();

// Class used to evaluate the performance of switching from std::map to
// absl::flat_hash_map in place. This class is used exactly like the underlying
// map implementation for the implemented subset of operations. Constructing can
// be done with a chosen `MapType` or if the default constructor is used the
// variant is chosen automatically with a base::Feature.
//
// Example:
//   VariantMap<int, int> map(MapType::kFlatHashMap);
//   map[4] = 5;
//
// Since this class supports backing map implementations with different
// guarantees users have to assume that the least permissive guarantees apply.
// This includes but is not limited to:
// 1) No specific entry ordering
// 2) No iterator stability through modifications
// 3) No storage stability through modifications
//
// TODO(crbug.com/433462519): Remove this entire class by M145.
template <typename Key, typename Value>
class VariantMap {
 public:
  using StdMapVariant = std::map<Key, Value>;
  using FlatHashMapVariant = absl::flat_hash_map<Key, Value>;
  using value_type = std::pair<const Key, Value>;

  // Iterator class used to erase the difference in backend variant. This should
  // mostly be a drop-in replacement for the iterator types of the underlying
  // map and user code that already uses `auto` for iterator variables should
  // not need to be updated.
  template <bool is_const>
  class IteratorImpl {
   public:
    using StdMapIter =
        std::conditional_t<is_const,
                           typename StdMapVariant::const_iterator,
                           typename StdMapVariant::iterator>;
    using FlatHashMapIter =
        std::conditional_t<is_const,
                           typename FlatHashMapVariant::const_iterator,
                           typename FlatHashMapVariant::iterator>;

    using pointer =
        std::conditional_t<is_const, const value_type*, value_type*>;
    using reference =
        std::conditional_t<is_const, const value_type&, value_type&>;

    explicit IteratorImpl(StdMapIter it) : iter_variant_(it) {}
    explicit IteratorImpl(FlatHashMapIter it) : iter_variant_(it) {}

    // Allow narrowing access from a non-const iterator to a const iterator but
    // not the opposite.
    template <bool other_is_const>
      requires(is_const && !other_is_const)
    explicit IteratorImpl(IteratorImpl<other_is_const> other)
        : iter_variant_(std::visit(
              [](const auto& it) { return decltype(iter_variant_)(it); },
              other.iter_variant_)) {}

    IteratorImpl& operator++() {
      std::visit([](auto& it) { ++it; }, iter_variant_);
      return *this;
    }

    reference operator*() const {
      return std::visit([](auto& it) -> reference { return *it; },
                        iter_variant_);
    }

    pointer operator->() const {
      // Tie the implementation of this operator to operator*.
      // *this accesses this instance * of that uses the * operator.
      // & of that result is a pointer to the value.
      return &(**this);
    }

    bool operator==(const IteratorImpl& other) const {
      // Comparing iterators from different variants should never happen.
      CHECK_EQ(iter_variant_.index(), other.iter_variant_.index());

      return iter_variant_ == other.iter_variant_;
    }

   private:
    template <bool>
    friend class IteratorImpl;

    // For access to `iter_variant_`.
    friend class VariantMap;

    // The variant holds the specific iterator from the underlying map.
    std::variant<StdMapIter, FlatHashMapIter> iter_variant_;
  };

  using iterator = IteratorImpl<false>;
  using const_iterator = IteratorImpl<true>;

  // Protected by PassKey because not intended for general use but only
  // experimenting.
  template <typename ContextType>
  explicit VariantMap(
      base::PassKey<mojo::BinderMapWithContext<ContextType>> passkey)
      : VariantMap() {}

  template <typename ReceiverType, typename ContextType>
  explicit VariantMap(
      base::PassKey<mojo::ReceiverSetBase<ReceiverType, ContextType>> passkey)
      : VariantMap() {}

  explicit VariantMap(base::PassKey<metrics::SubprocessMetricsProvider> passkey)
      : VariantMap() {}

  explicit VariantMap(base::PassKey<mojo::ReceiverSetState> passkey)
      : VariantMap() {}

  explicit VariantMap(
      base::PassKey<resource_attribution::CPUMeasurementMonitor> passkey)
      : VariantMap() {}

  explicit VariantMap(
      base::PassKey<resource_attribution::FakeMemoryMeasurementDelegateFactory>
          passkey)
      : VariantMap() {}

  explicit VariantMap(
      base::PassKey<resource_attribution::MemoryMeasurementDelegate> passkey)
      : VariantMap() {}

  explicit VariantMap(
      base::PassKey<resource_attribution::QueryResultMap> passkey)
      : VariantMap() {}

  size_t size() const {
    return std::visit([](const auto& map) { return map.size(); }, data_);
  }

  bool empty() const {
    return std::visit([](const auto& map) { return map.empty(); }, data_);
  }

  void clear() {
    return std::visit([](auto& map) { return map.clear(); }, data_);
  }

  Value& operator[](const Key& key) {
    return std::visit([&key](auto& map) -> Value& { return map[key]; }, data_);
  }

  Value& at(const Key& key) {
    return std::visit([&key](auto& map) -> Value& { return map.at(key); },
                      data_);
  }

  const Value& at(const Key& key) const {
    return std::visit(
        [&key](const auto& map) -> const Value& { return map.at(key); }, data_);
  }

  template <class... Args>
  std::pair<iterator, bool> emplace(Args&&... args) {
    return std::visit(
        [&](auto& map) {
          auto result = map.emplace(std::forward<Args>(args)...);
          return std::make_pair(iterator(result.first), result.second);
        },
        data_);
  }

  template <class... Args>
  std::pair<iterator, bool> try_emplace(Args&&... args) {
    return std::visit(
        [&](auto& map) {
          auto result = map.try_emplace(std::forward<Args>(args)...);
          return std::make_pair(iterator(result.first), result.second);
        },
        data_);
  }

  std::pair<iterator, bool> insert(value_type&& value) {
    return std::visit(
        [&](auto& map) {
          auto result = map.insert(std::move(value));
          return std::make_pair(iterator(result.first), result.second);
        },
        data_);
  }

  size_t erase(const Key& key) {
    return std::visit([&](auto& map) { return map.erase(key); }, data_);
  }

  void erase(iterator pos) {
    std::visit(
        [&](auto& map) {
          // Get the correct native_iterator out.
          using MapType = typename std::decay<decltype(map)>::type;
          auto native_it =
              std::get<typename MapType::iterator>(pos.iter_variant_);

          map.erase(native_it);
        },
        data_);
  }

  iterator begin() {
    return std::visit([](auto& map) { return iterator(map.begin()); }, data_);
  }
  const_iterator begin() const {
    return const_iterator(const_cast<VariantMap*>(this)->begin());
  }

  iterator end() {
    return std::visit([](auto& map) { return iterator(map.end()); }, data_);
  }
  const_iterator end() const {
    return const_iterator(const_cast<VariantMap*>(this)->end());
  }

  iterator find(const Key& key) {
    return std::visit([&key](auto& map) { return iterator(map.find(key)); },
                      data_);
  }
  const_iterator find(const Key& key) const {
    return const_iterator(const_cast<VariantMap*>(this)->find(key));
  }

  bool contains(const Key& key) const { return find(key) != end(); }

 private:
  FRIEND_TEST_ALL_PREFIXES(VariantMapTest, Construction);
  FRIEND_TEST_ALL_PREFIXES(VariantMapTest, Insertion);
  FRIEND_TEST_ALL_PREFIXES(VariantMapTest, At);
  FRIEND_TEST_ALL_PREFIXES(VariantMapTest, Find);
  FRIEND_TEST_ALL_PREFIXES(VariantMapTest, Contains);
  FRIEND_TEST_ALL_PREFIXES(VariantMapTest, Iteration);
  FRIEND_TEST_ALL_PREFIXES(VariantMapTest, Empty);
  FRIEND_TEST_ALL_PREFIXES(VariantMapTest, Clear);

  using Map = std::variant<StdMapVariant, FlatHashMapVariant>;

  // Constructors private because protected via PassKey.

  explicit VariantMap(MapType type)
      : data_([&]() {
          switch (type) {
            case MapType::kStdMap:
              return Map(std::in_place_index_t<0>());
            case MapType::kFlatHashMap:
              return Map(std::in_place_index_t<1>());

              NOTREACHED();
          }
        }()) {}

  VariantMap()
      : VariantMap(base::IsAbslFlatMapInVariantMapEnabled()
                       ? MapType::kFlatHashMap
                       : MapType::kStdMap) {}

  // The variant that holds one of the two map types.
  Map data_;
};

}  // namespace base

#endif  // BASE_CONTAINERS_VARIANT_MAP_H_