package com.jscape.util.io.primitive;

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

import java.io.*;

/**
 * @author Alex Usun
 */
public class StringArrayCodec
        implements DataCodec<String[]> {

    public void write(String[] data, OutputStream out)
            throws IOException {
        DataOutputStream writer = new DataOutputStream(out);

        writer.writeInt(data.length);

        for (String string : data) {
            writer.writeUTF(string);
        }

        writer.flush();
    }

    public String[] read(InputStream in)
            throws IOException {
        DataInputStream reader = new DataInputStream(in);

        try {
            int length = reader.readInt();

            String[] ret = new String[length];
            for (int i = 0; i < ret.length; ++i) {
                ret[i] = reader.readUTF();
            }

            return ret;
        } catch (Throwable e) {
            throw IOTools.ioException(e);
        }
    }


}