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

Side by Side Diff: base/observer_list.h

Issue 2340583005: Base ObserverList: Add basic support for standard C++ iterators. (Closed)
Patch Set: Fix bugs. Add new tests. 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:
92 WeakPtr<ObserverListBase<ObserverType>> list_; 110 FRIEND_TEST_ALL_PREFIXES(ObserverListTest, BasicStdIterator);
111 FRIEND_TEST_ALL_PREFIXES(ObserverListTest, StdIteratorRemoveFront);
112
113 ObserverType* GetCurrent() const;
114 size_t GetNonNullIndex() const;
115
116 size_t clamped_max_index() const {
117 return std::min(max_index_, list_->observers_.size());
118 }
119
120 bool is_end() const {
121 return !list_ || index_ == clamped_max_index();
122 }
123
124 WeakPtr<ContainerType> list_;
125 // When initially constructed and each time the iterator is incremented,
126 // |index_| is guaranteed to point to a non-null index if the iterator
127 // has not reached the end of the ObserverList.
93 size_t index_; 128 size_t index_;
94 size_t max_index_; 129 size_t max_index_;
95 }; 130 };
96 131
132 using Iterator = Iter<ObserverListBase<ObserverType>>;
133
134 using iterator = Iter<ObserverListBase<ObserverType>>;
135 iterator begin() {
136 // An optimization: do not involve weak pointers for empty list.
137 // Note: can't use ?: operator here due to some MSVC bug (unit tests fail)
138 if (observers_.empty())
139 return iterator();
140 return iterator(this);
141 }
142 iterator end() { return iterator(); }
143
144 using const_iterator = Iter<const ObserverListBase<ObserverType>>;
145 const_iterator begin() const {
146 if (observers_.empty())
147 return const_iterator();
148 return const_iterator(this);
149 }
150 const_iterator end() const { return const_iterator(); }
151
97 ObserverListBase() : notify_depth_(0), type_(NOTIFY_ALL) {} 152 ObserverListBase() : notify_depth_(0), type_(NOTIFY_ALL) {}
98 explicit ObserverListBase(NotificationType type) 153 explicit ObserverListBase(NotificationType type)
99 : notify_depth_(0), type_(type) {} 154 : notify_depth_(0), type_(type) {}
100 155
101 // Add an observer to the list. An observer should not be added to 156 // Add an observer to the list. An observer should not be added to
102 // the same list more than once. 157 // the same list more than once.
103 void AddObserver(ObserverType* obs); 158 void AddObserver(ObserverType* obs);
104 159
105 // Remove an observer from the list if it is in the list. 160 // Remove an observer from the list if it is in the list.
106 void RemoveObserver(ObserverType* obs); 161 void RemoveObserver(ObserverType* obs);
107 162
108 // Determine whether a particular observer is in the list. 163 // Determine whether a particular observer is in the list.
109 bool HasObserver(const ObserverType* observer) const; 164 bool HasObserver(const ObserverType* observer) const;
110 165
111 void Clear(); 166 void Clear();
112 167
113 protected: 168 protected:
114 size_t size() const { return observers_.size(); } 169 size_t size() const { return observers_.size(); }
115 170
116 void Compact(); 171 // Defragments the list despite const.
172 void Compact() const;
117 173
118 private: 174 private:
119 friend class ObserverListThreadSafe<ObserverType>; 175 friend class ObserverListThreadSafe<ObserverType>;
120 176
121 typedef std::vector<ObserverType*> ListType; 177 typedef std::vector<ObserverType*> ListType;
122 178
123 ListType observers_; 179 ListType observers_;
124 int notify_depth_; 180 mutable int notify_depth_;
125 NotificationType type_; 181 NotificationType type_;
126 182
127 friend class ObserverListBase::Iterator; 183 template <class ContainerType>
184 friend class Iter;
128 185
129 DISALLOW_COPY_AND_ASSIGN(ObserverListBase); 186 DISALLOW_COPY_AND_ASSIGN(ObserverListBase);
130 }; 187 };
131 188
132 template <class ObserverType> 189 template <class ObserverType>
133 ObserverListBase<ObserverType>::Iterator::Iterator( 190 template <class ContainerType>
134 ObserverListBase<ObserverType>* list) 191 ObserverListBase<ObserverType>::Iter<ContainerType>::Iter()
135 : list_(list->AsWeakPtr()), 192 : index_(0), max_index_(0) {
193 }
194
195 template <class ObserverType>
196 template <class ContainerType>
197 ObserverListBase<ObserverType>::Iter<ContainerType>::Iter(ContainerType* list)
198 : list_(const_cast<ObserverListBase<ObserverType>*>(list)->AsWeakPtr()),
136 index_(0), 199 index_(0),
137 max_index_(list->type_ == NOTIFY_ALL ? std::numeric_limits<size_t>::max() 200 max_index_(list->type_ == NOTIFY_ALL ? std::numeric_limits<size_t>::max()
138 : list->observers_.size()) { 201 : list->observers_.size()) {
202 index_ = GetNonNullIndex();
139 ++list_->notify_depth_; 203 ++list_->notify_depth_;
140 } 204 }
141 205
142 template <class ObserverType> 206 template <class ObserverType>
143 ObserverListBase<ObserverType>::Iterator::~Iterator() { 207 template <class ContainerType>
144 if (list_.get() && --list_->notify_depth_ == 0) 208 ObserverListBase<ObserverType>::Iter<ContainerType>::~Iter() {
209 if (list_ && --list_->notify_depth_ == 0)
145 list_->Compact(); 210 list_->Compact();
146 } 211 }
147 212
148 template <class ObserverType> 213 template <class ObserverType>
149 ObserverType* ObserverListBase<ObserverType>::Iterator::GetNext() { 214 template <class ContainerType>
150 if (!list_.get()) 215 bool ObserverListBase<ObserverType>::Iter<ContainerType>::operator==(
151 return nullptr; 216 const Iter& other) const {
152 ListType& observers = list_->observers_; 217 if (is_end() && other.is_end())
dcheng 2016/10/07 05:43:16 Good catch on the is_end() thing! I think with one
153 // Advance if the current element is null 218 return true;
154 size_t max_index = std::min(max_index_, observers.size()); 219 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 } 220 }
159 221
160 template <class ObserverType> 222 template <class ObserverType>
223 template <class ContainerType>
224 bool ObserverListBase<ObserverType>::Iter<ContainerType>::operator!=(
225 const Iter& other) const {
226 return !operator==(other);
227 }
228
229 template <class ObserverType>
230 template <class ContainerType>
231 typename ObserverListBase<ObserverType>::template Iter<ContainerType>&
232 ObserverListBase<ObserverType>::Iter<ContainerType>::operator++() {
233 if (list_) {
234 ++index_;
235 index_ = GetNonNullIndex();
236 }
237 return *this;
238 }
239
240 template <class ObserverType>
241 template <class ContainerType>
242 ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::operator->()
243 const {
244 ObserverType* current = GetCurrent();
245 DCHECK(current);
246 return current;
247 }
248
249 template <class ObserverType>
250 template <class ContainerType>
251 ObserverType& ObserverListBase<ObserverType>::Iter<ContainerType>::operator*()
252 const {
253 ObserverType* current = GetCurrent();
254 DCHECK(current);
255 return *current;
256 }
257
258 template <class ObserverType>
259 template <class ContainerType>
260 ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::GetCurrent()
261 const {
262 if (!list_)
263 return nullptr;
264 return index_ < clamped_max_index() ? list_->observers_[index_] : nullptr;
265 }
266
267 template <class ObserverType>
268 template <class ContainerType>
269 size_t ObserverListBase<ObserverType>::Iter<ContainerType>::GetNonNullIndex()
270 const {
271 size_t index = index_;
dcheng 2016/10/07 05:43:16 Let's be a little clever here to remove the need f
272 size_t max_index = clamped_max_index();
273 while (index < max_index && !list_->observers_[index])
274 ++index;
275 return index;
276 }
277
278 template <class ObserverType>
279 template <class ContainerType>
280 ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::GetNext() {
281 // Make sure index_ is pointing at a non-null element, if the
282 // current index_ has been nulled out.
283 index_ = GetNonNullIndex();
284 ObserverType* current = GetCurrent();
285 operator++();
286 return current;
287 }
288
289 template <class ObserverType>
161 void ObserverListBase<ObserverType>::AddObserver(ObserverType* obs) { 290 void ObserverListBase<ObserverType>::AddObserver(ObserverType* obs) {
162 DCHECK(obs); 291 DCHECK(obs);
163 if (ContainsValue(observers_, obs)) { 292 if (ContainsValue(observers_, obs)) {
164 NOTREACHED() << "Observers can only be added once!"; 293 NOTREACHED() << "Observers can only be added once!";
165 return; 294 return;
166 } 295 }
167 observers_.push_back(obs); 296 observers_.push_back(obs);
168 } 297 }
169 298
170 template <class ObserverType> 299 template <class ObserverType>
(...skipping 26 matching lines...) Expand all
197 for (typename ListType::iterator it = observers_.begin(); 326 for (typename ListType::iterator it = observers_.begin();
198 it != observers_.end(); ++it) { 327 it != observers_.end(); ++it) {
199 *it = nullptr; 328 *it = nullptr;
200 } 329 }
201 } else { 330 } else {
202 observers_.clear(); 331 observers_.clear();
203 } 332 }
204 } 333 }
205 334
206 template <class ObserverType> 335 template <class ObserverType>
207 void ObserverListBase<ObserverType>::Compact() { 336 void ObserverListBase<ObserverType>::Compact() const {
208 observers_.erase( 337 auto& observers = const_cast<ListType&>(observers_);
209 std::remove(observers_.begin(), observers_.end(), nullptr), 338 observers.erase(std::remove(observers.begin(), observers.end(), nullptr),
210 observers_.end()); 339 observers.end());
211 } 340 }
212 341
213 template <class ObserverType, bool check_empty = false> 342 template <class ObserverType, bool check_empty = false>
214 class ObserverList : public ObserverListBase<ObserverType> { 343 class ObserverList : public ObserverListBase<ObserverType> {
215 public: 344 public:
216 typedef typename ObserverListBase<ObserverType>::NotificationType 345 typedef typename ObserverListBase<ObserverType>::NotificationType
217 NotificationType; 346 NotificationType;
218 347
219 ObserverList() {} 348 ObserverList() {}
220 explicit ObserverList(NotificationType type) 349 explicit ObserverList(NotificationType type)
221 : ObserverListBase<ObserverType>(type) {} 350 : ObserverListBase<ObserverType>(type) {}
222 351
223 ~ObserverList() { 352 ~ObserverList() {
224 // When check_empty is true, assert that the list is empty on destruction. 353 // When check_empty is true, assert that the list is empty on destruction.
225 if (check_empty) { 354 if (check_empty) {
226 ObserverListBase<ObserverType>::Compact(); 355 ObserverListBase<ObserverType>::Compact();
227 DCHECK_EQ(ObserverListBase<ObserverType>::size(), 0U); 356 DCHECK_EQ(ObserverListBase<ObserverType>::size(), 0U);
228 } 357 }
229 } 358 }
230 359
231 bool might_have_observers() const { 360 bool might_have_observers() const {
232 return ObserverListBase<ObserverType>::size() != 0; 361 return ObserverListBase<ObserverType>::size() != 0;
233 } 362 }
234 }; 363 };
235 364
236 #define FOR_EACH_OBSERVER(ObserverType, observer_list, func) \ 365 // Deprecated. Use the range-based for loop instead.
237 do { \ 366 #define FOR_EACH_OBSERVER(ObserverType, observer_list, func) \
238 if ((observer_list).might_have_observers()) { \ 367 do { \
239 typename base::ObserverListBase<ObserverType>::Iterator \ 368 for (ObserverType & o : observer_list) \
240 it_inside_observer_macro(&observer_list); \ 369 o.func; \
241 ObserverType* obs; \
242 while ((obs = it_inside_observer_macro.GetNext()) != nullptr) \
243 obs->func; \
244 } \
245 } while (0) 370 } while (0)
246 371
247 } // namespace base 372 } // namespace base
248 373
249 #endif // BASE_OBSERVER_LIST_H_ 374 #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