• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 SRC_ANDROID_SDK_NATIVEHELPER_SCOPED_STRING_CHARS_H_
18 #define SRC_ANDROID_SDK_NATIVEHELPER_SCOPED_STRING_CHARS_H_
19 
20 // Copied from
21 // https://cs.android.com/android/platform/superproject/main/+/main:libnativehelper/header_only_include/nativehelper/scoped_string_chars.h;drc=4be05051ef76b2c24d8385732a892401eb45d911
22 
23 #include <stddef.h>
24 
25 #include <jni.h>
26 
27 #include "src/android_sdk/nativehelper/nativehelper_utils.h"
28 
29 // A smart pointer that provides access to a jchar* given a JNI jstring.
30 // Unlike GetStringChars, we throw NullPointerException rather than abort if
31 // passed a null jstring, and get will return nullptr.
32 // This makes the correct idiom very simple:
33 //
34 //   ScopedStringChars name(env, java_name);
35 //   if (name.get() == nullptr) {
36 //     return nullptr;
37 //   }
38 class ScopedStringChars {
39  public:
ScopedStringChars(JNIEnv * env,jstring s)40   ScopedStringChars(JNIEnv* env, jstring s) : env_(env), string_(s), size_(0) {
41     if (s == nullptr) {
42       chars_ = nullptr;
43       jniThrowNullPointerException(env);
44     } else {
45       chars_ = env->GetStringChars(string_, nullptr);
46       if (chars_ != nullptr) {
47         size_ = env->GetStringLength(string_);
48       }
49     }
50   }
51 
~ScopedStringChars()52   ~ScopedStringChars() {
53     if (chars_ != nullptr) {
54       env_->ReleaseStringChars(string_, chars_);
55     }
56   }
57 
get()58   const jchar* get() const { return chars_; }
59 
size()60   size_t size() const { return size_; }
61 
62   const jchar& operator[](size_t n) const { return chars_[n]; }
63 
64  private:
65   JNIEnv* const env_;
66   const jstring string_;
67   const jchar* chars_;
68   size_t size_;
69 
70   DISALLOW_COPY_AND_ASSIGN(ScopedStringChars);
71 };
72 
73 #endif  // SRC_ANDROID_SDK_NATIVEHELPER_SCOPED_STRING_CHARS_H_
74