From 1c074eabe59aa1d3a5e4d70190c39f33b49310e8 Mon Sep 17 00:00:00 2001 From: "Bourne, Geoff" Date: Thu, 13 Mar 2014 15:10:24 -0500 Subject: [PATCH] Fix limit computation of NIO ByteBuffers obtained via ReadOnlyByteBufferBuf.nioBuffer Motivation: When starting with a read-only NIO buffer, wrapping it in a ByteBuf, and then later retrieving a re-wrapped NIO buffer the limit was getting too short. Modifications: Changed ReadOnlyByteBufferBuf.nioBuffer(int,int) to compute the limit in the same manner as the internalNioBuffer method. Result: Round-trip conversion from NIO to ByteBuf to NIO will work reliably. --- .../java/io/netty/buffer/ReadOnlyByteBufferBuf.java | 2 +- .../buffer/ReadOnlyDirectByteBufferBufTest.java | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/buffer/src/main/java/io/netty/buffer/ReadOnlyByteBufferBuf.java b/buffer/src/main/java/io/netty/buffer/ReadOnlyByteBufferBuf.java index 47e4eb7473..31a9fc8066 100644 --- a/buffer/src/main/java/io/netty/buffer/ReadOnlyByteBufferBuf.java +++ b/buffer/src/main/java/io/netty/buffer/ReadOnlyByteBufferBuf.java @@ -299,7 +299,7 @@ class ReadOnlyByteBufferBuf extends AbstractReferenceCountedByteBuf { @Override public ByteBuffer nioBuffer(int index, int length) { - return (ByteBuffer) buffer.duplicate().position(index).limit(length); + return (ByteBuffer) buffer.duplicate().position(index).limit(index + length); } @Override diff --git a/buffer/src/test/java/io/netty/buffer/ReadOnlyDirectByteBufferBufTest.java b/buffer/src/test/java/io/netty/buffer/ReadOnlyDirectByteBufferBufTest.java index 06ae54eca4..9c9373ed2a 100644 --- a/buffer/src/test/java/io/netty/buffer/ReadOnlyDirectByteBufferBufTest.java +++ b/buffer/src/test/java/io/netty/buffer/ReadOnlyDirectByteBufferBufTest.java @@ -194,4 +194,17 @@ public class ReadOnlyDirectByteBufferBufTest { ByteBuf slice = buf.slice(); Assert.assertEquals(buf, slice); } + + @Test + public void testWrapBufferRoundTrip() { + ByteBuf buf = buffer(((ByteBuffer) allocate(16).putInt(1).putInt(2).flip()).asReadOnlyBuffer()); + buffers.add(buf); + + Assert.assertEquals(1, buf.readInt()); + + ByteBuffer nioBuffer = buf.nioBuffer(); + + // Ensure this can be accessed without throwing a BufferUnderflowException + Assert.assertEquals(2, nioBuffer.getInt()); + } }