Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core: reduce CompositeReadableBuffer allocation #3279

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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