Efficient way to convert io.netty.buffer.ByteBuf to java.nio.ByteBuffer

I came across this query: Create ByteBuf in Netty 4.0 about converting from byte [] to ByteBuf and ByteBuffer to ByteBuf. I was curious to learn about the treatment differently:

io.netty.buffer.ByteBuf to java.nio.ByteBuffer

and how to do it efficiently, with minimal / no copying? I read a little, and with some trial and error, I found this inefficient way to convert it (with two copies):

// io.netty.handler.codec.http.FullHttpRequest fullHttpRequest; ByteBuf conByteBuf = fullHttpRequest.content (); int numReadBytes = conByteBuf.readableBytes (); conBytes = new byte[numReadBytes]; conByteBuf .readBytes (conBytes); // First Copy ByteBuffer conByteBuffer = ByteBuffer.allocate (conBytes.length); conByteBuffer.put (conByteBuf); // Second Copy 

My question is: can we avoid one or both copies and make an internal ByteBuffer buffer to use the internal ByteBuf buffer.

Thanks!

+6
source share
3 answers

You can at least use ByteBuffer.wrap() to avoid a second copy.

+3
source

You can use ByteBuf.nioBuffers () . Which will return the ByteBuf as an array of ByteBuffer objects.

In most cases, this array will have only one element, but in some more complex implementations of ByteBuf can be several basic ByteBuffer objects, and ByteBuf.nioBuffers() can return them as -s instead of merging them, and also call ByteBuf.nioBuffer() .

You can tell in advance how long the array will be with ByteBuf.nioBufferCount()

+8
source

Not particularly effective, but does the trick:

 public static ByteBuffer toNioBuffer(ByteBuf buffer) { if (buffer.isDirect()) { return buffer.nioBuffer(); } final byte[] bytes = new byte[buffer.readableBytes()]; buffer.getBytes(buffer.readerIndex(), bytes); return ByteBuffer.wrap(bytes); } 
0
source

Source: https://habr.com/ru/post/955707/


All Articles