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, java_name);
29//   if (name.c_str() == NULL) {
30//     return NULL;
31//   }
32class ScopedUtfChars {
33 public:
34  ScopedUtfChars(JNIEnv* env, jstring s) : env_(env), string_(s) {
35    if (s == NULL) {
36      utf_chars_ = NULL;
37      jniThrowNullPointerException(env, NULL);
38    } else {
39      utf_chars_ = env->GetStringUTFChars(s, NULL);
40    }
41  }
42
43  ~ScopedUtfChars() {
44    if (utf_chars_) {
45      env_->ReleaseStringUTFChars(string_, utf_chars_);
46    }
47  }
48
49  const char* c_str() const {
50    return utf_chars_;
51  }
52
53  size_t size() const {
54    return strlen(utf_chars_);
55  }
56
57  const char& operator[](size_t n) const {
58    return utf_chars_[n];
59  }
60
61 private:
62  JNIEnv* env_;
63  jstring string_;
64  const char* utf_chars_;
65
66  // Disallow copy and assignment.
67  ScopedUtfChars(const ScopedUtfChars&);
68  void operator=(const ScopedUtfChars&);
69};
70
71#endif  // SCOPED_UTF_CHARS_H_included
72