blob: e553e4b6428c874961cb4992dd34068764655100 [file] [log] [blame]
[email protected]d379b0c2013-12-05 05:48:011// 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.
4
5#ifndef GIN_HANDLE_H_
6#define GIN_HANDLE_H_
7
8#include "gin/converter.h"
9
10namespace gin {
11
12// You can use gin::Handle on the stack to retain a gin::Wrappable object.
13// Currently we don't have a mechanism for retaining a gin::Wrappable object
14// in the C++ heap because strong references from C++ to V8 can cause memory
15// leaks.
16template<typename T>
17class Handle {
18 public:
19 Handle() : object_(NULL) {}
20
deepak.sfaaa1b62015-04-30 07:30:4821 Handle(v8::Local<v8::Value> wrapper, T* object)
[email protected]d379b0c2013-12-05 05:48:0122 : wrapper_(wrapper),
23 object_(object) {
24 }
25
26 bool IsEmpty() const { return !object_; }
27
28 void Clear() {
29 wrapper_.Clear();
30 object_ = NULL;
31 }
32
33 T* operator->() const { return object_; }
deepak.sfaaa1b62015-04-30 07:30:4834 v8::Local<v8::Value> ToV8() const { return wrapper_; }
[email protected]d379b0c2013-12-05 05:48:0135 T* get() const { return object_; }
36
37 private:
deepak.sfaaa1b62015-04-30 07:30:4838 v8::Local<v8::Value> wrapper_;
[email protected]d379b0c2013-12-05 05:48:0139 T* object_;
40};
41
42template<typename T>
43struct Converter<gin::Handle<T> > {
deepak.sfaaa1b62015-04-30 07:30:4844 static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
[email protected]d379b0c2013-12-05 05:48:0145 const gin::Handle<T>& val) {
46 return val.ToV8();
47 }
deepak.sfaaa1b62015-04-30 07:30:4848 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
[email protected]d379b0c2013-12-05 05:48:0149 gin::Handle<T>* out) {
50 T* object = NULL;
[email protected]481d2492013-12-13 23:55:2551 if (!Converter<T*>::FromV8(isolate, val, &object)) {
52 return false;
53 }
54 *out = gin::Handle<T>(val, object);
55 return true;
[email protected]d379b0c2013-12-05 05:48:0156 }
57};
58
59// This function is a convenient way to create a handle from a raw pointer
60// without having to write out the type of the object explicitly.
61template<typename T>
62gin::Handle<T> CreateHandle(v8::Isolate* isolate, T* object) {
deepak.sfaaa1b62015-04-30 07:30:4863 v8::Local<v8::Object> wrapper = object->GetWrapper(isolate);
[email protected]e0719edc2014-02-28 14:48:2564 if (wrapper.IsEmpty())
65 return gin::Handle<T>();
66 return gin::Handle<T>(wrapper, object);
[email protected]d379b0c2013-12-05 05:48:0167}
68
69} // namespace gin
70
71#endif // GIN_HANDLE_H_