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 SCOPED_UTF_CHARS_H_included
18#define SCOPED_UTF_CHARS_H_included
19
20#include <string.h>
21#include <jni.h>
22
23#include "android-base/logging.h"
24
25// This file was copied with some minor modifications from libnativehelper.
26// As soon as libnativehelper can be compiled for Windows, this file should be
27// replaced with libnativehelper's implementation.
28class ScopedUtfChars {
29 public:
30  ScopedUtfChars(JNIEnv* env, jstring s) : env_(env), string_(s) {
31    CHECK(s != nullptr);
32    utf_chars_ = env->GetStringUTFChars(s, nullptr);
33  }
34
35  ScopedUtfChars(ScopedUtfChars&& rhs) :
36      env_(rhs.env_), string_(rhs.string_), utf_chars_(rhs.utf_chars_) {
37    rhs.env_ = nullptr;
38    rhs.string_ = nullptr;
39    rhs.utf_chars_ = nullptr;
40  }
41
42  ~ScopedUtfChars() {
43    if (utf_chars_) {
44      env_->ReleaseStringUTFChars(string_, utf_chars_);
45    }
46  }
47
48  ScopedUtfChars& operator=(ScopedUtfChars&& rhs) {
49    if (this != &rhs) {
50      // Delete the currently owned UTF chars.
51      this->~ScopedUtfChars();
52
53      // Move the rhs ScopedUtfChars and zero it out.
54      env_ = rhs.env_;
55      string_ = rhs.string_;
56      utf_chars_ = rhs.utf_chars_;
57      rhs.env_ = nullptr;
58      rhs.string_ = nullptr;
59      rhs.utf_chars_ = nullptr;
60    }
61    return *this;
62  }
63
64  const char* c_str() const {
65    return utf_chars_;
66  }
67
68  size_t size() const {
69    return strlen(utf_chars_);
70  }
71
72  const char& operator[](size_t n) const {
73    return utf_chars_[n];
74  }
75
76 private:
77  JNIEnv* env_;
78  jstring string_;
79  const char* utf_chars_;
80
81  DISALLOW_COPY_AND_ASSIGN(ScopedUtfChars);
82};
83
84#endif  // SCOPED_UTF_CHARS_H_included
85