blob: 7492a0c98eec88e9c11d3e28f56da0b041008139 [file] [log] [blame]
Elliott Hughesbcf7c662010-03-26 11:30:00 -07001/*
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"
Elliott Hughesa5d02942010-06-01 23:02:53 -070021#include <string.h>
Elliott Hughesbcf7c662010-03-26 11:30:00 -070022
23// A smart pointer that provides read-only access to a Java string's UTF chars.
Elliott Hughes05960872010-05-26 17:45:07 -070024// 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// }
Elliott Hughesbcf7c662010-03-26 11:30:00 -070032class ScopedUtfChars {
33public:
34 ScopedUtfChars(JNIEnv* env, jstring s)
Elliott Hughes05960872010-05-26 17:45:07 -070035 : mEnv(env), mString(s)
Elliott Hughesbcf7c662010-03-26 11:30:00 -070036 {
Elliott Hughes05960872010-05-26 17:45:07 -070037 if (s == NULL) {
38 mUtfChars = NULL;
39 jniThrowNullPointerException(env, NULL);
40 } else {
41 mUtfChars = env->GetStringUTFChars(s, NULL);
42 }
Elliott Hughesbcf7c662010-03-26 11:30:00 -070043 }
44
45 ~ScopedUtfChars() {
46 if (mUtfChars) {
47 mEnv->ReleaseStringUTFChars(mString, mUtfChars);
48 }
49 }
50
Elliott Hughes0808cae2010-04-23 16:15:38 -070051 const char* c_str() const {
Elliott Hughesbcf7c662010-03-26 11:30:00 -070052 return mUtfChars;
53 }
54
Elliott Hughes753dcd82010-06-01 18:07:56 -070055 size_t size() const {
56 return strlen(mUtfChars);
57 }
58
Elliott Hughesbcf7c662010-03-26 11:30:00 -070059 // Element access.
60 const char& operator[](size_t n) const {
61 return mUtfChars[n];
62 }
63
64private:
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