• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 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_UTF_CHARS_H_included
18 #define SCOPED_UTF_CHARS_H_included
19 
20 #include "JNIHelp.h"
21 #include <string.h>
22 
23 // A smart pointer that provides read-only access to a Java string's UTF chars.
24 // Unlike GetStringUTFChars, we throw NullPointerException rather than abort if
25 // passed a null jstring, and c_str will return NULL.
26 // This makes the correct idiom very simple:
27 //
28 //   ScopedUtfChars name(env, javaName);
29 //   if (name.c_str() == NULL) {
30 //       return NULL;
31 //   }
32 class ScopedUtfChars {
33 public:
ScopedUtfChars(JNIEnv * env,jstring s)34     ScopedUtfChars(JNIEnv* env, jstring s)
35     : mEnv(env), mString(s)
36     {
37         if (s == NULL) {
38             mUtfChars = NULL;
39             jniThrowNullPointerException(env, NULL);
40         } else {
41             mUtfChars = env->GetStringUTFChars(s, NULL);
42         }
43     }
44 
~ScopedUtfChars()45     ~ScopedUtfChars() {
46         if (mUtfChars) {
47             mEnv->ReleaseStringUTFChars(mString, mUtfChars);
48         }
49     }
50 
c_str()51     const char* c_str() const {
52         return mUtfChars;
53     }
54 
size()55     size_t size() const {
56         return strlen(mUtfChars);
57     }
58 
59     // Element access.
60     const char& operator[](size_t n) const {
61         return mUtfChars[n];
62     }
63 
64 private:
65     JNIEnv* mEnv;
66     jstring mString;
67     const char* mUtfChars;
68 
69     // Disallow copy and assignment.
70     ScopedUtfChars(const ScopedUtfChars&);
71     void operator=(const ScopedUtfChars&);
72 };
73 
74 #endif  // SCOPED_UTF_CHARS_H_included
75