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 #pragma once
18 
19 #include <stddef.h>
20 #include <string.h>
21 
22 #include <jni.h>
23 
24 #include "nativehelper_utils.h"
25 
26 // A smart pointer that provides read-only access to a Java string's UTF chars.
27 // Unlike GetStringUTFChars, we throw NullPointerException rather than abort if
28 // passed a null jstring, and c_str will return nullptr.
29 // This makes the correct idiom very simple:
30 //
31 //   ScopedUtfChars name(env, java_name);
32 //   if (name.c_str() == nullptr) {
33 //     return nullptr;
34 //   }
35 class ScopedUtfChars {
36  public:
ScopedUtfChars(JNIEnv * env,jstring s)37   ScopedUtfChars(JNIEnv* env, jstring s) : env_(env), string_(s) {
38     if (s == nullptr) {
39       utf_chars_ = nullptr;
40       jniThrowNullPointerException(env);
41     } else {
42       utf_chars_ = env->GetStringUTFChars(s, nullptr);
43     }
44   }
45 
ScopedUtfChars(ScopedUtfChars && rhs)46   ScopedUtfChars(ScopedUtfChars&& rhs) noexcept :
47       env_(rhs.env_), string_(rhs.string_), utf_chars_(rhs.utf_chars_) {
48     rhs.env_ = nullptr;
49     rhs.string_ = nullptr;
50     rhs.utf_chars_ = nullptr;
51   }
52 
~ScopedUtfChars()53   ~ScopedUtfChars() {
54     if (utf_chars_) {
55       env_->ReleaseStringUTFChars(string_, utf_chars_);
56     }
57   }
58 
59   ScopedUtfChars& operator=(ScopedUtfChars&& rhs) noexcept {
60     if (this != &rhs) {
61       // Delete the currently owned UTF chars.
62       this->~ScopedUtfChars();
63 
64       // Move the rhs ScopedUtfChars and zero it out.
65       env_ = rhs.env_;
66       string_ = rhs.string_;
67       utf_chars_ = rhs.utf_chars_;
68       rhs.env_ = nullptr;
69       rhs.string_ = nullptr;
70       rhs.utf_chars_ = nullptr;
71     }
72     return *this;
73   }
74 
c_str()75   const char* c_str() const {
76     return utf_chars_;
77   }
78 
size()79   size_t size() const {
80     return strlen(utf_chars_);
81   }
82 
83   const char& operator[](size_t n) const {
84     return utf_chars_[n];
85   }
86 
87  private:
88   JNIEnv* env_;
89   jstring string_;
90   const char* utf_chars_;
91 
92   DISALLOW_COPY_AND_ASSIGN(ScopedUtfChars);
93 };
94 
95