156. Copying and slicing memory segments
Let’s consider the following memory segment (arena
is an instance of Arena
):
MemorySegment srcSegment = arena.allocateArray(
ValueLayout.JAVA_INT, 1, 2, 3, 4, -1, -1, -1,
52, 22, 33, -1, -1, -1, -1, -1, 4);
Next, let’s see how we can copy the content of this segment.
Copying a segment
We can make a copy of this memory segment via copyFrom(MemorySegment src)
as follows:
MemorySegment copySegment = srcSegment.copyFrom(srcSegment);
We can easily see if the data was copied as follows:
System.out.println("Data: " + Arrays.toString(
copySegment.toArray(ValueLayout.JAVA_INT)));
This is a bulk operation that creates a full copy of the given memory segment.
Copying a part of the segment into another segment (1)
Let’s suppose that we want to copy only a part of srcSegment
into another segment (dstSegment
). For instance, if we wanted to copy the last...