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.
5 #ifndef BASE_OBSERVER_LIST_H_
6 #define BASE_OBSERVER_LIST_H_
16 #include "base/gtest_prod_util.h"
17 #include "base/logging.h"
18 #include "base/macros.h"
19 #include "base/observer_list_internal.h"
20 #include "base/sequence_checker.h"
21 #include "base/stl_util.h"
23 ///////////////////////////////////////////////////////////////////////////////
27 // A list of observers. Unlike a standard vector or list, this container can
28 // be modified during iteration without invalidating the iterator. So, it
29 // safely handles the case of an observer removing itself or other observers
30 // from the list while observers are being notified.
35 // ObserverList is not thread-compatible. Iterating on the same ObserverList
36 // simultaneously in different threads is not safe, even when the ObserverList
37 // itself is not modified.
39 // For a thread-safe observer list, see ObserverListThreadSafe.
50 // virtual void OnFoo(MyWidget* w) = 0;
51 // virtual void OnBar(MyWidget* w, int x, int y) = 0;
54 // void AddObserver(Observer* obs) {
55 // observers_.AddObserver(obs);
58 // void RemoveObserver(const Observer* obs) {
59 // observers_.RemoveObserver(obs);
63 // for (Observer& obs : observers_)
67 // void NotifyBar(int x, int y) {
68 // for (Observer& obs : observers_)
69 // obs.OnBar(this, x, y);
73 // base::ObserverList<Observer> observers_;
77 ///////////////////////////////////////////////////////////////////////////////
81 // Enumeration of which observers are notified by ObserverList.
82 enum class ObserverListPolicy {
83 // Specifies that any observers added during notification are notified.
84 // This is the default policy if no policy is provided to the constructor.
87 // Specifies that observers added while sending out notification are not
92 // When check_empty is true, assert that the list is empty on destruction.
93 // When allow_reentrancy is false, iterating throught the list while already in
94 // the iteration loop will result in DCHECK failure.
95 // TODO(oshima): Change the default to non reentrant. https://crbug.com/812109
96 template <class ObserverType,
97 bool check_empty = false,
98 bool allow_reentrancy = true,
99 class ObserverStorageType = internal::CheckedObserverAdapter>
102 // Allow declaring an ObserverList<...>::Unchecked that replaces the default
103 // ObserverStorageType to use raw pointers. This is required to support legacy
104 // observers that do not inherit from CheckedObserver. The majority of new
105 // code should not use this, but it may be suited for performance-critical
106 // situations to avoid overheads of a CHECK(). Note the type can't be chosen
107 // based on ObserverType's definition because ObserverLists are often declared
108 // in headers using a forward-declare of ObserverType.
109 using Unchecked = ObserverList<ObserverType,
112 internal::UncheckedObserverAdapter>;
114 // An iterator class that can be used to access the list of observers.
117 using iterator_category = std::forward_iterator_tag;
118 using value_type = ObserverType;
119 using difference_type = ptrdiff_t;
120 using pointer = ObserverType*;
121 using reference = ObserverType&;
123 Iter() : index_(0), max_index_(0) {}
125 explicit Iter(const ObserverList* list)
126 : list_(const_cast<ObserverList*>(list)),
128 max_index_(list->policy_ == ObserverListPolicy::ALL
129 ? std::numeric_limits<size_t>::max()
130 : list->observers_.size()) {
132 DCHECK(allow_reentrancy || list_.IsOnlyRemainingNode());
133 // Bind to this sequence when creating the first iterator.
134 DCHECK_CALLED_ON_VALID_SEQUENCE(list_->iteration_sequence_checker_);
139 if (list_.IsOnlyRemainingNode())
143 Iter(const Iter& other)
144 : index_(other.index_), max_index_(other.max_index_) {
146 list_.SetList(other.list_.get());
149 Iter& operator=(const Iter& other) {
153 if (list_.IsOnlyRemainingNode())
158 list_.SetList(other.list_.get());
160 index_ = other.index_;
161 max_index_ = other.max_index_;
165 bool operator==(const Iter& other) const {
166 return (is_end() && other.is_end()) ||
167 (list_.get() == other.list_.get() && index_ == other.index_);
170 bool operator!=(const Iter& other) const { return !(*this == other); }
180 Iter operator++(int) {
186 ObserverType* operator->() const {
187 ObserverType* const current = GetCurrent();
192 ObserverType& operator*() const {
193 ObserverType* const current = GetCurrent();
199 friend class ObserverListTestBase;
201 ObserverType* GetCurrent() const {
203 DCHECK_LT(index_, clamped_max_index());
204 return ObserverStorageType::template Get<ObserverType>(
205 list_->observers_[index_]);
208 void EnsureValidIndex() {
210 const size_t max_index = clamped_max_index();
211 while (index_ < max_index &&
212 list_->observers_[index_].IsMarkedForRemoval()) {
217 size_t clamped_max_index() const {
218 return std::min(max_index_, list_->observers_.size());
221 bool is_end() const { return !list_ || index_ == clamped_max_index(); }
223 // Lightweight weak pointer to the ObserverList.
224 internal::WeakLinkNode<ObserverList> list_;
226 // When initially constructed and each time the iterator is incremented,
227 // |index_| is guaranteed to point to a non-null index if the iterator
228 // has not reached the end of the ObserverList.
233 using iterator = Iter;
234 using const_iterator = Iter;
235 using value_type = ObserverType;
237 const_iterator begin() const {
238 // An optimization: do not involve weak pointers for empty list.
239 return observers_.empty() ? const_iterator() : const_iterator(this);
242 const_iterator end() const { return const_iterator(); }
244 explicit ObserverList(ObserverListPolicy policy = ObserverListPolicy::ALL)
246 // Sequence checks only apply when iterators are live.
247 DETACH_FROM_SEQUENCE(iteration_sequence_checker_);
251 // If there are live iterators, ensure destruction is thread-safe.
252 if (!live_iterators_.empty())
253 DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_);
255 while (!live_iterators_.empty())
256 live_iterators_.head()->value()->Invalidate();
259 DCHECK(observers_.empty());
263 // Add an observer to this list. An observer should not be added to the same
264 // list more than once.
266 // Precondition: obs != nullptr
267 // Precondition: !HasObserver(obs)
268 void AddObserver(ObserverType* obs) {
270 if (HasObserver(obs)) {
271 NOTREACHED() << "Observers can only be added once!";
274 observers_.emplace_back(ObserverStorageType(obs));
277 // Removes the given observer from this list. Does nothing if this observer is
279 void RemoveObserver(const ObserverType* obs) {
282 std::find_if(observers_.begin(), observers_.end(),
283 [obs](const auto& o) { return o.IsEqual(obs); });
284 if (it == observers_.end())
287 if (live_iterators_.empty()) {
288 observers_.erase(it);
290 DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_);
291 it->MarkForRemoval();
295 // Determine whether a particular observer is in the list.
296 bool HasObserver(const ObserverType* obs) const {
297 // Client code passing null could be confused by the treatment of observers
298 // removed mid-iteration. TODO(https://crbug.com/876588): This should
299 // probably DCHECK, but some client code currently does pass null.
302 return std::find_if(observers_.begin(), observers_.end(),
303 [obs](const auto& o) { return o.IsEqual(obs); }) !=
307 // Removes all the observers from this list.
309 if (live_iterators_.empty()) {
312 DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_);
313 for (auto& observer : observers_)
314 observer.MarkForRemoval();
318 bool might_have_observers() const { return !observers_.empty(); }
321 friend class internal::WeakLinkNode<ObserverList>;
323 // Compacts list of observers by removing those marked for removal.
325 // Detach whenever the last iterator is destroyed. Detaching is safe because
326 // Compact() is only ever called when the last iterator is destroyed.
327 DETACH_FROM_SEQUENCE(iteration_sequence_checker_);
329 EraseIf(observers_, [](const auto& o) { return o.IsMarkedForRemoval(); });
332 std::vector<ObserverStorageType> observers_;
334 base::LinkedList<internal::WeakLinkNode<ObserverList>> live_iterators_;
336 const ObserverListPolicy policy_;
338 SEQUENCE_CHECKER(iteration_sequence_checker_);
340 DISALLOW_COPY_AND_ASSIGN(ObserverList);
343 template <class ObserverType, bool check_empty = false>
344 using ReentrantObserverList = ObserverList<ObserverType, check_empty, true>;
348 #endif // BASE_OBSERVER_LIST_H_