blob: e4eeaca6f5c587ffc404a877fbae43b8164d6962 [file] [log] [blame]
Martin Stjernholmc15e7e42020-12-02 22:50:53 +00001/*
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
27template <typename StringVisitor>
28jobjectArray toStringArray(JNIEnv* env, size_t count, StringVisitor&& visitor) {
29 jclass stringClass = env->FindClass("java/lang/String");
30 ScopedLocalRef<jobjectArray> result(env, env->NewObjectArray(count, stringClass, NULL));
31 env->DeleteLocalRef(stringClass);
32 if (result == nullptr) {
33 return nullptr;
34 }
35 for (size_t i = 0; i < count; ++i) {
36 ScopedLocalRef<jstring> s(env, env->NewStringUTF(visitor(i)));
37 if (env->ExceptionCheck()) {
38 return nullptr;
39 }
40 env->SetObjectArrayElement(result.get(), i, s.get());
41 if (env->ExceptionCheck()) {
42 return nullptr;
43 }
44 }
45 return result.release();
46}
47
48inline jobjectArray toStringArray(JNIEnv* env, const std::vector<std::string>& strings) {
49 return toStringArray(env, strings.size(), [&strings](size_t i) { return strings[i].c_str(); });
50}
51
52inline jobjectArray toStringArray(JNIEnv* env, const char* const* strings) {
53 size_t count = 0;
54 for (; strings[count] != nullptr; ++count) {}
55 return toStringArray(env, count, [&strings](size_t i) { return strings[i]; });
56}
57
58template <typename Counter, typename Getter>
59jobjectArray toStringArray(JNIEnv* env, Counter* counter, Getter* getter) {
60 return toStringArray(env, counter(), [getter](size_t i) { return getter(i); });
61}
62
63#endif // __cplusplus
64