package com.jscape.util.io.primitive;

import com.jscape.util.IOTools;
import com.jscape.util.io.DataCodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static com.jscape.util.Parameters.assertLesserOrEqual;

/**
 * @author Alex Usun
 */
public class ByteArrayCodec
        implements DataCodec<byte[]> {

    public static void writeValue(byte[] value, int offset, int length, OutputStream out)
            throws IOException {
        assertLesserOrEqual(length, 255, "Bad data length.");
        ByteCodec.writeValue((byte) length, out);
        out.write(value, offset, length);
    }

    public static void writeValue(byte[] value, OutputStream out)
            throws IOException {
        writeValue(value, 0, value.length, out);
    }

    public static byte[] readValue(InputStream in)
            throws IOException {
        int length = ByteCodec.readValue(in) & 0xFF;
        return IOTools.read(new byte[length], in);
    }

    @Override
    public byte[] read(InputStream in)
            throws IOException {
        return readValue(in);
    }

    @Override
    public void write(byte[] value, OutputStream out)
            throws IOException {
        writeValue(value, out);
    }
}
