Add ICU message format support
[chromium-blink-merge.git] / ios / web / public / web_state / web_state_user_data.h
blob61145b9bbe198058a993daa7b3dc44c790cde26b
1 // Copyright 2013 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 IOS_WEB_PUBLIC_WEB_STATE_WEB_STATE_USER_DATA_H_
6 #define IOS_WEB_PUBLIC_WEB_STATE_WEB_STATE_USER_DATA_H_
8 #include "base/logging.h"
9 #include "base/supports_user_data.h"
10 #include "ios/web/public/web_state/web_state.h"
12 namespace web {
14 // A base class for classes attached to, and scoped to, the lifetime of a
15 // WebState. For example:
17 // --- in foo.h ---
18 // class Foo : public web::WebStateUserData<Foo> {
19 // public:
20 // ~Foo() override;
21 // // ... more public stuff here ...
22 // private:
23 // explicit Foo(web::WebState* web_state);
24 // friend class web::WebStateUserData<Foo>;
25 // // ... more private stuff here ...
26 // }
27 // --- in foo.cc ---
28 // DEFINE_WEB_CONTENTS_USER_DATA_KEY(Foo);
30 template <typename T>
31 class WebStateUserData : public base::SupportsUserData::Data {
32 public:
33 // Creates an object of type T, and attaches it to the specified WebState.
34 // If an instance is already attached, does nothing.
35 static void CreateForWebState(WebState* web_state) {
36 DCHECK(web_state);
37 if (!FromWebState(web_state))
38 web_state->SetUserData(UserDataKey(), new T(web_state));
41 // Retrieves the instance of type T that was attached to the specified
42 // WebState (via CreateForWebState above) and returns it. If no instance
43 // of the type was attached, returns null.
44 static T* FromWebState(WebState* web_state) {
45 return static_cast<T*>(web_state->GetUserData(UserDataKey()));
47 static const T* FromWebState(const WebState* web_state) {
48 return static_cast<const T*>(web_state->GetUserData(UserDataKey()));
50 // Removes the instance attached to the specified WebState.
51 static void RemoveFromWebState(WebState* web_state) {
52 web_state->RemoveUserData(UserDataKey());
55 protected:
56 static inline void* UserDataKey() { return &kLocatorKey; }
58 private:
59 // The user data key.
60 static int kLocatorKey;
63 // The macro to define the locator key. This key should be defined in the .cc
64 // file of the derived class.
66 // The "= 0" is surprising, but is required to effect a definition rather than
67 // a declaration. Without it, this would be merely a declaration of a template
68 // specialization. (C++98: 14.7.3.15; C++11: 14.7.3.13)
70 #define DEFINE_WEB_STATE_USER_DATA_KEY(TYPE) \
71 template <> \
72 int web::WebStateUserData<TYPE>::kLocatorKey = 0
74 } // namespace web
76 #endif // IOS_WEB_PUBLIC_WEB_STATE_WEB_STATE_USER_DATA_H_