ByteBuf.readBytes(...) should use the allocator of the buffer to create the new buffer. Related to [#5093]

Motivation:

ByteBuf.readBytes(...) uses Unpooled.buffer(...) internally which will use a heap ByteBuf and also not able to make use of the allocator which may be pooled. We should better make use of the allocator.

Modifications:

Use the allocator for thenew buffer.

Result:

Take allocator into account when copy bytes.
This commit is contained in:
Norman Maurer 2016-04-07 09:56:03 +02:00
parent 200ca39b5c
commit 69070c37ba
3 changed files with 24 additions and 3 deletions

View File

@ -786,8 +786,7 @@ public abstract class AbstractByteBuf extends ByteBuf {
return Unpooled.EMPTY_BUFFER;
}
// Use an unpooled heap buffer because there's no way to mandate a user to free the returned buffer.
ByteBuf buf = Unpooled.buffer(length, maxCapacity);
ByteBuf buf = alloc().buffer(length, maxCapacity);
buf.writeBytes(this, readerIndex, length);
readerIndex += length;
return buf;

View File

@ -1496,6 +1496,7 @@ public abstract class AbstractByteBufTest {
// Make sure if it is a copied buffer.
actualValue.setByte(0, (byte) (actualValue.getByte(0) + 1));
assertFalse(buffer.getByte(i) == actualValue.getByte(0));
actualValue.release();
}
}
@ -2980,6 +2981,21 @@ public abstract class AbstractByteBufTest {
}
}
@Test
public void testReadBytes() {
ByteBuf buffer = newBuffer(8);
byte[] bytes = new byte[8];
buffer.writeBytes(bytes);
ByteBuf buffer2 = buffer.readBytes(4);
assertSame(buffer.alloc(), buffer2.alloc());
assertEquals(4, buffer.readerIndex());
assertTrue(buffer.release());
assertEquals(0, buffer.refCnt());
assertTrue(buffer2.release());
assertEquals(0, buffer2.refCnt());
}
private void testRefCnt0(final boolean parameter) throws Exception {
for (int i = 0; i < 10; i++) {
final CountDownLatch latch = new CountDownLatch(1);

View File

@ -120,6 +120,12 @@ public class SlicedByteBufTest extends AbstractByteBufTest {
// ignore for SlicedByteBuf
}
@Test
@Override
public void testReadBytes() {
// ignore for SlicedByteBuf
}
@Test
public void testReaderIndexAndMarks() {
ByteBuf wrapped = Unpooled.buffer(16);