Elly | 3e40616 | 2024-01-23 16:18:48 | [diff] [blame] | 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 | |
Arthur Sonzogni | e5fff99c | 2024-02-21 15:58:24 | [diff] [blame] | 10 | #include <optional> |
| 11 | |
Elly | 3e40616 | 2024-01-23 16:18:48 | [diff] [blame] | 12 | #include "base/base_export.h" |
| 13 | #include "base/containers/span.h" |
Elly | 3e40616 | 2024-01-23 16:18:48 | [diff] [blame] | 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 |
Arthur Sonzogni | e5fff99c | 2024-02-21 15:58:24 | [diff] [blame] | 28 | // std::nullopt in that case and do not crash. |
Stefano Duo | f749c1b8 | 2024-09-23 22:56:36 | [diff] [blame] | 29 | base::span<const uint8_t> BASE_EXPORT JavaByteBufferToSpan(JNIEnv* env, |
| 30 | jobject buffer); |
Elly | 3e40616 | 2024-01-23 16:18:48 | [diff] [blame] | 31 | |
Stefano Duo | f749c1b8 | 2024-09-23 22:56:36 | [diff] [blame] | 32 | base::span<uint8_t> BASE_EXPORT JavaByteBufferToMutableSpan(JNIEnv* env, |
| 33 | jobject buffer); |
Elly | 3e40616 | 2024-01-23 16:18:48 | [diff] [blame] | 34 | |
Arthur Sonzogni | e5fff99c | 2024-02-21 15:58:24 | [diff] [blame] | 35 | std::optional<base::span<const uint8_t>> BASE_EXPORT |
Stefano Duo | f749c1b8 | 2024-09-23 22:56:36 | [diff] [blame] | 36 | MaybeJavaByteBufferToSpan(JNIEnv* env, jobject buffer); |
Elly | 3e40616 | 2024-01-23 16:18:48 | [diff] [blame] | 37 | |
Arthur Sonzogni | e5fff99c | 2024-02-21 15:58:24 | [diff] [blame] | 38 | std::optional<base::span<uint8_t>> BASE_EXPORT |
Stefano Duo | f749c1b8 | 2024-09-23 22:56:36 | [diff] [blame] | 39 | MaybeJavaByteBufferToMutableSpan(JNIEnv* env, jobject buffer); |
Elly | 3e40616 | 2024-01-23 16:18:48 | [diff] [blame] | 40 | |
| 41 | } // namespace base::android |
| 42 | |
| 43 | #endif // BASE_ANDROID_JNI_BYTEBUFFER_H_ |