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.
5 #ifndef BASE_SUPPORTS_USER_DATA_H_
6 #define BASE_SUPPORTS_USER_DATA_H_
10 #include "base/base_export.h"
11 #include "base/memory/linked_ptr.h"
12 #include "base/memory/ref_counted.h"
16 // This is a helper for classes that want to allow users to stash random data by
17 // key. At destruction all the objects will be destructed.
18 class BASE_EXPORT SupportsUserData
{
22 // Derive from this class and add your own data members to associate extra
23 // information with this object. Alternatively, add this as a public base
24 // class to any class with a virtual destructor.
25 class BASE_EXPORT Data
{
30 // The user data allows the clients to associate data with this object.
31 // Multiple user data values can be stored under different keys.
32 // This object will TAKE OWNERSHIP of the given data pointer, and will
33 // delete the object if it is changed or the object is destroyed.
34 Data
* GetUserData(const void* key
) const;
35 void SetUserData(const void* key
, Data
* data
);
36 void RemoveUserData(const void* key
);
39 virtual ~SupportsUserData();
42 typedef std::map
<const void*, linked_ptr
<Data
> > DataMap
;
44 // Externally-defined data accessible by key.
47 DISALLOW_COPY_AND_ASSIGN(SupportsUserData
);
50 // Adapter class that releases a refcounted object when the
51 // SupportsUserData::Data object is deleted.
53 class UserDataAdapter
: public base::SupportsUserData::Data
{
55 static T
* Get(SupportsUserData
* supports_user_data
, const char* key
) {
56 UserDataAdapter
* data
=
57 static_cast<UserDataAdapter
*>(supports_user_data
->GetUserData(key
));
58 return static_cast<T
*>(data
->object_
.get());
61 UserDataAdapter(T
* object
) : object_(object
) {}
62 T
* release() { return object_
.release(); }
65 scoped_refptr
<T
> object_
;
67 DISALLOW_COPY_AND_ASSIGN(UserDataAdapter
);
72 #endif // BASE_SUPPORTS_USER_DATA_H_