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 #ifdef __cplusplus
20 
21 #include <string>
22 #include <vector>
23 
24 #include "JNIHelp.h"
25 #include "ScopedLocalRef.h"
26 
27 template <typename StringVisitor>
toStringArray(JNIEnv * env,size_t count,StringVisitor && visitor)28 jobjectArray toStringArray(JNIEnv* env, size_t count, StringVisitor&& visitor) {
29     C_JNIEnv* c_env = static_cast<C_JNIEnv*>(&env->functions);
30     ScopedLocalRef<jobjectArray> result(env, jniCreateStringArray(c_env, count));
31     if (result == nullptr) {
32         return nullptr;
33     }
34     for (size_t i = 0; i < count; ++i) {
35         ScopedLocalRef<jstring> s(env, env->NewStringUTF(visitor(i)));
36         if (env->ExceptionCheck()) {
37             return nullptr;
38         }
39         env->SetObjectArrayElement(result.get(), i, s.get());
40         if (env->ExceptionCheck()) {
41             return nullptr;
42         }
43     }
44     return result.release();
45 }
46 
toStringArray(JNIEnv * env,const std::vector<std::string> & strings)47 inline jobjectArray toStringArray(JNIEnv* env, const std::vector<std::string>& strings) {
48     return toStringArray(env, strings.size(), [&strings](size_t i) { return strings[i].c_str(); });
49 }
50 
toStringArray(JNIEnv * env,const char * const * strings)51 inline jobjectArray toStringArray(JNIEnv* env, const char* const* strings) {
52     size_t count = 0;
53     for (; strings[count] != nullptr; ++count) {}
54     return toStringArray(env, count, [&strings](size_t i) { return strings[i]; });
55 }
56 
57 template <typename Counter, typename Getter>
toStringArray(JNIEnv * env,Counter * counter,Getter * getter)58 jobjectArray toStringArray(JNIEnv* env, Counter* counter, Getter* getter) {
59     return toStringArray(env, counter(), [getter](size_t i) { return getter(i); });
60 }
61 
62 #endif  // __cplusplus
63 
64