blob: cfbd2473fa5af39e30f3fdec0596c01fbdf39ab0 [file] [log] [blame]
Brian Carlstrom3d9d2142013-05-10 14:09:30 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of 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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef SCOPED_STRING_CHARS_H_included
18#define SCOPED_STRING_CHARS_H_included
19
20#include "JNIHelp.h"
21
22// A smart pointer that provides access to a jchar* given a JNI jstring.
23// Unlike GetStringChars, we throw NullPointerException rather than abort if
24// passed a null jstring, and get will return NULL.
25// This makes the correct idiom very simple:
26//
27// ScopedStringChars name(env, java_name);
28// if (name.get() == NULL) {
29// return NULL;
30// }
31class ScopedStringChars {
32 public:
33 ScopedStringChars(JNIEnv* env, jstring s) : env_(env), string_(s), size_(0) {
34 if (s == NULL) {
35 chars_ = NULL;
36 jniThrowNullPointerException(env, NULL);
37 } else {
38 chars_ = env->GetStringChars(string_, NULL);
39 if (chars_ != NULL) {
40 size_ = env->GetStringLength(string_);
41 }
42 }
43 }
44
45 ~ScopedStringChars() {
46 if (chars_ != NULL) {
47 env_->ReleaseStringChars(string_, chars_);
48 }
49 }
50
51 const jchar* get() const {
52 return chars_;
53 }
54
55 size_t size() const {
56 return size_;
57 }
58
59 const jchar& operator[](size_t n) const {
60 return chars_[n];
61 }
62
63 private:
64 JNIEnv* env_;
65 jstring string_;
66 const jchar* chars_;
67 size_t size_;
68
69 // Disallow copy and assignment.
70 ScopedStringChars(const ScopedStringChars&);
71 void operator=(const ScopedStringChars&);
72};
73
74#endif // SCOPED_STRING_CHARS_H_included