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

Side by Side Diff: base/observer_list.h

Issue 2340583005: Base ObserverList: Add basic support for standard C++ iterators. (Closed)
Patch Set: Add a comment on MSVC. 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>
(...skipping 28 matching lines...) Expand all
39 // 39 //
40 // void AddObserver(Observer* obs) { 40 // void AddObserver(Observer* obs) {
41 // observer_list_.AddObserver(obs); 41 // observer_list_.AddObserver(obs);
42 // } 42 // }
43 // 43 //
44 // void RemoveObserver(Observer* obs) { 44 // void RemoveObserver(Observer* obs) {
45 // observer_list_.RemoveObserver(obs); 45 // observer_list_.RemoveObserver(obs);
46 // } 46 // }
47 // 47 //
48 // void NotifyFoo() { 48 // void NotifyFoo() {
49 // FOR_EACH_OBSERVER(Observer, observer_list_, OnFoo(this)); 49 // for (auto& observer : observer_list_)
50 // observer.OnFoo(this);
50 // } 51 // }
51 // 52 //
52 // void NotifyBar(int x, int y) { 53 // void NotifyBar(int x, int y) {
53 // FOR_EACH_OBSERVER(Observer, observer_list_, OnBar(this, x, y)); 54 // for (FooList::iterator i = observer_list.begin(),
55 // e = observer_list.end(); i != e; ++i)
56 // i->OnBar(this, x, y);
54 // } 57 // }
55 // 58 //
56 // private: 59 // private:
57 // base::ObserverList<Observer> observer_list_; 60 // base::ObserverList<Observer> observer_list_;
58 // }; 61 // };
59 // 62 //
60 // 63 //
61 /////////////////////////////////////////////////////////////////////////////// 64 ///////////////////////////////////////////////////////////////////////////////
62 65
63 namespace base { 66 namespace base {
64 67
65 template <typename ObserverType> 68 template <typename ObserverType>
66 class ObserverListThreadSafe; 69 class ObserverListThreadSafe;
67 70
68 template <class ObserverType> 71 template <class ObserverType>
69 class ObserverListBase 72 class ObserverListBase
70 : public SupportsWeakPtr<ObserverListBase<ObserverType>> { 73 : public SupportsWeakPtr<ObserverListBase<ObserverType>> {
71 public: 74 public:
72 // Enumeration of which observers are notified. 75 // Enumeration of which observers are notified.
73 enum NotificationType { 76 enum NotificationType {
74 // Specifies that any observers added during notification are notified. 77 // Specifies that any observers added during notification are notified.
75 // This is the default type if non type is provided to the constructor. 78 // This is the default type if non type is provided to the constructor.
76 NOTIFY_ALL, 79 NOTIFY_ALL,
77 80
78 // Specifies that observers added while sending out notification are not 81 // Specifies that observers added while sending out notification are not
79 // notified. 82 // notified.
80 NOTIFY_EXISTING_ONLY 83 NOTIFY_EXISTING_ONLY
81 }; 84 };
82 85
83 // An iterator class that can be used to access the list of observers. See 86 // An iterator class that can be used to access the list of observers.
84 // also the FOR_EACH_OBSERVER macro defined below. 87 template <class ContainerType>
85 class Iterator { 88 class Iter {
dcheng 2016/10/03 07:29:18 Derive from std::iterator.
loyso (OOO) 2016/10/04 03:46:57 This comment conflicts with your previous comment
loyso (OOO) 2016/10/04 04:12:02 Also, please notice that ObserverList isn't a C++
dcheng 2016/10/04 23:53:39 As discussed offline, this does work (e.g. https:/
86 public: 89 public:
87 explicit Iterator(ObserverListBase<ObserverType>* list); 90 Iter();
88 ~Iterator(); 91 explicit Iter(ContainerType* list);
92 ~Iter();
93
94 // Deprecated.
89 ObserverType* GetNext(); 95 ObserverType* GetNext();
90 96
97 // A workaround for C2244. MSVC requires fully qualified type name for
98 // return type on a function definition to match a function declaration.
99 using ThisType =
100 typename ObserverListBase<ObserverType>::template Iter<ContainerType>;
101
102 bool operator!=(const Iter& other) const;
103 ThisType& operator++();
104 ObserverType* operator->() const;
105 ObserverType& operator*() const;
106
91 private: 107 private:
92 WeakPtr<ObserverListBase<ObserverType>> list_; 108 ObserverType* GetCurrent() const;
109
110 size_t GetNonNullIndex() const;
111
112 size_t clamped_max_index() const {
113 return std::min(max_index_, list_->observers_.size());
114 }
115 WeakPtr<ContainerType> list_;
93 size_t index_; 116 size_t index_;
94 size_t max_index_; 117 size_t max_index_;
95 }; 118 };
96 119
120 using Iterator = Iter<ObserverListBase<ObserverType>>;
121
122 using iterator = Iter<ObserverListBase<ObserverType>>;
123 iterator begin() {
124 // An optimization: do not involve weak pointers for empty list.
125 // Note: can't use ?: operator here due to some MSVC bug (unit tests fail)
126 if (observers_.empty())
127 return iterator();
128 return iterator(this);
129 }
130 iterator end() { return iterator(); }
131
132 using const_iterator = Iter<const ObserverListBase<ObserverType>>;
133 const_iterator begin() const {
134 if (observers_.empty())
135 return const_iterator();
136 return const_iterator(this);
137 }
138 const_iterator end() const { return const_iterator(); }
139
97 ObserverListBase() : notify_depth_(0), type_(NOTIFY_ALL) {} 140 ObserverListBase() : notify_depth_(0), type_(NOTIFY_ALL) {}
98 explicit ObserverListBase(NotificationType type) 141 explicit ObserverListBase(NotificationType type)
99 : notify_depth_(0), type_(type) {} 142 : notify_depth_(0), type_(type) {}
100 143
101 // Add an observer to the list. An observer should not be added to 144 // Add an observer to the list. An observer should not be added to
102 // the same list more than once. 145 // the same list more than once.
103 void AddObserver(ObserverType* obs); 146 void AddObserver(ObserverType* obs);
104 147
105 // Remove an observer from the list if it is in the list. 148 // Remove an observer from the list if it is in the list.
106 void RemoveObserver(ObserverType* obs); 149 void RemoveObserver(ObserverType* obs);
107 150
108 // Determine whether a particular observer is in the list. 151 // Determine whether a particular observer is in the list.
109 bool HasObserver(const ObserverType* observer) const; 152 bool HasObserver(const ObserverType* observer) const;
110 153
111 void Clear(); 154 void Clear();
112 155
113 protected: 156 protected:
114 size_t size() const { return observers_.size(); } 157 size_t size() const { return observers_.size(); }
115 158
116 void Compact(); 159 // Defragments the list despite const.
160 void Compact() const;
117 161
118 private: 162 private:
119 friend class ObserverListThreadSafe<ObserverType>; 163 friend class ObserverListThreadSafe<ObserverType>;
120 164
121 typedef std::vector<ObserverType*> ListType; 165 typedef std::vector<ObserverType*> ListType;
122 166
123 ListType observers_; 167 ListType observers_;
124 int notify_depth_; 168 mutable int notify_depth_;
125 NotificationType type_; 169 NotificationType type_;
126 170
127 friend class ObserverListBase::Iterator; 171 template <class ContainerType>
172 friend class Iter;
128 173
129 DISALLOW_COPY_AND_ASSIGN(ObserverListBase); 174 DISALLOW_COPY_AND_ASSIGN(ObserverListBase);
130 }; 175 };
131 176
132 template <class ObserverType> 177 template <class ObserverType>
133 ObserverListBase<ObserverType>::Iterator::Iterator( 178 template <class ContainerType>
134 ObserverListBase<ObserverType>* list) 179 ObserverListBase<ObserverType>::Iter<ContainerType>::Iter()
135 : list_(list->AsWeakPtr()), 180 : index_(), max_index_() {}
dcheng 2016/10/03 07:29:18 Nit: write 0 explicitly here forconsistency.
loyso (OOO) 2016/10/04 03:46:57 Done.
181
182 template <class ObserverType>
183 template <class ContainerType>
184 ObserverListBase<ObserverType>::Iter<ContainerType>::Iter(ContainerType* list)
185 : list_(const_cast<ObserverListBase<ObserverType>*>(list)->AsWeakPtr()),
136 index_(0), 186 index_(0),
137 max_index_(list->type_ == NOTIFY_ALL ? std::numeric_limits<size_t>::max() 187 max_index_(list->type_ == NOTIFY_ALL ? std::numeric_limits<size_t>::max()
138 : list->observers_.size()) { 188 : list->observers_.size()) {
139 ++list_->notify_depth_; 189 ++list_->notify_depth_;
140 } 190 }
141 191
142 template <class ObserverType> 192 template <class ObserverType>
143 ObserverListBase<ObserverType>::Iterator::~Iterator() { 193 template <class ContainerType>
194 ObserverListBase<ObserverType>::Iter<ContainerType>::~Iter() {
144 if (list_.get() && --list_->notify_depth_ == 0) 195 if (list_.get() && --list_->notify_depth_ == 0)
145 list_->Compact(); 196 list_->Compact();
146 } 197 }
147 198
148 template <class ObserverType> 199 template <class ObserverType>
149 ObserverType* ObserverListBase<ObserverType>::Iterator::GetNext() { 200 template <class ContainerType>
150 if (!list_.get()) 201 bool ObserverListBase<ObserverType>::Iter<ContainerType>::operator!=(
151 return nullptr; 202 const Iter& other) const {
152 ListType& observers = list_->observers_; 203 return GetCurrent() != other.GetCurrent();
153 // Advance if the current element is null
154 size_t max_index = std::min(max_index_, observers.size());
155 while (index_ < max_index && !observers[index_])
156 ++index_;
157 return index_ < max_index ? observers[index_++] : nullptr;
158 } 204 }
159 205
160 template <class ObserverType> 206 template <class ObserverType>
207 template <class ContainerType>
208 typename ObserverListBase<ObserverType>::template Iter<ContainerType>&
209 ObserverListBase<ObserverType>::Iter<ContainerType>::operator++() {
210 if (list_) {
211 ++index_;
212 index_ = GetNonNullIndex();
213 }
214 return *this;
215 }
216
217 template <class ObserverType>
218 template <class ContainerType>
219 ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::operator->()
220 const {
221 ObserverType* current = GetCurrent();
222 DCHECK(current);
223 return current;
224 }
225
226 template <class ObserverType>
227 template <class ContainerType>
228 ObserverType& ObserverListBase<ObserverType>::Iter<ContainerType>::operator*()
229 const {
230 ObserverType* current = GetCurrent();
231 DCHECK(current);
232 return *current;
233 }
234
235 template <class ObserverType>
236 template <class ContainerType>
237 ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::GetCurrent()
238 const {
239 if (!list_)
240 return nullptr;
241 size_t index = GetNonNullIndex();
242 return index < clamped_max_index() ? list_->observers_[index] : nullptr;
243 }
244
245 template <class ObserverType>
246 template <class ContainerType>
247 size_t ObserverListBase<ObserverType>::Iter<ContainerType>::GetNonNullIndex()
248 const {
249 size_t index = index_;
250 size_t max_index = clamped_max_index();
251 while (index < max_index && !list_->observers_[index])
252 ++index;
253 return index;
254 }
255
256 template <class ObserverType>
257 template <class ContainerType>
258 ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::GetNext() {
259 if (!list_)
260 return nullptr;
261
262 ObserverType* current = GetCurrent();
263
264 index_ = GetNonNullIndex();
265 ++index_;
266
267 return current;
268 }
269
270 template <class ObserverType>
161 void ObserverListBase<ObserverType>::AddObserver(ObserverType* obs) { 271 void ObserverListBase<ObserverType>::AddObserver(ObserverType* obs) {
162 DCHECK(obs); 272 DCHECK(obs);
163 if (ContainsValue(observers_, obs)) { 273 if (ContainsValue(observers_, obs)) {
164 NOTREACHED() << "Observers can only be added once!"; 274 NOTREACHED() << "Observers can only be added once!";
165 return; 275 return;
166 } 276 }
167 observers_.push_back(obs); 277 observers_.push_back(obs);
168 } 278 }
169 279
170 template <class ObserverType> 280 template <class ObserverType>
(...skipping 26 matching lines...) Expand all
197 for (typename ListType::iterator it = observers_.begin(); 307 for (typename ListType::iterator it = observers_.begin();
198 it != observers_.end(); ++it) { 308 it != observers_.end(); ++it) {
199 *it = nullptr; 309 *it = nullptr;
200 } 310 }
201 } else { 311 } else {
202 observers_.clear(); 312 observers_.clear();
203 } 313 }
204 } 314 }
205 315
206 template <class ObserverType> 316 template <class ObserverType>
207 void ObserverListBase<ObserverType>::Compact() { 317 void ObserverListBase<ObserverType>::Compact() const {
208 observers_.erase( 318 auto& observers = const_cast<ListType&>(observers_);
209 std::remove(observers_.begin(), observers_.end(), nullptr), 319 observers.erase(std::remove(observers.begin(), observers.end(), nullptr),
210 observers_.end()); 320 observers.end());
211 } 321 }
212 322
213 template <class ObserverType, bool check_empty = false> 323 template <class ObserverType, bool check_empty = false>
214 class ObserverList : public ObserverListBase<ObserverType> { 324 class ObserverList : public ObserverListBase<ObserverType> {
215 public: 325 public:
216 typedef typename ObserverListBase<ObserverType>::NotificationType 326 typedef typename ObserverListBase<ObserverType>::NotificationType
217 NotificationType; 327 NotificationType;
218 328
219 ObserverList() {} 329 ObserverList() {}
220 explicit ObserverList(NotificationType type) 330 explicit ObserverList(NotificationType type)
221 : ObserverListBase<ObserverType>(type) {} 331 : ObserverListBase<ObserverType>(type) {}
222 332
223 ~ObserverList() { 333 ~ObserverList() {
224 // When check_empty is true, assert that the list is empty on destruction. 334 // When check_empty is true, assert that the list is empty on destruction.
225 if (check_empty) { 335 if (check_empty) {
226 ObserverListBase<ObserverType>::Compact(); 336 ObserverListBase<ObserverType>::Compact();
227 DCHECK_EQ(ObserverListBase<ObserverType>::size(), 0U); 337 DCHECK_EQ(ObserverListBase<ObserverType>::size(), 0U);
228 } 338 }
229 } 339 }
230 340
231 bool might_have_observers() const { 341 bool might_have_observers() const {
232 return ObserverListBase<ObserverType>::size() != 0; 342 return ObserverListBase<ObserverType>::size() != 0;
233 } 343 }
234 }; 344 };
235 345
346 // Deprecated. Use the range-based for loop instead.
236 #define FOR_EACH_OBSERVER(ObserverType, observer_list, func) \ 347 #define FOR_EACH_OBSERVER(ObserverType, observer_list, func) \
237 do { \ 348 do { \
238 if ((observer_list).might_have_observers()) { \ 349 if ((observer_list).might_have_observers()) { \
dcheng 2016/10/03 07:29:18 Can we structure the macro so we can use the new r
loyso (OOO) 2016/10/04 03:46:57 No, we can't. Some places use GetNext method and I
dcheng 2016/10/04 23:53:39 As discussed offline, let's switch the macro to us
loyso (OOO) 2016/10/05 07:24:42 Done.
239 typename base::ObserverListBase<ObserverType>::Iterator \ 350 typename base::ObserverListBase<ObserverType>::Iterator \
240 it_inside_observer_macro(&observer_list); \ 351 it_inside_observer_macro(&observer_list); \
241 ObserverType* obs; \ 352 ObserverType* obs; \
242 while ((obs = it_inside_observer_macro.GetNext()) != nullptr) \ 353 while ((obs = it_inside_observer_macro.GetNext()) != nullptr) \
243 obs->func; \ 354 obs->func; \
244 } \ 355 } \
245 } while (0) 356 } while (0)
246 357
247 } // namespace base 358 } // namespace base
248 359
249 #endif // BASE_OBSERVER_LIST_H_ 360 #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