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