1 // Copyright 2012 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 #include "base/supports_user_data.h"
7 #include "base/sequence_checker.h"
11 std::unique_ptr<SupportsUserData::Data> SupportsUserData::Data::Clone() {
15 SupportsUserData::SupportsUserData() {
16 // Harmless to construct on a different execution sequence to subsequent
18 DETACH_FROM_SEQUENCE(sequence_checker_);
21 SupportsUserData::SupportsUserData(SupportsUserData&&) = default;
22 SupportsUserData& SupportsUserData::operator=(SupportsUserData&&) = default;
24 SupportsUserData::Data* SupportsUserData::GetUserData(const void* key) const {
25 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
26 // Avoid null keys; they are too vulnerable to collision.
28 auto found = user_data_.find(key);
29 if (found != user_data_.end())
30 return found->second.get();
34 void SupportsUserData::SetUserData(const void* key,
35 std::unique_ptr<Data> data) {
36 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
37 // Avoid null keys; they are too vulnerable to collision.
40 user_data_[key] = std::move(data);
45 void SupportsUserData::RemoveUserData(const void* key) {
46 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
47 user_data_.erase(key);
50 void SupportsUserData::DetachFromSequence() {
51 DETACH_FROM_SEQUENCE(sequence_checker_);
54 void SupportsUserData::CloneDataFrom(const SupportsUserData& other) {
55 for (const auto& data_pair : other.user_data_) {
56 auto cloned_data = data_pair.second->Clone();
58 SetUserData(data_pair.first, std::move(cloned_data));
62 SupportsUserData::~SupportsUserData() {
63 if (!user_data_.empty()) {
64 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
66 DataMap local_user_data;
67 user_data_.swap(local_user_data);
68 // Now this->user_data_ is empty, and any destructors called transitively from
69 // the destruction of |local_user_data| will see it that way instead of
70 // examining a being-destroyed object.
73 void SupportsUserData::ClearAllUserData() {
74 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);