Skip to content

Commit 968b3bc

Browse files
committed
[jextract-swift] Add an API to produce a MemoryLayout for a given Swift type
Given Swift type metadata, inspect the metadata to produce a memory layout for the Swift type that covers its size/alignment and can be used to refer to memory containing a Swift value of that type.
1 parent 8c69803 commit 968b3bc

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

JavaSwiftKitDemo/src/main/java/org/example/HelloJava2Swift.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,5 +74,6 @@ static void tests() {
7474
System.out.println(" size = " + SwiftKit.sizeOfSwiftType(swiftType));
7575
System.out.println(" stride = " + SwiftKit.strideOfSwiftType(swiftType));
7676
System.out.println(" alignment = " + SwiftKit.alignmentOfSwiftType(swiftType));
77+
System.out.println(" Java layout = " + SwiftKit.layoutOfSwiftType(swiftType));
7778
}
7879
}

JavaSwiftKitDemo/src/main/java/org/swift/javakit/SwiftKit.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,4 +348,23 @@ public static long alignmentOfSwiftType(MemorySegment typeMetadata) {
348348
long flags = getSwiftInt(valueWitnessTable(typeMetadata), valueWitnessTable$flags$offset);
349349
return (flags & 0xFF) + 1;
350350
}
351+
352+
/**
353+
* Produce a layout that describes a Swift type based on its
354+
* type metadata. The resulting layout is completely opaque to Java, but
355+
* has appropriate size/alignment to model the memory associated with a
356+
* Swift type.
357+
*
358+
* In the future, this layout could be extended to provide more detail,
359+
* such as the fields of a Swift struct.
360+
*/
361+
public static MemoryLayout layoutOfSwiftType(MemorySegment typeMetadata) {
362+
long size = sizeOfSwiftType(typeMetadata);
363+
long stride = strideOfSwiftType(typeMetadata);
364+
return MemoryLayout.structLayout(
365+
MemoryLayout.sequenceLayout(size, JAVA_BYTE)
366+
.withByteAlignment(alignmentOfSwiftType(typeMetadata)),
367+
MemoryLayout.paddingLayout(stride - size)
368+
);
369+
}
351370
}

0 commit comments

Comments
 (0)