/* 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.IOException;
import java.io.RandomAccessFile;


/**
 *
 * @author Vincent Calame
 */
public final class CacheRef {

    private final long position;
    private final int length;


    public CacheRef(long position, int length) {
        this.position = position;
        this.length = length;
    }

    public long getPosition() {
        return position;
    }

    public int getLength() {
        return length;
    }

    public static byte[] read(RandomAccessFile randomAccessFile, CacheRef cacheRef) throws IOException {
        randomAccessFile.seek(cacheRef.position);
        int cacheLength = cacheRef.length;
        byte[] cache = new byte[cacheLength];
        randomAccessFile.read(cache, 0, cacheLength);
        return cache;
    }

    public static CacheRef write(RandomAccessFile randomAccessFile, byte[] cache) throws IOException {
        long position = randomAccessFile.getFilePointer();
        int cacheLength = cache.length;
        randomAccessFile.write(cache, 0, cacheLength);
        return new CacheRef(position, cacheLength);
    }

}
