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