import java.lang.invoke.*;

import java.lang.foreign.*;


public class CrashExample {
    private static final VarHandle byteHandle = MethodHandles.memorySegmentViewVarHandle(ValueLayout.JAVA_BYTE);
    private static final long len = 100;
    private static final byte CR = (byte) '\r';
    private static final byte LF = (byte) '\n';

    public static void main(String[] args) {
        for(int round = 0; round < 1000; round++) {
            try(Arena arena = Arena.ofConfined()) {
                MemorySegment memorySegment = arena.allocateArray(ValueLayout.JAVA_BYTE, len);
                for(int i = 0; i < 100000; i++) {
                    int index = i % 99;
                    byteHandle.set(memorySegment, index, CR);
                    byteHandle.set(memorySegment, index + 1, LF);
                    byte[] bytes = readUntil(memorySegment, CR, LF);
                }
            }
        }
    }

    private static byte[] readUntil(MemorySegment segment, byte... separators) {
        for(long cur = 0; cur <= segment.byteSize() - separators.length; cur++) {
            if(matches(segment, cur, separators)) {
                return segment.asSlice(0, cur).toArray(ValueLayout.JAVA_BYTE);
            }
        }
        return null;
    }

    public static boolean matches(MemorySegment m, long offset, byte[] bytes) {
        for(int index = 0; index < bytes.length; index++) {
            if ((byte) byteHandle.get(m, offset + index) != bytes[index]) {
                return false;
            }
        }
        return true;
    }
}
