blob: 7251034de5be44ac89c5b63cc6f1e9c85563e41b [file] [log] [blame]
jat@google.com134be542009-08-03 15:30:11 +00001#ifndef _H_RootedObject
2#define _H_RootedObject
3/*
4 * Copyright 2008 Google Inc.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 * use this file except in compliance with the License. You may obtain a copy of
8 * the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 * License for the specific language governing permissions and limitations under
16 * the License.
17 */
18
19#include "Debug.h"
20
21#include "jsapi.h"
22
23class RootedObject {
24public:
25 RootedObject(JSContext* ctx, const char* name = 0) : ctx(ctx), obj(0) {
26 if (!JS_AddNamedRoot(ctx, &obj, name)) {
27 Debug::log(Debug::Error) << "RootedObject(" << (name ? name : "")
28 << "): JS_AddNamedRoot failed" << Debug::flush;
29 }
30 }
31
32 ~RootedObject() {
33 // Always returns success, so no need to check.
34 JS_RemoveRoot(ctx, &obj);
35 }
36
37 JSObject& operator*() const {
38 assert(obj != 0);
39 return *obj;
40 }
41
42 JSObject* operator->() const {
43 assert(obj != 0);
44 return obj;
45 }
46
47 bool operator==(JSObject* p) const {
48 return obj == p;
49 }
50
51 bool operator!=(JSObject* p) const {
52 return obj != p;
53 }
54
55 JSObject* get() const {
56 return obj;
57 }
58
59 RootedObject& operator=(JSObject* val) {
60 obj = val;
61 return *this;
62 }
63
64private:
65 JSContext* ctx;
66 JSObject* obj;
67};
68
69inline bool operator==(JSObject* p, const RootedObject& ro) {
70 return p == ro.get();
71}
72
73inline bool operator!=(JSObject* p, const RootedObject& ro) {
74 return p != ro.get();
75}
76
77#endif