blob: 990f6729e7727eede47e168edbbc61f4dbacda1f [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#ifndef BASE_ANDROID_JNI_BYTEBUFFER_H_
6#define BASE_ANDROID_JNI_BYTEBUFFER_H_
7
8#include <jni.h>
9
Arthur Sonzognie5fff99c2024-02-21 15:58:2410#include <optional>
11
Elly3e406162024-01-23 16:18:4812#include "base/base_export.h"
13#include "base/containers/span.h"
Elly3e406162024-01-23 16:18:4814
15namespace 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 Sonzognie5fff99c2024-02-21 15:58:2428// std::nullopt in that case and do not crash.
Stefano Duof749c1b82024-09-23 22:56:3629base::span<const uint8_t> BASE_EXPORT JavaByteBufferToSpan(JNIEnv* env,
30 jobject buffer);
Elly3e406162024-01-23 16:18:4831
Stefano Duof749c1b82024-09-23 22:56:3632base::span<uint8_t> BASE_EXPORT JavaByteBufferToMutableSpan(JNIEnv* env,
33 jobject buffer);
Elly3e406162024-01-23 16:18:4834
Arthur Sonzognie5fff99c2024-02-21 15:58:2435std::optional<base::span<const uint8_t>> BASE_EXPORT
Stefano Duof749c1b82024-09-23 22:56:3636MaybeJavaByteBufferToSpan(JNIEnv* env, jobject buffer);
Elly3e406162024-01-23 16:18:4837
Arthur Sonzognie5fff99c2024-02-21 15:58:2438std::optional<base::span<uint8_t>> BASE_EXPORT
Stefano Duof749c1b82024-09-23 22:56:3639MaybeJavaByteBufferToMutableSpan(JNIEnv* env, jobject buffer);
Elly3e406162024-01-23 16:18:4840
41} // namespace base::android
42
43#endif // BASE_ANDROID_JNI_BYTEBUFFER_H_