Home | History | Annotate | Download | only in libnativehelper
      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 #include "JniConstants.h"
     18 #include "toStringArray.h"
     19 
     20 #include <string>
     21 #include <vector>
     22 
     23 jobjectArray newStringArray(JNIEnv* env, size_t count) {
     24     return env->NewObjectArray(count, JniConstants::stringClass, NULL);
     25 }
     26 
     27 struct VectorCounter {
     28     const std::vector<std::string>& strings;
     29     VectorCounter(const std::vector<std::string>& strings) : strings(strings) {}
     30     size_t operator()() {
     31         return strings.size();
     32     }
     33 };
     34 struct VectorGetter {
     35     const std::vector<std::string>& strings;
     36     VectorGetter(const std::vector<std::string>& strings) : strings(strings) {}
     37     const char* operator()(size_t i) {
     38         return strings[i].c_str();
     39     }
     40 };
     41 
     42 jobjectArray toStringArray(JNIEnv* env, const std::vector<std::string>& strings) {
     43     VectorCounter counter(strings);
     44     VectorGetter getter(strings);
     45     return toStringArray<VectorCounter, VectorGetter>(env, &counter, &getter);
     46 }
     47 
     48 struct ArrayCounter {
     49     const char* const* strings;
     50     ArrayCounter(const char* const* strings) : strings(strings) {}
     51     size_t operator()() {
     52         size_t count = 0;
     53         while (strings[count] != NULL) {
     54             ++count;
     55         }
     56         return count;
     57     }
     58 };
     59 
     60 struct ArrayGetter {
     61     const char* const* strings;
     62     ArrayGetter(const char* const* strings) : strings(strings) {}
     63     const char* operator()(size_t i) {
     64         return strings[i];
     65     }
     66 };
     67 
     68 jobjectArray toStringArray(JNIEnv* env, const char* const* strings) {
     69     ArrayCounter counter(strings);
     70     ArrayGetter getter(strings);
     71     return toStringArray(env, &counter, &getter);
     72 }
     73