package com.jscape.inet.ssh.protocol.v2.marshaling.primitive;

import com.jscape.util.io.primitive.IntByteArrayCodec;

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

/**
 * @author Alex Usun
 */
public class MpintCodec {

    private static final byte[] ZERO_DATA = new byte[0];

    public static BigInteger readValue(InputStream in)
            throws IOException {
        byte[] data = IntByteArrayCodec.readBigEndianValue(in);
        return data.length > 0 ? new BigInteger(data) : new BigInteger("0");
    }

    public static void writeValue(BigInteger value, OutputStream out)
            throws IOException {
        byte[] data = value.compareTo(BigInteger.ZERO) == 0 ? ZERO_DATA : value.toByteArray();

        IntByteArrayCodec.writeBigEndianValue(data, out);
    }

    private MpintCodec() {
        // empty
    }
}
