/* UtilLib - Copyright (c) 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.EOFException;
import java.io.IOException;
import java.io.RandomAccessFile;
import net.mapeadores.util.primitives.PrimUtils;


/**
 *
 * @author Vincent Calame
 */
public class RandomAccessPrimitivesReader extends DataInputPrimitivesReader {

    private final RandomAccessFile randomAccessFile;
    private final byte[] intBuffer = new byte[4];
    private final byte[] longBuffer = new byte[8];

    public RandomAccessPrimitivesReader(RandomAccessFile randomAccessFile) {
        super(randomAccessFile);
        this.randomAccessFile = randomAccessFile;
    }

    @Override
    public int readInt() throws IOException {
        int length = randomAccessFile.read(intBuffer, 0, 4);
        if (length != 4) {
            throw new EOFException();
        }
        return PrimUtils.toInt(intBuffer);
    }

    @Override
    public long readLong() throws IOException {
        int length = randomAccessFile.read(longBuffer, 0, 8);
        if (length != 8) {
            throw new EOFException();
        }
        return PrimUtils.toLong(longBuffer);
    }

    @Override
    public void read(byte[] buffer, int offset, int length) throws IOException {
        int result = randomAccessFile.read(buffer, offset, length);
        if (result != length) {
            throw new EOFException();
        }
    }

}
