package org.kne.io;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class VarDataInputStream extends DataInputStream {

	public VarDataInputStream(InputStream in) {
		super(in);
		
	}
	public byte[] readPacketVarBytes() throws IOException {
		
		int i;
		try {
		i=readVarInt();
		}catch(Exception e) {
			return null;
		}
		byte[]b=new byte[i];
		readFully(b);
		return b;
	}
	public byte[] readVarBytes() throws IOException {
		
		int i=readVarInt();
		byte[]b=new byte[i];
		readFully(b);
		return b;
	}
	public String readVarUTF8() throws IOException {
		return new String(readVarBytes(), Charset.forName("UTF-8"));
	}
	int cache=0;
	public int readVarInt_addd()throws IOException {
		cache+=readVarInt();
		return cache;
	}
	public int readVarInt() throws IOException {
		int i = 0;
		int j = 0;

		while (true) {
			byte b0 = this.readByte();
			i |= (b0 & 127) << j++ * 7;

			if (j > 5) {
				throw new RuntimeException("VarInt too big");
			}

			if ((b0 & 128) != 128) {
				break;
			}
		}

		return i;
	}
	public long readVarLong() throws IOException {
		long i = 0L;
		int j = 0;

		while (true) {
			byte b0 = this.readByte();
			i |= (long) (b0 & 127) << j++ * 7;

			if (j > 10) {
				throw new RuntimeException("VarLong too big");
			}

			if ((b0 & 128) != 128) {
				break;
			}
		}

		return i;
	}
}
