Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(283)

Side by Side Diff: base/observer_list.h

Issue 2340583005: Base ObserverList: Add basic support for standard C++ iterators. (Closed)
Patch Set: Remove excessive mutable. Created 4 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | base/observer_list_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #ifndef BASE_OBSERVER_LIST_H_ 5 #ifndef BASE_OBSERVER_LIST_H_
6 #define BASE_OBSERVER_LIST_H_ 6 #define BASE_OBSERVER_LIST_H_
7 7
8 #include <stddef.h> 8 #include <stddef.h>
9 9
10 #include <algorithm> 10 #include <algorithm>
11 #include <limits> 11 #include <limits>
12 #include <vector> 12 #include <vector>
13 13
14 #include "base/gtest_prod_util.h"
14 #include "base/logging.h" 15 #include "base/logging.h"
15 #include "base/macros.h" 16 #include "base/macros.h"
16 #include "base/memory/weak_ptr.h" 17 #include "base/memory/weak_ptr.h"
17 #include "base/stl_util.h" 18 #include "base/stl_util.h"
18 19
19 /////////////////////////////////////////////////////////////////////////////// 20 ///////////////////////////////////////////////////////////////////////////////
20 // 21 //
21 // OVERVIEW: 22 // OVERVIEW:
22 // 23 //
23 // A container for a list of observers. Unlike a normal STL vector or list, 24 // A container for a list of observers. Unlike a normal STL vector or list,
(...skipping 15 matching lines...) Expand all
39 // 40 //
40 // void AddObserver(Observer* obs) { 41 // void AddObserver(Observer* obs) {
41 // observer_list_.AddObserver(obs); 42 // observer_list_.AddObserver(obs);
42 // } 43 // }
43 // 44 //
44 // void RemoveObserver(Observer* obs) { 45 // void RemoveObserver(Observer* obs) {
45 // observer_list_.RemoveObserver(obs); 46 // observer_list_.RemoveObserver(obs);
46 // } 47 // }
47 // 48 //
48 // void NotifyFoo() { 49 // void NotifyFoo() {
49 // FOR_EACH_OBSERVER(Observer, observer_list_, OnFoo(this)); 50 // for (auto& observer : observer_list_)
51 // observer.OnFoo(this);
50 // } 52 // }
51 // 53 //
52 // void NotifyBar(int x, int y) { 54 // void NotifyBar(int x, int y) {
53 // FOR_EACH_OBSERVER(Observer, observer_list_, OnBar(this, x, y)); 55 // for (FooList::iterator i = observer_list.begin(),
56 // e = observer_list.end(); i != e; ++i)
57 // i->OnBar(this, x, y);
54 // } 58 // }
55 // 59 //
56 // private: 60 // private:
57 // base::ObserverList<Observer> observer_list_; 61 // base::ObserverList<Observer> observer_list_;
58 // }; 62 // };
59 // 63 //
60 // 64 //
61 /////////////////////////////////////////////////////////////////////////////// 65 ///////////////////////////////////////////////////////////////////////////////
62 66
63 namespace base { 67 namespace base {
64 68
65 template <typename ObserverType> 69 template <typename ObserverType>
66 class ObserverListThreadSafe; 70 class ObserverListThreadSafe;
67 71
68 template <class ObserverType> 72 template <class ObserverType>
69 class ObserverListBase 73 class ObserverListBase
70 : public SupportsWeakPtr<ObserverListBase<ObserverType>> { 74 : public SupportsWeakPtr<ObserverListBase<ObserverType>> {
71 public: 75 public:
72 // Enumeration of which observers are notified. 76 // Enumeration of which observers are notified.
73 enum NotificationType { 77 enum NotificationType {
74 // Specifies that any observers added during notification are notified. 78 // Specifies that any observers added during notification are notified.
75 // This is the default type if non type is provided to the constructor. 79 // This is the default type if non type is provided to the constructor.
76 NOTIFY_ALL, 80 NOTIFY_ALL,
77 81
78 // Specifies that observers added while sending out notification are not 82 // Specifies that observers added while sending out notification are not
79 // notified. 83 // notified.
80 NOTIFY_EXISTING_ONLY 84 NOTIFY_EXISTING_ONLY
81 }; 85 };
82 86
83 // An iterator class that can be used to access the list of observers. See 87 // An iterator class that can be used to access the list of observers.
84 // also the FOR_EACH_OBSERVER macro defined below. 88 template <class ContainerType>
85 class Iterator { 89 class Iter {
86 public: 90 public:
87 explicit Iterator(ObserverListBase<ObserverType>* list); 91 Iter();
88 ~Iterator(); 92 explicit Iter(ContainerType* list);
93 ~Iter();
94
95 // Deprecated.
89 ObserverType* GetNext(); 96 ObserverType* GetNext();
90 97
98 // A workaround for C2244. MSVC requires fully qualified type name for
99 // return type on a function definition to match a function declaration.
100 using ThisType =
101 typename ObserverListBase<ObserverType>::template Iter<ContainerType>;
102
103 bool operator==(const Iter& other) const;
104 bool operator!=(const Iter& other) const;
105 ThisType& operator++();
106 ObserverType* operator->() const;
107 ObserverType& operator*() const;
108
91 private: 109 private:
110 FRIEND_TEST_ALL_PREFIXES(ObserverListTest, BasicStdIterator);
111 FRIEND_TEST_ALL_PREFIXES(ObserverListTest, StdIteratorRemoveFront);
112
113 ObserverType* GetCurrent() const;
114 void EnsureValidIndex();
115
116 size_t clamped_max_index() const {
117 return std::min(max_index_, list_->observers_.size());
118 }
119
120 bool is_end() const { return !list_ || index_ == clamped_max_index(); }
121
92 WeakPtr<ObserverListBase<ObserverType>> list_; 122 WeakPtr<ObserverListBase<ObserverType>> list_;
123 // When initially constructed and each time the iterator is incremented,
124 // |index_| is guaranteed to point to a non-null index if the iterator
125 // has not reached the end of the ObserverList.
93 size_t index_; 126 size_t index_;
94 size_t max_index_; 127 size_t max_index_;
95 }; 128 };
96 129
130 using Iterator = Iter<ObserverListBase<ObserverType>>;
131
132 using iterator = Iter<ObserverListBase<ObserverType>>;
133 iterator begin() {
134 // An optimization: do not involve weak pointers for empty list.
135 // Note: can't use ?: operator here due to some MSVC bug (unit tests fail)
136 if (observers_.empty())
137 return iterator();
138 return iterator(this);
139 }
140 iterator end() { return iterator(); }
141
142 using const_iterator = Iter<const ObserverListBase<ObserverType>>;
143 const_iterator begin() const {
144 if (observers_.empty())
145 return const_iterator();
146 return const_iterator(this);
147 }
148 const_iterator end() const { return const_iterator(); }
149
97 ObserverListBase() : notify_depth_(0), type_(NOTIFY_ALL) {} 150 ObserverListBase() : notify_depth_(0), type_(NOTIFY_ALL) {}
98 explicit ObserverListBase(NotificationType type) 151 explicit ObserverListBase(NotificationType type)
99 : notify_depth_(0), type_(type) {} 152 : notify_depth_(0), type_(type) {}
100 153
101 // Add an observer to the list. An observer should not be added to 154 // Add an observer to the list. An observer should not be added to
102 // the same list more than once. 155 // the same list more than once.
103 void AddObserver(ObserverType* obs); 156 void AddObserver(ObserverType* obs);
104 157
105 // Remove an observer from the list if it is in the list. 158 // Remove an observer from the list if it is in the list.
106 void RemoveObserver(ObserverType* obs); 159 void RemoveObserver(ObserverType* obs);
(...skipping 10 matching lines...) Expand all
117 170
118 private: 171 private:
119 friend class ObserverListThreadSafe<ObserverType>; 172 friend class ObserverListThreadSafe<ObserverType>;
120 173
121 typedef std::vector<ObserverType*> ListType; 174 typedef std::vector<ObserverType*> ListType;
122 175
123 ListType observers_; 176 ListType observers_;
124 int notify_depth_; 177 int notify_depth_;
125 NotificationType type_; 178 NotificationType type_;
126 179
127 friend class ObserverListBase::Iterator; 180 template <class ContainerType>
181 friend class Iter;
128 182
129 DISALLOW_COPY_AND_ASSIGN(ObserverListBase); 183 DISALLOW_COPY_AND_ASSIGN(ObserverListBase);
130 }; 184 };
131 185
132 template <class ObserverType> 186 template <class ObserverType>
133 ObserverListBase<ObserverType>::Iterator::Iterator( 187 template <class ContainerType>
134 ObserverListBase<ObserverType>* list) 188 ObserverListBase<ObserverType>::Iter<ContainerType>::Iter()
135 : list_(list->AsWeakPtr()), 189 : index_(0), max_index_(0) {}
190
191 template <class ObserverType>
192 template <class ContainerType>
193 ObserverListBase<ObserverType>::Iter<ContainerType>::Iter(ContainerType* list)
194 : list_(const_cast<ObserverListBase<ObserverType>*>(list)->AsWeakPtr()),
136 index_(0), 195 index_(0),
137 max_index_(list->type_ == NOTIFY_ALL ? std::numeric_limits<size_t>::max() 196 max_index_(list->type_ == NOTIFY_ALL ? std::numeric_limits<size_t>::max()
138 : list->observers_.size()) { 197 : list->observers_.size()) {
198 EnsureValidIndex();
199 DCHECK(list_);
139 ++list_->notify_depth_; 200 ++list_->notify_depth_;
140 } 201 }
141 202
142 template <class ObserverType> 203 template <class ObserverType>
143 ObserverListBase<ObserverType>::Iterator::~Iterator() { 204 template <class ContainerType>
144 if (list_.get() && --list_->notify_depth_ == 0) 205 ObserverListBase<ObserverType>::Iter<ContainerType>::~Iter() {
206 if (list_ && --list_->notify_depth_ == 0)
145 list_->Compact(); 207 list_->Compact();
146 } 208 }
147 209
148 template <class ObserverType> 210 template <class ObserverType>
149 ObserverType* ObserverListBase<ObserverType>::Iterator::GetNext() { 211 template <class ContainerType>
150 if (!list_.get()) 212 bool ObserverListBase<ObserverType>::Iter<ContainerType>::operator==(
151 return nullptr; 213 const Iter& other) const {
152 ListType& observers = list_->observers_; 214 if (is_end() && other.is_end())
153 // Advance if the current element is null 215 return true;
154 size_t max_index = std::min(max_index_, observers.size()); 216 return list_.get() == other.list_.get() && index_ == other.index_;
155 while (index_ < max_index && !observers[index_])
156 ++index_;
157 return index_ < max_index ? observers[index_++] : nullptr;
158 } 217 }
159 218
160 template <class ObserverType> 219 template <class ObserverType>
220 template <class ContainerType>
221 bool ObserverListBase<ObserverType>::Iter<ContainerType>::operator!=(
222 const Iter& other) const {
223 return !operator==(other);
224 }
225
226 template <class ObserverType>
227 template <class ContainerType>
228 typename ObserverListBase<ObserverType>::template Iter<ContainerType>&
229 ObserverListBase<ObserverType>::Iter<ContainerType>::operator++() {
230 if (list_) {
231 ++index_;
232 EnsureValidIndex();
233 }
234 return *this;
235 }
236
237 template <class ObserverType>
238 template <class ContainerType>
239 ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::operator->()
240 const {
241 ObserverType* current = GetCurrent();
242 DCHECK(current);
243 return current;
244 }
245
246 template <class ObserverType>
247 template <class ContainerType>
248 ObserverType& ObserverListBase<ObserverType>::Iter<ContainerType>::operator*()
249 const {
250 ObserverType* current = GetCurrent();
251 DCHECK(current);
252 return *current;
253 }
254
255 template <class ObserverType>
256 template <class ContainerType>
257 ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::GetCurrent()
258 const {
259 if (!list_)
260 return nullptr;
261 return index_ < clamped_max_index() ? list_->observers_[index_] : nullptr;
262 }
263
264 template <class ObserverType>
265 template <class ContainerType>
266 void ObserverListBase<ObserverType>::Iter<ContainerType>::EnsureValidIndex() {
267 if (!list_)
268 return;
269
270 size_t max_index = clamped_max_index();
271 while (index_ < max_index && !list_->observers_[index_])
272 ++index_;
273 }
274
275 template <class ObserverType>
276 template <class ContainerType>
277 ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::GetNext() {
278 EnsureValidIndex();
279 ObserverType* current = GetCurrent();
280 operator++();
281 return current;
282 }
283
284 template <class ObserverType>
161 void ObserverListBase<ObserverType>::AddObserver(ObserverType* obs) { 285 void ObserverListBase<ObserverType>::AddObserver(ObserverType* obs) {
162 DCHECK(obs); 286 DCHECK(obs);
163 if (ContainsValue(observers_, obs)) { 287 if (ContainsValue(observers_, obs)) {
164 NOTREACHED() << "Observers can only be added once!"; 288 NOTREACHED() << "Observers can only be added once!";
165 return; 289 return;
166 } 290 }
167 observers_.push_back(obs); 291 observers_.push_back(obs);
168 } 292 }
169 293
170 template <class ObserverType> 294 template <class ObserverType>
(...skipping 27 matching lines...) Expand all
198 it != observers_.end(); ++it) { 322 it != observers_.end(); ++it) {
199 *it = nullptr; 323 *it = nullptr;
200 } 324 }
201 } else { 325 } else {
202 observers_.clear(); 326 observers_.clear();
203 } 327 }
204 } 328 }
205 329
206 template <class ObserverType> 330 template <class ObserverType>
207 void ObserverListBase<ObserverType>::Compact() { 331 void ObserverListBase<ObserverType>::Compact() {
208 observers_.erase( 332 observers_.erase(std::remove(observers_.begin(), observers_.end(), nullptr),
209 std::remove(observers_.begin(), observers_.end(), nullptr), 333 observers_.end());
210 observers_.end());
211 } 334 }
212 335
213 template <class ObserverType, bool check_empty = false> 336 template <class ObserverType, bool check_empty = false>
214 class ObserverList : public ObserverListBase<ObserverType> { 337 class ObserverList : public ObserverListBase<ObserverType> {
215 public: 338 public:
216 typedef typename ObserverListBase<ObserverType>::NotificationType 339 typedef typename ObserverListBase<ObserverType>::NotificationType
217 NotificationType; 340 NotificationType;
218 341
219 ObserverList() {} 342 ObserverList() {}
220 explicit ObserverList(NotificationType type) 343 explicit ObserverList(NotificationType type)
221 : ObserverListBase<ObserverType>(type) {} 344 : ObserverListBase<ObserverType>(type) {}
222 345
223 ~ObserverList() { 346 ~ObserverList() {
224 // When check_empty is true, assert that the list is empty on destruction. 347 // When check_empty is true, assert that the list is empty on destruction.
225 if (check_empty) { 348 if (check_empty) {
226 ObserverListBase<ObserverType>::Compact(); 349 ObserverListBase<ObserverType>::Compact();
227 DCHECK_EQ(ObserverListBase<ObserverType>::size(), 0U); 350 DCHECK_EQ(ObserverListBase<ObserverType>::size(), 0U);
228 } 351 }
229 } 352 }
230 353
231 bool might_have_observers() const { 354 bool might_have_observers() const {
232 return ObserverListBase<ObserverType>::size() != 0; 355 return ObserverListBase<ObserverType>::size() != 0;
233 } 356 }
234 }; 357 };
235 358
236 #define FOR_EACH_OBSERVER(ObserverType, observer_list, func) \ 359 // Deprecated. Use the range-based for loop instead.
237 do { \ 360 #define FOR_EACH_OBSERVER(ObserverType, observer_list, func) \
238 if ((observer_list).might_have_observers()) { \ 361 do { \
239 typename base::ObserverListBase<ObserverType>::Iterator \ 362 for (ObserverType & o : observer_list) \
240 it_inside_observer_macro(&observer_list); \ 363 o.func; \
241 ObserverType* obs; \
242 while ((obs = it_inside_observer_macro.GetNext()) != nullptr) \
243 obs->func; \
244 } \
245 } while (0) 364 } while (0)
246 365
247 } // namespace base 366 } // namespace base
248 367
249 #endif // BASE_OBSERVER_LIST_H_ 368 #endif // BASE_OBSERVER_LIST_H_
OLDNEW
« no previous file with comments | « no previous file | base/observer_list_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698