1 // Copyright 2011 The Chromium Authors
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_
18 #include "base/check.h"
19 #include "base/check_op.h"
20 #include "base/containers/cxx20_erase_vector.h"
21 #include "base/dcheck_is_on.h"
22 #include "base/debug/dump_without_crashing.h"
23 #include "base/notreached.h"
24 #include "base/observer_list_internal.h"
25 #include "base/ranges/algorithm.h"
26 #include "base/sequence_checker.h"
27 #include "build/build_config.h"
29 ///////////////////////////////////////////////////////////////////////////////
33 // A list of observers. Unlike a standard vector or list, this container can
34 // be modified during iteration without invalidating the iterator. So, it
35 // safely handles the case of an observer removing itself or other observers
36 // from the list while observers are being notified.
41 // ObserverList is not thread-compatible. Iterating on the same ObserverList
42 // simultaneously in different threads is not safe, even when the ObserverList
43 // itself is not modified.
45 // For a thread-safe observer list, see ObserverListThreadSafe.
54 // class Observer : public base::CheckedObserver {
56 // virtual void OnFoo(MyWidget* w) = 0;
57 // virtual void OnBar(MyWidget* w, int x, int y) = 0;
60 // void AddObserver(Observer* obs) {
61 // observers_.AddObserver(obs);
64 // void RemoveObserver(Observer* obs) {
65 // observers_.RemoveObserver(obs);
69 // for (Observer& obs : observers_)
73 // void NotifyBar(int x, int y) {
74 // for (Observer& obs : observers_)
75 // obs.OnBar(this, x, y);
79 // base::ObserverList<Observer> observers_;
83 ///////////////////////////////////////////////////////////////////////////////
87 // Enumeration of which observers are notified by ObserverList.
88 enum class ObserverListPolicy {
89 // Specifies that any observers added during notification are notified.
90 // This is the default policy if no policy is provided to the constructor.
93 // Specifies that observers added while sending out notification are not
98 // When check_empty is true, assert that the list is empty on destruction.
99 // When allow_reentrancy is false, iterating throught the list while already in
100 // the iteration loop will result in DCHECK failure.
101 // TODO(oshima): Change the default to non reentrant. https://crbug.com/812109
102 template <class ObserverType,
103 bool check_empty = false,
104 bool allow_reentrancy = true,
105 class ObserverStorageType = internal::CheckedObserverAdapter>
108 // Allow declaring an ObserverList<...>::Unchecked that replaces the default
109 // ObserverStorageType to use raw pointers. This is required to support legacy
110 // observers that do not inherit from CheckedObserver. The majority of new
111 // code should not use this, but it may be suited for performance-critical
112 // situations to avoid overheads of a CHECK(). Note the type can't be chosen
113 // based on ObserverType's definition because ObserverLists are often declared
114 // in headers using a forward-declare of ObserverType.
115 using Unchecked = ObserverList<ObserverType,
118 internal::UncheckedObserverAdapter>;
120 // An iterator class that can be used to access the list of observers.
123 using iterator_category = std::forward_iterator_tag;
124 using value_type = ObserverType;
125 using difference_type = ptrdiff_t;
126 using pointer = ObserverType*;
127 using reference = ObserverType&;
129 Iter() : index_(0), max_index_(0) {}
131 explicit Iter(const ObserverList* list)
132 : list_(const_cast<ObserverList*>(list)),
134 max_index_(list->policy_ == ObserverListPolicy::ALL
135 ? std::numeric_limits<size_t>::max()
136 : list->observers_.size()) {
138 // TODO(crbug.com/1423093): Turn into CHECK once very prevalent failures
140 DUMP_WILL_BE_CHECK(allow_reentrancy || list_.IsOnlyRemainingNode());
141 // Bind to this sequence when creating the first iterator.
142 DCHECK_CALLED_ON_VALID_SEQUENCE(list_->iteration_sequence_checker_);
147 if (list_.IsOnlyRemainingNode())
151 Iter(const Iter& other)
152 : index_(other.index_), max_index_(other.max_index_) {
154 list_.SetList(other.list_.get());
157 Iter& operator=(const Iter& other) {
161 if (list_.IsOnlyRemainingNode())
166 list_.SetList(other.list_.get());
168 index_ = other.index_;
169 max_index_ = other.max_index_;
173 bool operator==(const Iter& other) const {
174 return (is_end() && other.is_end()) ||
175 (list_.get() == other.list_.get() && index_ == other.index_);
178 bool operator!=(const Iter& other) const { return !(*this == other); }
188 Iter operator++(int) {
194 ObserverType* operator->() const {
195 ObserverType* const current = GetCurrent();
200 ObserverType& operator*() const {
201 ObserverType* const current = GetCurrent();
207 friend class ObserverListTestBase;
209 ObserverType* GetCurrent() const {
211 DCHECK_LT(index_, clamped_max_index());
212 return ObserverStorageType::template Get<ObserverType>(
213 list_->observers_[index_]);
216 void EnsureValidIndex() {
218 const size_t max_index = clamped_max_index();
219 while (index_ < max_index &&
220 list_->observers_[index_].IsMarkedForRemoval()) {
225 size_t clamped_max_index() const {
226 return std::min(max_index_, list_->observers_.size());
229 bool is_end() const { return !list_ || index_ == clamped_max_index(); }
231 // Lightweight weak pointer to the ObserverList.
232 internal::WeakLinkNode<ObserverList> list_;
234 // When initially constructed and each time the iterator is incremented,
235 // |index_| is guaranteed to point to a non-null index if the iterator
236 // has not reached the end of the ObserverList.
241 using iterator = Iter;
242 using const_iterator = Iter;
243 using value_type = ObserverType;
245 const_iterator begin() const {
246 // An optimization: do not involve weak pointers for empty list.
247 return observers_.empty() ? const_iterator() : const_iterator(this);
250 const_iterator end() const { return const_iterator(); }
252 explicit ObserverList(ObserverListPolicy policy = ObserverListPolicy::ALL)
254 // Sequence checks only apply when iterators are live.
255 DETACH_FROM_SEQUENCE(iteration_sequence_checker_);
257 ObserverList(const ObserverList&) = delete;
258 ObserverList& operator=(const ObserverList&) = delete;
260 // If there are live iterators, ensure destruction is thread-safe.
261 if (!live_iterators_.empty())
262 DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_);
264 while (!live_iterators_.empty())
265 live_iterators_.head()->value()->Invalidate();
268 // TODO(crbug.com/1423093): Turn into a CHECK once very prevalent failures
270 DUMP_WILL_BE_CHECK(observers_.empty())
272 << GetObserversCreationStackString();
276 // Add an observer to this list. An observer should not be added to the same
277 // list more than once.
279 // Precondition: obs != nullptr
280 // Precondition: !HasObserver(obs)
281 void AddObserver(ObserverType* obs) {
283 // TODO(crbug.com/1423093): Turn this into a CHECK once very prevalent
284 // failures are weeded out.
285 if (HasObserver(obs)) {
286 NOTREACHED() << "Observers can only be added once!";
290 observers_.emplace_back(ObserverStorageType(obs));
293 // Removes the given observer from this list. Does nothing if this observer is
295 void RemoveObserver(const ObserverType* obs) {
297 const auto it = ranges::find_if(
298 observers_, [obs](const auto& o) { return o.IsEqual(obs); });
299 if (it == observers_.end())
301 if (!it->IsMarkedForRemoval())
303 if (live_iterators_.empty()) {
304 observers_.erase(it);
306 DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_);
307 it->MarkForRemoval();
311 // Determine whether a particular observer is in the list.
312 bool HasObserver(const ObserverType* obs) const {
313 // Client code passing null could be confused by the treatment of observers
314 // removed mid-iteration. TODO(https://crbug.com/876588): This should
315 // probably DCHECK, but some client code currently does pass null.
318 return ranges::find_if(observers_, [obs](const auto& o) {
319 return o.IsEqual(obs);
320 }) != observers_.end();
323 // Removes all the observers from this list.
325 if (live_iterators_.empty()) {
328 DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_);
329 for (auto& observer : observers_)
330 observer.MarkForRemoval();
332 observers_count_ = 0;
335 bool empty() const { return !observers_count_; }
338 friend class internal::WeakLinkNode<ObserverList>;
340 // Compacts list of observers by removing those marked for removal.
342 // Detach whenever the last iterator is destroyed. Detaching is safe because
343 // Compact() is only ever called when the last iterator is destroyed.
344 DETACH_FROM_SEQUENCE(iteration_sequence_checker_);
346 base::EraseIf(observers_,
347 [](const auto& o) { return o.IsMarkedForRemoval(); });
350 std::string GetObserversCreationStackString() const {
353 #if BUILDFLAG(IS_IOS)
354 result += "Use go/observer-list-empty to interpret.\n";
356 for (const auto& observer : observers_) {
357 result += observer.GetCreationStackString();
362 return "For observer stack traces, build with `dcheck_always_on=true`.";
363 #endif // DCHECK_IS_ON()
366 std::vector<ObserverStorageType> observers_;
368 base::LinkedList<internal::WeakLinkNode<ObserverList>> live_iterators_;
370 size_t observers_count_{0};
372 const ObserverListPolicy policy_;
374 SEQUENCE_CHECKER(iteration_sequence_checker_);
377 template <class ObserverType, bool check_empty = false>
378 using ReentrantObserverList = ObserverList<ObserverType, check_empty, true>;
382 #endif // BASE_OBSERVER_LIST_H_