• 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 #ifndef TO_STRING_ARRAY_H_included
18 #define TO_STRING_ARRAY_H_included
19 
20 #include <stddef.h>
21 
22 #include <jni.h>
23 #include "module_api.h"
24 
25 // Public API for libnativehelper library.
26 MODULE_API jobjectArray newStringArray(JNIEnv* env, size_t count);
27 MODULE_API jobjectArray toStringArray(JNIEnv* env, const char* const* strings);
28 
29 #ifdef __cplusplus
30 
31 #include <string>
32 #include <vector>
33 #include "ScopedLocalRef.h"
34 
35 template <typename Counter, typename Getter>
toStringArray(JNIEnv * env,Counter * counter,Getter * getter)36 jobjectArray toStringArray(JNIEnv* env, Counter* counter, Getter* getter) {
37     size_t count = (*counter)();
38     jobjectArray result = newStringArray(env, count);
39     if (result == NULL) {
40         return NULL;
41     }
42     for (size_t i = 0; i < count; ++i) {
43         ScopedLocalRef<jstring> s(env, env->NewStringUTF((*getter)(i)));
44         if (env->ExceptionCheck()) {
45             return NULL;
46         }
47         env->SetObjectArrayElement(result, i, s.get());
48         if (env->ExceptionCheck()) {
49             return NULL;
50         }
51     }
52     return result;
53 }
54 
55 struct VectorCounter {
56     const std::vector<std::string>& strings;
VectorCounterVectorCounter57     explicit VectorCounter(const std::vector<std::string>& strings) : strings(strings) {}
operatorVectorCounter58     size_t operator()() {
59         return strings.size();
60     }
61 };
62 struct VectorGetter {
63     const std::vector<std::string>& strings;
VectorGetterVectorGetter64     explicit VectorGetter(const std::vector<std::string>& strings) : strings(strings) {}
operatorVectorGetter65     const char* operator()(size_t i) {
66         return strings[i].c_str();
67     }
68 };
69 
toStringArray(JNIEnv * env,const std::vector<std::string> & strings)70 inline jobjectArray toStringArray(JNIEnv* env, const std::vector<std::string>& strings) {
71     VectorCounter counter(strings);
72     VectorGetter getter(strings);
73     return toStringArray<VectorCounter, VectorGetter>(env, &counter, &getter);
74 }
75 
76 #endif  // __cplusplus
77 
78 #endif  // TO_STRING_ARRAY_H_included
79