从Bytes <bytebuffer>检索ByteBuffer对象

时间:2018-07-12 12:52:10

标签: chronicle chronicle-bytes

我一直在尝试从Bytes对象中检索ByteBuffer(直接)对象引用。以下是代码:

TestMessageWire testMessageWire = new TestMessageWire();
testMessageWire.data('H');
testMessageWire.setIntData(100);

//Below does not give ByteBuffer with correct position & offset
Bytes<ByteBuffer> bytes = Bytes.elasticByteBuffer(10);
Wire wire = new RawWire(bytes);
testMessageWire.writeMarshallable(wire);
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes.toByteArray());

//Another approach, but still does not populate "byteBuffer" object correctly.
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(6);
Bytes<?> bytes = Bytes.wrapForWrite(byteBuffer);
Wire wire = new RawWire(bytes);
testMessageWire.writeMarshallable(wire);

我想在创建ByteBuffer对象时避免多次分配。因此,要重用字节包装的相同Bitebuffer。我该如何实现?

1 个答案:

答案 0 :(得分:1)

您可以创建一个包装ByteBuffer的Bytes。这样可以避免多余的副本。

Bytes<ByteBuffer> bytes = Bytes.elasticByteBuffer();
ByteBuffer bb = bytes.underlyingObject();

由于Bytes具有单独的读/写位置和限制,因此不必再维护ByteBuffer的位置和限制。

例如写入后,您可能需要执行以下操作,以便可以从ByteBuffer中读取写入字节的内容。

bb.position((int) bytes.readPosition());
bb.limit((int) bytes.readLimit());