blob: 00b7e2f9250e2ee7deaae0024b04f132f9f75bff [file] [log] [blame]
Elly3e406162024-01-23 16:18:481// Copyright 2024 The Chromium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/android/jni_bytebuffer.h"
6
7#include <stddef.h>
8#include <stdint.h>
9
10#include <algorithm>
11#include <limits>
12
13#include "base/android/jni_android.h"
14#include "base/android/jni_string.h"
15#include "base/android/scoped_java_ref.h"
Elly3e406162024-01-23 16:18:4816#include "base/containers/span.h"
17#include "base/strings/utf_string_conversions.h"
18#include "testing/gmock/include/gmock/gmock.h"
19#include "testing/gtest/include/gtest/gtest.h"
20
Elly3e406162024-01-23 16:18:4821namespace base::android {
22
23TEST(JniByteBuffer, ConversionDoesNotCopy) {
24 uint8_t bytes[] = {0, 1, 2, 3};
25 JNIEnv* env = AttachCurrentThread();
26
27 ScopedJavaLocalRef<jobject> jbuffer(
28 env, env->NewDirectByteBuffer(bytes, sizeof(bytes)));
29 ASSERT_TRUE(jbuffer);
30
Stefano Duof749c1b82024-09-23 22:56:3631 base::span<const uint8_t> span = JavaByteBufferToSpan(env, jbuffer.obj());
Elly3e406162024-01-23 16:18:4832 EXPECT_EQ(span.data(), bytes);
33 EXPECT_EQ(span.size(), sizeof(bytes));
34}
35
Elly5de814432024-01-25 16:57:1236// Disabled pending diagnosis: https://crbug.com/1521406
37// Specifically, under test, env->GetDirectBufferAddress() is returning non-null
38// and env->GetDirectBufferCapacity() is returning >= 0, both of which they are
39// not supposed to do in this situation.
40TEST(JniByteBuffer, DISABLED_ConversionFromNonBuffer) {
Elly3e406162024-01-23 16:18:4841 JNIEnv* env = AttachCurrentThread();
42 jclass cls = env->FindClass("java/util/ArrayList");
43 ASSERT_TRUE(cls);
44
45 jmethodID init =
46 base::android::MethodID::Get<base::android::MethodID::TYPE_INSTANCE>(
47 env, cls, "<init>", "()V");
48
49 ScopedJavaLocalRef<jobject> jnonbuffer(env, env->NewObject(cls, init));
50
Arthur Sonzognie5fff99c2024-02-21 15:58:2451 std::optional<base::span<const uint8_t>> maybe_span =
Stefano Duof749c1b82024-09-23 22:56:3652 MaybeJavaByteBufferToSpan(env, jnonbuffer.obj());
Elly3e406162024-01-23 16:18:4853 EXPECT_FALSE(maybe_span.has_value());
54}
55
Ellyc9d1b632024-02-14 18:23:0956TEST(JniByteBuffer, ZeroByteConversionSucceeds) {
57 JNIEnv* env = AttachCurrentThread();
58 ScopedJavaLocalRef<jobject> jbuffer(env,
59 env->NewDirectByteBuffer(nullptr, 0));
60 ASSERT_TRUE(jbuffer);
61
Stefano Duof749c1b82024-09-23 22:56:3662 base::span<const uint8_t> span = JavaByteBufferToSpan(env, jbuffer.obj());
Ellyc9d1b632024-02-14 18:23:0963 EXPECT_EQ(span.data(), nullptr);
64 EXPECT_EQ(span.size(), 0u);
65}
66
Elly3e406162024-01-23 16:18:4867} // namespace base::android