package com.jscape.util.io.primitive;

import com.jscape.util.io.DataCodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

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

/**
 * @author Alex Usun
 */
public class ByteStringCodec
        implements DataCodec<String> {

    private final Charset charset;

    public static void writeValue(String value, Charset charset, OutputStream out)
            throws IOException {
        ByteArrayCodec.writeValue(value.getBytes(charset), out);
    }

    public static String readValue(Charset charset, InputStream in)
            throws IOException {
        byte[] data = ByteArrayCodec.readValue(in);
        return new String(data, charset);
    }

    public ByteStringCodec(Charset charset) {
        assertNotNull(charset);
        this.charset = charset;
    }

    @Override
    public String read(InputStream in)
            throws IOException {
        return readValue(this.charset, in);
    }

    @Override
    public void write(String value, OutputStream out)
            throws IOException {
        writeValue(value, this.charset, out);
    }
}
