1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/android/jni_array.h"
7 #include "base/android/jni_android.h"
8 #include "base/android/scoped_java_ref.h"
9 #include "testing/gtest/include/gtest/gtest.h"
14 TEST(JniArray
, BasicConversions
) {
15 const uint8 kBytes
[] = { 0, 1, 2, 3 };
16 const size_t kLen
= arraysize(kBytes
);
17 JNIEnv
* env
= AttachCurrentThread();
18 ScopedJavaLocalRef
<jbyteArray
> bytes
= ToJavaByteArray(env
, kBytes
, kLen
);
19 ASSERT_TRUE(bytes
.obj());
21 std::vector
<uint8
> vec(5);
22 JavaByteArrayToByteVector(env
, bytes
.obj(), &vec
);
23 EXPECT_EQ(4U, vec
.size());
24 EXPECT_EQ(std::vector
<uint8
>(kBytes
, kBytes
+ kLen
), vec
);
26 AppendJavaByteArrayToByteVector(env
, bytes
.obj(), &vec
);
27 EXPECT_EQ(8U, vec
.size());
30 void CheckLongConversion(
32 const int64
* long_array
,
34 const ScopedJavaLocalRef
<jlongArray
>& longs
) {
35 ASSERT_TRUE(longs
.obj());
37 jsize java_array_len
= env
->GetArrayLength(longs
.obj());
38 ASSERT_EQ(static_cast<int>(len
), java_array_len
);
41 for (size_t i
= 0; i
< len
; ++i
) {
42 env
->GetLongArrayRegion(longs
.obj(), i
, 1, &value
);
43 ASSERT_EQ(long_array
[i
], value
);
47 TEST(JniArray
, LongConversions
) {
48 const int64 kLongs
[] = { 0, 1, -1, kint64min
, kint64max
};
49 const size_t kLen
= arraysize(kLongs
);
51 JNIEnv
* env
= AttachCurrentThread();
52 CheckLongConversion(env
, kLongs
, kLen
, ToJavaLongArray(env
, kLongs
, kLen
));
54 const std::vector
<int64
> vec(kLongs
, kLongs
+ kLen
);
55 CheckLongConversion(env
, kLongs
, kLen
, ToJavaLongArray(env
, vec
));
58 TEST(JniArray
, JavaArrayOfByteArrayToStringVector
) {
59 const int kMaxItems
= 50;
60 JNIEnv
* env
= AttachCurrentThread();
62 // Create a byte[][] object.
63 ScopedJavaLocalRef
<jclass
> byte_array_clazz(env
, env
->FindClass("[B"));
64 ASSERT_TRUE(byte_array_clazz
.obj());
66 ScopedJavaLocalRef
<jobjectArray
> array(
67 env
, env
->NewObjectArray(kMaxItems
, byte_array_clazz
.obj(), NULL
));
68 ASSERT_TRUE(array
.obj());
70 // Create kMaxItems byte buffers.
72 for (int i
= 0; i
< kMaxItems
; ++i
) {
73 snprintf(text
, sizeof text
, "%d", i
);
74 ScopedJavaLocalRef
<jbyteArray
> byte_array
= ToJavaByteArray(
75 env
, reinterpret_cast<uint8
*>(text
),
76 static_cast<size_t>(strlen(text
)));
77 ASSERT_TRUE(byte_array
.obj());
79 env
->SetObjectArrayElement(array
.obj(), i
, byte_array
.obj());
80 ASSERT_FALSE(HasException(env
));
83 // Convert to std::vector<std::string>, check the content.
84 std::vector
<std::string
> vec
;
85 JavaArrayOfByteArrayToStringVector(env
, array
.obj(), &vec
);
87 EXPECT_EQ(static_cast<size_t>(kMaxItems
), vec
.size());
88 for (int i
= 0; i
< kMaxItems
; ++i
) {
89 snprintf(text
, sizeof text
, "%d", i
);
90 EXPECT_STREQ(text
, vec
[i
].c_str());
94 } // namespace android