jat@google.com | 134be54 | 2009-08-03 15:30:11 +0000 | [diff] [blame] | 1 | #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 | |
| 23 | class RootedObject { |
| 24 | public: |
| 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 | |
| 64 | private: |
| 65 | JSContext* ctx; |
| 66 | JSObject* obj; |
| 67 | }; |
| 68 | |
| 69 | inline bool operator==(JSObject* p, const RootedObject& ro) { |
| 70 | return p == ro.get(); |
| 71 | } |
| 72 | |
| 73 | inline bool operator!=(JSObject* p, const RootedObject& ro) { |
| 74 | return p != ro.get(); |
| 75 | } |
| 76 | |
| 77 | #endif |