/* UtilLib - Copyright (c) 2006-2019 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.primitives.io;

import java.io.IOException;
import net.mapeadores.util.primitives.PrimUtils;


/**
 *
 * @author Vincent Calame
 */
public interface PrimitivesReader {

    public int readInt() throws IOException;

    public short readShort() throws IOException;

    public boolean readBoolean() throws IOException;

    public char readChar() throws IOException;

    public String readString() throws IOException;

    public double readDouble() throws IOException;

    public long readLong() throws IOException;

    public byte readByte() throws IOException;

    public float readFloat() throws IOException;

    public int skipBytes(int length) throws IOException;

    public void read(byte[] buffer, int offset, int length) throws IOException;

    public default int[] readInts(int size) throws IOException {
        int bufferLength = size * 4;
        byte[] buffer = new byte[bufferLength];
        read(buffer, 0, bufferLength);
        int[] result = new int[size];
        for (int i = 0; i < size; i++) {
            result[i] = PrimUtils.toInt(buffer, i * 4);
        }
        return result;
    }

    public default Integer[] readIntegers(int size) throws IOException {
        int bufferLength = size * 4;
        byte[] buffer = new byte[bufferLength];
        read(buffer, 0, bufferLength);
        Integer[] result = new Integer[size];
        for (int i = 0; i < size; i++) {
            result[i] = PrimUtils.toInt(buffer, i * 4);
        }
        return result;
    }

    public default void skipInts(int size) throws IOException {
        skipBytes(size * 4);
    }

    public default void skipLongs(int size) throws IOException {
        skipBytes(size * 8);
    }

    public default void skipIntArray() throws IOException {
        int length = readInt();
        skipInts(length);
    }

    public default int[] readIntArray() throws IOException {
        int length = readInt();
        return readInts(length);
    }

    public default Integer[] readIntegerArray() throws IOException {
        int length = readInt();
        return readIntegers(length);
    }

    public default String readLongString() throws IOException {
        int length = readInt();
        switch (length) {
            case -1:
                return null;
            case 0:
                return "";
            default:
                byte[] bytes = new byte[length];
                read(bytes, 0, length);
                return new String(bytes, "UTF-8");
        }
    }

}
