diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java new file mode 100644 index 0000000000..b2264f30e6 --- /dev/null +++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.java14.foreign.api; + +import jdk.incubator.foreign.*; +import org.junit.Test; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +import java.lang.invoke.VarHandle; +import java.nio.ByteOrder; + +public class ForeignMemoryUnitTest { + + @Test + public void whenAValueIsSet_thenAccessTheValue() { + long value = 10; + MemoryAddress memoryAddress = + MemorySegment.allocateNative(8).baseAddress(); + VarHandle varHandle = MemoryHandles.varHandle(long.class, + ByteOrder.nativeOrder()); + varHandle.set(memoryAddress, value); + assertThat(varHandle.get(memoryAddress), is(value)); + } + + @Test + public void whenMultipleValuesAreSet_thenAccessAll() { + VarHandle varHandle = MemoryHandles.varHandle(int.class, + ByteOrder.nativeOrder()); + + try(MemorySegment memorySegment = + MemorySegment.allocateNative(100)) { + MemoryAddress base = memorySegment.baseAddress(); + for(int i=0; i<25; i++) { + varHandle.set(base.addOffset((i*4)), i); + } + for(int i=0; i<25; i++) { + assertThat(varHandle.get(base.addOffset((i*4))), is(i)); + } + } + } + + @Test + public void whenSetValuesWithMemoryLayout_thenTheyCanBeRetrieved() { + SequenceLayout sequenceLayout = + MemoryLayout.ofSequence(25, + MemoryLayout.ofValueBits(64, ByteOrder.nativeOrder())); + VarHandle varHandle = + sequenceLayout.varHandle(long.class, + MemoryLayout.PathElement.sequenceElement()); + + try(MemorySegment memorySegment = + MemorySegment.allocateNative(sequenceLayout)) { + MemoryAddress base = memorySegment.baseAddress(); + for(long i=0; i