capnproto-java-rpc/runtime/src/main/java/org/capnproto/Serialize.java

36 lines
1 KiB
Java
Raw Normal View History

2014-05-24 18:39:47 +00:00
package org.capnproto;
import java.io.IOException;
2014-09-03 21:21:44 +00:00
import java.nio.channels.WritableByteChannel;
2014-05-24 18:39:47 +00:00
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public final class Serialize {
2014-06-30 14:30:04 +00:00
2014-09-03 21:21:44 +00:00
public static void writeMessage(WritableByteChannel outputChannel,
2014-05-24 18:39:47 +00:00
MessageBuilder message) throws IOException {
ByteBuffer[] segments = message.getSegmentsForOutput();
int tableSize = (segments.length + 2) & (~1);
ByteBuffer table = ByteBuffer.allocate(4 * tableSize);
table.order(ByteOrder.LITTLE_ENDIAN);
table.putInt(0, segments.length - 1);
for (int i = 0; i < segments.length; ++i) {
table.putInt(4 * (i + 1), segments[i].limit() / 8);
}
// Any padding is already zeroed.
2014-06-30 14:30:04 +00:00
while (table.hasRemaining()) {
outputChannel.write(table);
}
2014-05-24 18:39:47 +00:00
2014-09-03 21:21:44 +00:00
for (ByteBuffer buffer : segments) {
while(buffer.hasRemaining()) {
outputChannel.write(buffer);
}
2014-06-30 14:30:04 +00:00
}
2014-05-24 18:39:47 +00:00
}
}