1 // Copyright (c) 2012 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.
4 
5 #include "base/supports_user_data.h"
6 
7 namespace base {
8 
SupportsUserData()9 SupportsUserData::SupportsUserData() {
10   // Harmless to construct on a different execution sequence to subsequent
11   // usage.
12   sequence_checker_.DetachFromSequence();
13 }
14 
GetUserData(const void * key) const15 SupportsUserData::Data* SupportsUserData::GetUserData(const void* key) const {
16   DCHECK(sequence_checker_.CalledOnValidSequence());
17   // Avoid null keys; they are too vulnerable to collision.
18   DCHECK(key);
19   DataMap::const_iterator found = user_data_.find(key);
20   if (found != user_data_.end())
21     return found->second.get();
22   return nullptr;
23 }
24 
SetUserData(const void * key,std::unique_ptr<Data> data)25 void SupportsUserData::SetUserData(const void* key,
26                                    std::unique_ptr<Data> data) {
27   DCHECK(sequence_checker_.CalledOnValidSequence());
28   // Avoid null keys; they are too vulnerable to collision.
29   DCHECK(key);
30   user_data_[key] = std::move(data);
31 }
32 
RemoveUserData(const void * key)33 void SupportsUserData::RemoveUserData(const void* key) {
34   DCHECK(sequence_checker_.CalledOnValidSequence());
35   user_data_.erase(key);
36 }
37 
DetachFromSequence()38 void SupportsUserData::DetachFromSequence() {
39   sequence_checker_.DetachFromSequence();
40 }
41 
~SupportsUserData()42 SupportsUserData::~SupportsUserData() {
43   DCHECK(sequence_checker_.CalledOnValidSequence() || user_data_.empty());
44   DataMap local_user_data;
45   user_data_.swap(local_user_data);
46   // Now this->user_data_ is empty, and any destructors called transitively from
47   // the destruction of |local_user_data| will see it that way instead of
48   // examining a being-destroyed object.
49 }
50 
51 }  // namespace base
52