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);
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With