Skip to content

Commit

Permalink
feat: Add bigEndian() and littleEndian() fields to JByteOrder (#93
Browse files Browse the repository at this point in the history
)

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: #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
  • Loading branch information
mrousavy authored and facebook-github-bot committed Jan 25, 2024
1 parent 8b45d9c commit 0454714
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
12 changes: 12 additions & 0 deletions cxx/fbjni/ByteBuffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,18 @@ local_ref<JByteOrder> JByteOrder::nativeOrder() {
return meth(JByteOrder::javaClassStatic());
}

local_ref<JByteOrder> JByteOrder::bigEndian() {
static auto field =
JByteOrder::javaClassStatic()->getStaticField<JByteOrder>("BIG_ENDIAN");
return JByteOrder::javaClassStatic()->getStaticFieldValue(field);
}

local_ref<JByteOrder> JByteOrder::littleEndian() {
static auto field = JByteOrder::javaClassStatic()->getStaticField<JByteOrder>(
"LITTLE_ENDIAN");
return JByteOrder::javaClassStatic()->getStaticFieldValue(field);
}

local_ref<JByteBuffer> 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.
Expand Down
2 changes: 2 additions & 0 deletions cxx/fbjni/ByteBuffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ class JByteOrder : public JavaClass<JByteOrder> {
constexpr static const char* kJavaDescriptor = "Ljava/nio/ByteOrder;";

static local_ref<JByteOrder> nativeOrder();
static local_ref<JByteOrder> bigEndian();
static local_ref<JByteOrder> littleEndian();
};

// JNI's NIO support has some awkward preconditions and error reporting. This
Expand Down

0 comments on commit 0454714

Please sign in to comment.