1 /* 2 * Copyright (C) 2018 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 LIBTEXTCLASSIFIER_UTILS_JAVA_STRING_UTILS_H_ 18 #define LIBTEXTCLASSIFIER_UTILS_JAVA_STRING_UTILS_H_ 19 20 #include <jni.h> 21 #include <memory> 22 #include <string> 23 24 #include "utils/base/logging.h" 25 26 namespace libtextclassifier3 { 27 28 bool JByteArrayToString(JNIEnv* env, const jbyteArray& array, 29 std::string* result); 30 bool JStringToUtf8String(JNIEnv* env, const jstring& jstr, std::string* result); 31 32 // A deleter to be used with std::unique_ptr to release Java string chars. 33 class StringCharsReleaser { 34 public: StringCharsReleaser()35 StringCharsReleaser() : env_(nullptr) {} 36 StringCharsReleaser(JNIEnv * env,jstring jstr)37 StringCharsReleaser(JNIEnv* env, jstring jstr) : env_(env), jstr_(jstr) {} 38 39 StringCharsReleaser(const StringCharsReleaser& orig) = default; 40 41 // Copy assignment to allow move semantics in StringCharsReleaser. 42 StringCharsReleaser& operator=(const StringCharsReleaser& rhs) { 43 // As the releaser and its state are thread-local, it's enough to only 44 // ensure the envs are consistent but do nothing. 45 TC3_CHECK_EQ(env_, rhs.env_); 46 return *this; 47 } 48 49 // The delete operator. operator()50 void operator()(const char* chars) const { 51 if (env_ != nullptr) { 52 env_->ReleaseStringUTFChars(jstr_, chars); 53 } 54 } 55 56 private: 57 // The env_ stashed to use for deletion. Thread-local, don't share! 58 JNIEnv* const env_; 59 60 // The referenced jstring. 61 jstring jstr_; 62 }; 63 64 // A smart pointer that releases string chars when it goes out of scope. 65 // of scope. 66 // Note that this class is not thread-safe since it caches JNIEnv in 67 // the deleter. Do not use the same jobject across different threads. 68 using ScopedStringChars = std::unique_ptr<const char, StringCharsReleaser>; 69 70 // Returns a scoped pointer to the array of Unicode characters of a string. 71 ScopedStringChars GetScopedStringChars(JNIEnv* env, jstring string, 72 jboolean* is_copy = nullptr); 73 74 } // namespace libtextclassifier3 75 76 #endif // LIBTEXTCLASSIFIER_UTILS_JAVA_STRING_UTILS_H_ 77