Home | History | Annotate | Download | only in nativehelper
      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 SCOPEDUTFCHARS_H_
     18 #define SCOPEDUTFCHARS_H_
     19 
     20 #include <string.h>
     21 #include <conscrypt/jniutil.h>
     22 
     23 // A smart pointer that provides read-only access to a Java string's UTF chars.
     24 // Unlike GetStringUTFChars, we throw NullPointerException rather than abort if
     25 // passed a null jstring, and c_str will return nullptr.
     26 // This makes the correct idiom very simple:
     27 //
     28 //   ScopedUtfChars name(env, java_name);
     29 //   if (name.c_str() == nullptr) {
     30 //     return nullptr;
     31 //   }
     32 class ScopedUtfChars {
     33  public:
     34     ScopedUtfChars(JNIEnv* env, jstring s) : env_(env), string_(s) {
     35         if (s == nullptr) {
     36             utf_chars_ = nullptr;
     37             conscrypt::jniutil::throwNullPointerException(env, nullptr);
     38         } else {
     39             utf_chars_ = env->GetStringUTFChars(s, nullptr);
     40         }
     41     }
     42 
     43     ~ScopedUtfChars() {
     44         if (utf_chars_) {
     45             env_->ReleaseStringUTFChars(string_, utf_chars_);
     46         }
     47     }
     48 
     49     const char* c_str() const {
     50         return utf_chars_;
     51     }
     52 
     53     size_t size() const {
     54         return strlen(utf_chars_);
     55     }
     56 
     57     const char& operator[](size_t n) const {
     58         return utf_chars_[n];
     59     }
     60 
     61  private:
     62     JNIEnv* env_;
     63     jstring string_;
     64     const char* utf_chars_;
     65 
     66     // Disallow copy and assignment.
     67     ScopedUtfChars(const ScopedUtfChars&);
     68     void operator=(const ScopedUtfChars&);
     69 };
     70 
     71 #endif  // SCOPEDUTFCHARS_H_
     72