Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a short array from ByteBuf efficiently?

Tags:

netty

When using java.nio.ByteBuffer,my code is like this:

ByteBuffer buffer = ...
ShortBuffer shortBuffer = buffer.asShortBuffer();
short[] shortArray = new short[shortBuffer .remaining()];
shortBuffer.get(shortArray);

Now using netty 4,how can I get the short array from ByteBufefficiently? Or I just use ByteBuf.nioBuffer() to get a ByteBuffer first?

And,how to put a short array to ByteBuf efficiently?Could I write code like this:

Unpooled.buffer(...).nioBuffer().asShortBuffer().put(shortArray);
like image 307
labmem Avatar asked May 16 '26 20:05

labmem


1 Answers

Netty doesn't have a good mechanism to extract a Short[] from a ByteBuf. You can use a compound solution that detects the backend type and uses different ways to address this backend, falling back over to simple copying of the underlying array.

The NioBuffer case is simple, it has a simple get() operation for reading the resulting short array.

The direct and array based cases are harder, these cases require us to call readShort() in a loop until we filled the resulting array.

The resulting code would look like:

ByteBuf buf = ...;
short[] result;
if(buf.readableBytes() % 2 != 0) {
    throw new IllegalArgumentException();
}
result = new short[buf.readableBytes() / 2];
if (buf.nioBufferCount() > 0 ){
    buf.nioBuffer().asShortBuffer().get(result);
} else {
    for(int i = 0; i < result.length; i++) {
        result[i] = buf.readShort();
    }
}
like image 55
Ferrybig Avatar answered May 20 '26 08:05

Ferrybig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!