kMaxBlockSize -> kMaxHeaderBlockSize to avoid shadowing warning on VS2015
[chromium-blink-merge.git] / extensions / renderer / scoped_persistent.h
blobd7fe3066cfb51698302015eb6a8c2be15347a496
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.
5 #ifndef EXTENSIONS_RENDERER_SCOPED_PERSISTENT_H_
6 #define EXTENSIONS_RENDERER_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.
15 template <typename T>
16 class ScopedPersistent {
17 public:
18 ScopedPersistent() {}
20 explicit ScopedPersistent(v8::Handle<T> handle) { reset(handle); }
22 ScopedPersistent(v8::Isolate* isolate, v8::Handle<T> handle) {
23 reset(isolate, handle);
26 ~ScopedPersistent() { reset(); }
28 void reset(v8::Isolate* isolate, v8::Handle<T> handle) {
29 if (!handle.IsEmpty())
30 handle_.Reset(isolate, handle);
31 else
32 reset();
35 void reset(v8::Handle<T> handle) { reset(GetIsolate(handle), handle); }
37 void reset() { handle_.Reset(); }
39 bool IsEmpty() const { return handle_.IsEmpty(); }
41 v8::Handle<T> NewHandle() const {
42 if (handle_.IsEmpty())
43 return v8::Local<T>();
44 return v8::Local<T>::New(GetIsolate(handle_), handle_);
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_);
53 template <typename P>
54 void SetWeak(P* parameters,
55 typename v8::WeakCallbackData<T, P>::Callback callback) {
56 handle_.SetWeak(parameters, callback);
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();
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();
73 static v8::Isolate* GetIsolate(
74 v8::Handle<v8::ObjectTemplate> template_handle) {
75 return v8::Isolate::GetCurrent();
78 v8::Persistent<T> handle_;
80 DISALLOW_COPY_AND_ASSIGN(ScopedPersistent);
83 } // namespace extensions
85 #endif // EXTENSIONS_RENDERER_SCOPED_PERSISTENT_H_