package hh.dejsem.net;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

import hh.lib.D;

/**
 * channel I/O interface
 */
public class InChIO /*implements GetPut*/ {
	D d;
	ReadableByteChannel ch = null;
	// ----------------------------------------------------------

	public InChIO(D d, ReadableByteChannel ch) throws Exception {
		this.d = d.klon(this);
		this.ch = ch;
	}

	public boolean get(ByteBuffer buf) throws Exception {
		if(d.ll(5)) d.l("get from channel, buf=" + D.bufStat(buf));
		try { while(buf.hasRemaining()) if(ch.read(buf) < 0) break; }
		catch(Exception x) { close(); throw new Exception("channel read", x); };
		if(d.ll(5)) d.l("" + buf.position()+ " read");
		return buf.position() > 0;
	}

	public void close() {
		try { ch.close(); }
		catch(IOException e) { d.l("close channel" + e.getMessage()); }
	}
}
