Skip to content

Commit

Permalink
core: reduce CompositeReadableBuffer allocation (#3279)
Browse files Browse the repository at this point in the history
* core: reduce CompositeReadableBuffer allocation

Add ability for CompositeReadableBuffer read specified length bytes
to another CompositeReadableBuffer instead of create temp
CompositeReadableBuffer.

fixes #3278
---------

Co-authored-by: Larry Safran <107004254+larry-safran@users.noreply.github.com>
  • Loading branch information
Gordiychuk and larry-safran committed Dec 28, 2023
1 parent 846e008 commit 0f21574
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions core/src/main/java/io/grpc/internal/CompositeReadableBuffer.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.nio.InvalidMarkException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
import javax.annotation.Nullable;

/**
Expand All @@ -38,6 +39,7 @@ public class CompositeReadableBuffer extends AbstractReadableBuffer {
private final Deque<ReadableBuffer> readableBuffers;
private Deque<ReadableBuffer> rewindableBuffers;
private int readableBytes;
private final Queue<ReadableBuffer> buffers = new ArrayDeque<ReadableBuffer>(2);
private boolean marked;

public CompositeReadableBuffer(int initialCapacity) {
Expand Down Expand Up @@ -159,6 +161,31 @@ public void readBytes(OutputStream dest, int length) throws IOException {
execute(STREAM_OP, length, dest, 0);
}

/**
* Reads {@code length} bytes from this buffer and writes them to the destination buffer.
* Increments the read position by {@code length}. If the required bytes are not readable, throws
* {@link IndexOutOfBoundsException}.
*
* @param dest the destination buffer to receive the bytes.
* @param length the number of bytes to be copied.
* @throws IndexOutOfBoundsException if required bytes are not readable
*/
public void readBytes(CompositeReadableBuffer dest, int length) {
checkReadable(length);
readableBytes -= length;

while (length > 0) {
ReadableBuffer buffer = buffers.peek();
if (buffer.readableBytes() > length) {
dest.addBuffer(buffer.readBytes(length));
length = 0;
} else {
dest.addBuffer(buffers.poll());
length -= buffer.readableBytes();
}
}
}

@Override
public ReadableBuffer readBytes(int length) {
if (length <= 0) {
Expand Down

0 comments on commit 0f21574

Please sign in to comment.