blob: 1c90e011ae9493134ec78c88811236e634b018ea [file] [log] [blame]
[email protected]ea8e1812012-02-15 22:07:341// 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#ifndef BASE_SUPPORTS_USER_DATA_H_
6#define BASE_SUPPORTS_USER_DATA_H_
7
8#include <map>
9
10#include "base/base_export.h"
11#include "base/memory/linked_ptr.h"
[email protected]314c3e22012-02-21 03:57:4212#include "base/memory/ref_counted.h"
[email protected]ea8e1812012-02-15 22:07:3413
14namespace base {
15
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.
18class BASE_EXPORT SupportsUserData {
19 public:
20 SupportsUserData();
21 virtual ~SupportsUserData();
22
23 // Derive from this class and add your own data members to associate extra
24 // information with this object. Use GetUserData(key) and SetUserData()
25 class BASE_EXPORT Data {
26 public:
27 virtual ~Data() {}
28 };
29
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
37 private:
38 typedef std::map<const void*, linked_ptr<Data> > DataMap;
39
40 // Externally-defined data accessible by key
41 DataMap user_data_;
42
43 DISALLOW_COPY_AND_ASSIGN(SupportsUserData);
44};
45
[email protected]314c3e22012-02-21 03:57:4246// Adapter class that releases a refcounted object when the
47// SupportsUserData::Data object is deleted.
48template <typename T>
49class UserDataAdapter : public base::SupportsUserData::Data {
50 public:
51 static T* Get(SupportsUserData* supports_user_data, const char* key) {
52 UserDataAdapter* data =
53 static_cast<UserDataAdapter*>(supports_user_data->GetUserData(key));
54 return static_cast<T*>(data->object_.get());
55 }
56
57 UserDataAdapter(T* object) : object_(object) {}
58
59 private:
60 scoped_refptr<T> object_;
61
62 DISALLOW_COPY_AND_ASSIGN(UserDataAdapter);
63};
64
[email protected]ea8e1812012-02-15 22:07:3465} // namespace base
66
67#endif // BASE_SUPPORTS_USER_DATA_H_