Skip to content

Commit 0dd772b

Browse files
authored
jextract: Implement fromByteBuffer helper for the foundation Data (#848)
* jextract: Implement fromByteBuffer helper for the foundation Data * Use the typeName not hard code Date type
1 parent c72f032 commit 0dd772b

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

Samples/SwiftJavaExtractFFMSampleApp/src/test/java/com/example/swift/DataImportTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import org.swift.swiftkit.ffm.AllocatingSwiftArena;
1919

2020
import java.lang.foreign.ValueLayout;
21+
import java.nio.ByteBuffer;
2122

2223
import static org.junit.jupiter.api.Assertions.*;
2324

@@ -90,6 +91,16 @@ void test_Data_fromByteArray() {
9091
}
9192
}
9293

94+
@Test
95+
void test_Data_fromByteBuffer() {
96+
try (var arena = AllocatingSwiftArena.ofConfined()) {
97+
byte[] original = new byte[] { 1, 2, 3, 4, 5 };
98+
ByteBuffer buffer = ByteBuffer.wrap(original);
99+
var data = Data.fromByteBuffer(buffer, arena);
100+
assertEquals(5, data.getCount());
101+
}
102+
}
103+
93104
@Test
94105
void test_Data_toMemorySegment() {
95106
try (var arena = AllocatingSwiftArena.ofConfined()) {

Sources/JExtractSwiftLib/FFM/FFMSwift2JavaGenerator+FoundationData.swift

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,21 @@ extension FFMSwift2JavaGenerator {
4747
"""
4848
)
4949

50-
// TODO: Implement a fromByteBuffer as well
50+
printer.print(
51+
"""
52+
/**
53+
* Creates a new Swift {@link \(typeName)} instance from a {@link ByteBuffer}.
54+
*
55+
* @param buffer The ByteBuffer to copy byte from it into the \(typeName)
56+
* @param arena The arena for memory management
57+
* @return A new \(typeName) instance containing a copy of the bytes
58+
*/
59+
public static \(typeName) fromByteBuffer(java.nio.ByteBuffer buffer, AllocatingSwiftArena arena) {
60+
Objects.requireNonNull(buffer, "buffer cannot be null");
61+
return \(typeName).init(buffer.array(), arena);
62+
}
63+
"""
64+
)
5165

5266
// Print the descriptor class for copyBytes native call using the shared helper
5367
let copyBytesCFunc = CFunction(

0 commit comments

Comments
 (0)