NettyBufferFactory implements BufferFactory<ByteBuf> { public static void writeRaw(final Buffer buffer, final Consumer<ByteBuf> consumer) { if (buffer instanceof NettyBuffer) { consumer.accept(((NettyBuffer)buffer).getUnderlyingBuffer()); return; } final int initialIndex = buffer.writerIndex(); final ByteBuf newBuffer = getFromIndex(buffer, initialIndex); newBuffer.writerIndex(0); try { consumer.accept(newBuffer); buffer.writerIndex(initialIndex + newBuffer.writerIndex()); } finally { newBuffer.release(); } }  @Override Buffer create(final ByteBuf value); @Override Buffer wrap(final ByteBuffer value); static void readRaw(final Buffer buffer, final Consumer<ByteBuf> consumer); static void writeRaw(final Buffer buffer, final Consumer<ByteBuf> consumer);  }
@Test public void writeRawShouldAdvanceWriterIndexAndReleaseIt() { final int intValue1 = 314; final int intValue2 = 314; final FakeBuffer fakeBuffer = new FakeBuffer(); fakeBuffer.writeInt(intValue1); assertEquals(4, fakeBuffer.writerIndex()); assertEquals(0, fakeBuffer.readerIndex()); final ByteBuf[] captured = new ByteBuf[1]; NettyBufferFactory.writeRaw(fakeBuffer, byteBuf -> { byteBuf.writeInt(intValue2); assertNotSame(byteBuf, fakeBuffer.getUnderlyingRaw()); assertEquals(1, byteBuf.refCnt()); captured[0] = byteBuf; }); assertEquals(8, fakeBuffer.writerIndex()); assertEquals(0, fakeBuffer.readerIndex()); assertEquals(intValue1, fakeBuffer.readInt()); assertEquals(intValue2, fakeBuffer.readInt()); assertEquals(0, captured[0].refCnt()); }
@Test public void writeRawShouldUseTheSameBufferWhenNettyBuffer() { final NettyBuffer wrapperBuffer = new NettyBuffer(allocator.buffer()); NettyBufferFactory.writeRaw(wrapperBuffer, byteBuf -> { assertSame(byteBuf, wrapperBuffer.getUnderlyingBuffer()); assertEquals(1, byteBuf.refCnt()); }); assertEquals(1, wrapperBuffer.referenceCount()); }