From 0454714cf0692c4efdb49a94d29d5d8f11667bbc Mon Sep 17 00:00:00 2001 From: Marc Rousavy Date: Thu, 25 Jan 2024 14:31:45 -0800 Subject: [PATCH] feat: Add `bigEndian()` and `littleEndian()` fields to `JByteOrder` (#93) Summary: ## Motivation `JByteBuffer`s could only be initialized with `nativeOrder` endianness. With this PR, both `littleEndian()` and `bigEndian()` fields are exposed in `JByteOrder` and can now be set through `JByteBuffer::order(...)`. Get static fields `LITTLE_ENDIAN` and `BIG_ENDIAN` through `JByteOrder`. Pull Request resolved: https://github.com/facebookincubator/fbjni/pull/93 Test Plan: Test code: Default: ```cpp auto buffer = JByteBuffer::allocateDirect(5); uint8_t* data = buffer->getDirectData(); data[0] = 255; data[1] = 1; __android_log_print(ANDROID_LOG_INFO, "Test", "First item: %i", data[0]); ``` With custom Endian: ```cpp auto buffer = JByteBuffer::allocateDirect(5); buffer->order(JByteOrder::bigEndian()); // <-- or littleEndian() uint8_t* data = buffer->getDirectData(); data[0] = 255; data[1] = 1; __android_log_print(ANDROID_LOG_INFO, "Test", "First item: %i", data[0]); ``` Reviewed By: cipolleschi Differential Revision: D53089814 Pulled By: cortinico fbshipit-source-id: 4f683ccba46caf5a62842944d44b3a201473f522 --- cxx/fbjni/ByteBuffer.cpp | 12 ++++++++++++ cxx/fbjni/ByteBuffer.h | 2 ++ 2 files changed, 14 insertions(+) diff --git a/cxx/fbjni/ByteBuffer.cpp b/cxx/fbjni/ByteBuffer.cpp index 27fa4ca..24c747e 100644 --- a/cxx/fbjni/ByteBuffer.cpp +++ b/cxx/fbjni/ByteBuffer.cpp @@ -69,6 +69,18 @@ local_ref JByteOrder::nativeOrder() { return meth(JByteOrder::javaClassStatic()); } +local_ref JByteOrder::bigEndian() { + static auto field = + JByteOrder::javaClassStatic()->getStaticField("BIG_ENDIAN"); + return JByteOrder::javaClassStatic()->getStaticFieldValue(field); +} + +local_ref JByteOrder::littleEndian() { + static auto field = JByteOrder::javaClassStatic()->getStaticField( + "LITTLE_ENDIAN"); + return JByteOrder::javaClassStatic()->getStaticFieldValue(field); +} + local_ref JByteBuffer::wrapBytes(uint8_t* data, size_t size) { // env->NewDirectByteBuffer requires that size is positive. Android's // dalvik returns an invalid result and Android's art aborts if size == 0. diff --git a/cxx/fbjni/ByteBuffer.h b/cxx/fbjni/ByteBuffer.h index 27dba0b..7b4ef39 100644 --- a/cxx/fbjni/ByteBuffer.h +++ b/cxx/fbjni/ByteBuffer.h @@ -36,6 +36,8 @@ class JByteOrder : public JavaClass { constexpr static const char* kJavaDescriptor = "Ljava/nio/ByteOrder;"; static local_ref nativeOrder(); + static local_ref bigEndian(); + static local_ref littleEndian(); }; // JNI's NIO support has some awkward preconditions and error reporting. This