jat@google.com | 64a55cb | 2009-10-16 14:16:57 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2007 Google Inc. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 5 | * use this file except in compliance with the License. You may obtain a copy of |
| 6 | * the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | * License for the specific language governing permissions and limitations under |
| 14 | * the License. |
| 15 | */ |
| 16 | |
| 17 | #ifndef JNI_LINUX_JSSTRINGWRAP_H_ |
| 18 | #define JNI_LINUX_JSSTRINGWRAP_H_ |
| 19 | |
| 20 | /* |
| 21 | * Wrapper arouond JavaScript Strings, keeps pointers to unpacked strings |
| 22 | * and makes sure they are not cleaned up early. |
| 23 | */ |
| 24 | class JsStringWrap { |
| 25 | private: |
| 26 | JSContext* context_; |
| 27 | JSString* string_; |
| 28 | const char* bytes_; |
| 29 | const wchar_t* chars_; |
| 30 | |
| 31 | public: |
| 32 | JsStringWrap(JSContext* context, JSString* str) |
| 33 | : context_(context), string_(str), bytes_(0), chars_(0) { |
| 34 | JS_AddRoot(context_, &string_); |
| 35 | JS_AddRoot(context_, &bytes_); |
| 36 | JS_AddRoot(context_, &chars_); |
| 37 | } |
| 38 | JsStringWrap(JSContext* context, jsval str) |
| 39 | : context_(context), string_(JSVAL_TO_STRING(str)), bytes_(0), chars_(0) { |
| 40 | JS_AddRoot(context_, &string_); |
| 41 | JS_AddRoot(context_, &bytes_); |
| 42 | JS_AddRoot(context_, &chars_); |
| 43 | } |
| 44 | ~JsStringWrap() { |
| 45 | JS_RemoveRoot(context_, &string_); |
| 46 | JS_RemoveRoot(context_, &bytes_); |
| 47 | JS_RemoveRoot(context_, &chars_); |
| 48 | } |
| 49 | const char* bytes() { |
| 50 | if (!bytes_) bytes_ = JS_GetStringBytes(string_); |
| 51 | return bytes_; |
| 52 | } |
| 53 | const wchar_t* chars() { |
| 54 | if (!chars_) { |
| 55 | chars_ = reinterpret_cast<wchar_t*>(JS_GetStringChars(string_)); |
| 56 | } |
| 57 | return chars_; |
| 58 | } |
| 59 | int length() { |
| 60 | return JS_GetStringLength(string_); |
| 61 | } |
| 62 | }; |
| 63 | |
| 64 | #endif // JNI_LINUX_JSSTRINGWRAP_H_ |