id_map.h 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. // Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_CONTAINERS_ID_MAP_H_
  5. #define BASE_CONTAINERS_ID_MAP_H_
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <memory>
  9. #include <set>
  10. #include <type_traits>
  11. #include <unordered_map>
  12. #include <utility>
  13. #include "base/check_op.h"
  14. #include "base/containers/flat_set.h"
  15. #include "base/notreached.h"
  16. #include "base/sequence_checker.h"
  17. namespace base {
  18. // This object maintains a list of IDs that can be quickly converted to
  19. // pointers to objects. It is implemented as a hash table, optimized for
  20. // relatively small data sets (in the common case, there will be exactly one
  21. // item in the list).
  22. //
  23. // Items can be inserted into the container with arbitrary ID, but the caller
  24. // must ensure they are unique. Inserting IDs and relying on automatically
  25. // generated ones is not allowed because they can collide.
  26. // The map's value type (the V param) can be any dereferenceable type, such as a
  27. // raw pointer or smart pointer
  28. template <typename V, typename K = int32_t>
  29. class IDMap final {
  30. public:
  31. using KeyType = K;
  32. private:
  33. using T = typename std::remove_reference<decltype(*V())>::type;
  34. using HashTable = std::unordered_map<KeyType, V>;
  35. public:
  36. IDMap() : iteration_depth_(0), next_id_(1), check_on_null_data_(false) {
  37. // A number of consumers of IDMap create it on one thread but always
  38. // access it from a different, but consistent, thread (or sequence)
  39. // post-construction. The first call to CalledOnValidSequence() will re-bind
  40. // it.
  41. DETACH_FROM_SEQUENCE(sequence_checker_);
  42. }
  43. IDMap(const IDMap&) = delete;
  44. IDMap& operator=(const IDMap&) = delete;
  45. ~IDMap() {
  46. // Many IDMap's are static, and hence will be destroyed on the main
  47. // thread. However, all the accesses may take place on another thread (or
  48. // sequence), such as the IO thread. Detaching again to clean this up.
  49. DETACH_FROM_SEQUENCE(sequence_checker_);
  50. }
  51. // Sets whether Add and Replace should DCHECK if passed in NULL data.
  52. // Default is false.
  53. void set_check_on_null_data(bool value) { check_on_null_data_ = value; }
  54. // Adds a view with an automatically generated unique ID. See AddWithID.
  55. KeyType Add(V data) { return AddInternal(std::move(data)); }
  56. // Adds a new data member with the specified ID. The ID must not be in
  57. // the list. The caller either must generate all unique IDs itself and use
  58. // this function, or allow this object to generate IDs and call Add. These
  59. // two methods may not be mixed, or duplicate IDs may be generated.
  60. void AddWithID(V data, KeyType id) { AddWithIDInternal(std::move(data), id); }
  61. void Remove(KeyType id) {
  62. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  63. typename HashTable::iterator i = data_.find(id);
  64. if (i == data_.end() || IsRemoved(id)) {
  65. NOTREACHED() << "Attempting to remove an item not in the list";
  66. return;
  67. }
  68. if (iteration_depth_ == 0) {
  69. data_.erase(i);
  70. } else {
  71. removed_ids_.insert(id);
  72. }
  73. }
  74. // Replaces the value for |id| with |new_data| and returns the existing value.
  75. // Should only be called with an already added id.
  76. V Replace(KeyType id, V new_data) {
  77. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  78. DCHECK(!check_on_null_data_ || new_data);
  79. typename HashTable::iterator i = data_.find(id);
  80. DCHECK(i != data_.end());
  81. DCHECK(!IsRemoved(id));
  82. using std::swap;
  83. swap(i->second, new_data);
  84. return new_data;
  85. }
  86. void Clear() {
  87. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  88. if (iteration_depth_ == 0) {
  89. data_.clear();
  90. } else {
  91. removed_ids_.reserve(data_.size());
  92. removed_ids_.insert(KeyIterator(data_.begin()), KeyIterator(data_.end()));
  93. }
  94. }
  95. bool IsEmpty() const {
  96. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  97. return size() == 0u;
  98. }
  99. T* Lookup(KeyType id) const {
  100. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  101. typename HashTable::const_iterator i = data_.find(id);
  102. if (i == data_.end() || !i->second || IsRemoved(id))
  103. return nullptr;
  104. return &*i->second;
  105. }
  106. size_t size() const {
  107. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  108. return data_.size() - removed_ids_.size();
  109. }
  110. #if defined(UNIT_TEST)
  111. int iteration_depth() const {
  112. return iteration_depth_;
  113. }
  114. #endif // defined(UNIT_TEST)
  115. // It is safe to remove elements from the map during iteration. All iterators
  116. // will remain valid.
  117. template<class ReturnType>
  118. class Iterator {
  119. public:
  120. Iterator(IDMap<V, K>* map) : map_(map), iter_(map_->data_.begin()) {
  121. Init();
  122. }
  123. Iterator(const Iterator& iter)
  124. : map_(iter.map_),
  125. iter_(iter.iter_) {
  126. Init();
  127. }
  128. const Iterator& operator=(const Iterator& iter) {
  129. map_ = iter.map;
  130. iter_ = iter.iter;
  131. Init();
  132. return *this;
  133. }
  134. ~Iterator() {
  135. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  136. // We're going to decrement iteration depth. Make sure it's greater than
  137. // zero so that it doesn't become negative.
  138. DCHECK_LT(0, map_->iteration_depth_);
  139. if (--map_->iteration_depth_ == 0)
  140. map_->Compact();
  141. }
  142. bool IsAtEnd() const {
  143. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  144. return iter_ == map_->data_.end();
  145. }
  146. KeyType GetCurrentKey() const {
  147. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  148. return iter_->first;
  149. }
  150. ReturnType* GetCurrentValue() const {
  151. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  152. if (!iter_->second || map_->IsRemoved(iter_->first))
  153. return nullptr;
  154. return &*iter_->second;
  155. }
  156. void Advance() {
  157. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  158. ++iter_;
  159. SkipRemovedEntries();
  160. }
  161. private:
  162. void Init() {
  163. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  164. ++map_->iteration_depth_;
  165. SkipRemovedEntries();
  166. }
  167. void SkipRemovedEntries() {
  168. while (iter_ != map_->data_.end() && map_->IsRemoved(iter_->first))
  169. ++iter_;
  170. }
  171. IDMap<V, K>* map_;
  172. typename HashTable::const_iterator iter_;
  173. };
  174. typedef Iterator<T> iterator;
  175. typedef Iterator<const T> const_iterator;
  176. private:
  177. // Transforms a map iterator to an iterator on the keys of the map.
  178. // Used by Clear() to populate |removed_ids_| in bulk.
  179. struct KeyIterator : std::iterator<std::forward_iterator_tag, KeyType> {
  180. using inner_iterator = typename HashTable::iterator;
  181. inner_iterator iter_;
  182. KeyIterator(inner_iterator iter) : iter_(iter) {}
  183. KeyType operator*() const { return iter_->first; }
  184. KeyIterator& operator++() {
  185. ++iter_;
  186. return *this;
  187. }
  188. KeyIterator operator++(int) { return KeyIterator(iter_++); }
  189. bool operator==(const KeyIterator& other) const {
  190. return iter_ == other.iter_;
  191. }
  192. bool operator!=(const KeyIterator& other) const {
  193. return iter_ != other.iter_;
  194. }
  195. };
  196. KeyType AddInternal(V data) {
  197. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  198. DCHECK(!check_on_null_data_ || data);
  199. KeyType this_id = next_id_;
  200. DCHECK(data_.find(this_id) == data_.end()) << "Inserting duplicate item";
  201. data_[this_id] = std::move(data);
  202. next_id_++;
  203. return this_id;
  204. }
  205. void AddWithIDInternal(V data, KeyType id) {
  206. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  207. DCHECK(!check_on_null_data_ || data);
  208. if (IsRemoved(id)) {
  209. removed_ids_.erase(id);
  210. } else {
  211. DCHECK(data_.find(id) == data_.end()) << "Inserting duplicate item";
  212. }
  213. data_[id] = std::move(data);
  214. }
  215. bool IsRemoved(KeyType key) const {
  216. return removed_ids_.find(key) != removed_ids_.end();
  217. }
  218. void Compact() {
  219. DCHECK_EQ(0, iteration_depth_);
  220. for (const auto& i : removed_ids_)
  221. data_.erase(i);
  222. removed_ids_.clear();
  223. }
  224. // Keep track of how many iterators are currently iterating on us to safely
  225. // handle removing items during iteration.
  226. int iteration_depth_;
  227. // Keep set of IDs that should be removed after the outermost iteration has
  228. // finished. This way we manage to not invalidate the iterator when an element
  229. // is removed.
  230. base::flat_set<KeyType> removed_ids_;
  231. // The next ID that we will return from Add()
  232. KeyType next_id_;
  233. HashTable data_;
  234. // See description above setter.
  235. bool check_on_null_data_;
  236. SEQUENCE_CHECKER(sequence_checker_);
  237. };
  238. } // namespace base
  239. #endif // BASE_CONTAINERS_ID_MAP_H_