Skip to main content

prebindgen_jni_runtime/
byte_array_helpers.rs

1//! JNI byte-array conversion helpers for use in type converters and runtime code.
2
3use jni::{
4    objects::{JByteArray, JObject},
5    JNIEnv,
6};
7
8/// Converts a JNI `JByteArray` into a Rust `Vec<u8>`.
9pub fn decode_byte_array(env: &mut JNIEnv, payload: &JByteArray) -> Result<Vec<u8>, String> {
10    env.convert_byte_array(payload)
11        .map_err(|err| format!("Error while decoding JByteArray: {}", err))
12}
13
14/// Converts a Rust byte slice into a JNI `JByteArray`.
15pub fn encode_byte_array<'local>(
16    env: &mut JNIEnv<'local>,
17    bytes: &[u8],
18) -> Result<JByteArray<'local>, String> {
19    env.byte_array_from_slice(bytes)
20        .map_err(|err| format!("Error while encoding JByteArray: {}", err))
21}
22
23/// Returns a null JNI byte-array handle.
24pub fn null_byte_array() -> JByteArray<'static> {
25    JByteArray::from(JObject::null())
26}