blob: a0f9b02badb04e752ee22572f8bfef806dc0c709 [file] [log] [blame]
[email protected]4bc4f122011-03-08 02:07:291// Copyright (c) 2011 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
Brett Wilsonf976d3f2017-08-18 17:23:395#ifndef BASE_CONTAINERS_ID_MAP_H_
6#define BASE_CONTAINERS_ID_MAP_H_
initial.commitd7cae122008-07-26 21:49:387
avi9b6f42932015-12-26 22:15:148#include <stddef.h>
jkarlin7bc034c2015-09-25 20:45:479#include <stdint.h>
brettw1ce49f62017-04-27 19:42:3210
aeliasaed214d02016-09-24 01:26:4211#include <memory>
[email protected]9de09f82009-08-17 20:13:5312#include <set>
aeliasaed214d02016-09-24 01:26:4213#include <type_traits>
brettw1ce49f62017-04-27 19:42:3214#include <unordered_map>
aeliasaed214d02016-09-24 01:26:4215#include <utility>
[email protected]9de09f82009-08-17 20:13:5316
Hans Wennborg7b533712020-06-22 20:52:2717#include "base/check_op.h"
brettw1ce49f62017-04-27 19:42:3218#include "base/containers/flat_set.h"
Keishi Hattori0e45c022021-11-27 09:25:5219#include "base/memory/raw_ptr.h"
Hans Wennborg7b533712020-06-22 20:52:2720#include "base/notreached.h"
jsbell41359ee2015-11-16 19:43:3421#include "base/sequence_checker.h"
initial.commitd7cae122008-07-26 21:49:3822
Brett Wilsonf976d3f2017-08-18 17:23:3923namespace base {
24
initial.commitd7cae122008-07-26 21:49:3825// This object maintains a list of IDs that can be quickly converted to
26// pointers to objects. It is implemented as a hash table, optimized for
27// relatively small data sets (in the common case, there will be exactly one
28// item in the list).
29//
30// Items can be inserted into the container with arbitrary ID, but the caller
31// must ensure they are unique. Inserting IDs and relying on automatically
32// generated ones is not allowed because they can collide.
rlandayde24c6d2016-12-01 03:05:4033
34// The map's value type (the V param) can be any dereferenceable type, such as a
35// raw pointer or smart pointer
36template <typename V, typename K = int32_t>
37class IDMap final {
[email protected]b8b670812014-05-27 18:10:0638 public:
jkarlin7bc034c2015-09-25 20:45:4739 using KeyType = K;
[email protected]b8b670812014-05-27 18:10:0640
41 private:
rlandayde24c6d2016-12-01 03:05:4042 using T = typename std::remove_reference<decltype(*V())>::type;
brettw1ce49f62017-04-27 19:42:3243
44 using HashTable = std::unordered_map<KeyType, V>;
initial.commitd7cae122008-07-26 21:49:3845
46 public:
[email protected]9de09f82009-08-17 20:13:5347 IDMap() : iteration_depth_(0), next_id_(1), check_on_null_data_(false) {
jsbell41359ee2015-11-16 19:43:3448 // A number of consumers of IDMap create it on one thread but always
49 // access it from a different, but consistent, thread (or sequence)
fdoraye2b19a12016-07-29 02:30:1650 // post-construction. The first call to CalledOnValidSequence() will re-bind
51 // it.
tzikfd754ee2018-03-28 15:49:2852 DETACH_FROM_SEQUENCE(sequence_checker_);
initial.commitd7cae122008-07-26 21:49:3853 }
54
Lei Zhang6825df462020-06-23 16:17:4355 IDMap(const IDMap&) = delete;
56 IDMap& operator=(const IDMap&) = delete;
57
[email protected]9e7e0e02010-01-25 23:25:1658 ~IDMap() {
jsbell41359ee2015-11-16 19:43:3459 // Many IDMap's are static, and hence will be destroyed on the main
60 // thread. However, all the accesses may take place on another thread (or
61 // sequence), such as the IO thread. Detaching again to clean this up.
tzikfd754ee2018-03-28 15:49:2862 DETACH_FROM_SEQUENCE(sequence_checker_);
[email protected]9e7e0e02010-01-25 23:25:1663 }
64
michaelnbfea6ec2014-12-09 23:16:1365 // Sets whether Add and Replace should DCHECK if passed in NULL data.
66 // Default is false.
[email protected]a6ed9432009-07-01 22:35:2667 void set_check_on_null_data(bool value) { check_on_null_data_ = value; }
68
initial.commitd7cae122008-07-26 21:49:3869 // Adds a view with an automatically generated unique ID. See AddWithID.
rlanday6eada0322016-11-30 18:59:3070 KeyType Add(V data) { return AddInternal(std::move(data)); }
initial.commitd7cae122008-07-26 21:49:3871
72 // Adds a new data member with the specified ID. The ID must not be in
73 // the list. The caller either must generate all unique IDs itself and use
74 // this function, or allow this object to generate IDs and call Add. These
aeliasaed214d02016-09-24 01:26:4275 // two methods may not be mixed, or duplicate IDs may be generated.
rlanday6eada0322016-11-30 18:59:3076 void AddWithID(V data, KeyType id) { AddWithIDInternal(std::move(data), id); }
initial.commitd7cae122008-07-26 21:49:3877
[email protected]9e7e0e02010-01-25 23:25:1678 void Remove(KeyType id) {
tzikfd754ee2018-03-28 15:49:2879 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
[email protected]9de09f82009-08-17 20:13:5380 typename HashTable::iterator i = data_.find(id);
tzikd1646672018-03-28 20:41:1381 if (i == data_.end() || IsRemoved(id)) {
initial.commitd7cae122008-07-26 21:49:3882 NOTREACHED() << "Attempting to remove an item not in the list";
83 return;
84 }
[email protected]9de09f82009-08-17 20:13:5385
[email protected]9e7e0e02010-01-25 23:25:1686 if (iteration_depth_ == 0) {
[email protected]9de09f82009-08-17 20:13:5387 data_.erase(i);
[email protected]9e7e0e02010-01-25 23:25:1688 } else {
[email protected]9de09f82009-08-17 20:13:5389 removed_ids_.insert(id);
[email protected]9e7e0e02010-01-25 23:25:1690 }
initial.commitd7cae122008-07-26 21:49:3891 }
92
sungmann.cho82e601f92017-02-17 04:43:1393 // Replaces the value for |id| with |new_data| and returns the existing value.
94 // Should only be called with an already added id.
aeliasaed214d02016-09-24 01:26:4295 V Replace(KeyType id, V new_data) {
tzikfd754ee2018-03-28 15:49:2896 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
michaelnbfea6ec2014-12-09 23:16:1397 DCHECK(!check_on_null_data_ || new_data);
98 typename HashTable::iterator i = data_.find(id);
aeliasaed214d02016-09-24 01:26:4299 DCHECK(i != data_.end());
tzikd1646672018-03-28 20:41:13100 DCHECK(!IsRemoved(id));
michaelnbfea6ec2014-12-09 23:16:13101
tzikd1646672018-03-28 20:41:13102 using std::swap;
103 swap(i->second, new_data);
aeliasaed214d02016-09-24 01:26:42104 return new_data;
michaelnbfea6ec2014-12-09 23:16:13105 }
106
[email protected]fea0b9612012-10-29 21:36:22107 void Clear() {
tzikfd754ee2018-03-28 15:49:28108 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
[email protected]fea0b9612012-10-29 21:36:22109 if (iteration_depth_ == 0) {
aeliasaed214d02016-09-24 01:26:42110 data_.clear();
[email protected]fea0b9612012-10-29 21:36:22111 } else {
tzikc5837e22018-03-29 05:31:15112 removed_ids_.reserve(data_.size());
113 removed_ids_.insert(KeyIterator(data_.begin()), KeyIterator(data_.end()));
[email protected]fea0b9612012-10-29 21:36:22114 }
115 }
116
initial.commitd7cae122008-07-26 21:49:38117 bool IsEmpty() const {
tzikfd754ee2018-03-28 15:49:28118 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
[email protected]2de069e2010-02-16 09:15:38119 return size() == 0u;
initial.commitd7cae122008-07-26 21:49:38120 }
121
[email protected]9e7e0e02010-01-25 23:25:16122 T* Lookup(KeyType id) const {
tzikfd754ee2018-03-28 15:49:28123 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
[email protected]9de09f82009-08-17 20:13:53124 typename HashTable::const_iterator i = data_.find(id);
tzikd1646672018-03-28 20:41:13125 if (i == data_.end() || !i->second || IsRemoved(id))
aeliasaed214d02016-09-24 01:26:42126 return nullptr;
127 return &*i->second;
initial.commitd7cae122008-07-26 21:49:38128 }
129
130 size_t size() const {
tzikfd754ee2018-03-28 15:49:28131 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
[email protected]2de069e2010-02-16 09:15:38132 return data_.size() - removed_ids_.size();
initial.commitd7cae122008-07-26 21:49:38133 }
134
[email protected]0c8b8942012-10-27 01:03:01135#if defined(UNIT_TEST)
136 int iteration_depth() const {
137 return iteration_depth_;
138 }
139#endif // defined(UNIT_TEST)
140
[email protected]9de09f82009-08-17 20:13:53141 // It is safe to remove elements from the map during iteration. All iterators
142 // will remain valid.
143 template<class ReturnType>
144 class Iterator {
145 public:
rlandayde24c6d2016-12-01 03:05:40146 Iterator(IDMap<V, K>* map) : map_(map), iter_(map_->data_.begin()) {
[email protected]0c8b8942012-10-27 01:03:01147 Init();
148 }
149
150 Iterator(const Iterator& iter)
151 : map_(iter.map_),
152 iter_(iter.iter_) {
153 Init();
154 }
155
156 const Iterator& operator=(const Iterator& iter) {
157 map_ = iter.map;
158 iter_ = iter.iter;
159 Init();
160 return *this;
[email protected]9de09f82009-08-17 20:13:53161 }
162
163 ~Iterator() {
tzikfd754ee2018-03-28 15:49:28164 DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
[email protected]0c8b8942012-10-27 01:03:01165
166 // We're going to decrement iteration depth. Make sure it's greater than
167 // zero so that it doesn't become negative.
168 DCHECK_LT(0, map_->iteration_depth_);
169
[email protected]9de09f82009-08-17 20:13:53170 if (--map_->iteration_depth_ == 0)
171 map_->Compact();
172 }
173
174 bool IsAtEnd() const {
tzikfd754ee2018-03-28 15:49:28175 DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
[email protected]9de09f82009-08-17 20:13:53176 return iter_ == map_->data_.end();
177 }
178
[email protected]9e7e0e02010-01-25 23:25:16179 KeyType GetCurrentKey() const {
tzikfd754ee2018-03-28 15:49:28180 DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
[email protected]9de09f82009-08-17 20:13:53181 return iter_->first;
182 }
183
184 ReturnType* GetCurrentValue() const {
tzikfd754ee2018-03-28 15:49:28185 DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
tzikd1646672018-03-28 20:41:13186 if (!iter_->second || map_->IsRemoved(iter_->first))
187 return nullptr;
aeliasaed214d02016-09-24 01:26:42188 return &*iter_->second;
[email protected]9de09f82009-08-17 20:13:53189 }
190
191 void Advance() {
tzikfd754ee2018-03-28 15:49:28192 DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
[email protected]9de09f82009-08-17 20:13:53193 ++iter_;
194 SkipRemovedEntries();
195 }
196
197 private:
[email protected]0c8b8942012-10-27 01:03:01198 void Init() {
tzikfd754ee2018-03-28 15:49:28199 DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
[email protected]0c8b8942012-10-27 01:03:01200 ++map_->iteration_depth_;
201 SkipRemovedEntries();
202 }
203
[email protected]9de09f82009-08-17 20:13:53204 void SkipRemovedEntries() {
tzikd1646672018-03-28 20:41:13205 while (iter_ != map_->data_.end() && map_->IsRemoved(iter_->first))
[email protected]9de09f82009-08-17 20:13:53206 ++iter_;
[email protected]9de09f82009-08-17 20:13:53207 }
208
Keishi Hattori0e45c022021-11-27 09:25:52209 raw_ptr<IDMap<V, K>> map_;
[email protected]9de09f82009-08-17 20:13:53210 typename HashTable::const_iterator iter_;
211 };
212
213 typedef Iterator<T> iterator;
214 typedef Iterator<const T> const_iterator;
215
216 private:
tzikc5837e22018-03-29 05:31:15217 // Transforms a map iterator to an iterator on the keys of the map.
218 // Used by Clear() to populate |removed_ids_| in bulk.
219 struct KeyIterator : std::iterator<std::forward_iterator_tag, KeyType> {
220 using inner_iterator = typename HashTable::iterator;
221 inner_iterator iter_;
222
223 KeyIterator(inner_iterator iter) : iter_(iter) {}
224 KeyType operator*() const { return iter_->first; }
225 KeyIterator& operator++() {
226 ++iter_;
227 return *this;
228 }
229 KeyIterator operator++(int) { return KeyIterator(iter_++); }
230 bool operator==(const KeyIterator& other) const {
231 return iter_ == other.iter_;
232 }
233 bool operator!=(const KeyIterator& other) const {
234 return iter_ != other.iter_;
235 }
236 };
237
aeliasaed214d02016-09-24 01:26:42238 KeyType AddInternal(V data) {
tzikfd754ee2018-03-28 15:49:28239 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
aeliasaed214d02016-09-24 01:26:42240 DCHECK(!check_on_null_data_ || data);
241 KeyType this_id = next_id_;
242 DCHECK(data_.find(this_id) == data_.end()) << "Inserting duplicate item";
243 data_[this_id] = std::move(data);
244 next_id_++;
245 return this_id;
246 }
[email protected]9e7e0e02010-01-25 23:25:16247
aeliasaed214d02016-09-24 01:26:42248 void AddWithIDInternal(V data, KeyType id) {
tzikfd754ee2018-03-28 15:49:28249 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
aeliasaed214d02016-09-24 01:26:42250 DCHECK(!check_on_null_data_ || data);
tzikd1646672018-03-28 20:41:13251 if (IsRemoved(id)) {
252 removed_ids_.erase(id);
253 } else {
254 DCHECK(data_.find(id) == data_.end()) << "Inserting duplicate item";
255 }
aeliasaed214d02016-09-24 01:26:42256 data_[id] = std::move(data);
257 }
[email protected]9e7e0e02010-01-25 23:25:16258
tzikd1646672018-03-28 20:41:13259 bool IsRemoved(KeyType key) const {
260 return removed_ids_.find(key) != removed_ids_.end();
261 }
262
[email protected]9de09f82009-08-17 20:13:53263 void Compact() {
264 DCHECK_EQ(0, iteration_depth_);
jkarlin7bc034c2015-09-25 20:45:47265 for (const auto& i : removed_ids_)
tzikd1646672018-03-28 20:41:13266 data_.erase(i);
[email protected]9de09f82009-08-17 20:13:53267 removed_ids_.clear();
268 }
269
270 // Keep track of how many iterators are currently iterating on us to safely
271 // handle removing items during iteration.
272 int iteration_depth_;
273
274 // Keep set of IDs that should be removed after the outermost iteration has
275 // finished. This way we manage to not invalidate the iterator when an element
276 // is removed.
brettw1ce49f62017-04-27 19:42:32277 base::flat_set<KeyType> removed_ids_;
[email protected]9de09f82009-08-17 20:13:53278
initial.commitd7cae122008-07-26 21:49:38279 // The next ID that we will return from Add()
[email protected]9e7e0e02010-01-25 23:25:16280 KeyType next_id_;
initial.commitd7cae122008-07-26 21:49:38281
282 HashTable data_;
[email protected]a6ed9432009-07-01 22:35:26283
[email protected]a6ed9432009-07-01 22:35:26284 // See description above setter.
285 bool check_on_null_data_;
[email protected]9de09f82009-08-17 20:13:53286
tzikfd754ee2018-03-28 15:49:28287 SEQUENCE_CHECKER(sequence_checker_);
initial.commitd7cae122008-07-26 21:49:38288};
289
Brett Wilsonf976d3f2017-08-18 17:23:39290} // namespace base
291
292#endif // BASE_CONTAINERS_ID_MAP_H_