1 /*
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 //   }
31 class ScopedStringChars {
32  public:
ScopedStringChars(JNIEnv * env,jstring s)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 
~ScopedStringChars()45   ~ScopedStringChars() {
46     if (chars_ != NULL) {
47       env_->ReleaseStringChars(string_, chars_);
48     }
49   }
50 
get()51   const jchar* get() const {
52     return chars_;
53   }
54 
size()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* const env_;
65   const jstring string_;
66   const jchar* chars_;
67   size_t size_;
68 
69   DISALLOW_COPY_AND_ASSIGN(ScopedStringChars);
70 };
71 
72 #endif  // SCOPED_STRING_CHARS_H_included
73