// java --add-modules java.base --add-exports java.base/jdk.internal.misc=ALL-UNNAMED --add-exports java.base/jdk.internal.util=ALL-UNNAMED -Xbatch -XX:-TieredCompilation -XX:CompileCommand=compileonly,Test.test -XX:CompileCommand=printcompilation,Test.test -XX:PrintPhaseLevel=4 Test.java

import java.lang.foreign.*;

public class TestMemSeg {
    private static final int SIZE = 10;

    public static void main(String[] args) {
        byte[] aB = new byte[10_000];
        int[] aI = new int[10_000];

        byte[] goldB = aB.clone();
        int[] goldI = aI.clone();
        test(goldB, goldI, 0, goldB);

        for (int i = 0; i < 1_000; i++) {
            byte[] bb = aB.clone();
            int[] ii = aI.clone();
            test(bb, ii, i, bb);
        }

        byte[] bb = aB.clone();
        int[] ii = aI.clone();
        test(bb, ii, 0, bb);

        for (int i = 0; i < 10_000; i++) {
            if (bb[i] != goldB[i] || ii[i] != goldI[i]) {
                throw new RuntimeException("wrong value");
            }
        }
    }

    static void test(byte[] aB, int[] aI, int i, byte[] bB) {
        MemorySegment in;
        MemorySegment out = MemorySegment.ofArray(bB);
        if (i % 2 == 0) {
            in = MemorySegment.ofArray(aB);
        } else {
            in = MemorySegment.ofArray(aI);
        }

        for (int j = 0; j < 9_000; j++) {
            byte v = in.getAtIndex(ValueLayout.JAVA_BYTE, j);
            out.setAtIndex(ValueLayout.JAVA_BYTE, j, (byte)(v + 1));
        }
    }
}
