/*
 * Class: DataReader
 *
 * Author: Alex Usun
 *
 * Date: 1/9/2005
 */
package com.jscape.inet.ssh.util.keyreader.putty;

import com.jscape.util.Assert;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;

/**
 * Putty format data reader.
 *
 * @author Alex Usun
 * @version 1.0
 * @see <a href="DataReader.java.html">Source code</a>
 */
public class DataReader {

    private final DataInputStream in;

    /**
     * Creates a new reader instance.
     *
     * @param in underlayed input stream
     */
    public DataReader(InputStream in) {
        Assert.notNull(in);
        this.in = new DataInputStream(in);
    }

    /**
     * Reads string value as byte array.
     *
     * @return readed value
     *
     * @throws IOException if an I/O error occurs
     */
    public byte[] readStringAsByteArray()
            throws IOException {
        try {
            int length = this.in.readInt();
            byte[] data = new byte[length];
            this.in.readFully(data);

            return data;
        } catch (NegativeArraySizeException | OutOfMemoryError e) {
            throw new IOException("File corrupted or bad passphrase.");
        }
    }

    /**
     * Reads string value.
     *
     * @return readed value
     *
     * @throws IOException if an I/O error occurs
     */
    public String readString()
            throws IOException {
        return new String(readStringAsByteArray(), StandardCharsets.US_ASCII);
    }

    /**
     * Reads big integer value.
     *
     * @return readed value
     *
     * @throws IOException if an I/O error occurs
     */
    public BigInteger readMpint()
            throws IOException {
        return new BigInteger(readStringAsByteArray());
    }

}
