Reputation: 2535
In Netty 3 we enforced LITTLE_ENDIAN ChannelBuffers on each end using
bootstrap.setOption("child.bufferFactory", new HeapChannelBufferFactory(ByteOrder.LITTLE_ENDIAN));
but in Netty 4, configuration of ByteBuf now appears to be via ChannelOption.ALLOCATOR:
bootstrap.option(ChannelOption.ALLOCATOR, someAllocator);
All we really want to do is decorate UnpooledByteBufAllocator, but it is final and the methods we need to decorate are protected, so we cant extend the class or delegate to it. We have had to resort to a proxy approach:
private static class AllocatorProxyHandler implements InvocationHandler {
private final ByteBufAllocator allocator;
public AllocatorProxyHandler(ByteBufAllocator allocator) {
this.allocator = allocator;
}
public static ByteBufAllocator proxy(ByteBufAllocator allocator) {
return (ByteBufAllocator) Proxy.newProxyInstance(AllocatorProxyHandler.class.getClassLoader(), new Class[]{ByteBufAllocator.class}, new AllocatorProxyHandler(allocator));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(allocator, args);
if (result instanceof ByteBuf) {
return ((ByteBuf) result).order(ByteOrder.LITTLE_ENDIAN);
} else {
return result;
}
}
}
setting the Bootstrap option like this:
bootstrap.option(ChannelOption.ALLOCATOR, AllocatorProxyHandler.proxy(UnpooledByteBufAllocator.DEFAULT));
Is there some other (better) way to do this we are missing?
Upvotes: 1
Views: 3080
Reputation: 12351
Netty 4.0's ByteBuf
is big-endian by default. You can get the little-endian view of the ByteBuf
using the order(ByteOrder)
method:
ByteBuf buf = ctx.alloc().buffer();
ByteBuf leBuf = buf.order(ByteOrder.LITTLE_ENDIAN);
leBuf.getByte(...);
...
This is by design to avoid any confusion caused by keeping byte order as a state variable. If there is a good reason why it has to provide a way to change the default byte order, please let us know so we can reconsider this decision.
Upvotes: 2