private static int channelIO(ReadableByteChannel readCh, WritableByteChannel writeCh,
    ByteBuffer buf) throws IOException {

    int originalLimit = buf.limit();
    int initialRemaining = buf.remaining();
    int ret = 0;

    while (buf.remaining() > 0) {
      try {
        int ioSize = Math.min(buf.remaining(), NIO_BUFFER_LIMIT);
        buf.limit(buf.position() + ioSize);

        ret = (readCh == null) ? writeCh.write(buf) : readCh.read(buf);

        if (ret < ioSize) {
          break;
        }

      } finally {
        buf.limit(originalLimit);
      }
    }

    int nBytes = initialRemaining - buf.remaining();
    return (nBytes > 0) ? nBytes : ret;
  }
Helper for {@link #channelRead(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer)}.
Only one of readCh or writeCh should be non-null.
@param readCh  read channel
@param writeCh write channel
@param buf     buffer to read or write into/out of
@return bytes written
@throws java.io.IOException e
@see #channelRead(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer)
hbase-server/src/main/java/org/apache/hadoop/hbase/ipc/RpcServer.java