package jp.cssj.cti.ctip;

import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author <a href="mailto:miyabe at gnn.co.jp">MIYABE Tatsuhiko </a>
 * @version $Id: CTIPUtils.java,v 1.2 2005/08/18 04:51:26 harumanx Exp $
 */
public final class CTIPUtils {
	private CTIPUtils() {
		// unused
	}

	public static int readInt(SocketChannel channel, ByteBuffer destInt)
			throws IOException {
		CTIPUtils.readAll(channel, destInt);
		return destInt.getInt(0);
	}

	public static byte readByte(SocketChannel channel, ByteBuffer destByte)
			throws IOException {
		CTIPUtils.readAll(channel, destByte);
		return destByte.get(0);
	}

	public static String readString(SocketChannel channel,
			ByteBuffer destShort, String encoding) throws IOException {
		CTIPUtils.readAll(channel, destShort);
		short len = destShort.getShort(0);
		if (len == 0) {
			return "";
		}
		byte[] buff = new byte[len];
		ByteBuffer dest = ByteBuffer.wrap(buff);
		CTIPUtils.readAll(channel, dest);
		return new String(buff, encoding);
	}

	public static void readAll(SocketChannel channel, ByteBuffer dest)
			throws IOException {
		dest.position(0);
		do {
			if (channel.read(dest) == -1) {
				throw new EOFException();
			}
		} while (dest.remaining() > 0);
	}

	public static byte[] toBytes(String str, String encoding)
			throws IOException {
		if (str == null) {
			str = "";
		}
		return str.getBytes(encoding);
	}

	public static void writeAll(SocketChannel channel, ByteBuffer src)
			throws IOException {
		src.position(0);
		do {
			channel.write(src);
		} while (src.remaining() > 0);
	}
}