/* UtilLib - Copyright (c) 2014-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;

import java.io.IOException;
import java.util.Arrays;
import net.mapeadores.util.base64.Base64;
import net.mapeadores.util.primitives.io.PrimitivesReader;
import net.mapeadores.util.primitives.io.PrimitivesWriter;


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

    private final byte[] byteArray;
    private final int hashCode;

    public ByteArrayKey(byte[] byteArray) {
        if (byteArray == null) {
            throw new NullPointerException();
        }
        this.byteArray = byteArray;
        this.hashCode = Arrays.hashCode(byteArray);
    }

    @Override
    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }
        if (other == this) {
            return true;
        }
        if (other.getClass() != this.getClass()) {
            return false;
        }
        ByteArrayKey otherByteArrayKey = (ByteArrayKey) other;
        if (otherByteArrayKey.hashCode != this.hashCode) {
            return false;
        }
        return Arrays.equals(otherByteArrayKey.byteArray, this.byteArray);
    }

    @Override
    public int hashCode() {
        return hashCode;
    }

    @Override
    public String toString() {
        return Base64.encodeBase64String(byteArray);
    }

    public static ByteArrayKey fromPrimitives(PrimitivesReader primitivesReader) throws IOException {
        int length = primitivesReader.readInt();
        byte[] byteArray = new byte[length];
        primitivesReader.read(byteArray, 0, length);
        return new ByteArrayKey(byteArray);
    }

    public static void toPrimitives(PrimitivesWriter primitivesWriter, ByteArrayKey byteArrayKey) throws IOException {
        byte[] byteArray = byteArrayKey.byteArray;
        int length = byteArray.length;
        primitivesWriter.writeInt(length);
        primitivesWriter.write(byteArray, 0, length);
    }

}
