151. Introducing slice handle
Let’s suppose that we have the following nested model (10 sequences of 5 double values each):
SequenceLayout innerSeq
= MemoryLayout.sequenceLayout(5, ValueLayout.JAVA_DOUBLE);
SequenceLayout outerSeq
= MemoryLayout.sequenceLayout(10, innerSeq);
Next, we define a VarHandle via PathElement and we populate this model accordingly with some random data:
VarHandle handle = outerSeq.varHandle(
PathElement.sequenceElement(),
PathElement.sequenceElement());
try (Arena arena = Arena.openConfined()) {
MemorySegment segment = arena.allocate(outerSeq);
for (int i = 0; i < outerSeq.elementCount(); i++) {
for (int j = 0; j < innerSeq.elementCount(); j++) {
handle.set(segment, i, j, Math.random());
}
}
}
Ok, you should be familiar with this code, so nothing new so far. Next, we plan to extract from this model the third sequence from 10 containing 5 sequences of double values. We can accomplish this via the sliceHandle(PathElement… elements) method which returns a java.lang.invoke.MethodHandle. This MethodHandle takes a memory segment and returns a slice of it corresponding to the selected memory layout. Here is the code for our scenario:
MethodHandle mHandle = outerSeq.sliceHandle(
PathElement.sequenceElement());
System.out.println(“\n The third sequence of 10: “
+ Arrays.toString(
((MemorySegment) mHandle.invoke(segment, 3))
.toArray(ValueLayout.JAVA_DOUBLE)));
Done! Now, you know how to slice out a certain memory layout from the given memory segment.
152. Introducing layout flattening
Let’s suppose that we have the following nested model (the exact same model as in Problem 151):
SequenceLayout innerSeq
= MemoryLayout.sequenceLayout(5, ValueLayout.JAVA_DOUBLE);
SequenceLayout outerSeq
= MemoryLayout.sequenceLayout(10, innerSeq);
Next, we define a VarHandle via PathElement and we populate this model accordingly with some random data (you can see the code listed in Problem 151).Our goal is to take this nested model and obtain a flat model. So, instead of having 10 sequences of 5 double values each, we want one sequence of 50 double values. This can be achieved via the flatten() method as follows:
SequenceLayout flatten = outerSeq.flatten();
VarHandle fhandle = flatten.varHandle(
PathElement.sequenceElement());
for (int i = 0; i < flatten.elementCount(); i++) {
System.out.printf(“\nx = %.2f”, fhandle.get(segment, i));
}
Notice the PathElement which traverses a single sequence. This is the sequence that resulted after the flatten operation. We can go further and allocate another memory segment for this sequence and set new data:
try (Arena arena = Arena.openConfined()) {
MemorySegment segment = arena.allocate(flatten);
for (int i = 0; i < flatten.elementCount(); i++) {
fhandle.set(segment, i, Math.random());
}
}
Next, let’s see how we can reshape a memory layout.