package org.xnio.conduits;
import static org.xnio._private.Messages.msg;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import org.xnio.Buffers;
import org.xnio.Pooled;
public final class FramingMessageSourceConduit extends AbstractSourceConduit<StreamSourceConduit> implements MessageSourceConduit {
private final Pooled<ByteBuffer> receiveBuffer;
private boolean ready;
public FramingMessageSourceConduit(final StreamSourceConduit next, final Pooled<ByteBuffer> receiveBuffer) {
super(next);
this.receiveBuffer = receiveBuffer;
}
public void resumeReads() {
if (ready) next.wakeupReads(); else next.resumeReads();
}
public void awaitReadable(final long time, final TimeUnit timeUnit) throws IOException {
if (! ready) next.awaitReadable(time, timeUnit);
}
public void awaitReadable() throws IOException {
if (! ready) next.awaitReadable();
}
public void terminateReads() throws IOException {
receiveBuffer.free();
next.terminateReads();
}
public int receive(final ByteBuffer dst) throws IOException {
final ByteBuffer receiveBuffer = this.receiveBuffer.getResource();
int res;
do {
res = next.read(receiveBuffer);
} while (res > 0);
if (receiveBuffer.position() < 4) {
if (res == -1) {
receiveBuffer.clear();
}
ready = false;
return res;
}
receiveBuffer.flip();
try {
final int length = receiveBuffer.getInt();
if (length < 0 || length > receiveBuffer.capacity() - 4) {
Buffers.unget(receiveBuffer, 4);
throw msg.recvInvalidMsgLength(length);
}
if (receiveBuffer.remaining() < length) {
if (res == -1) {
receiveBuffer.clear();
} else {
Buffers.unget(receiveBuffer, 4);
}
ready = false;
return res;
}
if (dst.hasRemaining()) {
return Buffers.copy(length, dst, receiveBuffer);
} else {
Buffers.skip(receiveBuffer, length);
return 0;
}
} finally {
if (res != -1) {
receiveBuffer.compact();
if (receiveBuffer.position() >= 4 && receiveBuffer.position() >= 4 + receiveBuffer.getInt(0)) {
ready = true;
}
}
}
}
public long receive(final ByteBuffer[] dsts, final int offs, final int len) throws IOException {
final ByteBuffer receiveBuffer = this.receiveBuffer.getResource();
int res;
do {
res = next.read(receiveBuffer);
} while (res > 0);
if (receiveBuffer.position() < 4) {
if (res == -1) {
receiveBuffer.clear();
}
ready = false;
return res;
}
receiveBuffer.flip();
try {
final int length = receiveBuffer.getInt();
if (length < 0 || length > receiveBuffer.capacity() - 4) {
Buffers.unget(receiveBuffer, 4);
throw msg.recvInvalidMsgLength(length);
}
if (receiveBuffer.remaining() < length) {
if (res == -1) {
receiveBuffer.clear();
} else {
Buffers.unget(receiveBuffer, 4);
}
ready = false;
return res;
}
if (Buffers.hasRemaining(dsts, offs, len)) {
return Buffers.copy(length, dsts, offs, len, receiveBuffer);
} else {
Buffers.skip(receiveBuffer, length);
return 0;
}
} finally {
if (res != -1) {
receiveBuffer.compact();
if (receiveBuffer.position() >= 4 && receiveBuffer.position() >= 4 + receiveBuffer.getInt(0)) {
ready = true;
}
}
}
}
}