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 CHROME_RENDERER_EXTENSIONS_SCOPED_PERSISTENT_H_
6 #define CHROME_RENDERER_EXTENSIONS_SCOPED_PERSISTENT_H_
8 #include "base/logging.h"
9 #include "v8/include/v8.h"
11 namespace extensions {
13 // A v8::Persistent handle to a V8 value which destroys and clears the
14 // underlying handle on destruction.
16 class ScopedPersistent {
21 explicit ScopedPersistent(v8::Handle<T> handle) {
29 void reset(v8::Handle<T> handle) {
30 if (!handle.IsEmpty())
31 handle_.Reset(GetIsolate(handle), handle);
37 if (handle_.IsEmpty())
43 bool IsEmpty() const {
44 return handle_.IsEmpty();
47 v8::Handle<T> NewHandle() const {
48 if (handle_.IsEmpty())
49 return v8::Local<T>();
50 return v8::Local<T>::New(GetIsolate(handle_), handle_);
53 v8::Handle<T> NewHandle(v8::Isolate* isolate) const {
54 if (handle_.IsEmpty())
55 return v8::Local<T>();
56 return v8::Local<T>::New(isolate, handle_);
60 void MakeWeak(P* parameters,
61 typename v8::WeakReferenceCallbacks<T, P>::Revivable callback) {
62 handle_.MakeWeak(parameters, callback);
67 static v8::Isolate* GetIsolate(v8::Handle<U> object_handle) {
68 // Only works for v8::Object and its subclasses. Add specialisations for
70 if (!object_handle.IsEmpty())
71 return GetIsolate(object_handle->CreationContext());
72 return v8::Isolate::GetCurrent();
74 static v8::Isolate* GetIsolate(v8::Handle<v8::Context> context_handle) {
75 if (!context_handle.IsEmpty())
76 return context_handle->GetIsolate();
77 return v8::Isolate::GetCurrent();
79 static v8::Isolate* GetIsolate(
80 v8::Handle<v8::ObjectTemplate> template_handle) {
81 return v8::Isolate::GetCurrent();
84 v8::Persistent<T> handle_;
86 DISALLOW_COPY_AND_ASSIGN(ScopedPersistent);
89 } // namespace extensions
91 #endif // CHROME_RENDERER_EXTENSIONS_SCOPED_PERSISTENT_H_