blob: d9954683a8f2adf34463ece29ec028e04b46600c [file] [log] [blame]
Lukas Zilkae5ea2ab2017-10-11 10:50:05 +02001/*
2 * Copyright (C) 2017 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_UTIL_JAVA_SCOPED_LOCAL_REF_H_
18#define LIBTEXTCLASSIFIER_UTIL_JAVA_SCOPED_LOCAL_REF_H_
19
20#include <jni.h>
21#include <memory>
22#include <type_traits>
23
24#include "util/base/logging.h"
25
26namespace libtextclassifier {
27
28// A deleter to be used with std::unique_ptr to delete JNI local references.
29class LocalRefDeleter {
30 public:
31 // Style guide violating implicit constructor so that the LocalRefDeleter
32 // is implicitly constructed from the second argument to ScopedLocalRef.
33 LocalRefDeleter(JNIEnv* env) : env_(env) {} // NOLINT(runtime/explicit)
34
35 LocalRefDeleter(const LocalRefDeleter& orig) = default;
36
37 // Copy assignment to allow move semantics in ScopedLocalRef.
38 LocalRefDeleter& operator=(const LocalRefDeleter& rhs) {
39 // As the deleter and its state are thread-local, ensure the envs
40 // are consistent but do nothing.
41 TC_CHECK_EQ(env_, rhs.env_);
42 return *this;
43 }
44
45 // The delete operator.
46 void operator()(jobject o) const { env_->DeleteLocalRef(o); }
47
48 private:
49 // The env_ stashed to use for deletion. Thread-local, don't share!
50 JNIEnv* const env_;
51};
52
53// A smart pointer that deletes a JNI local reference when it goes out
54// of scope. Usage is:
55// ScopedLocalRef<jobject> scoped_local(env->JniFunction(), env);
56//
57// Note that this class is not thread-safe since it caches JNIEnv in
58// the deleter. Do not use the same jobject across different threads.
59template <typename T>
60using ScopedLocalRef =
61 std::unique_ptr<typename std::remove_pointer<T>::type, LocalRefDeleter>;
62
63} // namespace libtextclassifier
64
65#endif // LIBTEXTCLASSIFIER_UTIL_JAVA_SCOPED_LOCAL_REF_H_