diff --git a/server/src/main/java/org/elasticsearch/common/bytes/ByteBufferReference.java b/server/src/main/java/org/elasticsearch/common/bytes/ByteBufferReference.java index fbdcdfd68853d..998a06a2643ba 100644 --- a/server/src/main/java/org/elasticsearch/common/bytes/ByteBufferReference.java +++ b/server/src/main/java/org/elasticsearch/common/bytes/ByteBufferReference.java @@ -25,8 +25,8 @@ /** * This is a {@link BytesReference} backed by a {@link ByteBuffer}. The byte buffer can either be a heap or - * direct byte buffer. The reference is composed of the space between the {@link ByteBuffer#position} and - * {@link ByteBuffer#limit} at construction time. If the position or limit of the underlying byte buffer is + * direct byte buffer. The reference is composed of the space between the {@link ByteBuffer#position()} and + * {@link ByteBuffer#limit()} at construction time. If the position or limit of the underlying byte buffer is * changed, those changes will not be reflected in this reference. However, modifying the limit or position * of the underlying byte buffer is not recommended as those can be used during {@link ByteBuffer#get()} * bounds checks. Use {@link ByteBuffer#duplicate()} at creation time if you plan on modifying the markers of diff --git a/server/src/main/java/org/elasticsearch/common/bytes/BytesReference.java b/server/src/main/java/org/elasticsearch/common/bytes/BytesReference.java index aa2f0524cc0b4..a16b8e4ef3bc5 100644 --- a/server/src/main/java/org/elasticsearch/common/bytes/BytesReference.java +++ b/server/src/main/java/org/elasticsearch/common/bytes/BytesReference.java @@ -195,17 +195,24 @@ public static ByteBuffer[] toByteBuffers(BytesReference reference) { * Returns BytesReference composed of the provided ByteBuffers. */ public static BytesReference fromByteBuffers(ByteBuffer[] buffers) { - ByteBufferReference[] references = new ByteBufferReference[buffers.length]; - for (int i = 0; i < references.length; ++i) { - references[i] = new ByteBufferReference(buffers[i]); - } + int bufferCount = buffers.length; + if (bufferCount == 0) { + return BytesArray.EMPTY; + } else if (bufferCount == 1) { + return new ByteBufferReference(buffers[0]); + } else { + ByteBufferReference[] references = new ByteBufferReference[bufferCount]; + for (int i = 0; i < bufferCount; ++i) { + references[i] = new ByteBufferReference(buffers[i]); + } - return new CompositeBytesReference(references); + return new CompositeBytesReference(references); + } } @Override public int compareTo(final BytesReference other) { - return compareIterators(this, other, (a, b) -> a.compareTo(b)); + return compareIterators(this, other, BytesRef::compareTo); } /**