// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import jdk.incubator.foreign.MemorySegment;
import jdk.incubator.foreign.ResourceScope;
import jdk.incubator.foreign.ValueLayout;

public class Mem18 {
    public static void test(MemorySegment ms) {
        System.out.println(ms.byteSize());
        for(int i = 0; i < 3; i++) {
            ms.setAtIndex(ValueLayout.JAVA_INT, i, i + 1);
        }
        for(int i = 0; i < 3; i++) {
            System.out.println(ms.getAtIndex(ValueLayout.JAVA_INT,i));
        }
    }
    public static void main(String[] args) {
        try (ResourceScope scope = ResourceScope.newSharedScope()) {
            MemorySegment ms = MemorySegment.allocateNative(12, scope);
            test(ms);
        }
        {
            byte[] b = new byte[12];
            MemorySegment ms = MemorySegment.ofArray(b);
            test(ms);
        }
        try (ResourceScope scope = ResourceScope.newSharedScope()) {
            MemorySegment ms = MemorySegment.allocateNative(20, scope);
            test(ms.asSlice(4, 12));
        }
    }
}
