import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;

public class MbbAlignmentOffTest {

    public static void main(String[] args) {
        System.out.println("--- inside MbbAlignmentOffTest ---");
       new MbbAlignmentOffTest().test();

    }

    public  void test() {
        MappedByteBuffer[] mbb = buffers();
        for (MappedByteBuffer bb : mbb) {
            try {
                int offset = bb.alignmentOffset(1, 4);
                if (offset >= 0) {
                    System.out.println("PASSED");
                } else {
                    System.out.println("FAILED "+offset);
                }
            } catch (UnsupportedOperationException e) {
                System.out.println("Not applicable, UOE thrown: ");
            }
        }
    }


    public MappedByteBuffer[] buffers() {
        return new MappedByteBuffer[]{
                createMBB(new byte[]{0, 1, 2, 3}),
                createMBB(new byte[]{0, 1, 2, -3, 45, 6, 7, 78, 3, -7, 6, 7, -128, 127}),
        };
    }


    private MappedByteBuffer createMBB(byte[] contents) {
        try {
            Path tempFile = File.createTempFile("tmp", null, new File("/scratch")).toPath();
            tempFile.toFile().deleteOnExit();
            Files.write(tempFile, contents);
            MappedByteBuffer map = FileChannel.open(tempFile).map(FileChannel.MapMode.READ_ONLY, 0, contents.length);
            map.load();
            return map;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
