/* UtilLib - Copyright (c) 2006-2025 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.util.List;
import net.mapeadores.util.primitives.PrimUtils;


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

    public void writeInt(int i) throws IOException;

    public void writeShort(short s) throws IOException;

    public void writeByte(byte b) throws IOException;

    public void writeString(String s) throws IOException;

    public void writeBoolean(boolean b) throws IOException;

    public void writeChar(char carac) throws IOException;

    public void writeDouble(double d) throws IOException;

    public void writeLong(long l) throws IOException;

    public void writeFloat(float f) throws IOException;

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

    public default void writeIntArray(int[] intArray) throws IOException {
        int length = intArray.length;
        int bufferLength = (length + 1) * 4;
        byte[] buffer = new byte[bufferLength];
        PrimUtils.convertInt(length, buffer);
        for (int i = 0; i < length; i++) {
            PrimUtils.convertInt(intArray[i], buffer, (i + 1) * 4);
        }
        write(buffer, 0, bufferLength);
    }

    public default void writeIntArray(List<Integer> integerList) throws IOException {
        int length = integerList.size();
        int bufferLength = (length + 1) * 4;
        byte[] buffer = new byte[bufferLength];
        PrimUtils.convertInt(length, buffer);
        for (int i = 0; i < length; i++) {
            PrimUtils.convertInt(integerList.get(i), buffer, (i + 1) * 4);
        }
        write(buffer, 0, bufferLength);
    }

    public default void writeLongString(String s) throws IOException {
        if (s == null) {
            writeInt(-1);
        } else if (s.isEmpty()) {
            writeInt(0);
        } else {
            byte[] b = s.getBytes("UTF-8");
            writeInt(b.length);
            write(b, 0, b.length);
        }
    }

}
