Skip to content

Commit 6b5417f

Browse files
authored
core: Keep getByteBuffer() support when coalescing small buffers (#13108)
1 parent cf7c13c commit 6b5417f

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

‎core/src/main/java/io/grpc/internal/CompositeReadableBuffer.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,9 @@ private void coalesceTailSmallBuffers(int count) {
123123
b.close();
124124
}
125125

126-
// Wrap and enqueue the single compacted buffer back at the tail
127-
ReadableBuffer singleBuffer = ReadableBuffers.wrap(coalescedBytes);
126+
// Wrap and enqueue the single compacted buffer back at the tail. Wrap it as a ByteBuffer,
127+
// since wrap(byte[]) doesn't support getByteBuffer() and would disable it for the composite.
128+
ReadableBuffer singleBuffer = ReadableBuffers.wrap(ByteBuffer.wrap(coalescedBytes));
128129
readableBuffers.add(singleBuffer);
129130

130131
// Note: The global `readableBytes` remains perfectly synced since we

‎core/src/test/java/io/grpc/internal/CompositeReadableBufferTest.java‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828

2929
import java.io.ByteArrayOutputStream;
3030
import java.io.IOException;
31+
import java.nio.ByteBuffer;
3132
import java.nio.InvalidMarkException;
3233
import org.junit.After;
3334
import org.junit.Before;
@@ -336,6 +337,33 @@ public void coalesceBeforeLargeBuffer() {
336337
assertEquals(1524, composite.readableBytes());
337338
}
338339

340+
@Test
341+
public void coalesceBeforeLargeBufferKeepsByteBufferSupport() {
342+
composite = new CompositeReadableBuffer();
343+
// Small frames that support getByteBuffer(), as Netty's do
344+
composite.addBuffer(ReadableBuffers.wrap(ByteBuffer.wrap("hello ".getBytes(UTF_8))));
345+
composite.addBuffer(ReadableBuffers.wrap(ByteBuffer.wrap("world".getBytes(UTF_8))));
346+
composite.addBuffer(ReadableBuffers.wrap(ByteBuffer.wrap(new byte[1024])));
347+
assertEquals(2, composite.getBufferCount());
348+
349+
assertTrue(composite.byteBufferSupported());
350+
assertEquals(ByteBuffer.wrap("hello world".getBytes(UTF_8)), composite.getByteBuffer());
351+
}
352+
353+
@Test
354+
public void coalesceOnMaxSmallBuffersKeepsByteBufferSupport() {
355+
composite = new CompositeReadableBuffer();
356+
byte[] expected = new byte[1000];
357+
for (int i = 0; i < 1000; i++) {
358+
expected[i] = (byte) i;
359+
composite.addBuffer(ReadableBuffers.wrap(ByteBuffer.wrap(new byte[] {(byte) i})));
360+
}
361+
assertEquals(1, composite.getBufferCount());
362+
363+
assertTrue(composite.byteBufferSupported());
364+
assertEquals(ByteBuffer.wrap(expected), composite.getByteBuffer());
365+
}
366+
339367
@Test
340368
public void largeBufferResetsTailSmallBufferCount() {
341369
composite = new CompositeReadableBuffer();

0 commit comments

Comments
 (0)