Skip to content

Commit

Permalink
Rework template code to use MemorySegment::copyFrom directly as much …
Browse files Browse the repository at this point in the history
…as possible
  • Loading branch information
mcimadamore committed May 15, 2020
1 parent 4224081 commit 4e51ab8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,6 @@ public class C-X {
private static final VarHandle handle = LAYOUT.varHandle(CARRIER);
private static final VarHandle arrayHandle = arrayHandle(LAYOUT, CARRIER);

private static void copy(MemoryAddress addr, ${CARRIER}[] arr) {
var heapSegment = MemorySegment.ofArray(arr);
addr.segment().copyFrom(heapSegment);
}

public static ${CARRIER} get(MemoryAddress addr) {
return (${CARRIER}) handle.get(addr);
}
Expand Down Expand Up @@ -69,14 +64,14 @@ public class C-X {
public static MemorySegment allocateArray(${CARRIER}[] arr) {
var arrLayout = MemoryLayout.ofSequence(arr.length, LAYOUT);
var seg = MemorySegment.allocateNative(arrLayout);
copy(seg.baseAddress(), arr);
seg.copyFrom(MemorySegment.ofArray(arr));
return seg;
}

public static MemoryAddress allocateArray(${CARRIER}[] arr, NativeAllocationScope scope) {
var arrLayout = MemoryLayout.ofSequence(arr.length, LAYOUT);
var addr = scope.allocate(arrLayout);
copy(addr, arr);
addr.segment().copyFrom(MemorySegment.ofArray(arr));
return addr;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,6 @@ public final class Cstring {
}
private final static VarHandle byteArrHandle = arrayHandle(C_CHAR, byte.class);

private static void copy(MemoryAddress addr, byte[] bytes) {
var heapSegment = MemorySegment.ofArray(bytes);
addr.segment().copyFrom(heapSegment);
byteArrHandle.set(addr, (long)bytes.length, (byte)0);
}

private static MemorySegment toCString(byte[] bytes) {
MemoryLayout strLayout = MemoryLayout.ofSequence(bytes.length + 1, C_CHAR);
MemorySegment segment = MemorySegment.allocateNative(strLayout);
Expand All @@ -36,7 +30,7 @@ public final class Cstring {
private static MemoryAddress toCString(byte[] bytes, NativeAllocationScope scope) {
MemoryLayout strLayout = MemoryLayout.ofSequence(bytes.length + 1, C_CHAR);
MemoryAddress addr = scope.allocate(strLayout);
copy(addr, bytes);
addr.segment().copyFrom(MemorySegment.ofArray(bytes));
return addr;
}

Expand All @@ -48,6 +42,15 @@ public final class Cstring {
copy(addr, str.getBytes(charset));
}

//where
private static void copy(MemoryAddress addr, byte[] bytes) {
var heapSegment = MemorySegment.ofArray(bytes);
addr.segment()
.asSlice(addr.segmentOffset(), bytes.length)
.copyFrom(heapSegment);
byteArrHandle.set(addr, (long)bytes.length, (byte)0);
}

public static MemorySegment toCString(String str) {
return toCString(str.getBytes());
}
Expand Down

0 comments on commit 4e51ab8

Please sign in to comment.