id_map.h 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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/containers/flat_set.h"
  14. #include "base/logging.h"
  15. #include "base/macros.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() {
  44. // Many IDMap's are static, and hence will be destroyed on the main
  45. // thread. However, all the accesses may take place on another thread (or
  46. // sequence), such as the IO thread. Detaching again to clean this up.
  47. DETACH_FROM_SEQUENCE(sequence_checker_);
  48. }
  49. // Sets whether Add and Replace should DCHECK if passed in NULL data.
  50. // Default is false.
  51. void set_check_on_null_data(bool value) { check_on_null_data_ = value; }
  52. // Adds a view with an automatically generated unique ID. See AddWithID.
  53. KeyType Add(V data) { return AddInternal(std::move(data)); }
  54. // Adds a new data member with the specified ID. The ID must not be in
  55. // the list. The caller either must generate all unique IDs itself and use
  56. // this function, or allow this object to generate IDs and call Add. These
  57. // two methods may not be mixed, or duplicate IDs may be generated.
  58. void AddWithID(V data, KeyType id) { AddWithIDInternal(std::move(data), id); }
  59. void Remove(KeyType id) {
  60. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  61. typename HashTable::iterator i = data_.find(id);
  62. if (i == data_.end() || IsRemoved(id)) {
  63. NOTREACHED() << "Attempting to remove an item not in the list";
  64. return;
  65. }
  66. if (iteration_depth_ == 0) {
  67. data_.erase(i);
  68. } else {
  69. removed_ids_.insert(id);
  70. }
  71. }
  72. // Replaces the value for |id| with |new_data| and returns the existing value.
  73. // Should only be called with an already added id.
  74. V Replace(KeyType id, V new_data) {
  75. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  76. DCHECK(!check_on_null_data_ || new_data);
  77. typename HashTable::iterator i = data_.find(id);
  78. DCHECK(i != data_.end());
  79. DCHECK(!IsRemoved(id));
  80. using std::swap;
  81. swap(i->second, new_data);
  82. return new_data;
  83. }
  84. void Clear() {
  85. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  86. if (iteration_depth_ == 0) {
  87. data_.clear();
  88. } else {
  89. removed_ids_.reserve(data_.size());
  90. removed_ids_.insert(KeyIterator(data_.begin()), KeyIterator(data_.end()));
  91. }
  92. }
  93. bool IsEmpty() const {
  94. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  95. return size() == 0u;
  96. }
  97. T* Lookup(KeyType id) const {
  98. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  99. typename HashTable::const_iterator i = data_.find(id);
  100. if (i == data_.end() || !i->second || IsRemoved(id))
  101. return nullptr;
  102. return &*i->second;
  103. }
  104. size_t size() const {
  105. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  106. return data_.size() - removed_ids_.size();
  107. }
  108. #if defined(UNIT_TEST)
  109. int iteration_depth() const {
  110. return iteration_depth_;
  111. }
  112. #endif // defined(UNIT_TEST)
  113. // It is safe to remove elements from the map during iteration. All iterators
  114. // will remain valid.
  115. template<class ReturnType>
  116. class Iterator {
  117. public:
  118. Iterator(IDMap<V, K>* map) : map_(map), iter_(map_->data_.begin()) {
  119. Init();
  120. }
  121. Iterator(const Iterator& iter)
  122. : map_(iter.map_),
  123. iter_(iter.iter_) {
  124. Init();
  125. }
  126. const Iterator& operator=(const Iterator& iter) {
  127. map_ = iter.map;
  128. iter_ = iter.iter;
  129. Init();
  130. return *this;
  131. }
  132. ~Iterator() {
  133. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  134. // We're going to decrement iteration depth. Make sure it's greater than
  135. // zero so that it doesn't become negative.
  136. DCHECK_LT(0, map_->iteration_depth_);
  137. if (--map_->iteration_depth_ == 0)
  138. map_->Compact();
  139. }
  140. bool IsAtEnd() const {
  141. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  142. return iter_ == map_->data_.end();
  143. }
  144. KeyType GetCurrentKey() const {
  145. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  146. return iter_->first;
  147. }
  148. ReturnType* GetCurrentValue() const {
  149. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  150. if (!iter_->second || map_->IsRemoved(iter_->first))
  151. return nullptr;
  152. return &*iter_->second;
  153. }
  154. void Advance() {
  155. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  156. ++iter_;
  157. SkipRemovedEntries();
  158. }
  159. private:
  160. void Init() {
  161. DCHECK_CALLED_ON_VALID_SEQUENCE(map_->sequence_checker_);
  162. ++map_->iteration_depth_;
  163. SkipRemovedEntries();
  164. }
  165. void SkipRemovedEntries() {
  166. while (iter_ != map_->data_.end() && map_->IsRemoved(iter_->first))
  167. ++iter_;
  168. }
  169. IDMap<V, K>* map_;
  170. typename HashTable::const_iterator iter_;
  171. };
  172. typedef Iterator<T> iterator;
  173. typedef Iterator<const T> const_iterator;
  174. private:
  175. // Transforms a map iterator to an iterator on the keys of the map.
  176. // Used by Clear() to populate |removed_ids_| in bulk.
  177. struct KeyIterator : std::iterator<std::forward_iterator_tag, KeyType> {
  178. using inner_iterator = typename HashTable::iterator;
  179. inner_iterator iter_;
  180. KeyIterator(inner_iterator iter) : iter_(iter) {}
  181. KeyType operator*() const { return iter_->first; }
  182. KeyIterator& operator++() {
  183. ++iter_;
  184. return *this;
  185. }
  186. KeyIterator operator++(int) { return KeyIterator(iter_++); }
  187. bool operator==(const KeyIterator& other) const {
  188. return iter_ == other.iter_;
  189. }
  190. bool operator!=(const KeyIterator& other) const {
  191. return iter_ != other.iter_;
  192. }
  193. };
  194. KeyType AddInternal(V data) {
  195. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  196. DCHECK(!check_on_null_data_ || data);
  197. KeyType this_id = next_id_;
  198. DCHECK(data_.find(this_id) == data_.end()) << "Inserting duplicate item";
  199. data_[this_id] = std::move(data);
  200. next_id_++;
  201. return this_id;
  202. }
  203. void AddWithIDInternal(V data, KeyType id) {
  204. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  205. DCHECK(!check_on_null_data_ || data);
  206. if (IsRemoved(id)) {
  207. removed_ids_.erase(id);
  208. } else {
  209. DCHECK(data_.find(id) == data_.end()) << "Inserting duplicate item";
  210. }
  211. data_[id] = std::move(data);
  212. }
  213. bool IsRemoved(KeyType key) const {
  214. return removed_ids_.find(key) != removed_ids_.end();
  215. }
  216. void Compact() {
  217. DCHECK_EQ(0, iteration_depth_);
  218. for (const auto& i : removed_ids_)
  219. data_.erase(i);
  220. removed_ids_.clear();
  221. }
  222. // Keep track of how many iterators are currently iterating on us to safely
  223. // handle removing items during iteration.
  224. int iteration_depth_;
  225. // Keep set of IDs that should be removed after the outermost iteration has
  226. // finished. This way we manage to not invalidate the iterator when an element
  227. // is removed.
  228. base::flat_set<KeyType> removed_ids_;
  229. // The next ID that we will return from Add()
  230. KeyType next_id_;
  231. HashTable data_;
  232. // See description above setter.
  233. bool check_on_null_data_;
  234. SEQUENCE_CHECKER(sequence_checker_);
  235. DISALLOW_COPY_AND_ASSIGN(IDMap);
  236. };
  237. } // namespace base
  238. #endif // BASE_CONTAINERS_ID_MAP_H_