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