xref: /aosp_15_r20/external/cronet/base/android/jni_bytebuffer.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // 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 #ifndef BASE_ANDROID_JNI_BYTEBUFFER_H_
6 #define BASE_ANDROID_JNI_BYTEBUFFER_H_
7 
8 #include <jni.h>
9 
10 #include <optional>
11 
12 #include "base/base_export.h"
13 #include "base/containers/span.h"
14 
15 namespace base::android {
16 
17 // Given a JNIEnv and a jobject representing a byte buffer, produce a base::span
18 // corresponding to that byte buffer. These crash at runtime if the passed-in
19 // jobject does not correspond to a java.nio.Buffer, or if the passed-in buffer
20 // is unaligned and the current CPU architecture may sometimes require aligned
21 // accesses - this requirement is enforced even if your code never actually
22 // *does* the types of accesses that require alignment.
23 //
24 // Usually, that is what you want, since both of those conditions are programmer
25 // errors.
26 //
27 // If needed, there are also variants below starting with Maybe that return
28 // std::nullopt in that case and do not crash.
29 base::span<const uint8_t> BASE_EXPORT JavaByteBufferToSpan(JNIEnv* env,
30                                                            jobject buffer);
31 
32 base::span<uint8_t> BASE_EXPORT JavaByteBufferToMutableSpan(JNIEnv* env,
33                                                             jobject buffer);
34 
35 std::optional<base::span<const uint8_t>> BASE_EXPORT
36 MaybeJavaByteBufferToSpan(JNIEnv* env, jobject buffer);
37 
38 std::optional<base::span<uint8_t>> BASE_EXPORT
39 MaybeJavaByteBufferToMutableSpan(JNIEnv* env, jobject buffer);
40 
41 }  // namespace base::android
42 
43 #endif  // BASE_ANDROID_JNI_BYTEBUFFER_H_
44