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 nullptr.
26 // This makes the correct idiom very simple:
27 //
28 //   ScopedUtfChars name(env, java_name);
29 //   if (name.c_str() == nullptr) {
30 //     return nullptr;
31 //   }
32 class ScopedUtfChars {
33  public:
ScopedUtfChars(JNIEnv * env,jstring s)34   ScopedUtfChars(JNIEnv* env, jstring s) : env_(env), string_(s) {
35     if (s == nullptr) {
36       utf_chars_ = nullptr;
37       jniThrowNullPointerException(env, nullptr);
38     } else {
39       utf_chars_ = env->GetStringUTFChars(s, nullptr);
40     }
41   }
42 
ScopedUtfChars(ScopedUtfChars && rhs)43   ScopedUtfChars(ScopedUtfChars&& rhs) :
44       env_(rhs.env_), string_(rhs.string_), utf_chars_(rhs.utf_chars_) {
45     rhs.env_ = nullptr;
46     rhs.string_ = nullptr;
47     rhs.utf_chars_ = nullptr;
48   }
49 
~ScopedUtfChars()50   ~ScopedUtfChars() {
51     if (utf_chars_) {
52       env_->ReleaseStringUTFChars(string_, utf_chars_);
53     }
54   }
55 
56   ScopedUtfChars& operator=(ScopedUtfChars&& rhs) {
57     if (this != &rhs) {
58       // Delete the currently owned UTF chars.
59       this->~ScopedUtfChars();
60 
61       // Move the rhs ScopedUtfChars and zero it out.
62       env_ = rhs.env_;
63       string_ = rhs.string_;
64       utf_chars_ = rhs.utf_chars_;
65       rhs.env_ = nullptr;
66       rhs.string_ = nullptr;
67       rhs.utf_chars_ = nullptr;
68     }
69     return *this;
70   }
71 
c_str()72   const char* c_str() const {
73     return utf_chars_;
74   }
75 
size()76   size_t size() const {
77     return strlen(utf_chars_);
78   }
79 
80   const char& operator[](size_t n) const {
81     return utf_chars_[n];
82   }
83 
84  private:
85   JNIEnv* env_;
86   jstring string_;
87   const char* utf_chars_;
88 
89   DISALLOW_COPY_AND_ASSIGN(ScopedUtfChars);
90 };
91 
92 #endif  // SCOPED_UTF_CHARS_H_included
93