import java.io.UnsupportedEncodingException;

/**
 * Byte buffer - Bigendian
 * this class is limited, doesn't grow
 * @author ggongaware _at_ itensil _dot_ com
 *
 */
public class ByteBuffer {
	int pos;
	int size;
	byte [] buf;

	public ByteBuffer(int size) {
		buf = new byte[size];
		pos = 0;
		this.size = 0;
	}


	public void putByte(byte v) {
		buf[pos++] = v;
	}

	public void putChar(char v) {
		buf[pos++] = (byte)(0xff & v);
		buf[pos++] = (byte)(0xff & (v >> 8));
	}

	public void putInt(int v) {
		buf[pos++] = (byte)(0xff & v);
		buf[pos++] = (byte)(0xff & (v >> 8));
		buf[pos++] = (byte)(0xff & (v >> 16));
		buf[pos++] = (byte)(0xff & (v >> 24));
	}

	public void putLong(long v) {
		buf[pos++] = (byte)(0xff & v);
		buf[pos++] = (byte)(0xff & (v >> 8));
		buf[pos++] = (byte)(0xff & (v >> 16));
		buf[pos++] = (byte)(0xff & (v >> 24));
		buf[pos++] = (byte)(0xff & (v >> 32));
		buf[pos++] = (byte)(0xff & (v >> 40));
		buf[pos++] = (byte)(0xff & (v >> 48));
		buf[pos++] = (byte)(0xff & (v >> 56));
	}

	public void putBytes(byte [] v) {
		for (int i = 0; i < v.length; i++) {
			buf[pos++] = v[i];
		}
	}

	public void putString(String v) {
		try {
			putBytes(v.getBytes("US-ASCII"));
		} catch (UnsupportedEncodingException uee) {
			throw new RuntimeException(uee.toString());
		}
	}

	public void putUTF(String v) {
		try {
			putBytes(v.getBytes("UTF-16LE"));
		} catch (UnsupportedEncodingException uee) {
			throw new RuntimeException(uee.toString());
		}
	}

	public void putBSTR(String v, boolean UTF) {
		putChar((char)v.length());
		if (UTF) {
			putUTF(v);
			putChar((char)0); // null terminate
		} else {
			putString(v);
			putByte((byte)0); // null terminate
		}
	}

	public void reset() {
		if (size < pos) size = pos;
		pos = 0;
	}

	public int position() {
		return pos;
	}

	public byte [] getBytes() {
		if (size < pos) size = pos;
		byte [] b = new byte[size];
		for (int i=0; i < size; i++) {
		 	b[i] = buf[i];
		}
		return b;
	}
}

