OLD | NEW |
| (Empty) |
1 // Copyright 2014 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 EXTENSIONS_RENDERER_SCOPED_PERSISTENT_H_ | |
6 #define EXTENSIONS_RENDERER_SCOPED_PERSISTENT_H_ | |
7 | |
8 #include "base/logging.h" | |
9 #include "v8/include/v8.h" | |
10 | |
11 namespace extensions { | |
12 | |
13 // A v8::Persistent handle to a V8 value which destroys and clears the | |
14 // underlying handle on destruction. | |
15 template <typename T> | |
16 class ScopedPersistent { | |
17 public: | |
18 ScopedPersistent() {} | |
19 | |
20 explicit ScopedPersistent(v8::Handle<T> handle) { reset(handle); } | |
21 | |
22 ScopedPersistent(v8::Isolate* isolate, v8::Handle<T> handle) { | |
23 reset(isolate, handle); | |
24 } | |
25 | |
26 ~ScopedPersistent() { reset(); } | |
27 | |
28 void reset(v8::Isolate* isolate, v8::Handle<T> handle) { | |
29 if (!handle.IsEmpty()) | |
30 handle_.Reset(isolate, handle); | |
31 else | |
32 reset(); | |
33 } | |
34 | |
35 void reset(v8::Handle<T> handle) { reset(GetIsolate(handle), handle); } | |
36 | |
37 void reset() { handle_.Reset(); } | |
38 | |
39 bool IsEmpty() const { return handle_.IsEmpty(); } | |
40 | |
41 v8::Handle<T> NewHandle() const { | |
42 if (handle_.IsEmpty()) | |
43 return v8::Local<T>(); | |
44 return v8::Local<T>::New(GetIsolate(handle_), handle_); | |
45 } | |
46 | |
47 v8::Handle<T> NewHandle(v8::Isolate* isolate) const { | |
48 if (handle_.IsEmpty()) | |
49 return v8::Local<T>(); | |
50 return v8::Local<T>::New(isolate, handle_); | |
51 } | |
52 | |
53 template <typename P> | |
54 void SetWeak(P* parameters, | |
55 typename v8::WeakCallbackData<T, P>::Callback callback) { | |
56 handle_.SetWeak(parameters, callback); | |
57 } | |
58 | |
59 private: | |
60 template <typename U> | |
61 static v8::Isolate* GetIsolate(v8::Handle<U> object_handle) { | |
62 // Only works for v8::Object and its subclasses. Add specialisations for | |
63 // anything else. | |
64 if (!object_handle.IsEmpty()) | |
65 return GetIsolate(object_handle->CreationContext()); | |
66 return v8::Isolate::GetCurrent(); | |
67 } | |
68 static v8::Isolate* GetIsolate(v8::Handle<v8::Context> context_handle) { | |
69 if (!context_handle.IsEmpty()) | |
70 return context_handle->GetIsolate(); | |
71 return v8::Isolate::GetCurrent(); | |
72 } | |
73 static v8::Isolate* GetIsolate( | |
74 v8::Handle<v8::ObjectTemplate> template_handle) { | |
75 return v8::Isolate::GetCurrent(); | |
76 } | |
77 | |
78 v8::Persistent<T> handle_; | |
79 | |
80 DISALLOW_COPY_AND_ASSIGN(ScopedPersistent); | |
81 }; | |
82 | |
83 } // namespace extensions | |
84 | |
85 #endif // EXTENSIONS_RENDERER_SCOPED_PERSISTENT_H_ | |
OLD | NEW |