Skip to content

Add withByteArrayElements and newByteArray(_:) for Java byte[] - #27

Open
piercifani wants to merge 1 commit into
swiftlang:mainfrom
piercifani:jnicore/array-elements
Open

piercifani wants to merge 1 commit into
swiftlang:mainfrom
piercifani:jnicore/array-elements

Conversation

@piercifani

Copy link
Copy Markdown

Problem

Binary payloads (Data, [UInt8]) are where copying through a Swift array first costs real time and memory. jni-core's Array JavaValue conversions copy element by element. Libraries that need direct access fall back to the raw Get/ReleaseByteArrayElements functions and their bare jint release-mode constants.

Change

  • JavaArrayReleaseMode: .copyBackAndRelease (0), .copyBack (JNI_COMMIT), .discard (JNI_ABORT).
  • JNIEnvironment.withByteArrayElements(_:releaseMode:_:): scoped access to the elements, released in the chosen mode. The default, .discard, is right for read-only access.
  • JNIEnvironment.newByteArray(_ bytes: UnsafeRawBufferPointer) -> jbyteArray?: one NewByteArray + SetByteArrayRegion.

This covers only byte[], the case with real demand. Other primitive types can follow the same shape if needed.

Tests

ByteArrayTests:

  • round-trip of 0, 1, 5 and 64 KiB;
  • .copyBackAndRelease writes changes back to the Java array.

Results:

Platform Result
macOS 21 tests in 5 suites pass
Linux (swift:6.4.2-noble, OpenJDK 17) 21 tests in 5 suites pass
Android API 36 emulator pass, but only in a combined run with follow-up changes

🤖 Generated with Claude Code

Bridging binary payloads (Data, [UInt8]) to and from byte[] is the common
case where copying through a Swift array first costs real time and memory.
jni-core's Array JavaValue conversions copy element-wise into a Swift
array; libraries that need direct access drop to the raw
Get/ReleaseByteArrayElements functions and their release-mode constants.

- withByteArrayElements(_:releaseMode:_:): scoped access to the elements,
  released with the chosen JavaArrayReleaseMode.
- newByteArray(_:): a byte[] filled from an UnsafeRawBufferPointer with one
  SetByteArrayRegion call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant