package hh.dejsem.net;

import java.io.InputStream;
import java.io.OutputStream;

public class StreamIO {
	/**----------------------------------------------------------
	 * specific network IO (java.io) operations
	 * ----------------------------------------------------------*/
	static int readStream(InputStream in, byte[] b, int i, int n) throws Exception {
		int r = 0, rr = 0;
		while(rr < n) {
			if((r = in.read(b, i + rr, n - rr)) < 0) break;
			rr += r; }
		if(rr == 0 && r < 0) rr = r;
		return rr;
	}

	static long getNum(InputStream in) throws Exception { 				// input stream may be net or file
		byte[] b = new byte[12];
		int n = 0;
		while(n < b.length) {
			int r;
			r = readStream(in, b, n, b.length - n);
			if(r < 0) return -2;										// rc = -1 means entity is directory
			else n += r; }
		if(n < b.length)throw new Exception("got deficient file attr");
		return Long.valueOf(new String(b));
	}

	static void putNum(long n, OutputStream out) throws Exception { 	// output stream may be net or file
		byte[] b = String.format("%012d", n).getBytes();
		out.write(b);
	}

	static String getStr(InputStream in) throws Exception { 			// input stream may be net or file
		int n = 0;
		byte[] b = new byte[512];
		if((n = (int)getNum(in)) == -2) return null;					// EOF in input stream
		if(n == 0) return "";
		int r = 0;
		while((r += readStream(in, b, r, n - r)) < n);
		return new String(b, 0, n);
	}

	static void putStr(String fn, OutputStream out) throws Exception {	// output stream may be net or file
		byte[] b = fn.getBytes();
		putNum(b.length, out);
		out.write(b);
	}
}
