#ifndef BASE_OBSERVER_LIST_H_
#define BASE_OBSERVER_LIST_H_
#include <stddef.h>
#include <algorithm>
#include <iterator>
#include <limits>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include "base/check.h"
#include "base/check_op.h"
#include "base/dcheck_is_on.h"
#include "base/debug/dump_without_crashing.h"
#include "base/notreached.h"
#include "base/observer_list_internal.h"
#include "base/ranges/algorithm.h"
#include "base/sequence_checker.h"
#include "build/build_config.h"
namespace base {
enum class ObserverListPolicy {
ALL,
EXISTING_ONLY,
};
template <class ObserverType,
bool check_empty = false,
bool allow_reentrancy = true,
class ObserverStorageType = internal::CheckedObserverAdapter>
class ObserverList {
public:
using Unchecked = ObserverList<ObserverType,
check_empty,
allow_reentrancy,
internal::UncheckedObserverAdapter>;
class Iter {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = ObserverType;
using difference_type = ptrdiff_t;
using pointer = ObserverType*;
using reference = ObserverType&;
Iter() : index_(0), max_index_(0) {}
explicit Iter(const ObserverList* list)
: list_(const_cast<ObserverList*>(list)),
index_(0),
max_index_(list->policy_ == ObserverListPolicy::ALL
? std::numeric_limits<size_t>::max()
: list->observers_.size()) {
DCHECK(list);
if (!allow_reentrancy) {
DCHECK(list_.IsOnlyRemainingNode());
if (!DCHECK_IS_ON() && !list_.IsOnlyRemainingNode()) {
base::debug::DumpWithoutCrashing();
}
}
DCHECK(allow_reentrancy || list_.IsOnlyRemainingNode());
DCHECK_CALLED_ON_VALID_SEQUENCE(list_->iteration_sequence_checker_);
EnsureValidIndex();
}
~Iter() {
if (list_.IsOnlyRemainingNode())
list_->Compact();
}
Iter(const Iter& other)
: index_(other.index_), max_index_(other.max_index_) {
if (other.list_)
list_.SetList(other.list_.get());
}
Iter& operator=(const Iter& other) {
if (&other == this)
return *this;
if (list_.IsOnlyRemainingNode())
list_->Compact();
list_.Invalidate();
if (other.list_)
list_.SetList(other.list_.get());
index_ = other.index_;
max_index_ = other.max_index_;
return *this;
}
bool operator==(const Iter& other) const {
return (is_end() && other.is_end()) ||
(list_.get() == other.list_.get() && index_ == other.index_);
}
bool operator!=(const Iter& other) const { return !(*this == other); }
Iter& operator++() {
if (list_) {
++index_;
EnsureValidIndex();
}
return *this;
}
Iter operator++(int) {
Iter it(*this);
++(*this);
return it;
}
ObserverType* operator->() const {
ObserverType* const current = GetCurrent();
DCHECK(current);
return current;
}
ObserverType& operator*() const {
ObserverType* const current = GetCurrent();
DCHECK(current);
return *current;
}
private:
friend class ObserverListTestBase;
ObserverType* GetCurrent() const {
DCHECK(list_);
DCHECK_LT(index_, clamped_max_index());
return ObserverStorageType::template Get<ObserverType>(
list_->observers_[index_]);
}
void EnsureValidIndex() {
DCHECK(list_);
const size_t max_index = clamped_max_index();
while (index_ < max_index &&
list_->observers_[index_].IsMarkedForRemoval()) {
++index_;
}
}
size_t clamped_max_index() const {
return std::min(max_index_, list_->observers_.size());
}
bool is_end() const { return !list_ || index_ == clamped_max_index(); }
internal::WeakLinkNode<ObserverList> list_;
size_t index_;
size_t max_index_;
};
using iterator = Iter;
using const_iterator = Iter;
using value_type = ObserverType;
const_iterator begin() const {
return observers_.empty() ? const_iterator() : const_iterator(this);
}
const_iterator end() const { return const_iterator(); }
explicit ObserverList(ObserverListPolicy policy = ObserverListPolicy::ALL)
: policy_(policy) {
DETACH_FROM_SEQUENCE(iteration_sequence_checker_);
}
ObserverList(const ObserverList&) = delete;
ObserverList& operator=(const ObserverList&) = delete;
~ObserverList() {
if (!live_iterators_.empty())
DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_);
while (!live_iterators_.empty())
live_iterators_.head()->value()->Invalidate();
if (check_empty) {
Compact();
DCHECK(observers_.empty()) << "\n" << GetObserversCreationStackString();
if (!DCHECK_IS_ON() && !observers_.empty()) {
base::debug::DumpWithoutCrashing();
}
}
}
void AddObserver(ObserverType* obs) {
DCHECK(obs);
if (HasObserver(obs)) {
NOTREACHED() << "Observers can only be added once!";
return;
}
observers_count_++;
observers_.emplace_back(ObserverStorageType(obs));
}
void RemoveObserver(const ObserverType* obs) {
DCHECK(obs);
const auto it = ranges::find_if(
observers_, [obs](const auto& o) { return o.IsEqual(obs); });
if (it == observers_.end())
return;
if (!it->IsMarkedForRemoval())
observers_count_--;
if (live_iterators_.empty()) {
observers_.erase(it);
} else {
DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_);
it->MarkForRemoval();
}
}
bool HasObserver(const ObserverType* obs) const {
if (obs == nullptr)
return false;
return ranges::find_if(observers_, [obs](const auto& o) {
return o.IsEqual(obs);
}) != observers_.end();
}
void Clear() {
if (live_iterators_.empty()) {
observers_.clear();
} else {
DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_);
for (auto& observer : observers_)
observer.MarkForRemoval();
}
observers_count_ = 0;
}
bool empty() const { return !observers_count_; }
private:
friend class internal::WeakLinkNode<ObserverList>;
void Compact() {
DETACH_FROM_SEQUENCE(iteration_sequence_checker_);
observers_.erase(
std::remove_if(observers_.begin(), observers_.end(),
[](const auto& o) { return o.IsMarkedForRemoval(); }),
observers_.end());
}
std::string GetObserversCreationStackString() const {
#if DCHECK_IS_ON()
std::string result;
#if BUILDFLAG(IS_IOS)
result += "Use go/observer-list-empty to interpret.\n";
#endif
for (const auto& observer : observers_) {
result += observer.GetCreationStackString();
result += "\n";
}
return result;
#else
return "For observer stack traces, build with `dcheck_always_on=true`.";
#endif
}
std::vector<ObserverStorageType> observers_;
base::LinkedList<internal::WeakLinkNode<ObserverList>> live_iterators_;
size_t observers_count_{0};
const ObserverListPolicy policy_;
SEQUENCE_CHECKER(iteration_sequence_checker_);
};
template <class ObserverType, bool check_empty = false>
using ReentrantObserverList = ObserverList<ObserverType, check_empty, true>;
}
#endif